An open source design system that's fully customizable and agent ready
TypeScript
XDSSwitch (#72)
Andrey Goder633f7f067fc6
diff --git a/apps/storybook/stories/Switch.stories.tsx b/apps/storybook/stories/Switch.stories.tsxnew file mode 100644index 0000000000..1f91966636--- /dev/null+++ b/apps/storybook/stories/Switch.stories.tsx@@ -0,0 +1,437 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSSwitch} from '@xds/core/Switch';+import {+ BellIcon,+ MoonIcon,+ ShieldCheckIcon,+ CloudArrowUpIcon,+} from '@heroicons/react/24/outline';++const meta: Meta<typeof XDSSwitch> = {+ title: 'Core/XDSSwitch',+ component: XDSSwitch,+ 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: 'boolean',+ description: 'Whether the switch is on or off',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Whether the switch is disabled',+ },+ isOptional: {+ control: 'boolean',+ description: 'Whether the field is optional',+ },+ isRequired: {+ control: 'boolean',+ description: 'Whether the switch is required',+ },+ labelPosition: {+ control: 'select',+ options: ['start', 'end'],+ description: 'Which side of the switch the label appears on',+ },+ labelSpacing: {+ control: 'select',+ options: ['default', 'spread'],+ description: 'Spacing behavior between label and switch',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSSwitch>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Enable notifications',+ },+};++export const On: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? true);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Notifications enabled',+ value: true,+ },+};++export const WithDescription: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Dark mode',+ description: 'Switch to a darker color scheme for reduced eye strain.',+ },+};++export const WithHiddenLabel: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Toggle row',+ isLabelHidden: true,+ },+};++export const Disabled: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Premium feature',+ description: 'Upgrade to enable this option',+ isDisabled: true,+ },+};++export const DisabledOn: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? true);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Feature enabled',+ value: true,+ isDisabled: true,+ },+};++export const Required: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Accept terms and conditions',+ isRequired: true,+ },+};++export const Optional: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Subscribe to newsletter',+ isOptional: true,+ },+};++export const WithLabelIcon: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Enable notifications',+ description: 'Receive alerts when important events occur',+ labelIcon: BellIcon,+ },+};++export const WithLabelTooltip: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Auto-save',+ labelTooltip: 'Automatically save your changes as you work',+ labelIcon: CloudArrowUpIcon,+ },+};++export const LabelPositionStart: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ );+ },+ args: {+ label: 'Enable dark mode',+ labelPosition: 'start',+ labelIcon: MoonIcon,+ },+};++export const LabelSpacingSpread: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? false);+ const {value: _, onChange: __, ...restArgs} = args;+ return (+ <div style={{width: 300, border: '1px solid #ccc', padding: 16}}>+ <XDSSwitch+ {...restArgs}+ value={value}+ onChange={checked => setValue(checked)}+ />+ </div>+ );+ },+ args: {+ label: 'Enable notifications',+ labelPosition: 'start',+ labelSpacing: 'spread',+ },+};++export const AllVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState(false);+ const [value2, setValue2] = useState(true);+ const [value3, setValue3] = useState(false);+ const [value4, setValue4] = useState(true);+ const [value5, setValue5] = useState(false);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '400px',+ }}>+ <XDSSwitch label="Off state" value={value1} onChange={setValue1} />+ <XDSSwitch label="On state" value={value2} onChange={setValue2} />+ <XDSSwitch+ label="Disabled off"+ value={value3}+ onChange={setValue3}+ isDisabled+ />+ <XDSSwitch+ label="Disabled on"+ value={value4}+ onChange={setValue4}+ isDisabled+ />+ <XDSSwitch+ label="With description"+ description="Additional context for this setting"+ value={value5}+ onChange={setValue5}+ />+ </div>+ );+ },+};++export const LabelIconVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState(false);+ const [value2, setValue2] = useState(true);+ const [value3, setValue3] = useState(false);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '400px',+ }}>+ <XDSSwitch+ label="Notifications"+ description="Receive push notifications"+ value={value1}+ onChange={setValue1}+ labelIcon={BellIcon}+ />+ <XDSSwitch+ label="Dark mode"+ description="Use dark color scheme"+ value={value2}+ onChange={setValue2}+ labelIcon={MoonIcon}+ />+ <XDSSwitch+ label="Two-factor authentication"+ description="Add an extra layer of security"+ value={value3}+ onChange={setValue3}+ labelIcon={ShieldCheckIcon}+ isDisabled+ />+ </div>+ );+ },+};++export const LabelPositionComparison: Story = {+ render: () => {+ const [value1, setValue1] = useState(false);+ const [value2, setValue2] = useState(false);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '400px',+ }}>+ <XDSSwitch+ label="Label at end (default)"+ value={value1}+ onChange={setValue1}+ labelPosition="end"+ />+ <XDSSwitch+ label="Label at start"+ value={value2}+ onChange={setValue2}+ labelPosition="start"+ />+ </div>+ );+ },+};++export const SpreadSpacingExample: Story = {+ render: () => {+ const [value1, setValue1] = useState(false);+ const [value2, setValue2] = useState(true);+ const [value3, setValue3] = useState(false);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ width: '350px',+ border: '1px solid #e0e0e0',+ borderRadius: '8px',+ padding: '16px',+ }}>+ <XDSSwitch+ label="Enable notifications"+ value={value1}+ onChange={setValue1}+ labelPosition="start"+ labelSpacing="spread"+ labelIcon={BellIcon}+ />+ <XDSSwitch+ label="Dark mode"+ value={value2}+ onChange={setValue2}+ labelPosition="start"+ labelSpacing="spread"+ labelIcon={MoonIcon}+ />+ <XDSSwitch+ label="Auto-save"+ value={value3}+ onChange={setValue3}+ labelPosition="start"+ labelSpacing="spread"+ labelIcon={CloudArrowUpIcon}+ labelTooltip="Save changes automatically as you work"+ />+ </div>+ );+ },+};diff --git a/packages/core/src/Switch/README.md b/packages/core/src/Switch/README.mdnew file mode 100644index 0000000000..850a3930bd--- /dev/null+++ b/packages/core/src/Switch/README.md@@ -0,0 +1,90 @@+# /packages/core/src/Switch++A toggle switch component for boolean values with integrated label support.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Boolean Toggle**: Clean on/off switch for boolean values (40x24px with 20px thumb)+- **Label Integration**: Uses XDSFieldLabel for accessible labels with optional tooltip and icon+- **Label Position**: Label can appear before or after the switch (`start` or `end`)+- **Label Spacing**: Support for spread layout (label and switch on opposite ends)+- **Description**: Optional description text below the label+- **Optional/Required**: Visual indicators for field status+- **Accessibility**: Uses native checkbox with `role="switch"`, proper ARIA attributes++## Usage++```tsx+import { XDSSwitch } from '@xds/core/Switch';++// Basic usage+<XDSSwitch+ label="Enable notifications"+ value={enabled}+ onChange={setEnabled}+/>++// With description+<XDSSwitch+ label="Dark mode"+ description="Switch to a darker color scheme"+ value={darkMode}+ onChange={setDarkMode}+/>++// With label icon and tooltip+<XDSSwitch+ label="Auto-save"+ labelIcon={CloudArrowUpIcon}+ labelTooltip="Automatically save changes"+ value={autoSave}+ onChange={setAutoSave}+/>++// Label at start with spread spacing (settings panel style)+<XDSSwitch+ label="Enable notifications"+ value={enabled}+ onChange={setEnabled}+ labelPosition="start"+ labelSpacing="spread"+/>+```++## Props++| Prop | Type | Default | Description |+| --------------- | -------------------------------------------- | ----------- | --------------------------------------------- |+| `label` | `string` | — | Label text for the switch (required) |+| `value` | `boolean` | — | Whether the switch is on or off |+| `onChange` | `(checked: boolean, e: ChangeEvent) => void` | — | Callback fired when state changes |+| `isLabelHidden` | `boolean` | `false` | Visually hide the label (still accessible) |+| `description` | `string` | — | Description text below the label |+| `isDisabled` | `boolean` | `false` | Whether the switch is disabled |+| `isOptional` | `boolean` | `false` | Whether the field is optional |+| `isRequired` | `boolean` | `false` | Whether the switch is required |+| `onFocus` | `(e: FocusEvent) => void` | — | Callback on focus |+| `onBlur` | `(e: FocusEvent) => void` | — | Callback on blur |+| `labelIcon` | `XDSIconType` | — | Icon before the label |+| `labelTooltip` | `string` | — | Tooltip on info icon after label |+| `labelPosition` | `'start' \| 'end'` | `'end'` | Which side of the switch the label appears on |+| `labelSpacing` | `'default' \| 'spread'` | `'default'` | Spacing behavior between label and switch |++## Files++| File | Role | Purpose |+| -------------------- | ----- | --------------------------- |+| `index.ts` | Entry | Exports component and types |+| `XDSSwitch.tsx` | Core | Component implementation |+| `XDSSwitch.test.tsx` | Test | Unit tests |++## Implementation Notes++- Fixed dimensions: 40px width, 24px height, 16px thumb (off) / 20px thumb (on)+- Uses CSS custom properties for hover state management+- Native checkbox input with `role="switch"` for proper semantics+- Track and thumb animation with CSS transitions+- Follows the same patterns as XDSCheckboxInput for consistency+- `labelPosition="start"` with `labelSpacing="spread"` creates a settings panel style layoutdiff --git a/packages/core/src/Switch/XDSSwitch.test.tsx b/packages/core/src/Switch/XDSSwitch.test.tsxnew file mode 100644index 0000000000..6af2c3e55f--- /dev/null+++ b/packages/core/src/Switch/XDSSwitch.test.tsx@@ -0,0 +1,235 @@+/**+ * @file XDSSwitch.test.tsx+ * @input Uses vitest, @testing-library/react, XDSSwitch component+ * @output Unit tests for XDSSwitch component behavior+ * @position Testing; validates XDSSwitch.tsx implementation+ *+ * SYNC: When XDSSwitch.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 {XDSSwitch} from './XDSSwitch';++describe('XDSSwitch', () => {+ it('renders with label', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ />+ );+ expect(screen.getByLabelText('Enable notifications')).toBeInTheDocument();+ });++ it('renders as off by default', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ />+ );+ expect(screen.getByRole('switch')).not.toBeChecked();+ });++ it('renders as on when value prop is true', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={true}+ onChange={() => {}}+ />+ );+ expect(screen.getByRole('switch')).toBeChecked();+ });++ it('calls onChange with new checked state when clicked', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={handleChange}+ />+ );++ const switchEl = screen.getByRole('switch');+ await user.click(switchEl);+ expect(handleChange).toHaveBeenCalledTimes(1);+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));+ });++ it('calls onChange with false when turning off', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSSwitch+ label="Enable notifications"+ value={true}+ onChange={handleChange}+ />+ );++ const switchEl = screen.getByRole('switch');+ await user.click(switchEl);+ expect(handleChange).toHaveBeenCalledWith(false, expect.any(Object));+ });++ it('works when clicking on the label', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={handleChange}+ />+ );++ const label = screen.getByText('Enable notifications');+ await user.click(label);+ expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));+ });++ it('renders description when provided', () => {+ render(+ <XDSSwitch+ label="Dark mode"+ description="Switch to a darker color scheme"+ value={false}+ onChange={() => {}}+ />+ );+ expect(+ screen.getByText('Switch to a darker color scheme')+ ).toBeInTheDocument();+ });++ it('associates description with switch via aria-describedby', () => {+ render(+ <XDSSwitch+ label="Dark mode"+ description="Switch to a darker color scheme"+ value={false}+ onChange={() => {}}+ />+ );+ const switchEl = screen.getByRole('switch');+ const description = screen.getByText('Switch to a darker color scheme');+ expect(switchEl).toHaveAttribute('aria-describedby', description.id);+ });++ it('is disabled when isDisabled prop is true', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ isDisabled+ />+ );+ expect(screen.getByRole('switch')).toBeDisabled();+ });++ it('does not call onChange when isDisabled', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={handleChange}+ isDisabled+ />+ );++ const switchEl = screen.getByRole('switch');+ await user.click(switchEl);+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('forwards ref correctly', () => {+ const ref = vi.fn();+ render(+ <XDSSwitch+ ref={ref}+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ />+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));+ });++ it('visually hides label when isLabelHidden is true', () => {+ render(+ <XDSSwitch+ label="Toggle row"+ isLabelHidden+ value={false}+ onChange={() => {}}+ />+ );+ const label = screen.getByText('Toggle row');+ expect(label).toBeInTheDocument();+ // Label should still be accessible+ expect(screen.getByLabelText('Toggle row')).toBeInTheDocument();+ });++ it('shows label visually by default', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ />+ );+ const label = screen.getByText('Enable notifications');+ expect(label).toBeVisible();+ });++ it('renders with labelPosition start (label before switch)', () => {+ const {container} = render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ labelPosition="start"+ />+ );+ const containerDiv = container.firstChild as HTMLElement;+ const children = Array.from(containerDiv.children);+ // First child should be label wrapper, second should be switch wrapper+ expect(children.length).toBe(2);+ });++ it('renders with labelPosition end (switch before label)', () => {+ const {container} = render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ labelPosition="end"+ />+ );+ const containerDiv = container.firstChild as HTMLElement;+ const children = Array.from(containerDiv.children);+ // First child should be switch wrapper, second should be label wrapper+ expect(children.length).toBe(2);+ });++ it('has role="switch" for accessibility', () => {+ render(+ <XDSSwitch+ label="Enable notifications"+ value={false}+ onChange={() => {}}+ />+ );+ expect(screen.getByRole('switch')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Switch/XDSSwitch.tsx b/packages/core/src/Switch/XDSSwitch.tsxnew file mode 100644index 0000000000..a35eb9500d--- /dev/null+++ b/packages/core/src/Switch/XDSSwitch.tsx@@ -0,0 +1,342 @@+/**+ * @file XDSSwitch.tsx+ * @input Uses React forwardRef, useId, ChangeEvent, XDSFieldLabel, XDSIconType+ * @output Exports XDSSwitch component, XDSSwitchProps, XDSSwitchLabelPosition, XDSSwitchLabelSpacing+ * @position Core implementation; consumed by index.ts, tested by XDSSwitch.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Switch/README.md (props table, features, implementation notes)+ * - /packages/core/src/Switch/XDSSwitch.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Switch/index.ts (exports if types change)+ * - /apps/storybook/stories/Switch.stories.tsx (storybook stories)+ */++import {forwardRef, useId, type ChangeEvent, type FocusEvent} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ transitionVars,+ typographyVars,+ elevationVars,+} from '../theme/tokens.stylex';+import {XDSFieldLabel} from '../Field/XDSFieldLabel';+import type {XDSIconType} from '../Icon';++// Fixed dimensions: 40px width, 24px height, 16px thumb (off), 20px thumb (on)+const SWITCH_WIDTH = 40;+const SWITCH_HEIGHT = 24;+const THUMB_SIZE_OFF = 16;+const THUMB_SIZE_ON = 20;+const TRACK_PADDING = 4;+const BORDER_WIDTH = 1;+// Travel distance for on state: accounts for larger thumb with tighter right padding+const THUMB_TRAVEL_ON =+ SWITCH_WIDTH - TRACK_PADDING * 2 - BORDER_WIDTH * 2 - THUMB_SIZE_ON + 2;++const styles = stylex.create({+ container: {+ display: 'flex',+ alignItems: 'flex-start',+ gap: spacingVars['--spacing-2'],+ },+ containerSpread: {+ justifyContent: 'space-between',+ width: '100%',+ },+ // Default CSS variables for off state+ containerOff: {+ '--xds-switch-track-bg': colorVars['--color-deemphasized'],+ '--xds-switch-track-border': colorVars['--color-divider-emphasized'],+ },+ // Default CSS variables for on state+ containerOn: {+ '--xds-switch-track-bg': colorVars['--color-accent'],+ '--xds-switch-track-border': colorVars['--color-accent'],+ },+ // Hover overrides for off state (only applied when not disabled)+ containerHoverOff: {+ ':hover': {+ '--xds-switch-track-bg': `color-mix(in srgb, ${colorVars['--color-deemphasized']}, ${colorVars['--color-hover-tint']} 5%)`,+ '--xds-switch-track-border': `color-mix(in srgb, ${colorVars['--color-divider-emphasized']}, ${colorVars['--color-hover-tint']} 20%)`,+ },+ },+ // Hover overrides for on state (only applied when not disabled)+ containerHoverOn: {+ ':hover': {+ '--xds-switch-track-bg': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-hover-tint']} 15%)`,+ '--xds-switch-track-border': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-hover-tint']} 15%)`,+ },+ },+ switchWrapper: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ flexShrink: 0,+ width: SWITCH_WIDTH,+ height: SWITCH_HEIGHT,+ },+ input: {+ position: 'absolute',+ margin: 0,+ padding: 0,+ opacity: 0,+ cursor: 'pointer',+ zIndex: 1,+ width: SWITCH_WIDTH,+ height: SWITCH_HEIGHT,+ },+ inputDisabled: {+ cursor: 'not-allowed',+ },+ track: {+ display: 'flex',+ alignItems: 'center',+ width: SWITCH_WIDTH,+ height: SWITCH_HEIGHT,+ padding: TRACK_PADDING,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'var(--xds-switch-track-border)',+ borderRadius: radiusVars['--radius-rounded'],+ backgroundColor: 'var(--xds-switch-track-bg)',+ transitionProperty: 'background-color, border-color',+ transitionDuration: transitionVars['--transition-fast'],+ boxSizing: 'border-box',+ },+ trackFocused: {+ outline: `2px solid ${colorVars['--color-focus-outline']}`,+ outlineOffset: 2,+ },+ trackDisabled: {+ opacity: 0.5,+ borderColor: colorVars['--color-divider'],+ },+ trackDisabledOff: {+ backgroundColor: colorVars['--color-deemphasized'],+ },+ thumb: {+ borderRadius: radiusVars['--radius-rounded'],+ backgroundColor: colorVars['--color-surface'],+ boxShadow: elevationVars['--elevation-thumb'],+ transitionProperty: 'transform, width, height',+ transitionDuration: transitionVars['--transition-fast'],+ },+ thumbOff: {+ width: THUMB_SIZE_OFF,+ height: THUMB_SIZE_OFF,+ transform: 'translateX(0)',+ },+ thumbOn: {+ width: THUMB_SIZE_ON,+ height: THUMB_SIZE_ON,+ transform: `translateX(${THUMB_TRAVEL_ON}px)`,+ },+ 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 type XDSSwitchLabelPosition = 'start' | 'end';+export type XDSSwitchLabelSpacing = 'default' | 'spread';++export interface XDSSwitchProps {+ /**+ * Label text for the switch (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 switch state changes.+ */+ onChange: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;+ /**+ * Whether the switch is on or off.+ */+ value: boolean;+ /**+ * Whether the switch is disabled.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Whether the field is optional. Mutually exclusive with isRequired.+ * @default false+ */+ isOptional?: boolean;+ /**+ * Whether the switch is required. Mutually exclusive with isOptional.+ * @default false+ */+ isRequired?: boolean;+ /**+ * Callback fired when the switch receives focus.+ */+ onFocus?: (e: FocusEvent<HTMLInputElement>) => void;+ /**+ * Callback fired when the switch loses focus.+ */+ onBlur?: (e: FocusEvent<HTMLInputElement>) => void;+ /**+ * Icon to display before the label text.+ */+ labelIcon?: XDSIconType;+ /**+ * Tooltip text to display in an info icon at the end of the label.+ */+ labelTooltip?: string;+ /**+ * Which side of the switch the label appears on.+ * - 'start': Label appears before the switch+ * - 'end': Label appears after the switch+ * @default 'end'+ */+ labelPosition?: XDSSwitchLabelPosition;+ /**+ * Spacing behavior between label and switch.+ * - 'default': Label and switch are positioned next to each other+ * - 'spread': Label and switch are pushed to opposite ends+ * @default 'default'+ */+ labelSpacing?: XDSSwitchLabelSpacing;+}++/**+ * A toggle switch component for boolean values.+ *+ * @example+ * ```tsx+ * <XDSSwitch+ * label="Enable notifications"+ * value={enabled}+ * onChange={setEnabled}+ * />+ * <XDSSwitch+ * label="Dark mode"+ * description="Switch to a darker color scheme"+ * value={darkMode}+ * onChange={setDarkMode}+ * />+ * ```+ */+export const XDSSwitch = forwardRef<HTMLInputElement, XDSSwitchProps>(+ (+ {+ label,+ isLabelHidden = false,+ description,+ onChange,+ value,+ isDisabled = false,+ isOptional = false,+ isRequired = false,+ onFocus,+ onBlur,+ labelIcon,+ labelTooltip,+ labelPosition = 'end',+ labelSpacing = 'default',+ },+ ref+ ) => {+ const id = useId();+ const descriptionID = useId();++ const isOn = value === true;++ const switchElement = (+ <div {...stylex.props(styles.switchWrapper)}>+ <input+ ref={ref}+ id={id}+ type="checkbox"+ role="switch"+ checked={isOn}+ disabled={isDisabled}+ required={isRequired}+ onChange={e => onChange(e.target.checked, e)}+ onFocus={onFocus}+ onBlur={onBlur}+ aria-describedby={description ? descriptionID : undefined}+ {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}+ />+ <div+ aria-hidden="true"+ {...stylex.props(+ styles.track,+ isDisabled && styles.trackDisabled,+ isDisabled && !isOn && styles.trackDisabledOff+ )}>+ <div+ {...stylex.props(+ styles.thumb,+ isOn ? styles.thumbOn : styles.thumbOff+ )}+ />+ </div>+ </div>+ );++ const labelElement = (+ <div {...stylex.props(styles.labelWrapper)}>+ <XDSFieldLabel+ label={label}+ inputID={id}+ isLabelHidden={isLabelHidden}+ isDisabled={isDisabled}+ isOptional={isOptional}+ isRequired={isRequired}+ startIcon={labelIcon}+ tooltip={labelTooltip}+ />+ {description && (+ <span id={descriptionID} {...stylex.props(styles.description)}>+ {description}+ </span>+ )}+ </div>+ );++ return (+ <div+ {...stylex.props(+ styles.container,+ labelSpacing === 'spread' && styles.containerSpread,+ isOn ? styles.containerOn : styles.containerOff,+ !isDisabled &&+ (isOn ? styles.containerHoverOn : styles.containerHoverOff)+ )}>+ {labelPosition === 'start' ? (+ <>+ {labelElement}+ {switchElement}+ </>+ ) : (+ <>+ {switchElement}+ {labelElement}+ </>+ )}+ </div>+ );+ }+);++XDSSwitch.displayName = 'XDSSwitch';diff --git a/packages/core/src/Switch/index.ts b/packages/core/src/Switch/index.tsnew file mode 100644index 0000000000..86c2008dc8--- /dev/null+++ b/packages/core/src/Switch/index.ts@@ -0,0 +1,6 @@+export {XDSSwitch} from './XDSSwitch';+export type {+ XDSSwitchProps,+ XDSSwitchLabelPosition,+ XDSSwitchLabelSpacing,+} from './XDSSwitch';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 633a141c54..b4c487049c 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -16,6 +16,7 @@ export * from './Calendar';export * from './Center';export * from './CheckboxInput';export * from './Divider';+export * from './Switch';export * from './DateInput';export * from './Field';export * from './Grid';