Skip to content

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

TypeScript

feat: Add hasClear prop to TextInput, NumberInput, Selector, MultiSelector, DateInput (#1155)

Cindy Zhang400094f71e20
diff --git a/apps/storybook/stories/DateInput.stories.tsx b/apps/storybook/stories/DateInput.stories.tsx
index c5e3d72377..69399add70 100644
--- a/apps/storybook/stories/DateInput.stories.tsx
+++ b/apps/storybook/stories/DateInput.stories.tsx
@@ -320,3 +320,29 @@ export const AllVariations: Story = {
);
},
};
+
+export const Clearable: Story = {
+ render: args => {
+ const [value, setValue] = useState<string | undefined>('2026-04-06');
+ return (
+ <XDSDateInput {...args} value={value} onChange={setValue} hasClear />
+ );
+ },
+ args: {
+ label: 'Event date',
+ placeholder: 'Select a date',
+ },
+};
+
+export const ClearableWithStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<string | undefined>('2026-04-06');
+ return (
+ <XDSDateInput {...args} value={value} onChange={setValue} hasClear />
+ );
+ },
+ args: {
+ label: 'Deadline',
+ status: {type: 'error', message: 'Date is in the past'},
+ },
+};
diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsx
index ca7fe4f410..79de8bbe18 100644
--- a/apps/storybook/stories/MultiSelector.stories.tsx
+++ b/apps/storybook/stories/MultiSelector.stories.tsx
@@ -355,3 +355,27 @@ export const ColumnVisibility: Story = {
},
decorators: [Story => <Story />],
};
+
+export const Clearable: Story = {
+ render: args => {
+ const [value, setValue] = useState<string[]>(['react', 'typescript']);
+ return (
+ <XDSMultiSelector
+ {...args}
+ options={[
+ {value: 'react', label: 'React'},
+ {value: 'typescript', label: 'TypeScript'},
+ {value: 'stylex', label: 'StyleX'},
+ {value: 'vitest', label: 'Vitest'},
+ ]}
+ value={value}
+ onChange={setValue}
+ hasClear
+ />
+ );
+ },
+ args: {
+ label: 'Technologies',
+ placeholder: 'Select technologies...',
+ },
+};
diff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsx
index a57921e50c..897c74061c 100644
--- a/apps/storybook/stories/NumberInput.stories.tsx
+++ b/apps/storybook/stories/NumberInput.stories.tsx
@@ -508,3 +508,31 @@ export const WithEventHandlers: Story = {
description: 'Events are logged below',
},
};
+
+export const Clearable: Story = {
+ render: args => {
+ const [value, setValue] = useState<number | null>(args.value ?? 42);
+ return (
+ <XDSNumberInput {...args} value={value} onChange={setValue} hasClear />
+ );
+ },
+ args: {
+ label: 'Quantity',
+ placeholder: 'Enter a number',
+ },
+};
+
+export const ClearableWithUnits: Story = {
+ render: args => {
+ const [value, setValue] = useState<number | null>(args.value ?? 75);
+ return (
+ <XDSNumberInput {...args} value={value} onChange={setValue} hasClear />
+ );
+ },
+ args: {
+ label: 'Progress',
+ units: '%',
+ min: 0,
+ max: 100,
+ },
+};
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index 1821768869..35e7c2cb09 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -444,3 +444,41 @@ export const AllVariations: Story = {
},
decorators: [Story => <Story />],
};
+
+export const Clearable: Story = {
+ render: args => {
+ const [value, setValue] = useState<string | null>('Banana');
+ return (
+ <XDSSelector
+ {...args}
+ options={['Apple', 'Banana', 'Cherry', 'Date']}
+ value={value}
+ onChange={setValue}
+ hasClear
+ />
+ );
+ },
+ args: {
+ label: 'Fruit',
+ placeholder: 'Select a fruit...',
+ },
+};
+
+export const ClearableWithStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<string | null>('Banana');
+ return (
+ <XDSSelector
+ {...args}
+ options={['Apple', 'Banana', 'Cherry']}
+ value={value}
+ onChange={setValue}
+ hasClear
+ />
+ );
+ },
+ args: {
+ label: 'Required fruit',
+ status: {type: 'warning', message: 'Selection is recommended'},
+ },
+};
diff --git a/apps/storybook/stories/TextInput.stories.tsx b/apps/storybook/stories/TextInput.stories.tsx
index 3affbeec70..8639386e4d 100644
--- a/apps/storybook/stories/TextInput.stories.tsx
+++ b/apps/storybook/stories/TextInput.stories.tsx
@@ -465,3 +465,27 @@ export const TooltipWithOptional: Story = {
isOptional: true,
},
};
+
+export const Clearable: Story = {
+ render: args => {
+ const [value, setValue] = useState(args.value ?? 'Hello world');
+ return <XDSTextInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Search',
+ placeholder: 'Type to search...',
+ hasClear: true,
+ },
+};
+
+export const ClearableWithStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState(args.value ?? 'invalid-email');
+ return <XDSTextInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Email',
+ hasClear: true,
+ status: {type: 'error', message: 'Invalid email address'},
+ },
+};
diff --git a/packages/core/src/DateInput/XDSDateInput.test.tsx b/packages/core/src/DateInput/XDSDateInput.test.tsx
index ae210c55ed..7fd67f4478 100644
--- a/packages/core/src/DateInput/XDSDateInput.test.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.test.tsx
@@ -450,4 +450,65 @@ describe('XDSDateInput', () => {
// Note: Tests involving popover rendering (show/hide with calendar)
// are limited because jsdom doesn't support the Popover API.
// Full popover interaction is tested in the browser via Storybook.
+
+ describe('hasClear', () => {
+ it('shows clear button when hasClear is true and value exists', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ value="2026-01-15"
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Clear Date'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when value is undefined', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} hasClear />);
+ expect(
+ screen.queryByRole('button', {name: 'Clear Date'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when hasClear is false', () => {
+ render(
+ <XDSDateInput label="Date" value="2026-01-15" onChange={() => {}} />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Date'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when disabled', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ value="2026-01-15"
+ onChange={() => {}}
+ hasClear
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Date'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with undefined when clear is clicked', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput
+ label="Date"
+ value="2026-01-15"
+ onChange={onChange}
+ hasClear
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Clear Date'}));
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+ });
});
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index cd3b42b67a..d6736ec1e7 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -224,6 +224,13 @@ export interface XDSDateInputProps extends Omit<
*/
labelTooltip?: string;
+ /**
+ * Whether to show a clear button when a date is set.
+ * When clicked, resets the value to undefined and returns focus to the input.
+ * @default false
+ */
+ hasClear?: boolean;
+
/**
* Number of months to display in the calendar popover.
* @default 1
@@ -261,6 +268,7 @@ export function XDSDateInput({
size = 'md',
status,
labelTooltip,
+ hasClear = false,
numberOfMonths = 1,
xstyle,
className,
@@ -372,6 +380,12 @@ export function XDSDateInput({
[isBusy, onChange, onChangeAction, startTransition, setOptimisticValue],
);
+ // Handle clear button click
+ const handleClear = useCallback(() => {
+ fireChange(undefined);
+ inputRef.current?.focus();
+ }, [fireChange]);
+
// Handle date selection from calendar
const handleDateSelect = useCallback(
(selectedDate: ISODateString) => {
@@ -519,6 +533,15 @@ export function XDSDateInput({
!isInputValid && styles.inputInvalid,
)}
/>
+ {hasClear && value !== undefined && !isEffectivelyDisabled && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label={`Clear ${label}`}
+ {...stylex.props(styles.iconButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
<button
type="button"
onClick={handleToggle}
diff --git a/packages/core/src/MultiSelector/XDSMultiSelector.tsx b/packages/core/src/MultiSelector/XDSMultiSelector.tsx
index cc700aee2a..e3d1004243 100644
--- a/packages/core/src/MultiSelector/XDSMultiSelector.tsx
+++ b/packages/core/src/MultiSelector/XDSMultiSelector.tsx
@@ -162,6 +162,25 @@ const styles = stylex.create({
transition: 'none',
},
+ // Clear button
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 1,
+ },
+
// Dropdown container
dropdown: {
boxSizing: 'border-box',
@@ -418,6 +437,13 @@ export interface XDSMultiSelectorProps<
*/
labelTooltip?: string;
+ /**
+ * Whether to show a clear button when values are selected.
+ * When clicked, resets the value to an empty array and returns focus to the trigger.
+ * @default false
+ */
+ hasClear?: boolean;
+
/**
* Whether to show a "Select all" checkbox.
* @default false
@@ -501,6 +527,7 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
size = 'md',
status,
labelTooltip,
+ hasClear = false,
hasSelectAll = false,
selectAllLabel = 'Select all',
hasSearch = false,
@@ -638,6 +665,21 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
});
// Handle toggle
+ // Handle clear button click
+ const handleClear = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation(); // Don't open dropdown
+ onChange([]);
+ if (onChangeAction) {
+ startTransition(async () => {
+ setOptimisticValue([]);
+ await onChangeAction([]);
+ });
+ }
+ },
+ [onChange, onChangeAction, startTransition, setOptimisticValue],
+ );
+
const handleToggle = useCallback(
(itemValue: string) => {
const newValue = optimisticValue.includes(itemValue)
@@ -1072,6 +1114,16 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
<span {...stylex.props(styles.triggerContent)}>
{renderTriggerContent()}
</span>
+ {hasClear && value.length > 0 && !isDisabled && (
+ <button
+ type="button"
+ tabIndex={-1}
+ onClick={handleClear}
+ aria-label={`Clear all ${label}`}
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
{isBusy && <XDSSpinner size="sm" />}
<span
{...stylex.props(
diff --git a/packages/core/src/NumberInput/XDSNumberInput.test.tsx b/packages/core/src/NumberInput/XDSNumberInput.test.tsx
index c14dfb1a23..ebb2b30a4d 100644
--- a/packages/core/src/NumberInput/XDSNumberInput.test.tsx
+++ b/packages/core/src/NumberInput/XDSNumberInput.test.tsx
@@ -575,4 +575,61 @@ describe('XDSNumberInput', () => {
);
});
});
+
+ describe('hasClear', () => {
+ it('shows clear button when hasClear is true and value exists', () => {
+ render(
+ <XDSNumberInput label="Qty" value={5} onChange={() => {}} hasClear />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Clear Qty'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when value is null', () => {
+ render(
+ <XDSNumberInput
+ label="Qty"
+ value={null}
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Qty'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when hasClear is false', () => {
+ render(<XDSNumberInput label="Qty" value={5} onChange={() => {}} />);
+ expect(
+ screen.queryByRole('button', {name: 'Clear Qty'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when disabled', () => {
+ render(
+ <XDSNumberInput
+ label="Qty"
+ value={5}
+ onChange={() => {}}
+ hasClear
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Qty'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with null when clear is clicked', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <XDSNumberInput label="Qty" value={5} onChange={onChange} hasClear />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Clear Qty'}));
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+ });
});
diff --git a/packages/core/src/NumberInput/XDSNumberInput.tsx b/packages/core/src/NumberInput/XDSNumberInput.tsx
index fcf99922b5..1f76d5d725 100644
--- a/packages/core/src/NumberInput/XDSNumberInput.tsx
+++ b/packages/core/src/NumberInput/XDSNumberInput.tsx
@@ -27,8 +27,10 @@ import type {XDSIconName} from '../Icon';
import {
colorVars,
sizeVars,
+ radiusVars,
typographyVars,
typeScaleVars,
+ borderVars,
} from '../theme/tokens.stylex';
import {
XDSField,
@@ -45,6 +47,23 @@ const styles = stylex.create({
wrapper: {
zIndex: 1,
},
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 1,
+ },
input: {
display: 'block',
flex: 1,
@@ -100,7 +119,7 @@ export type {
import {xdsClassName, mergeProps} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
-export interface XDSNumberInputProps extends Omit<
+interface XDSNumberInputPropsBase extends Omit<
XDSBaseProps,
'onChange' | 'defaultValue'
> {
@@ -157,11 +176,7 @@ export interface XDSNumberInputProps extends Omit<
* @default 'md'
*/
size?: XDSNumberInputSize;
- /**
- * Callback fired when the input value changes to a valid number.
- * Only called when the entered value passes validation.
- */
- onChange: (value: number) => void;
+ // onChange and hasClear defined in discriminated union below
/**
* The current value of the input.
* Use null or undefined to represent an empty/unset value.
@@ -225,6 +240,31 @@ export interface XDSNumberInputProps extends Omit<
onEnter?: () => void;
}
+/**
+ * Without `hasClear`, onChange only receives valid numbers.
+ * With `hasClear`, onChange also receives `null` when the user clears the input.
+ */
+type XDSNumberInputPropsNonClearable = XDSNumberInputPropsBase & {
+ hasClear?: false;
+ onChange: (value: number) => void;
+};
+
+type XDSNumberInputPropsClearable = XDSNumberInputPropsBase & {
+ /**
+ * Whether to show a clear button when a value is set.
+ * When clicked, resets the value to null and returns focus to the input.
+ *
+ * When enabled, the `onChange` callback type widens to also accept `null`,
+ * signaling that the user cleared the input.
+ */
+ hasClear: true;
+ onChange: (value: number | null) => void;
+};
+
+export type XDSNumberInputProps =
+ | XDSNumberInputPropsNonClearable
+ | XDSNumberInputPropsClearable;
+
/**
* Parse and validate a string input as a number.
* Returns null if the input is not a valid number or fails validation.
@@ -300,6 +340,7 @@ export function XDSNumberInput({
isIntegerOnly = false,
onFocus,
onBlur,
+ hasClear,
onEnter,
xstyle,
className,
@@ -435,6 +476,15 @@ export function XDSNumberInput({
[ref],
);
+ // Handle clear button click
+ const handleClear = useCallback(() => {
+ if (hasClear) {
+ (onChange as (value: number | null) => void)(null);
+ }
+ setPendingInput(null);
+ inputRef.current?.focus();
+ }, [hasClear, onChange]);
+
return (
<XDSField
label={label}
@@ -500,6 +550,15 @@ export function XDSNumberInput({
)}
/>
{units && <span {...stylex.props(styles.units)}>{units}</span>}
+ {hasClear && value != null && !isDisabled && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label={`Clear ${label}`}
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
{status && (
<XDSIcon
icon={statusIconMap[status.type]}
diff --git a/packages/core/src/Selector/XDSSelector.test.tsx b/packages/core/src/Selector/XDSSelector.test.tsx
new file mode 100644
index 0000000000..66a0289e8f
--- /dev/null
+++ b/packages/core/src/Selector/XDSSelector.test.tsx
@@ -0,0 +1,159 @@
+/**
+ * @file XDSSelector.test.tsx
+ * @input Uses vitest, @testing-library/react, @testing-library/user-event
+ * @output Unit tests for XDSSelector
+ * @position Tests; validates XDSSelector behavior
+ *
+ * SYNC: When XDSSelector.tsx API changes, update these tests.
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSSelector} from './XDSSelector';
+
+const OPTIONS = ['Apple', 'Banana', 'Cherry'];
+
+describe('XDSSelector', () => {
+ it('renders with placeholder when no value', () => {
+ render(
+ <XDSSelector label="Fruit" options={OPTIONS} placeholder="Pick one" />,
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Pick one');
+ });
+
+ it('renders selected value label', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Banana');
+ });
+
+ describe('hasClear', () => {
+ it('shows selected value label when hasClear is enabled', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Banana');
+ });
+
+ it('shows clear button when hasClear is true and value is selected', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Clear Fruit'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when value is null', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value={null}
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Fruit'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when hasClear is false', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Fruit'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when disabled', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ hasClear
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Fruit'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with null when clear is clicked', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={onChange}
+ hasClear
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Clear Fruit'}));
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ it('shows placeholder after clearing', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={OPTIONS}
+ value={null}
+ onChange={() => {}}
+ hasClear
+ placeholder="Select a fruit..."
+ />,
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent(
+ 'Select a fruit...',
+ );
+ });
+
+ it('renders selected label with object options and hasClear', () => {
+ render(
+ <XDSSelector
+ label="Fruit"
+ options={[
+ {value: 'apple', label: 'Red Apple'},
+ {value: 'banana', label: 'Yellow Banana'},
+ ]}
+ value="banana"
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Yellow Banana');
+ });
+ });
+});
diff --git a/packages/core/src/Selector/XDSSelector.tsx b/packages/core/src/Selector/XDSSelector.tsx
index 3dc8b03123..74b6d3438b 100644
--- a/packages/core/src/Selector/XDSSelector.tsx
+++ b/packages/core/src/Selector/XDSSelector.tsx
@@ -107,6 +107,14 @@ const styles = stylex.create({
triggerPlaceholder: {
color: colorVars['--color-text-secondary'],
},
+ triggerLabel: {
+ flexGrow: 1,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ textAlign: 'start',
+ },
triggerIcon: {
flexShrink: 0,
display: 'flex',
@@ -128,6 +136,25 @@ const styles = stylex.create({
transition: 'none',
},
+ // Clear button
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 1,
+ },
+
// Dropdown container
dropdown: {
boxSizing: 'border-box',
@@ -246,7 +273,7 @@ export interface XDSSelectorStatus {
message?: string;
}
-export interface XDSSelectorProps<
+interface XDSSelectorPropsBase<
T extends XDSSelectorOptionType = XDSSelectorOptionType,
> extends Omit<XDSBaseProps, 'onChange' | 'defaultValue' | 'children'> {
/**
@@ -289,20 +316,7 @@ export interface XDSSelectorProps<
*/
options: T[];
- /**
- * The currently selected value.
- */
- value?: string;
-
- /**
- * Callback when selection changes.
- */
- onChange?: (value: string) => void;
-
- /**
- * Async action on change. Fires after onChange.
- */
- onChangeAction?: (value: string) => void | Promise<void>;
+ // value, onChange, onChangeAction, and hasClear are in the discriminated union below
/**
* Whether the selector is in a loading state.
@@ -348,6 +362,38 @@ export interface XDSSelectorProps<
'data-testid'?: string;
}
+/**
+ * Without `hasClear`, the selector always has a string value (or undefined for placeholder).
+ * With `hasClear`, the value can be `null` and onChange receives `null` on clear.
+ */
+type XDSSelectorPropsNonClearable<
+ T extends XDSSelectorOptionType = XDSSelectorOptionType,
+> = XDSSelectorPropsBase<T> & {
+ hasClear?: false;
+ value?: string;
+ onChange?: (value: string) => void;
+ onChangeAction?: (value: string) => void | Promise<void>;
+};
+
+type XDSSelectorPropsClearable<
+ T extends XDSSelectorOptionType = XDSSelectorOptionType,
+> = XDSSelectorPropsBase<T> & {
+ /**
+ * Whether to show a clear button when a value is selected.
+ * When clicked, resets the value to `null` and returns focus to the trigger.
+ *
+ * When enabled, `value` and `onChange` widen to include `null`.
+ */
+ hasClear: true;
+ value: string | null;
+ onChange?: (value: string | null) => void;
+ onChangeAction?: (value: string | null) => void | Promise<void>;
+};
+
+export type XDSSelectorProps<
+ T extends XDSSelectorOptionType = XDSSelectorOptionType,
+> = XDSSelectorPropsNonClearable<T> | XDSSelectorPropsClearable<T>;
+
/**
* Default option renderer
*/
@@ -374,28 +420,35 @@ function DefaultOption({option}: {option: XDSSelectorOptionData}) {
* />
* ```
*/
-export function XDSSelector<T extends XDSSelectorOptionType>({
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- isDisabled = false,
- options,
- value,
- onChange,
- onChangeAction,
- isLoading = false,
- placeholder = 'Select...',
- size = 'md',
- status,
- labelTooltip,
- children,
- 'data-testid': testId,
- xstyle,
- className,
- style,
-}: XDSSelectorProps<T>) {
+export function XDSSelector<T extends XDSSelectorOptionType>(
+ props: XDSSelectorProps<T>,
+) {
+ const {
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ options,
+ value,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ placeholder = 'Select...',
+ size = 'md',
+ status,
+ labelTooltip,
+ children,
+ 'data-testid': testId,
+ xstyle,
+ className,
+ style,
+ } = props;
+ const hasClear = 'hasClear' in props && props.hasClear === true;
+
+ // Normalize null to undefined for internal use (null is the clear sentinel)
+ const normalizedValue = value === null ? undefined : value;
const triggerId = useId();
const listboxId = useId();
const descriptionId = useId();
@@ -403,8 +456,8 @@ export function XDSSelector<T extends XDSSelectorOptionType>({
const triggerRef = useRef<HTMLButtonElement>(null);
const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
+ const [optimisticValue, setOptimisticValue] = useOptimistic(normalizedValue);
+ const isBusy = isLoading || optimisticValue !== normalizedValue;
// Build aria-describedby
const ariaDescribedBy =
@@ -467,7 +520,7 @@ export function XDSSelector<T extends XDSSelectorOptionType>({
onItemMouseEnter,
} = useCombobox({
selectableItems,
- value,
+ value: normalizedValue,
isDisabled,
isOpen: popover.isOpen,
onOpen: popover.show,
@@ -487,11 +540,28 @@ export function XDSSelector<T extends XDSSelectorOptionType>({
listboxId,
});
+ // Handle clear button click
+ const handleClear = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation(); // Don't open dropdown
+ (onChange as ((value: string | null) => void) | undefined)?.(null);
+ if (onChangeAction) {
+ startTransition(async () => {
+ setOptimisticValue(undefined as unknown as string);
+ await (
+ onChangeAction as (value: string | null) => void | Promise<void>
+ )(null);
+ });
+ }
+ },
+ [onChange, onChangeAction, startTransition, setOptimisticValue],
+ );
+
// Render an individual item
const renderItem = useCallback(
(item: XDSSelectorOptionData, flatIndex: number) => {
const isHighlighted = flatIndex === highlightedIndex;
- const isSelected = item.value === value;
+ const isSelected = item.value === normalizedValue;
return (
<div
@@ -627,7 +697,19 @@ export function XDSSelector<T extends XDSSelectorOptionType>({
className,
style,
)}>
- <span>{selectedItem?.label ?? placeholder}</span>
+ <span {...stylex.props(styles.triggerLabel)}>
+ {selectedItem?.label ?? placeholder}
+ </span>
+ {hasClear && value != null && !isDisabled && (
+ <button
+ type="button"
+ tabIndex={-1}
+ onClick={handleClear}
+ aria-label={`Clear ${label}`}
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
{isBusy && <XDSSpinner size="sm" />}
<span
{...stylex.props(
diff --git a/packages/core/src/TextInput/XDSTextInput.test.tsx b/packages/core/src/TextInput/XDSTextInput.test.tsx
index 7b9f140f0e..ebf88e6a72 100644
--- a/packages/core/src/TextInput/XDSTextInput.test.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.test.tsx
@@ -323,4 +323,66 @@ describe('XDSTextInput', () => {
expect(screen.getByRole('textbox')).not.toHaveAttribute('name');
});
});
+
+ describe('hasClear', () => {
+ it('shows clear button when hasClear is true and value is non-empty', () => {
+ render(
+ <XDSTextInput
+ label="Name"
+ value="hello"
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Clear Name'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when value is empty', () => {
+ render(
+ <XDSTextInput label="Name" value="" onChange={() => {}} hasClear />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Name'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when hasClear is false', () => {
+ render(<XDSTextInput label="Name" value="hello" onChange={() => {}} />);
+ expect(
+ screen.queryByRole('button', {name: 'Clear Name'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when disabled', () => {
+ render(
+ <XDSTextInput
+ label="Name"
+ value="hello"
+ onChange={() => {}}
+ hasClear
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Name'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with empty string when clear is clicked', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <XDSTextInput
+ label="Name"
+ value="hello"
+ onChange={onChange}
+ hasClear
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Clear Name'}));
+ expect(onChange).toHaveBeenCalledWith('', null);
+ });
+ });
});
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index 93c7aff6e5..0415eb6e42 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -13,14 +13,23 @@
* - /apps/storybook/stories/TextInput.stories.tsx (storybook stories)
*/
-import {useId, useOptimistic, useTransition, type ChangeEvent} from 'react';
+import {
+ useId,
+ useOptimistic,
+ useTransition,
+ useCallback,
+ useRef,
+ type ChangeEvent,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {XDSIconName} from '../Icon';
import {
colorVars,
sizeVars,
+ radiusVars,
typographyVars,
typeScaleVars,
+ borderVars,
} from '../theme/tokens.stylex';
import {
XDSField,
@@ -38,6 +47,23 @@ const styles = stylex.create({
wrapper: {
zIndex: 1,
},
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 1,
+ },
input: {
display: 'block',
flex: 1,
@@ -165,6 +191,12 @@ export interface XDSTextInputProps extends Omit<
* Tooltip text to display in an info icon at the end of the label.
*/
labelTooltip?: string;
+ /**
+ * Whether to show a clear button when a value is set.
+ * When clicked, resets the value to an empty string and returns focus to the input.
+ * @default false
+ */
+ hasClear?: boolean;
/**
* Whether to automatically focus the input on mount.
* @default false
@@ -203,6 +235,7 @@ export function XDSTextInput({
value,
placeholder,
labelTooltip,
+ hasClear = false,
hasAutoFocus = false,
htmlName,
xstyle,
@@ -213,6 +246,7 @@ export function XDSTextInput({
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
@@ -252,6 +286,25 @@ export function XDSTextInput({
}
};
+ // Handle clear button click
+ const handleClear = useCallback(() => {
+ onChange?.('', null as unknown as ChangeEvent<HTMLInputElement>);
+ inputRef.current?.focus();
+ }, [onChange]);
+
+ // Combine refs
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLInputElement | null>).current = el;
+ }
+ },
+ [ref],
+ );
+
return (
<XDSField
label={label}
@@ -290,7 +343,7 @@ export function XDSTextInput({
)}>
{startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
<input
- ref={ref}
+ ref={setRefs}
id={id}
name={htmlName}
type={type}
@@ -306,6 +359,15 @@ export function XDSTextInput({
aria-busy={isBusy || undefined}
{...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
/>
+ {hasClear && value !== '' && !isDisabled && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label={`Clear ${label}`}
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
{isBusy && <XDSSpinner size="sm" />}
{status && (
<XDSIcon