An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add XDSToggleButton and XDSToggleButtonGroup (#1162)
Ernestf0eec4ceec3f
diff --git a/apps/storybook/stories/ToggleButton.stories.tsx b/apps/storybook/stories/ToggleButton.stories.tsxnew file mode 100644index 0000000000..6cd399542b--- /dev/null+++ b/apps/storybook/stories/ToggleButton.stories.tsx@@ -0,0 +1,221 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {XDSToggleButton, XDSToggleButtonGroup} from '@xds/core/ToggleButton';+import {+ BoldIcon,+ ItalicIcon,+ UnderlineIcon,+ ListBulletIcon,+ Squares2X2Icon,+ StarIcon,+ BookmarkIcon,+ BellIcon,+ BellSlashIcon,+} from '@heroicons/react/24/outline';+import {+ StarIcon as StarIconSolid,+ BookmarkIcon as BookmarkIconSolid,+} from '@heroicons/react/24/solid';++const iconSize = {width: 16, height: 16} as const;++const meta: Meta<typeof XDSToggleButton> = {+ title: 'Core/XDSToggleButton',+ component: XDSToggleButton,+ tags: ['autodocs'],+ argTypes: {+ label: {control: 'text'},+ isPressed: {control: 'boolean'},+ size: {control: 'select', options: ['sm', 'md', 'lg']},+ isDisabled: {control: 'boolean'},+ isLoading: {control: 'boolean'},+ },+};++export default meta;+type Story = StoryObj<typeof XDSToggleButton>;++// =============================================================================+// Standalone+// =============================================================================++/** Interactive standalone toggle — click to toggle. */+export const Standalone: Story = {+ render: function Render() {+ const [isPressed, setIsPressed] = useState(false);+ return (+ <XDSToggleButton+ label="Bold"+ icon={<BoldIcon style={iconSize} />}+ isPressed={isPressed}+ onPressedChange={setIsPressed}+ />+ );+ },+};++/** Icon-only toggles with icon swap. */+export const IconSwap: Story = {+ render: function Render() {+ const [isFavorited, setIsFavorited] = useState(false);+ const [isBookmarked, setIsBookmarked] = useState(true);+ return (+ <div style={{display: 'flex', gap: 8}}>+ <XDSToggleButton+ label="Favorite"+ icon={<StarIcon style={iconSize} />}+ pressedIcon={<StarIconSolid style={iconSize} />}+ isPressed={isFavorited}+ onPressedChange={setIsFavorited}+ />+ <XDSToggleButton+ label="Bookmark"+ icon={<BookmarkIcon style={iconSize} />}+ pressedIcon={<BookmarkIconSolid style={iconSize} />}+ isPressed={isBookmarked}+ onPressedChange={setIsBookmarked}+ />+ </div>+ );+ },+};++/** Toggle with visible label text — shows font weight shift on press. */+export const WithLabel: Story = {+ render: function Render() {+ const [isActive, setIsActive] = useState(false);+ return (+ <XDSToggleButton+ label="Active"+ isPressed={isActive}+ onPressedChange={setIsActive}>+ Active+ </XDSToggleButton>+ );+ },+};++/** Disabled state. */+export const Disabled: Story = {+ args: {+ label: 'Disabled toggle',+ isPressed: false,+ isDisabled: true,+ icon: <BoldIcon style={iconSize} />,+ },+};++/** Loading state. */+export const Loading: Story = {+ args: {+ label: 'Loading toggle',+ isPressed: true,+ isLoading: true,+ icon: <StarIcon style={iconSize} />,+ },+};++/** All sizes side by side. */+export const Sizes: Story = {+ render: function Render() {+ const [pressed, setPressed] = useState<Record<string, boolean>>({});+ const toggle = (key: string) =>+ setPressed(prev => ({...prev, [key]: !prev[key]}));+ return (+ <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>+ <XDSToggleButton+ label="Small"+ size="sm"+ icon={<BoldIcon style={iconSize} />}+ isPressed={!!pressed.sm}+ onPressedChange={() => toggle('sm')}+ />+ <XDSToggleButton+ label="Medium"+ size="md"+ icon={<BoldIcon style={iconSize} />}+ isPressed={!!pressed.md}+ onPressedChange={() => toggle('md')}+ />+ <XDSToggleButton+ label="Large"+ size="lg"+ icon={<BoldIcon style={{width: 20, height: 20}} />}+ isPressed={!!pressed.lg}+ onPressedChange={() => toggle('lg')}+ />+ </div>+ );+ },+};++// =============================================================================+// Groups+// =============================================================================++/** Single-select group — view mode switcher. Click active to deselect. */+export const GroupSingle: Story = {+ render: function Render() {+ const [view, setView] = useState<string | null>('list');+ return (+ <XDSToggleButtonGroup value={view} onChange={setView} label="View mode">+ <XDSToggleButton+ value="list"+ label="List view"+ icon={<ListBulletIcon style={iconSize} />}+ />+ <XDSToggleButton+ value="grid"+ label="Grid view"+ icon={<Squares2X2Icon style={iconSize} />}+ />+ </XDSToggleButtonGroup>+ );+ },+};++/** Multi-select group — text formatting toolbar. */+export const GroupMultiple: Story = {+ render: function Render() {+ const [formats, setFormats] = useState<string[]>([]);+ return (+ <XDSToggleButtonGroup+ type="multiple"+ value={formats}+ onChange={setFormats}+ label="Text formatting">+ <XDSToggleButton+ value="bold"+ label="Bold"+ icon={<BoldIcon style={iconSize} />}+ />+ <XDSToggleButton+ value="italic"+ label="Italic"+ icon={<ItalicIcon style={iconSize} />}+ />+ <XDSToggleButton+ value="underline"+ label="Underline"+ icon={<UnderlineIcon style={iconSize} />}+ />+ </XDSToggleButtonGroup>+ );+ },+};++/** Notification toggle — icon swap between bell and bell-slash. */+export const NotificationToggle: Story = {+ render: function Render() {+ const [isMuted, setIsMuted] = useState(false);+ return (+ <XDSToggleButton+ label={isMuted ? 'Unmute notifications' : 'Mute notifications'}+ icon={<BellIcon style={iconSize} />}+ pressedIcon={<BellSlashIcon style={iconSize} />}+ isPressed={isMuted}+ onPressedChange={setIsMuted}+ />+ );+ },+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 87260ad939..b0bc757422 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -400,6 +400,12 @@"import": "./dist/Timestamp/index.mjs","require": "./dist/Timestamp/index.js"},+ "./ToggleButton": {+ "source": "./src/ToggleButton/index.ts",+ "types": "./dist/ToggleButton/index.d.ts",+ "import": "./dist/ToggleButton/index.mjs",+ "require": "./dist/ToggleButton/index.js"+ },"./Token": {"source": "./src/Token/index.ts","types": "./dist/Token/index.d.ts",diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsxindex 418a05ac15..8856739441 100644--- a/packages/core/src/Button/XDSButton.tsx+++ b/packages/core/src/Button/XDSButton.tsx@@ -145,6 +145,7 @@ const sizeStyles = stylex.create({/*** Icon size per button size.* Matches XDSIcon sizing: sm/md=16px, lg=20px.+ * fontSize is set so emoji and text-based icons scale correctly.*/const iconSizeStyles = stylex.create({sm: {width: 16, height: 16, fontSize: 16},@@ -363,9 +364,6 @@ export interface XDSButtonProps extends XDSBaseProps<HTMLButtonElement> {rel?: string;}-/**- * Loading state styles- */const loadingStyles = stylex.create({loading: {position: 'relative',diff --git a/packages/core/src/ToggleButton/XDSToggleButton.test.tsx b/packages/core/src/ToggleButton/XDSToggleButton.test.tsxnew file mode 100644index 0000000000..b2c4dd3b06--- /dev/null+++ b/packages/core/src/ToggleButton/XDSToggleButton.test.tsx@@ -0,0 +1,324 @@+/**+ * @file XDSToggleButton.test.tsx+ * @input Uses vitest, @testing-library/react, XDSToggleButton, XDSToggleButtonGroup+ * @output Unit tests for XDSToggleButton and XDSToggleButtonGroup+ *+ * SYNC: When XDSToggleButton.tsx or XDSToggleButtonGroup.tsx changes, update tests+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {useState} from 'react';+import {XDSToggleButton} from './XDSToggleButton';+import {XDSToggleButtonGroup} from './XDSToggleButtonGroup';++// =============================================================================+// XDSToggleButton — Standalone+// =============================================================================++describe('XDSToggleButton', () => {+ it('renders with label as visible text', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ />,+ );+ expect(screen.getByRole('button', {name: 'Bold'})).toBeInTheDocument();+ });++ it('renders children instead of label when provided', () => {+ render(+ <XDSToggleButton+ label="Toggle bold"+ isPressed={false}+ onPressedChange={() => {}}>+ Custom content+ </XDSToggleButton>,+ );+ expect(screen.getByRole('button')).toHaveTextContent('Custom content');+ });++ it('renders icon-only button with aria-label', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ icon={<span data-testid="icon">B</span>}+ />,+ );+ const button = screen.getByRole('button', {name: 'Bold'});+ expect(button).toHaveAttribute('aria-label', 'Bold');+ expect(screen.getByTestId('icon')).toBeInTheDocument();+ });++ it('sets aria-pressed=false when not pressed', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ />,+ );+ expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'false');+ });++ it('sets aria-pressed=true when pressed', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={true}+ onPressedChange={() => {}}+ />,+ );+ expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'true');+ });++ it('calls onPressedChange with true when clicking unpressed button', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={handleChange}+ />,+ );++ await user.click(screen.getByRole('button'));+ expect(handleChange).toHaveBeenCalledWith(true);+ });++ it('calls onPressedChange with false when clicking pressed button', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={true}+ onPressedChange={handleChange}+ />,+ );++ await user.click(screen.getByRole('button'));+ expect(handleChange).toHaveBeenCalledWith(false);+ });++ it('renders pressedIcon when pressed', () => {+ render(+ <XDSToggleButton+ label="Favorite"+ isPressed={true}+ onPressedChange={() => {}}+ icon={<span data-testid="outline-icon">♡</span>}+ pressedIcon={<span data-testid="filled-icon">♥</span>}+ />,+ );+ expect(screen.getByTestId('filled-icon')).toBeInTheDocument();+ expect(screen.queryByTestId('outline-icon')).not.toBeInTheDocument();+ });++ it('renders icon when not pressed even if pressedIcon provided', () => {+ render(+ <XDSToggleButton+ label="Favorite"+ isPressed={false}+ onPressedChange={() => {}}+ icon={<span data-testid="outline-icon">♡</span>}+ pressedIcon={<span data-testid="filled-icon">♥</span>}+ />,+ );+ expect(screen.getByTestId('outline-icon')).toBeInTheDocument();+ expect(screen.queryByTestId('filled-icon')).not.toBeInTheDocument();+ });++ it('does not fire events when disabled', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={handleChange}+ isDisabled+ />,+ );++ await user.click(screen.getByRole('button'));+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('renders width reservation element for label text', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ />,+ );+ const button = screen.getByRole('button');+ const hiddenSpan = button.querySelector('[aria-hidden="true"]');+ expect(hiddenSpan).toBeInTheDocument();+ expect(hiddenSpan).toHaveTextContent('Bold');+ });++ it('does not render width reservation for icon-only buttons', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ icon={<span>B</span>}+ />,+ );+ const button = screen.getByRole('button');+ const hiddenSpan = button.querySelector('[aria-hidden="true"]');+ expect(hiddenSpan).not.toBeInTheDocument();+ });++ it('passes data-testid through', () => {+ render(+ <XDSToggleButton+ label="Bold"+ isPressed={false}+ onPressedChange={() => {}}+ data-testid="bold-toggle"+ />,+ );+ expect(screen.getByTestId('bold-toggle')).toBeInTheDocument();+ });+});++// =============================================================================+// XDSToggleButtonGroup — Single mode+// =============================================================================++describe('XDSToggleButtonGroup (single)', () => {+ function SingleGroup() {+ const [value, setValue] = useState<string | null>('list');+ return (+ <XDSToggleButtonGroup value={value} onChange={setValue} label="View mode">+ <XDSToggleButton value="list" label="List" icon={<span>≡</span>} />+ <XDSToggleButton value="grid" label="Grid" icon={<span>⊞</span>} />+ <XDSToggleButton value="card" label="Card" icon={<span>□</span>} />+ </XDSToggleButtonGroup>+ );+ }++ it('renders a group with role="group" and aria-label', () => {+ render(<SingleGroup />);+ expect(screen.getByRole('group', {name: 'View mode'})).toBeInTheDocument();+ });++ it('marks the selected button as pressed', () => {+ render(<SingleGroup />);+ expect(screen.getByRole('button', {name: 'List'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ expect(screen.getByRole('button', {name: 'Grid'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });++ it('selects a different button on click', async () => {+ const user = userEvent.setup();+ render(<SingleGroup />);++ await user.click(screen.getByRole('button', {name: 'Grid'}));++ expect(screen.getByRole('button', {name: 'Grid'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ expect(screen.getByRole('button', {name: 'List'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });++ it('allows deselection by clicking the active button', async () => {+ const user = userEvent.setup();+ render(<SingleGroup />);++ await user.click(screen.getByRole('button', {name: 'List'}));++ expect(screen.getByRole('button', {name: 'List'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ expect(screen.getByRole('button', {name: 'Grid'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });+});++// =============================================================================+// XDSToggleButtonGroup — Multiple mode+// =============================================================================++describe('XDSToggleButtonGroup (multiple)', () => {+ function MultipleGroup() {+ const [value, setValue] = useState<string[]>(['bold']);+ return (+ <XDSToggleButtonGroup+ type="multiple"+ value={value}+ onChange={setValue}+ label="Formatting">+ <XDSToggleButton value="bold" label="Bold" icon={<span>B</span>} />+ <XDSToggleButton value="italic" label="Italic" icon={<span>I</span>} />+ <XDSToggleButton+ value="underline"+ label="Underline"+ icon={<span>U</span>}+ />+ </XDSToggleButtonGroup>+ );+ }++ it('marks selected buttons as pressed', () => {+ render(<MultipleGroup />);+ expect(screen.getByRole('button', {name: 'Bold'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ expect(screen.getByRole('button', {name: 'Italic'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });++ it('adds a value when clicking an unpressed button', async () => {+ const user = userEvent.setup();+ render(<MultipleGroup />);++ await user.click(screen.getByRole('button', {name: 'Italic'}));++ expect(screen.getByRole('button', {name: 'Bold'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ expect(screen.getByRole('button', {name: 'Italic'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ });++ it('removes a value when clicking a pressed button', async () => {+ const user = userEvent.setup();+ render(<MultipleGroup />);++ await user.click(screen.getByRole('button', {name: 'Bold'}));++ expect(screen.getByRole('button', {name: 'Bold'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });+});diff --git a/packages/core/src/ToggleButton/XDSToggleButton.tsx b/packages/core/src/ToggleButton/XDSToggleButton.tsxnew file mode 100644index 0000000000..aed5ed9ca6--- /dev/null+++ b/packages/core/src/ToggleButton/XDSToggleButton.tsx@@ -0,0 +1,290 @@+'use client';++/**+ * @file XDSToggleButton.tsx+ * @input Uses XDSButton, React, StyleX, theme tokens+ * @output Exports XDSToggleButton component and types+ * @position Thin wrapper over XDSButton; adds controlled toggle pattern+ *+ * XDSToggleButton wraps XDSButton with `isPressed` and adds:+ * - `onPressedChange` controlled toggle callback+ * - `pressedIcon` for outline-to-filled icon swap+ * - Font weight shift on press with width reservation to prevent layout shift+ * - Group integration via ToggleButtonGroupContext+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/ToggleButton/index.ts (exports if types change)+ * - /apps/storybook/stories/ToggleButton.stories.tsx+ */++import {useCallback, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {fontWeightVars} from '../theme/tokens.stylex';+import {XDSButton, type XDSButtonSize} from '../Button';+import {useXDSToggleButtonGroup} from './XDSToggleButtonGroup';++// =============================================================================+// Styles+// =============================================================================++/**+ * Font weight shift on press with width reservation trick.+ * A hidden span renders the same text at semibold weight to reserve+ * the wider width, preventing layout shift when toggling.+ */+const labelStyles = stylex.create({+ wrapper: {+ display: 'inline-flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ },+ pressed: {+ fontWeight: fontWeightVars['--font-weight-semibold'],+ },+ widthReservation: {+ display: 'block',+ fontWeight: fontWeightVars['--font-weight-semibold'],+ height: 0,+ overflow: 'hidden',+ visibility: 'hidden',+ pointerEvents: 'none',+ },+});++// =============================================================================+// Props+// =============================================================================++export interface XDSToggleButtonProps {+ /**+ * Accessible label for the button (required).+ * Used as visible text, or as aria-label for icon-only buttons.+ */+ label: string;++ /**+ * Whether the button is currently pressed/active.+ * When used inside XDSToggleButtonGroup, this is controlled by the group+ * and this prop is ignored.+ */+ isPressed?: boolean;++ /**+ * Called when the pressed state should change.+ * When used inside XDSToggleButtonGroup, this is handled by the group+ * and this prop is ignored.+ */+ onPressedChange?: (isPressed: boolean) => void;++ /**+ * Async action handler for API-backed toggles.+ * The button shows a loading spinner while the promise is pending.+ *+ * @example+ * ```+ * <XDSToggleButton+ * label="Favorite"+ * isPressed={isFavorited}+ * onPressedChange={setIsFavorited}+ * onPressedChangeAction={async (newState) => {+ * await api.setFavorite(itemId, newState);+ * }}+ * />+ * ```+ */+ onPressedChangeAction?: (isPressed: boolean) => Promise<void>;++ /**+ * The size of the toggle button.+ * When used inside XDSToggleButtonGroup, defaults to the group's size.+ * @default 'md'+ */+ size?: XDSButtonSize;++ /**+ * Whether the button is disabled.+ * When used inside XDSToggleButtonGroup, the group's isDisabled overrides this.+ * @default false+ */+ isDisabled?: boolean;++ /**+ * Whether the button is in a loading state.+ * @default false+ */+ isLoading?: boolean;++ /**+ * Icon element to render in the button.+ * When provided without children, button becomes icon-only (square)+ * with an automatic tooltip from the label.+ */+ icon?: ReactNode;++ /**+ * Icon element to render when the button is pressed.+ * Use to swap between outline (unpressed) and filled (pressed) icon styles.+ * Falls back to `icon` if not provided.+ *+ * To color the pressed icon, pass an already-colored element:+ * @example+ * ```+ * pressedIcon={<StarIconSolid style={{color: 'var(--color-icon-yellow)'}} />}+ * ```+ */+ pressedIcon?: ReactNode;++ /**+ * Optional visible content. If omitted and icon is provided,+ * button becomes icon-only with label used as aria-label.+ */+ children?: ReactNode;++ /**+ * Tooltip text shown on hover.+ * Passed through to XDSButton.+ */+ tooltip?: string;++ /**+ * Value identifier when used inside XDSToggleButtonGroup.+ * Required when used in a group.+ */+ value?: string;++ /** Test ID for testing frameworks. */+ 'data-testid'?: string;+}++// =============================================================================+// Component+// =============================================================================++/**+ * A button that toggles between pressed and unpressed states.+ * Thin wrapper over XDSButton — adds controlled toggle pattern,+ * icon swap, and font weight emphasis.+ *+ * Use for toolbar actions, view mode switches, and formatting controls.+ * For on/off settings, use XDSSwitch instead.+ *+ * Works standalone (with `isPressed`/`onPressedChange`) or inside+ * XDSToggleButtonGroup (which controls selection via `value`).+ *+ * @example+ * ```+ * // Icon-only toggle (toolbar)+ * const [isBold, setIsBold] = useState(false);+ * <XDSToggleButton+ * label="Bold"+ * icon={<BoldIcon />}+ * isPressed={isBold}+ * onPressedChange={setIsBold}+ * />+ *+ * // Favorite with icon swap+ * <XDSToggleButton+ * label="Favorite"+ * icon={<StarIcon />}+ * pressedIcon={<StarIconSolid />}+ * isPressed={isFavorited}+ * onPressedChange={setIsFavorited}+ * />+ * ```+ */+export function XDSToggleButton({+ label,+ isPressed: isPressedProp,+ onPressedChange: onPressedChangeProp,+ onPressedChangeAction,+ size: sizeProp,+ isDisabled: isDisabledProp = false,+ isLoading = false,+ icon,+ pressedIcon,+ children,+ tooltip,+ value,+ ...props+}: XDSToggleButtonProps): ReactNode {+ // Read group context if inside a group+ const group = useXDSToggleButtonGroup();++ // Resolve state from group or props+ const isPressed =+ group && value != null+ ? group.selectedValues.has(value)+ : (isPressedProp ?? false);+ const size = sizeProp ?? group?.size ?? 'md';+ const isDisabled = group?.isDisabled ?? isDisabledProp;++ const resolvedIcon = isPressed && pressedIcon ? pressedIcon : icon;++ const handleClick = useCallback(() => {+ if (isDisabled || isLoading) return;++ if (group && value != null) {+ // Delegate to group context+ group.toggle(value);+ } else if (onPressedChangeProp) {+ // Standalone toggle+ const newState = !isPressed;+ onPressedChangeProp(newState);+ if (onPressedChangeAction) {+ onPressedChangeAction(newState);+ }+ }+ }, [+ isDisabled,+ isLoading,+ group,+ value,+ onPressedChangeProp,+ onPressedChangeAction,+ isPressed,+ ]);++ // Label with font weight shift and width reservation+ const isIconOnly = icon != null && children == null;+ const labelContent =+ children != null ? (+ <span {...stylex.props(labelStyles.wrapper)}>+ <span {...stylex.props(isPressed && labelStyles.pressed)}>+ {children}+ </span>+ <span+ {...stylex.props(labelStyles.widthReservation)}+ aria-hidden="true">+ {children}+ </span>+ </span>+ ) : !isIconOnly ? (+ <span {...stylex.props(labelStyles.wrapper)}>+ <span {...stylex.props(isPressed && labelStyles.pressed)}>{label}</span>+ <span+ {...stylex.props(labelStyles.widthReservation)}+ aria-hidden="true">+ {label}+ </span>+ </span>+ ) : undefined;++ return (+ <XDSButton+ label={label}+ variant="ghost"+ size={size}+ isDisabled={isDisabled}+ isLoading={isLoading}+ aria-pressed={isPressed}+ icon={resolvedIcon}+ tooltip={tooltip}+ onClick={handleClick}+ {...props}>+ {labelContent}+ </XDSButton>+ );+}++XDSToggleButton.displayName = 'XDSToggleButton';diff --git a/packages/core/src/ToggleButton/XDSToggleButtonGroup.tsx b/packages/core/src/ToggleButton/XDSToggleButtonGroup.tsxnew file mode 100644index 0000000000..dd80009e2b--- /dev/null+++ b/packages/core/src/ToggleButton/XDSToggleButtonGroup.tsx@@ -0,0 +1,252 @@+'use client';++/**+ * @file XDSToggleButtonGroup.tsx+ * @input Uses React Context, XDSToggleButton children+ * @output Exports XDSToggleButtonGroup component and types+ * @position Groups toggle buttons for single or multi-select behavior+ *+ * Uses a discriminated union on `type` to enforce type-safe value/onChange:+ * - type='single' → value: string | null, onChange: (v: string | null) => void+ * - type='multiple' → value: string[], onChange: (v: string[]) => void+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/ToggleButton/index.ts+ * - /apps/storybook/stories/ToggleButton.stories.tsx+ */++import {+ createContext,+ useCallback,+ useContext,+ useMemo,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {spacingVars} from '../theme/tokens.stylex';+import type {XDSButtonSize} from '../Button';+import {xdsClassName, mergeProps} from '../utils';+import type {StyleXStyles} from '@stylexjs/stylex';++// =============================================================================+// Context+// =============================================================================++interface ToggleButtonGroupContextValue {+ /** Currently selected value(s). */+ selectedValues: Set<string>;+ /** Toggle a value on/off. */+ toggle: (value: string) => void;+ /** Group size default — individual buttons can override. */+ size?: XDSButtonSize;+ /** Group disabled state. */+ isDisabled?: boolean;+}++export const ToggleButtonGroupContext =+ createContext<ToggleButtonGroupContextValue | null>(null);++/**+ * Hook for XDSToggleButton to read group context.+ * Returns null when used outside a group.+ */+export function useXDSToggleButtonGroup(): ToggleButtonGroupContextValue | null {+ return useContext(ToggleButtonGroupContext);+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ group: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ vertical: {+ flexDirection: 'column',+ alignItems: 'stretch',+ },+});++// =============================================================================+// Props — Discriminated Union+// =============================================================================++interface XDSToggleButtonGroupBaseProps {+ /** Toggle button children. */+ children: ReactNode;++ /**+ * Accessible label for the group (used as aria-label).+ */+ label: string;++ /**+ * Orientation of the button group.+ * @default 'horizontal'+ */+ orientation?: 'horizontal' | 'vertical';++ /**+ * Default size for buttons in the group.+ * Individual buttons can override this with their own `size` prop.+ * @default 'md'+ */+ size?: XDSButtonSize;++ /**+ * Whether all buttons in the group are disabled.+ * @default false+ */+ isDisabled?: boolean;++ /** StyleX overrides for the group container. */+ xstyle?: StyleXStyles;++ /** Test ID for testing frameworks. */+ 'data-testid'?: string;+}++/**+ * Single-select group props.+ * Only one button can be active at a time. Clicking the active+ * button deselects it (value becomes null).+ */+export interface XDSToggleButtonGroupSingleProps extends XDSToggleButtonGroupBaseProps {+ /**+ * Single selection mode (default).+ * @default 'single'+ */+ type?: 'single';++ /** Currently selected value, or null if none selected. */+ value: string | null;++ /** Called when selection changes. */+ onChange: (value: string | null) => void;+}++/**+ * Multi-select group props.+ * Multiple buttons can be active simultaneously.+ */+export interface XDSToggleButtonGroupMultipleProps extends XDSToggleButtonGroupBaseProps {+ /** Multiple selection mode. */+ type: 'multiple';++ /** Currently selected values. */+ value: string[];++ /** Called when selection changes. */+ onChange: (value: string[]) => void;+}++/** Discriminated union of single and multiple group props. */+export type XDSToggleButtonGroupProps =+ | XDSToggleButtonGroupSingleProps+ | XDSToggleButtonGroupMultipleProps;++// =============================================================================+// Component+// =============================================================================++/**+ * Groups toggle buttons for exclusive (single) or multi-select behavior.+ *+ * Uses a discriminated union on `type` for type-safe value/onChange:+ * - `'single'` (default): `value: string | null`, click active deselects+ * - `'multiple'`: `value: string[]`, toggles individual items+ *+ * @example+ * ```+ * // Exclusive: view mode switcher+ * const [view, setView] = useState<string | null>('grid');+ * <XDSToggleButtonGroup value={view} onChange={setView} label="View mode">+ * <XDSToggleButton value="list" label="List" icon={<ListIcon />} />+ * <XDSToggleButton value="grid" label="Grid" icon={<GridIcon />} />+ * </XDSToggleButtonGroup>+ *+ * // Multi-select: text formatting+ * const [formats, setFormats] = useState<string[]>([]);+ * <XDSToggleButtonGroup+ * type="multiple"+ * value={formats}+ * onChange={setFormats}+ * label="Formatting"+ * >+ * <XDSToggleButton value="bold" label="Bold" icon={<BoldIcon />} />+ * <XDSToggleButton value="italic" label="Italic" icon={<ItalicIcon />} />+ * </XDSToggleButtonGroup>+ * ```+ */+export function XDSToggleButtonGroup(+ props: XDSToggleButtonGroupProps,+): ReactNode {+ const {+ children,+ label,+ orientation = 'horizontal',+ size,+ isDisabled = false,+ xstyle,+ 'data-testid': testId,+ } = props;++ const isMultiple = props.type === 'multiple';++ const selectedValues = useMemo(() => {+ if (isMultiple) {+ return new Set(props.value as string[]);+ }+ const singleValue = props.value as string | null;+ return singleValue != null ? new Set([singleValue]) : new Set<string>();+ }, [isMultiple, props.value]);++ const toggle = useCallback(+ (itemValue: string) => {+ if (isMultiple) {+ const current = props.value as string[];+ const onChange = props.onChange as (value: string[]) => void;+ if (current.includes(itemValue)) {+ onChange(current.filter(v => v !== itemValue));+ } else {+ onChange([...current, itemValue]);+ }+ } else {+ const current = props.value as string | null;+ const onChange = props.onChange as (value: string | null) => void;+ // Allow deselection: clicking active → null+ onChange(current === itemValue ? null : itemValue);+ }+ },+ [isMultiple, props.value, props.onChange],+ );++ const contextValue = useMemo(+ () => ({selectedValues, toggle, size, isDisabled}),+ [selectedValues, toggle, size, isDisabled],+ );++ return (+ <ToggleButtonGroupContext.Provider value={contextValue}>+ <div+ role="group"+ aria-label={label}+ data-testid={testId}+ {...mergeProps(+ xdsClassName('toggle-button-group'),+ stylex.props(+ styles.group,+ orientation === 'vertical' && styles.vertical,+ xstyle,+ ),+ )}>+ {children}+ </div>+ </ToggleButtonGroupContext.Provider>+ );+}++XDSToggleButtonGroup.displayName = 'XDSToggleButtonGroup';diff --git a/packages/core/src/ToggleButton/index.ts b/packages/core/src/ToggleButton/index.tsnew file mode 100644index 0000000000..a96b02d9bd--- /dev/null+++ b/packages/core/src/ToggleButton/index.ts@@ -0,0 +1,18 @@+'use client';++/**+ * @file index.ts+ * @input Imports from XDSToggleButton.tsx and XDSToggleButtonGroup.tsx+ * @output Exports XDSToggleButton, XDSToggleButtonGroup, and types+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ */++export {XDSToggleButton} from './XDSToggleButton';+export type {XDSToggleButtonProps} from './XDSToggleButton';++export {XDSToggleButtonGroup} from './XDSToggleButtonGroup';+export type {+ XDSToggleButtonGroupProps,+ XDSToggleButtonGroupSingleProps,+ XDSToggleButtonGroupMultipleProps,+} from './XDSToggleButtonGroup';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex af3117c877..449ea490c8 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -56,6 +56,7 @@ export * from './TextArea';export * from './TimeInput';export * from './NumberInput';export * from './Table';+export * from './ToggleButton';export * from './Token';export * from './Typeahead';export * from './Tokenizer';