An open source design system that's fully customizable and agent ready
TypeScript
XDSField component (#19)
Andrey Goder97fbab90e6b8
diff --git a/apps/storybook/stories/Field.stories.tsx b/apps/storybook/stories/Field.stories.tsxnew file mode 100644index 0000000000..788b966f43--- /dev/null+++ b/apps/storybook/stories/Field.stories.tsx@@ -0,0 +1,123 @@+import { useState } from 'react';+import type { Meta, StoryObj } from '@storybook/react';+import { XDSField } from '@xds/core/Field';++const meta: Meta<typeof XDSField> = {+ title: 'Core/XDSField',+ component: XDSField,+ 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 between the label and input',+ },+ inputID: {+ control: 'text',+ description: 'ID for the input element (used for label htmlFor attribute)',+ },+ descriptionID: {+ control: 'text',+ description: 'ID for the description element (use for aria-describedby)',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSField>;++export const Default: Story = {+ render: (args) => {+ const [value, setValue] = useState('');+ return (+ <XDSField {...args} inputID="email-input">+ <input+ id="email-input"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ style={{ padding: '8px', fontSize: '14px', width: '100%', boxSizing: 'border-box' }}+ />+ </XDSField>+ );+ },+ args: {+ label: 'Email',+ },+};++export const WithDescription: Story = {+ render: (args) => {+ const [value, setValue] = useState('');+ return (+ <XDSField {...args} inputID="email-input" descriptionID="email-desc">+ <input+ id="email-input"+ aria-describedby="email-desc"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ style={{ padding: '8px', fontSize: '14px', width: '100%', boxSizing: 'border-box' }}+ />+ </XDSField>+ );+ },+ args: {+ label: 'Email',+ description: "We'll never share your email with anyone.",+ },+};++export const WithHiddenLabel: Story = {+ render: (args) => {+ const [value, setValue] = useState('');+ return (+ <XDSField {...args} inputID="search-input">+ <input+ id="search-input"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder="Search..."+ style={{ padding: '8px', fontSize: '14px', width: '100%', boxSizing: 'border-box' }}+ />+ </XDSField>+ );+ },+ args: {+ label: 'Search',+ isLabelHidden: true,+ },+};++export const AllVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState('');+ const [value2, setValue2] = useState('');+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '24px', maxWidth: '300px' }}>+ <XDSField label="Default field" inputID="default-input">+ <input+ id="default-input"+ value={value1}+ onChange={(e) => setValue1(e.target.value)}+ style={{ padding: '8px', fontSize: '14px', width: '100%', boxSizing: 'border-box' }}+ />+ </XDSField>+ <XDSField label="With description" description="This is helpful information" inputID="desc-input" descriptionID="desc-text">+ <input+ id="desc-input"+ aria-describedby="desc-text"+ value={value2}+ onChange={(e) => setValue2(e.target.value)}+ style={{ padding: '8px', fontSize: '14px', width: '100%', boxSizing: 'border-box' }}+ />+ </XDSField>+ </div>+ );+ },+};diff --git a/apps/storybook/stories/TextInput.stories.tsx b/apps/storybook/stories/TextInput.stories.tsxindex 3a64b1f676..f400754d69 100644--- a/apps/storybook/stories/TextInput.stories.tsx+++ b/apps/storybook/stories/TextInput.stories.tsx@@ -19,6 +19,10 @@ const meta: Meta<typeof XDSTextInput> = {control: 'text',description: 'Placeholder text',},+ description: {+ control: 'text',+ description: 'Description text displayed between the label and input',+ },value: {control: 'text',description: 'Current input value (required)',@@ -40,6 +44,18 @@ export const Default: Story = {},};+export const WithDescription: Story = {+ render: (args) => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Email',+ description: "We'll never share your email with anyone.",+ placeholder: 'Enter your email',+ },+};+export const WithHiddenLabel: Story = {render: (args) => {const [value, setValue] = useState(args.value ?? '');@@ -68,9 +84,11 @@ export const AllVariations: Story = {const [value1, setValue1] = useState('');const [value2, setValue2] = useState('');const [value3, setValue3] = useState('Pre-filled value');+ const [value4, setValue4] = useState('');return (<div style={{ display: 'flex', flexDirection: 'column', gap: '16px', maxWidth: '300px' }}><XDSTextInput label="Visible label" value={value1} onChange={setValue1} placeholder="Enter text..." />+ <XDSTextInput label="With description" description="Helpful description text" value={value4} onChange={setValue4} placeholder="Enter text..." /><XDSTextInput label="Hidden label" isLabelHidden value={value2} onChange={setValue2} placeholder="Hidden label input" /><XDSTextInput label="With value" value={value3} onChange={setValue3} /></div>diff --git a/packages/core/src/Field/README.md b/packages/core/src/Field/README.mdnew file mode 100644index 0000000000..d4f015e3a2--- /dev/null+++ b/packages/core/src/Field/README.md@@ -0,0 +1,69 @@+# /packages/core/src/Field++A form field wrapper component that provides label and description.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Label Support**: Required label for accessibility (can be visually hidden)+- **Description**: Optional description text displayed between the label and input+- **Accessible**: Label properly associated with input via htmlFor/id+- **Styled with StyleX**: Uses XDS design tokens for consistent styling++## Usage++```tsx+import { XDSField } from '@xds/core/Field';+import { useId } from 'react';++// Basic usage with explicit IDs+const id = useId();+<XDSField label="Email" inputID={id}>+ <input id={id} />+</XDSField>++// With description+const inputId = useId();+const descId = useId();+<XDSField+ label="Email"+ description="We'll never share your email"+ inputID={inputId}+ descriptionID={descId}+>+ <input id={inputId} aria-describedby={descId} />+</XDSField>++// Hidden label (for screen readers only)+const searchId = useId();+<XDSField label="Search" isLabelHidden inputID={searchId}>+ <input id={searchId} placeholder="Search..." />+</XDSField>+```++## Props++| Prop | Type | Required | Description |+|------|------|----------|-------------|+| `label` | `string` | Yes | Label text for the field (always rendered for accessibility) |+| `isLabelHidden` | `boolean` | No | Visually hide the label (still accessible to screen readers) |+| `description` | `string` | No | Description text displayed between the label and input |+| `inputID` | `string` | Yes | ID for the input element (used for label's htmlFor attribute) |+| `descriptionID` | `string` | No | ID for the description element (use for aria-describedby on the input) |+| `children` | `ReactNode` | Yes | The input or control to render |++## Files++| File | Role | Purpose |+|------|------|---------|+| `index.ts` | Entry | Exports component and types |+| `XDSField.tsx` | Core | Component implementation |+| `XDSField.test.tsx` | Test | Unit tests |++## Implementation Notes++- Parent components are responsible for generating IDs (using `useId` hook)+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually+- Hidden label uses CSS technique that remains accessible to screen readers+- Description is rendered when provided; if `descriptionID` is also provided, the description element gets that ID for `aria-describedby` associationdiff --git a/packages/core/src/Field/XDSField.test.tsx b/packages/core/src/Field/XDSField.test.tsxnew file mode 100644index 0000000000..6d9c26340f--- /dev/null+++ b/packages/core/src/Field/XDSField.test.tsx@@ -0,0 +1,85 @@+/**+ * @file XDSField.test.tsx+ * @input Uses vitest, @testing-library/react, XDSField component+ * @output Unit tests for XDSField component behavior+ * @position Testing; validates XDSField.tsx implementation+ *+ * SYNC: When XDSField.tsx changes, update tests to match new behavior+ */++import { describe, it, expect, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import { XDSField } from './XDSField';++describe('XDSField', () => {+ it('renders with label', () => {+ render(+ <XDSField label="Email" inputID="email-input">+ <input id="email-input" />+ </XDSField>+ );+ expect(screen.getByLabelText('Email')).toBeInTheDocument();+ });++ it('renders description text', () => {+ render(+ <XDSField label="Email" inputID="email-input" description="We'll never share your email" descriptionID="email-desc">+ <input id="email-input" aria-describedby="email-desc" />+ </XDSField>+ );+ expect(screen.getByText("We'll never share your email")).toBeInTheDocument();+ });++ it('associates description with correct ID', () => {+ render(+ <XDSField label="Email" inputID="email-input" description="Description text" descriptionID="email-desc">+ <input id="email-input" aria-describedby="email-desc" />+ </XDSField>+ );+ const description = screen.getByText('Description text');+ expect(description).toHaveAttribute('id', 'email-desc');+ });++ it('visually hides label when isLabelHidden is true', () => {+ render(+ <XDSField label="Search" isLabelHidden inputID="search-input">+ <input id="search-input" />+ </XDSField>+ );+ const label = screen.getByText('Search');+ expect(label).toBeInTheDocument();+ // Label should still be accessible+ expect(screen.getByLabelText('Search')).toBeInTheDocument();+ });++ it('shows label visually by default', () => {+ render(+ <XDSField label="Email" inputID="email-input">+ <input id="email-input" />+ </XDSField>+ );+ const label = screen.getByText('Email');+ expect(label).toBeVisible();+ });++ it('forwards ref correctly', () => {+ const ref = vi.fn();+ render(+ <XDSField ref={ref} label="Name" inputID="name-input">+ <input id="name-input" />+ </XDSField>+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLDivElement));+ });++ it('renders description without ID attribute when descriptionID is not provided', () => {+ render(+ <XDSField label="Email" inputID="email-input" description="Description text">+ <input id="email-input" />+ </XDSField>+ );+ const description = screen.getByText('Description text');+ expect(description).toBeInTheDocument();+ expect(description).not.toHaveAttribute('id');+ });+});diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsxnew file mode 100644index 0000000000..c9bbccbbaf--- /dev/null+++ b/packages/core/src/Field/XDSField.tsx@@ -0,0 +1,113 @@+/**+ * @file XDSField.tsx+ * @input Uses React forwardRef, HTMLAttributes, ReactNode+ * @output Exports XDSField component, XDSFieldProps+ * @position Core implementation; consumed by index.ts, tested by XDSField.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Field/README.md (props table, features, implementation notes)+ * - /packages/core/src/Field/XDSField.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Field/index.ts (exports if types change)+ * - /apps/storybook/stories/Field.stories.tsx (storybook stories)+ */++import { forwardRef, type HTMLAttributes, type ReactNode } from 'react';+import * as stylex from '@stylexjs/stylex';+import { color, spacing, typography } from '../theme/tokens.stylex';++const styles = stylex.create({+ container: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacing.space1,+ },+ label: {+ fontFamily: typography.fontFamilyBody,+ fontSize: '0.875rem',+ fontWeight: 500,+ color: color.textPrimary,+ },+ labelHidden: {+ borderStyle: 'none',+ clip: 'rect(0, 0, 0, 0)',+ height: 1,+ left: 0,+ margin: -1,+ overflow: 'hidden',+ padding: 0,+ pointerEvents: 'none',+ position: 'absolute',+ top: 0,+ userSelect: 'none',+ whiteSpace: 'nowrap',+ width: 1,+ },+ description: {+ fontFamily: typography.fontFamilyBody,+ fontSize: '0.75rem',+ color: color.textSecondary,+ },+});++export interface XDSFieldProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {+ /**+ * Label text for the field (always rendered for accessibility).+ */+ label: string;+ /**+ * Whether to visually hide the label (still accessible to screen readers).+ * @default false+ */+ isLabelHidden?: boolean;+ /**+ * Description text displayed between the label and input.+ */+ description?: string;+ /**+ * ID for the input element (used for label's htmlFor attribute).+ */+ inputID: string;+ /**+ * ID for the description element (use for aria-describedby on the input).+ */+ descriptionID?: string;+ /**+ * The input or control to render inside the field.+ */+ children: ReactNode;+}++/**+ * A form field wrapper that provides label and description.+ *+ * @example+ * ```tsx+ * const id = useId();+ * const descID = useId();+ * <XDSField label="Email" description="We'll never share your email" inputID={id} descriptionID={descID}>+ * <input id={id} aria-describedby={descID} />+ * </XDSField>+ * ```+ */+export const XDSField = forwardRef<HTMLDivElement, XDSFieldProps>(+ ({ label, isLabelHidden = false, description, inputID, descriptionID, children, ...props }, ref) => {+ return (+ <div ref={ref} {...stylex.props(styles.container)} {...props}>+ <label+ htmlFor={inputID}+ {...stylex.props(styles.label, isLabelHidden && styles.labelHidden)}+ >+ {label}+ </label>+ {description && (+ <span id={descriptionID} {...stylex.props(styles.description)}>+ {description}+ </span>+ )}+ {children}+ </div>+ );+ }+);++XDSField.displayName = 'XDSField';diff --git a/packages/core/src/Field/index.ts b/packages/core/src/Field/index.tsnew file mode 100644index 0000000000..c0c2c2a16a--- /dev/null+++ b/packages/core/src/Field/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @input Imports XDSField component and types from XDSField.tsx+ * @output Exports XDSField, XDSFieldProps+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/Field/README.md+ */++export { XDSField } from './XDSField';+export type { XDSFieldProps } from './XDSField';diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsxindex 4a7705e866..1c14367dab 100644--- a/packages/core/src/TextInput/XDSTextInput.tsx+++ b/packages/core/src/TextInput/XDSTextInput.tsx@@ -1,6 +1,6 @@/*** @file XDSTextInput.tsx- * @input Uses React forwardRef, ChangeEvent+ * @input Uses React forwardRef, useId, ChangeEvent, XDSField* @output Exports XDSTextInput component, XDSTextInputProps* @position Core implementation; consumed by index.ts, tested by XDSTextInput.test.tsx*@@ -13,41 +13,10 @@import { forwardRef, useId, type ChangeEvent } from 'react';import * as stylex from '@stylexjs/stylex';-import {- color,- spacing,- radius,- transition,- typography,-} from '../theme/tokens.stylex';+import { color, spacing, radius, transition, typography } from '../theme/tokens.stylex';+import { XDSField } from '../Field';const styles = stylex.create({- container: {- display: 'flex',- flexDirection: 'column',- gap: spacing.space1,- },- label: {- fontFamily: typography.fontFamilyBody,- fontSize: '0.875rem',- fontWeight: 500,- color: color.textPrimary,- },- labelHidden: {- borderStyle: 'none',- clip: 'rect(0, 0, 0, 0)',- height: 1,- left: 0,- margin: -1,- overflow: 'hidden',- padding: 0,- pointerEvents: 'none',- position: 'absolute',- top: 0,- userSelect: 'none',- whiteSpace: 'nowrap',- width: 1,- },input: {display: 'block',width: '100%',@@ -91,6 +60,10 @@ export interface XDSTextInputProps {* @default false*/isLabelHidden?: boolean;+ /**+ * Description text displayed between the label and input.+ */+ description?: string;/*** Callback fired when the input value changes.*/@@ -115,17 +88,18 @@ export interface XDSTextInputProps {* ```*/export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(- ({ label, isLabelHidden = false, onChange, value, placeholder }, ref) => {+ ({ label, isLabelHidden = false, description, onChange, value, placeholder }, ref) => {const id = useId();+ const descriptionID = useId();return (- <div {...stylex.props(styles.container)}>- <label- htmlFor={id}- {...stylex.props(styles.label, isLabelHidden && styles.labelHidden)}- >- {label}- </label>+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={id}+ descriptionID={description ? descriptionID : undefined}+ ><inputref={ref}id={id}@@ -133,9 +107,10 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(value={value}onChange={(e) => onChange(e.target.value, e)}placeholder={placeholder}+ aria-describedby={description ? descriptionID : undefined}{...stylex.props(styles.input)}/>- </div>+ </XDSField>);});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0185b7bc29..7de5aa0eb1 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -10,6 +10,7 @@// Componentsexport * from './Avatar';export * from './Button';+export * from './Field';export * from './TextInput';// Layout utilities and components (includes XDSHStack, XDSVStack)diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.tsindex 5817a92ba8..7380b294d2 100644--- a/packages/core/tsup.config.ts+++ b/packages/core/tsup.config.ts@@ -11,7 +11,7 @@ import { defineConfig } from 'tsup';import babel from 'esbuild-plugin-babel';export default defineConfig({- entry: ['src/index.ts', 'src/Avatar/index.ts', 'src/Button/index.ts', 'src/Layout/index.ts', 'src/TextInput/index.ts'],+ entry: ['src/index.ts', 'src/Avatar/index.ts', 'src/Button/index.ts', 'src/Field/index.ts', 'src/Layout/index.ts', 'src/TextInput/index.ts'],format: ['cjs', 'esm'],dts: true,splitting: true,