An open source design system that's fully customizable and agent ready
TypeScript
Add XDSToken component (#202)
Cindy Zhang6f21ff65144e
diff --git a/apps/storybook/stories/Token.stories.tsx b/apps/storybook/stories/Token.stories.tsxnew file mode 100644index 0000000000..51a92f5946--- /dev/null+++ b/apps/storybook/stories/Token.stories.tsx@@ -0,0 +1,254 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSToken, type XDSTokenColor} from '@xds/core/Token';++const meta: Meta<typeof XDSToken> = {+ title: 'Core/XDSToken',+ component: XDSToken,+ tags: ['autodocs'],+ argTypes: {+ color: {+ control: 'select',+ options: [+ 'default',+ 'red',+ 'orange',+ 'yellow',+ 'green',+ 'teal',+ 'cyan',+ 'blue',+ 'purple',+ 'pink',+ 'gray',+ ],+ description: 'Color variant',+ },+ label: {+ control: 'text',+ description: 'Token label text',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Whether the token is disabled',+ },+ isLabelHidden: {+ control: 'boolean',+ description: 'Visually hide the label',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSToken>;++export const Default: Story = {+ args: {+ label: 'Token',+ },+};++const allColors: XDSTokenColor[] = [+ 'default',+ 'red',+ 'orange',+ 'yellow',+ 'green',+ 'teal',+ 'cyan',+ 'blue',+ 'purple',+ 'pink',+ 'gray',+];++export const Colors: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', flexWrap: 'wrap'}}>+ {allColors.map(color => (+ <XDSToken key={color} label={color} color={color} />+ ))}+ </div>+ ),+};++export const WithIcon: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken+ label="Star"+ icon={+ <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">+ <path d="M6 0l1.8 3.6L12 4.2 8.9 7.1l.7 4.1L6 9.2 2.4 11.2l.7-4.1L0 4.2l4.2-.6z" />+ </svg>+ }+ />+ <XDSToken+ label="Info"+ color="blue"+ icon={+ <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">+ <circle+ cx="6"+ cy="6"+ r="5"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ />+ <text+ x="6"+ y="9"+ textAnchor="middle"+ fontSize="8"+ fill="currentColor">+ i+ </text>+ </svg>+ }+ />+ </div>+ ),+};++export const WithRemove: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken label="Removable" onRemove={() => alert('Removed!')} />+ <XDSToken+ label="Red tag"+ color="red"+ onRemove={() => alert('Removed!')}+ />+ <XDSToken+ label="Blue tag"+ color="blue"+ onRemove={() => alert('Removed!')}+ />+ </div>+ ),+};++export const Clickable: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken label="Click me" onClick={() => alert('Clicked!')} />+ <XDSToken+ label="Green action"+ color="green"+ onClick={() => alert('Clicked!')}+ />+ </div>+ ),+};++export const AsLink: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken label="Link token" href="#" />+ <XDSToken label="Purple link" color="purple" href="#" />+ </div>+ ),+};++export const WithEndContent: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken+ label="Count"+ endContent={+ <span+ style={{+ fontSize: '10px',+ opacity: 0.7,+ marginInlineStart: '2px',+ }}>+ (3)+ </span>+ }+ />+ <XDSToken+ label="Status"+ color="green"+ endContent={+ <span+ style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: 'currentColor',+ marginInlineStart: '2px',+ }}+ />+ }+ />+ </div>+ ),+};++export const Disabled: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSToken label="Disabled" isDisabled />+ <XDSToken+ label="Disabled click"+ onClick={() => alert('Should not fire')}+ isDisabled+ />+ <XDSToken+ label="Disabled remove"+ onRemove={() => alert('Should not fire')}+ isDisabled+ />+ <XDSToken label="Disabled link" href="#" isDisabled />+ </div>+ ),+};++export const AllVariations: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '16px'}}>+ <div>+ <h4 style={{margin: '0 0 8px'}}>Display only</h4>+ <div style={{display: 'flex', gap: '8px', flexWrap: 'wrap'}}>+ {allColors.map(color => (+ <XDSToken key={color} label={color} color={color} />+ ))}+ </div>+ </div>+ <div>+ <h4 style={{margin: '0 0 8px'}}>With remove</h4>+ <div style={{display: 'flex', gap: '8px', flexWrap: 'wrap'}}>+ {allColors.map(color => (+ <XDSToken+ key={color}+ label={color}+ color={color}+ onRemove={() => {}}+ />+ ))}+ </div>+ </div>+ <div>+ <h4 style={{margin: '0 0 8px'}}>Clickable</h4>+ <div style={{display: 'flex', gap: '8px', flexWrap: 'wrap'}}>+ {allColors.map(color => (+ <XDSToken+ key={color}+ label={color}+ color={color}+ onClick={() => {}}+ />+ ))}+ </div>+ </div>+ <div>+ <h4 style={{margin: '0 0 8px'}}>Disabled</h4>+ <div style={{display: 'flex', gap: '8px', flexWrap: 'wrap'}}>+ {allColors.map(color => (+ <XDSToken key={color} label={color} color={color} isDisabled />+ ))}+ </div>+ </div>+ </div>+ ),+};diff --git a/packages/core/src/Token/README.md b/packages/core/src/Token/README.mdnew file mode 100644index 0000000000..0d6a41adf1--- /dev/null+++ b/packages/core/src/Token/README.md@@ -0,0 +1,60 @@+# Token++A chip/tag component for displaying entities inline. Renders as a `<span>` by default, `<button>` when `onClick` is provided, or `<a>` when `href` is provided.++## Exports++| Export | Type | Description |+| --------------- | --------- | -------------------- |+| `XDSToken` | Component | Main token component |+| `XDSTokenProps` | Type | Props interface |+| `XDSTokenColor` | Type | Color union type |++## Props++| Prop | Type | Default | Description |+| --------------- | --------------------------------------------------------------------------------------------------------------------- | ----------- | -------------------------------------------- |+| `label` | `string` | — | Text label (required) |+| `color` | `'default' \| 'red' \| 'orange' \| 'yellow' \| 'green' \| 'teal' \| 'cyan' \| 'blue' \| 'purple' \| 'pink' \| 'gray'` | `'default'` | Color variant |+| `icon` | `ReactNode` | — | Optional leading icon |+| `isDisabled` | `boolean` | `false` | Whether the token is disabled |+| `onRemove` | `(e: MouseEvent \| KeyboardEvent) => void` | — | Remove handler; shows X button when provided |+| `onClick` | `(e: MouseEvent) => void` | — | Click handler; renders as `<button>` |+| `href` | `string` | — | Link URL; renders as `<a>` |+| `description` | `string` | — | Accessible description |+| `endContent` | `ReactNode` | — | Content after the label |+| `isLabelHidden` | `boolean` | `false` | Visually hide label (still accessible) |+| `xstyle` | `StyleXStyles` | — | Additional StyleX styles |+| `data-testid` | `string` | — | Test ID for testing frameworks |++## Usage++```tsx+import {XDSToken} from '@xds/core/Token';++// Basic+<XDSToken label="Tag" />++// Colored+<XDSToken label="Status" color="green" />++// Removable+<XDSToken label="Filter" onRemove={(e) => handleRemove(e)} />++// Clickable+<XDSToken label="Category" onClick={() => navigate('/category')} />++// As link+<XDSToken label="Profile" href="/user/123" />++// With icon+<XDSToken label="User" icon={<UserIcon />} />+```++## Files++| File | Purpose |+| ------------------- | ------------------------ |+| `XDSToken.tsx` | Component implementation |+| `XDSToken.test.tsx` | Unit tests |+| `index.ts` | Barrel exports |diff --git a/packages/core/src/Token/XDSToken.test.tsx b/packages/core/src/Token/XDSToken.test.tsxnew file mode 100644index 0000000000..54b3990f59--- /dev/null+++ b/packages/core/src/Token/XDSToken.test.tsx@@ -0,0 +1,319 @@+/**+ * @file XDSToken.test.tsx+ * @input Uses vitest, @testing-library/react, XDSToken component+ * @output Unit tests for XDSToken component behavior+ * @position Testing; validates XDSToken.tsx implementation+ *+ * SYNC: When XDSToken.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSToken} from './XDSToken';++describe('XDSToken', () => {+ it('renders with label', () => {+ render(<XDSToken label="Tag" />);+ expect(screen.getByText('Tag')).toBeInTheDocument();+ });++ it('renders as a span by default', () => {+ const {container} = render(<XDSToken label="Tag" />);+ const root = container.firstChild;+ expect(root?.nodeName).toBe('SPAN');+ });++ it('renders each color variant', () => {+ const colors = [+ 'default',+ 'red',+ 'orange',+ 'yellow',+ 'green',+ 'teal',+ 'cyan',+ 'blue',+ 'purple',+ 'pink',+ 'gray',+ ] as const;++ for (const color of colors) {+ const {unmount} = render(+ <XDSToken label={color} color={color} data-testid={`token-${color}`} />,+ );+ expect(screen.getByTestId(`token-${color}`)).toBeInTheDocument();+ expect(screen.getByText(color)).toBeInTheDocument();+ unmount();+ }+ });++ it('renders as a span with invisible button when onClick is provided', () => {+ const handleClick = vi.fn();+ render(+ <XDSToken label="Clickable" onClick={handleClick} data-testid="token" />,+ );+ const button = screen.getByRole('button', {name: 'Clickable'});+ expect(button).toBeInTheDocument();+ expect(button.tagName).toBe('BUTTON');+ // Container is a span, not a button+ const container = screen.getByTestId('token');+ expect(container.tagName).toBe('SPAN');+ fireEvent.click(button);+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('fires onClick when clicking the container span', () => {+ const handleClick = vi.fn();+ render(+ <XDSToken label="Clickable" onClick={handleClick} data-testid="token" />,+ );+ const container = screen.getByTestId('token');+ fireEvent.click(container);+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('renders as a link when href is provided', () => {+ render(<XDSToken label="Link" href="/test" />);+ const link = screen.getByRole('link', {name: 'Link'});+ expect(link).toBeInTheDocument();+ expect(link.tagName).toBe('A');+ expect(link).toHaveAttribute('href', '/test');+ });++ it('shows remove button when onRemove is provided', () => {+ const handleRemove = vi.fn();+ render(<XDSToken label="Removable" onRemove={handleRemove} />);+ const removeButton = screen.getByRole('button', {name: 'Remove Removable'});+ expect(removeButton).toBeInTheDocument();+ fireEvent.click(removeButton);+ expect(handleRemove).toHaveBeenCalledTimes(1);+ });++ it('stops propagation when remove button is clicked', () => {+ const handleRemove = vi.fn();+ const handleClick = vi.fn();+ render(+ <XDSToken label="Token" onClick={handleClick} onRemove={handleRemove} />,+ );+ const removeButton = screen.getByRole('button', {name: 'Remove Token'});+ fireEvent.click(removeButton);+ expect(handleRemove).toHaveBeenCalledTimes(1);+ expect(handleClick).not.toHaveBeenCalled();+ });++ it('renders disabled state', () => {+ const handleClick = vi.fn();+ render(+ <XDSToken+ label="Disabled"+ onClick={handleClick}+ isDisabled+ data-testid="token"+ />,+ );+ const button = screen.getByRole('button', {name: 'Disabled'});+ expect(button).toBeDisabled();+ expect(button.tagName).toBe('BUTTON');+ // Container click is also disabled+ const container = screen.getByTestId('token');+ fireEvent.click(container);+ expect(handleClick).not.toHaveBeenCalled();+ });++ it('hides label visually when isLabelHidden is true', () => {+ render(<XDSToken label="Hidden" isLabelHidden />);+ // Label text is still in the DOM for screen readers+ expect(screen.getByText('Hidden')).toBeInTheDocument();+ // Root element should have aria-label+ const root = screen.getByText('Hidden').closest('span[aria-label]');+ expect(root).toHaveAttribute('aria-label', 'Hidden');+ });++ it('renders endContent', () => {+ render(+ <XDSToken+ label="Token"+ endContent={<span data-testid="end">End</span>}+ />,+ );+ expect(screen.getByTestId('end')).toBeInTheDocument();+ expect(screen.getByText('End')).toBeInTheDocument();+ });++ it('renders icon', () => {+ render(<XDSToken label="Token" icon={<span data-testid="icon">★</span>} />);+ expect(screen.getByTestId('icon')).toBeInTheDocument();+ });++ it('supports data-testid', () => {+ render(<XDSToken label="Test" data-testid="my-token" />);+ expect(screen.getByTestId('my-token')).toBeInTheDocument();+ });++ it('renders description as aria-description', () => {+ render(+ <XDSToken+ label="Token"+ description="A helpful description"+ data-testid="described-token"+ />,+ );+ expect(screen.getByTestId('described-token')).toHaveAttribute(+ 'aria-description',+ 'A helpful description',+ );+ });++ it('forwards ref', () => {+ const ref = {current: null as HTMLElement | null};+ render(<XDSToken ref={ref} label="Ref test" />);+ expect(ref.current).toBeInstanceOf(HTMLSpanElement);+ });++ it('forwards ref to span when onClick provided', () => {+ const ref = {current: null as HTMLElement | null};+ render(<XDSToken ref={ref} label="Ref test" onClick={() => {}} />);+ expect(ref.current).toBeInstanceOf(HTMLSpanElement);+ });++ it('forwards ref to anchor when href provided', () => {+ const ref = {current: null as HTMLElement | null};+ render(<XDSToken ref={ref} label="Ref test" href="/test" />);+ expect(ref.current).toBeInstanceOf(HTMLAnchorElement);+ });+});++describe('XDSToken accessibility', () => {+ it('does not nest buttons when both onClick and onRemove are provided', () => {+ render(<XDSToken label="Token" onClick={() => {}} onRemove={() => {}} />);+ const buttons = screen.getAllByRole('button');+ // Should have exactly 2: invisible label button + remove button+ expect(buttons).toHaveLength(2);+ // No button should contain another button+ for (const button of buttons) {+ expect(button.querySelector('button')).toBeNull();+ }+ });++ it('allows independent focus on label button and remove button', async () => {+ const user = userEvent.setup();+ render(<XDSToken label="Token" onClick={() => {}} onRemove={() => {}} />);++ // Tab to first button (invisible label button)+ await user.tab();+ expect(screen.getByRole('button', {name: 'Token'})).toHaveFocus();++ // Tab to second button (remove button)+ await user.tab();+ expect(screen.getByRole('button', {name: 'Remove Token'})).toHaveFocus();+ });++ it('fires onClick when Enter is pressed on the invisible button', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn();+ render(<XDSToken label="Token" onClick={handleClick} />);++ await user.tab();+ await user.keyboard('{Enter}');+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('fires onClick when Space is pressed on the invisible button', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn();+ render(<XDSToken label="Token" onClick={handleClick} />);++ await user.tab();+ await user.keyboard(' ');+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('remove button has accessible name including the token label', () => {+ render(<XDSToken label="JavaScript" onRemove={() => {}} />);+ expect(+ screen.getByRole('button', {name: 'Remove JavaScript'}),+ ).toBeInTheDocument();+ });++ it('disables both buttons when isDisabled is true', () => {+ render(+ <XDSToken+ label="Token"+ onClick={() => {}}+ onRemove={() => {}}+ isDisabled+ />,+ );+ const buttons = screen.getAllByRole('button');+ for (const button of buttons) {+ expect(button).toBeDisabled();+ }+ });++ it('does not fire onClick or onRemove when disabled', () => {+ const handleClick = vi.fn();+ const handleRemove = vi.fn();+ render(+ <XDSToken+ label="Token"+ onClick={handleClick}+ onRemove={handleRemove}+ isDisabled+ data-testid="token"+ />,+ );++ // Click on container+ const container = screen.getByTestId('token');+ fireEvent.click(container);+ expect(handleClick).not.toHaveBeenCalled();++ // Try to click remove button (it's disabled)+ const removeBtn = screen.getByRole('button', {name: 'Remove Token'});+ fireEvent.click(removeBtn);+ expect(handleRemove).not.toHaveBeenCalled();+ });++ it('container click handler does not fire when clicking the remove button', () => {+ const handleClick = vi.fn();+ const handleRemove = vi.fn();+ render(+ <XDSToken label="Token" onClick={handleClick} onRemove={handleRemove} />,+ );++ const removeButton = screen.getByRole('button', {name: 'Remove Token'});+ fireEvent.click(removeButton);++ expect(handleRemove).toHaveBeenCalledTimes(1);+ expect(handleClick).not.toHaveBeenCalled();+ });++ it('hidden label is accessible to screen readers', () => {+ render(<XDSToken label="Hidden Tag" isLabelHidden onClick={() => {}} />);+ // The invisible button should still be findable by its accessible name+ expect(+ screen.getByRole('button', {name: 'Hidden Tag'}),+ ).toBeInTheDocument();+ });++ it('link token has correct role and is focusable', async () => {+ const user = userEvent.setup();+ render(<XDSToken label="Link Token" href="/test" />);++ const link = screen.getByRole('link', {name: 'Link Token'});+ expect(link).toHaveAttribute('href', '/test');++ await user.tab();+ expect(link).toHaveFocus();+ });++ it('remove button element exists with correct aria-label', () => {+ const {container} = render(<XDSToken label="Token" onRemove={() => {}} />);+ const removeButton = container.querySelector(+ 'button[aria-label="Remove Token"]',+ );+ expect(removeButton).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Token/XDSToken.tsx b/packages/core/src/Token/XDSToken.tsxnew file mode 100644index 0000000000..d8fc6962ae--- /dev/null+++ b/packages/core/src/Token/XDSToken.tsx@@ -0,0 +1,406 @@+/**+ * @file XDSToken.tsx+ * @input Uses React forwardRef, ReactNode, StyleXStyles+ * @output Exports XDSToken component, XDSTokenProps, XDSTokenColor types+ * @position Core implementation; consumed by index.ts, tested by XDSToken.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Token/README.md (props table, features, implementation notes)+ * - /packages/core/src/Token/XDSToken.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Token/index.ts (exports if types change)+ * - /apps/storybook/stories/Token.stories.tsx (storybook stories)+ */++import {forwardRef, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ sizeVars,+ transitionVars,+ textSizeVars,+ fontWeightVars,+ lineHeightVars,+} from '../theme/tokens.stylex';+import {XDSIcon} from '../Icon';++// =============================================================================+// Types+// =============================================================================++/**+ * Available color variants for the token.+ */+export type XDSTokenColor =+ | 'default'+ | 'red'+ | 'orange'+ | 'yellow'+ | 'green'+ | 'teal'+ | 'cyan'+ | 'blue'+ | 'purple'+ | 'pink'+ | 'gray';++export interface XDSTokenProps {+ /**+ * The text label displayed in the token.+ */+ label: string;+ /**+ * The color variant of the token.+ * @default 'default'+ */+ color?: XDSTokenColor;+ /**+ * Optional icon to display before the label.+ */+ icon?: ReactNode;+ /**+ * Whether the token is disabled.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Callback when the remove (X) button is clicked.+ * When provided, a remove button is rendered.+ */+ onRemove?: (e: React.MouseEvent) => void;+ /**+ * Click handler. When provided, the token renders as a `<span>` container+ * with an invisible `<button>` inside for accessibility.+ */+ onClick?: (e: React.MouseEvent) => void;+ /**+ * Link URL. When provided, the token renders as an `<a>`.+ */+ href?: string;+ /**+ * Accessible description for the token.+ */+ description?: string;+ /**+ * Content rendered after the label (before the remove button, if present).+ */+ endContent?: ReactNode;+ /**+ * Whether to visually hide the label (still accessible to screen readers).+ * @default false+ */+ isLabelHidden?: boolean;+ /**+ * Additional StyleX styles to apply to the root element.+ */+ xstyle?: StyleXStyles;+ /**+ * Test ID for testing frameworks.+ */+ 'data-testid'?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ base: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ height: sizeVars['--size-sm'],+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-3'],+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-content'],+ fontFamily: 'inherit',+ fontSize: textSizeVars['--text-sm'],+ lineHeight: lineHeightVars['--leading-snug'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ whiteSpace: 'nowrap',+ textDecoration: 'none',+ maxWidth: '100%',+ },+ interactive: {+ cursor: 'pointer',+ transitionProperty: 'background-image',+ transitionDuration: transitionVars['--transition-fast'],+ backgroundImage: {+ default: null,+ ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,+ ':active': `linear-gradient(${colorVars['--color-pressed-overlay']}, ${colorVars['--color-pressed-overlay']})`,+ },+ outline: {+ default: null,+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '2px',+ },+ },+ disabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ pointerEvents: 'none' as const,+ },+ labelHidden: {+ position: 'absolute' as const,+ width: '1px',+ height: '1px',+ padding: 0,+ margin: '-1px',+ overflow: 'hidden',+ clipPath: 'inset(50%)',+ whiteSpace: 'nowrap',+ borderWidth: 0,+ },+ invisibleButton: {+ all: 'unset',+ cursor: 'inherit',+ font: 'inherit',+ color: 'inherit',+ },+ focusWithinOutline: {+ outline: {+ default: null,+ ':focus-within': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-within': '2px',+ },+ },+ removeButton: {+ all: 'unset',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ position: 'relative',+ padding: 0,+ marginInlineEnd: `calc(-1 * ${spacingVars['--spacing-1']})`,+ cursor: 'pointer',+ borderRadius: radiusVars['--radius-rounded'],+ width: '16px',+ height: '16px',+ color: 'inherit',+ opacity: {+ default: 0.7,+ ':hover': 1,+ },+ outline: {+ default: null,+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ '::after': {+ content: '""',+ position: 'absolute',+ inset: '-14px',+ },+ },+});++const colorStyles = stylex.create({+ default: {+ backgroundColor: colorVars['--color-deemphasized'],+ color: colorVars['--color-text-primary'],+ },+ red: {+ backgroundColor: colorVars['--color-red-background'],+ color: colorVars['--color-red-text'],+ },+ orange: {+ backgroundColor: colorVars['--color-orange-background'],+ color: colorVars['--color-orange-text'],+ },+ yellow: {+ backgroundColor: colorVars['--color-yellow-background'],+ color: colorVars['--color-yellow-text'],+ },+ green: {+ backgroundColor: colorVars['--color-green-background'],+ color: colorVars['--color-green-text'],+ },+ teal: {+ backgroundColor: colorVars['--color-teal-background'],+ color: colorVars['--color-teal-text'],+ },+ cyan: {+ backgroundColor: colorVars['--color-cyan-background'],+ color: colorVars['--color-cyan-text'],+ },+ blue: {+ backgroundColor: colorVars['--color-blue-background'],+ color: colorVars['--color-blue-text'],+ },+ purple: {+ backgroundColor: colorVars['--color-purple-background'],+ color: colorVars['--color-purple-text'],+ },+ pink: {+ backgroundColor: colorVars['--color-pink-background'],+ color: colorVars['--color-pink-text'],+ },+ gray: {+ backgroundColor: colorVars['--color-gray-background'],+ color: colorVars['--color-gray-text'],+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * A chip/tag component for displaying entities inline.+ *+ * Renders as a `<span>` by default, `<a>` when `href` is provided, or a+ * `<span>` container with an invisible `<button>` when `onClick` is provided.+ * The invisible button pattern provides real button semantics for accessibility+ * while the container uses `:focus-within` to show focus outlines around the+ * entire token.+ *+ * @example+ * ```tsx+ * <XDSToken label="Tag" />+ * <XDSToken label="Status" color="green" />+ * <XDSToken label="Removable" onRemove={() => {}} />+ * <XDSToken label="Clickable" onClick={() => {}} />+ * <XDSToken label="Link" href="/path" />+ * ```+ */+export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>(+ (+ {+ label,+ color = 'default',+ icon,+ isDisabled = false,+ onRemove,+ onClick,+ href,+ description,+ endContent,+ isLabelHidden = false,+ xstyle,+ 'data-testid': testId,+ },+ ref,+ ) => {+ const content = (+ <>+ {icon}+ <span {...(isLabelHidden ? stylex.props(styles.labelHidden) : {})}>+ {label}+ </span>+ {endContent}+ {onRemove != null && (+ <button+ type="button"+ aria-label={`Remove ${label}`}+ onClick={e => {+ e.stopPropagation();+ onRemove(e);+ }}+ disabled={isDisabled}+ {...stylex.props(styles.removeButton)}>+ <XDSIcon icon="close" size="xsm" />+ </button>+ )}+ </>+ );++ const sharedProps = {+ 'data-testid': testId,+ 'aria-label': isLabelHidden ? label : undefined,+ 'aria-description': description,+ };++ if (href != null) {+ return (+ <a+ ref={ref as React.Ref<HTMLAnchorElement>}+ href={href}+ aria-disabled={isDisabled || undefined}+ {...sharedProps}+ {...stylex.props(+ styles.base,+ colorStyles[color],+ styles.interactive,+ isDisabled && styles.disabled,+ xstyle,+ )}>+ {content}+ </a>+ );+ }++ if (onClick != null) {+ const handleContainerClick = (e: React.MouseEvent) => {+ const target = e.target as HTMLElement;+ if (target.closest('button, a')) return;+ onClick(e);+ };++ return (+ <span+ ref={ref as React.Ref<HTMLSpanElement>}+ onClick={isDisabled ? undefined : handleContainerClick}+ {...sharedProps}+ {...stylex.props(+ styles.base,+ colorStyles[color],+ styles.interactive,+ styles.focusWithinOutline,+ isDisabled && styles.disabled,+ xstyle,+ )}>+ {icon}+ <button+ type="button"+ onClick={onClick}+ disabled={isDisabled}+ {...stylex.props(styles.invisibleButton)}>+ <span {...(isLabelHidden ? stylex.props(styles.labelHidden) : {})}>+ {label}+ </span>+ </button>+ {endContent}+ {onRemove != null && (+ <button+ type="button"+ aria-label={`Remove ${label}`}+ onClick={e => {+ e.stopPropagation();+ onRemove(e);+ }}+ disabled={isDisabled}+ {...stylex.props(styles.removeButton)}>+ <XDSIcon icon="close" size="xsm" />+ </button>+ )}+ </span>+ );+ }++ return (+ <span+ ref={ref as React.Ref<HTMLSpanElement>}+ {...sharedProps}+ {...stylex.props(+ styles.base,+ colorStyles[color],+ isDisabled && styles.disabled,+ xstyle,+ )}>+ {content}+ </span>+ );+ },+);++XDSToken.displayName = 'XDSToken';diff --git a/packages/core/src/Token/index.ts b/packages/core/src/Token/index.tsnew file mode 100644index 0000000000..1f1aebe642--- /dev/null+++ b/packages/core/src/Token/index.ts@@ -0,0 +1,6 @@+/**+ * @file Token component barrel export+ */++export {XDSToken} from './XDSToken';+export type {XDSTokenProps, XDSTokenColor} from './XDSToken';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex d0a30a2840..aa110e6120 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -40,6 +40,7 @@ export * from './TextArea';export * from './TimeInput';export * from './NumberInput';export * from './Table';+export * from './Token';export * from './Dialog';export * from './DropdownMenu';export * from './TopNav';