An open source design system that's fully customizable and agent ready
TypeScript
Status for XDSTextInput (#60)
Andrey Goderb0d1b29b35b0
diff --git a/apps/storybook/stories/TextInput.stories.tsx b/apps/storybook/stories/TextInput.stories.tsxindex 891f2654c6..96a9344671 100644--- a/apps/storybook/stories/TextInput.stories.tsx+++ b/apps/storybook/stories/TextInput.stories.tsx@@ -1,6 +1,6 @@import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';-import {XDSTextInput} from '@xds/core/TextInput';+import {XDSTextInput, type XDSTextInputStatus} from '@xds/core/TextInput';import {MagnifyingGlassIcon,EnvelopeIcon,@@ -47,6 +47,11 @@ const meta: Meta<typeof XDSTextInput> = {control: 'boolean',description: 'Whether the input is disabled',},+ status: {+ control: 'object',+ description:+ 'Status indicator with type (warning/error/success) and optional message',+ },},};@@ -283,3 +288,94 @@ export const StartIconVariations: Story = {);},};++export const ErrorStatus: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? 'invalid@');+ return <XDSTextInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Email',+ placeholder: 'Enter your email',+ status: {type: 'error', message: 'Please enter a valid email address'},+ },+};++export const WarningStatus: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? 'user123');+ return <XDSTextInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Username',+ placeholder: 'Enter your username',+ status: {type: 'warning', message: 'This username is already taken'},+ },+};++export const SuccessStatus: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? 'validuser');+ return <XDSTextInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Username',+ placeholder: 'Enter your username',+ status: {type: 'success', message: 'Username is available'},+ },+};++export const StatusWithoutMessage: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? 'test');+ return <XDSTextInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Field',+ placeholder: 'Enter value',+ status: {type: 'error'},+ },+};++export const StatusVariations: Story = {+ render: () => {+ const [error, setError] = useState('invalid@');+ const [warning, setWarning] = useState('user123');+ const [success, setSuccess] = useState('validuser');+ const [errorNoMsg, setErrorNoMsg] = useState('test');+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '300px',+ }}>+ <XDSTextInput+ label="Error with message"+ value={error}+ onChange={setError}+ status={{type: 'error', message: 'Please enter a valid email'}}+ />+ <XDSTextInput+ label="Warning with message"+ value={warning}+ onChange={setWarning}+ status={{type: 'warning', message: 'This username may be taken'}}+ />+ <XDSTextInput+ label="Success with message"+ value={success}+ onChange={setSuccess}+ status={{type: 'success', message: 'Username is available'}}+ />+ <XDSTextInput+ label="Error without message"+ value={errorNoMsg}+ onChange={setErrorNoMsg}+ status={{type: 'error'}}+ />+ </div>+ );+ },+};diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsxindex 7088ad0849..a7fa16ed54 100644--- a/packages/core/src/Field/XDSField.tsx+++ b/packages/core/src/Field/XDSField.tsx@@ -14,7 +14,13 @@import {forwardRef, type HTMLAttributes, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {XDSFieldLabel} from './XDSFieldLabel';-import {colorVars, spacingVars, typographyVars} from '../theme/tokens.stylex';+import {+ colorVars,+ radiusVars,+ spacingVars,+ textSizeVars,+ typographyVars,+} from '../theme/tokens.stylex';import type {XDSIconType} from '../Icon';const styles = stylex.create({@@ -30,7 +36,7 @@ const styles = stylex.create({},label: {fontFamily: typographyVars['--font-body'],- fontSize: '0.875rem',+ fontSize: textSizeVars['--text-base'],fontWeight: 500,color: colorVars['--color-text-primary'],},@@ -51,17 +57,64 @@ const styles = stylex.create({},description: {fontFamily: typographyVars['--font-body'],- fontSize: '0.75rem',+ fontSize: textSizeVars['--text-xsm'],color: colorVars['--color-text-secondary'],},optionalRequired: {fontFamily: typographyVars['--font-body'],- fontSize: '0.75rem',+ fontSize: textSizeVars['--text-xsm'],color: colorVars['--color-text-secondary'],marginInlineStart: spacingVars['--spacing-1'],},+ inputStatusWrapper: {+ display: 'flex',+ flexDirection: 'column',+ },+ statusMessage: {+ marginTop: -6,+ paddingBlockStart: 14,+ paddingBlockEnd: 8,+ paddingInline: spacingVars['--spacing-2'],+ borderBottomLeftRadius: radiusVars['--radius-element'],+ borderBottomRightRadius: radiusVars['--radius-element'],+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-xsm'],+ lineHeight: 1.333,+ },});+const statusMessageColorStyles = stylex.create({+ warning: {+ backgroundColor: colorVars['--color-warning-deemphasized'],+ color: colorVars['--color-yellow-text'],+ },+ error: {+ backgroundColor: colorVars['--color-negative-deemphasized'],+ color: colorVars['--color-red-text'],+ },+ success: {+ backgroundColor: colorVars['--color-positive-deemphasized'],+ color: colorVars['--color-green-text'],+ },+});++export type XDSFieldStatusType = 'warning' | 'error' | 'success';++export interface XDSFieldStatus {+ /**+ * The type of status to display.+ */+ type: XDSFieldStatusType;+ /**+ * Optional message to display below the input.+ */+ message?: string;+ /**+ * ID for the status message element (use for aria-describedby on the input).+ */+ messageID?: string;+}+export interface XDSFieldPropsextends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {/**@@ -99,6 +152,11 @@ export interface XDSFieldProps* Icon to display before the label text.*/labelStartIcon?: XDSIconType;+ /**+ * Status indicator for the field.+ * When set with a message, displays a colored message box below the input.+ */+ status?: XDSFieldStatus;/*** The input or control to render inside the field.*/@@ -128,6 +186,7 @@ export const XDSField = forwardRef<HTMLDivElement, XDSFieldProps>(isOptional = false,isRequired = false,labelStartIcon,+ status,children,...props},@@ -148,7 +207,19 @@ export const XDSField = forwardRef<HTMLDivElement, XDSFieldProps>({description}</span>)}- {children}+ <div {...stylex.props(styles.inputStatusWrapper)}>+ {children}+ {status?.message && (+ <div+ id={status.messageID}+ {...stylex.props(+ styles.statusMessage,+ statusMessageColorStyles[status.type]+ )}>+ {status.message}+ </div>+ )}+ </div></div>);}diff --git a/packages/core/src/Field/index.ts b/packages/core/src/Field/index.tsindex facedc443d..d511570922 100644--- a/packages/core/src/Field/index.ts+++ b/packages/core/src/Field/index.ts@@ -1,13 +1,17 @@/*** @file index.ts* @input Imports XDSField component and types from XDSField.tsx, XDSFieldLabel from XDSFieldLabel.tsx- * @output Exports XDSField, XDSFieldProps, XDSFieldLabel, XDSFieldLabelProps+ * @output Exports XDSField, XDSFieldProps, XDSFieldStatus, XDSFieldStatusType, XDSFieldLabel, XDSFieldLabelProps* @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';-export { XDSFieldLabel } from './XDSFieldLabel';-export type { XDSFieldLabelProps } from './XDSFieldLabel';+export {XDSField} from './XDSField';+export type {+ XDSFieldProps,+ XDSFieldStatus,+ XDSFieldStatusType,+} from './XDSField';+export {XDSFieldLabel} from './XDSFieldLabel';+export type {XDSFieldLabelProps} from './XDSFieldLabel';diff --git a/packages/core/src/TextInput/XDSTextInput.test.tsx b/packages/core/src/TextInput/XDSTextInput.test.tsxindex 1bbaa4321f..34d62bfc3d 100644--- a/packages/core/src/TextInput/XDSTextInput.test.tsx+++ b/packages/core/src/TextInput/XDSTextInput.test.tsx@@ -144,4 +144,123 @@ describe('XDSTextInput', () => {// No SVG should be presentexpect(container.querySelector('svg')).not.toBeInTheDocument();});++ describe('status prop', () => {+ it('renders with error status icon', () => {+ const {container} = render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'error'}}+ />+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders with warning status icon', () => {+ const {container} = render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'warning'}}+ />+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders with success status icon', () => {+ const {container} = render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'success'}}+ />+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders status message when provided', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'error', message: 'Invalid email address'}}+ />+ );+ expect(screen.getByText('Invalid email address')).toBeInTheDocument();+ });++ it('does not render status message when not provided', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'error'}}+ />+ );+ expect(screen.queryByText(/invalid/i)).not.toBeInTheDocument();+ });++ it('sets aria-invalid when status type is error', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'error'}}+ />+ );+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'aria-invalid',+ 'true'+ );+ });++ it('does not set aria-invalid for warning status', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'warning'}}+ />+ );+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-invalid');+ });++ it('does not set aria-invalid for success status', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'success'}}+ />+ );+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-invalid');+ });++ it('includes status message in aria-describedby', () => {+ render(+ <XDSTextInput+ label="Email"+ value=""+ onChange={() => {}}+ status={{type: 'error', message: 'Invalid email'}}+ />+ );+ const input = screen.getByRole('textbox');+ const describedBy = input.getAttribute('aria-describedby');+ expect(describedBy).toBeTruthy();+ // The status message should be reachable via the described-by ID+ const messageElement = screen.getByText('Invalid email');+ expect(messageElement).toHaveAttribute('id');+ expect(describedBy).toContain(messageElement.id);+ });+ });});diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsxindex 620917dec4..fdcf468c03 100644--- a/packages/core/src/TextInput/XDSTextInput.tsx+++ b/packages/core/src/TextInput/XDSTextInput.tsx@@ -13,6 +13,11 @@import {forwardRef, useId, type ChangeEvent} from 'react';import * as stylex from '@stylexjs/stylex';+import {+ CheckCircleIcon,+ ExclamationTriangleIcon,+ XCircleIcon,+} from '@heroicons/react/24/solid';import {colorVars,spacingVars,@@ -25,6 +30,8 @@ import {XDSIcon, type XDSIconType} from '../Icon';const styles = stylex.create({wrapper: {+ position: 'relative',+ zIndex: 1,display: 'flex',alignItems: 'center',gap: spacingVars['--spacing-2'],@@ -84,8 +91,33 @@ const sizeStyles = stylex.create({},});+const statusBorderStyles = stylex.create({+ warning: {+ borderColor: colorVars['--color-warning'],+ },+ error: {+ borderColor: colorVars['--color-negative'],+ },+ success: {+ borderColor: colorVars['--color-positive'],+ },+});+export type XDSTextInputSize = keyof typeof sizeStyles;+export type XDSTextInputStatusType = 'warning' | 'error' | 'success';++export interface XDSTextInputStatus {+ /**+ * The type of status to display.+ */+ type: XDSTextInputStatusType;+ /**+ * Optional message to display below the input.+ */+ message?: string;+}+export interface XDSTextInputProps {/*** Label text for the input (always rendered for accessibility).@@ -120,6 +152,12 @@ export interface XDSTextInputProps {* Import from @heroicons/react/24/outline or @heroicons/react/24/solid.*/startIcon?: XDSIconType;+ /**+ * Status indicator for the input.+ * When set, displays a colored border and status icon.+ * If message is provided, displays a floating message box below the input.+ */+ status?: XDSTextInputStatus;/*** The size of the input.* - 'sm': Compact size (18px height)@@ -160,6 +198,7 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(isRequired = false,isDisabled = false,startIcon,+ status,size = 'md',onChange,value,@@ -169,6 +208,30 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>() => {const id = useId();const descriptionID = useId();+ const statusMessageID = useId();++ const statusIconMap: Record<XDSTextInputStatusType, XDSIconType> = {+ warning: ExclamationTriangleIcon,+ error: XCircleIcon,+ success: CheckCircleIcon,+ };++ const statusIconColorMap: Record<+ XDSTextInputStatusType,+ 'warning' | 'negative' | 'positive'+ > = {+ warning: 'warning',+ error: 'negative',+ success: 'positive',+ };++ const ariaDescribedBy =+ [+ description ? descriptionID : null,+ status?.message ? statusMessageID : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;return (<XDSField@@ -178,11 +241,21 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(inputID={id}descriptionID={description ? descriptionID : undefined}isOptional={isOptional}- isRequired={isRequired}>+ isRequired={isRequired}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageID : undefined,+ }+ : undefined+ }><div{...stylex.props(styles.wrapper,- isDisabled && styles.wrapperDisabled+ isDisabled && styles.wrapperDisabled,+ status && statusBorderStyles[status.type])}>{startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}<input@@ -193,14 +266,22 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(onChange={e => onChange(e.target.value, e)}placeholder={placeholder}disabled={isDisabled}- aria-describedby={description ? descriptionID : undefined}+ aria-describedby={ariaDescribedBy}aria-required={isRequired === true ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}{...stylex.props(styles.input,sizeStyles[size],isDisabled && styles.inputDisabled)}/>+ {status && (+ <XDSIcon+ icon={statusIconMap[status.type]}+ size="md"+ color={statusIconColorMap[status.type]}+ />+ )}</div></XDSField>);diff --git a/packages/core/src/TextInput/index.ts b/packages/core/src/TextInput/index.tsindex 4b47ad7ac0..e83eabd27a 100644--- a/packages/core/src/TextInput/index.ts+++ b/packages/core/src/TextInput/index.ts@@ -1,11 +1,16 @@/*** @file index.ts* @input Imports XDSTextInput component and types from TextInput.tsx- * @output Exports XDSTextInput, XDSTextInputProps, XDSTextInputSize+ * @output Exports XDSTextInput, XDSTextInputProps, XDSTextInputSize, XDSTextInputStatus, XDSTextInputStatusType* @position Component entry point; re-exported by /packages/core/src/index.ts** SYNC: When modified, update this header and /packages/core/src/TextInput/README.md*/export {XDSTextInput} from './XDSTextInput';-export type {XDSTextInputProps, XDSTextInputSize} from './XDSTextInput';+export type {+ XDSTextInputProps,+ XDSTextInputSize,+ XDSTextInputStatus,+ XDSTextInputStatusType,+} from './XDSTextInput';diff --git a/packages/core/src/theme/defaultTheme.stylex.ts b/packages/core/src/theme/defaultTheme.stylex.tsindex 81cb1f2161..c723a7f083 100644--- a/packages/core/src/theme/defaultTheme.stylex.ts+++ b/packages/core/src/theme/defaultTheme.stylex.ts@@ -166,7 +166,7 @@ const colorRaw = {'--color-yellow-background': 'light-dark(#FFEB3B33, #FFEB3B33)','--color-yellow-border': 'light-dark(#FFEB3B, #FFF176)','--color-yellow-icon': 'light-dark(#FBC02D, #FFEE58)',- '--color-yellow-text': 'light-dark(#F57F17, #FFF9C4)',+ '--color-yellow-text': 'light-dark(#753F07, #FBCE03)',} as const satisfies Record<ColorVarName, string>;const spacingRaw = {@@ -248,47 +248,47 @@ const fontWeightRaw = {const colorTheme = stylex.createTheme(colorVars,- colorRaw as unknown as BaseColorRaw,+ colorRaw as unknown as BaseColorRaw);const spacingTheme = stylex.createTheme(spacingVars,- spacingRaw as unknown as BaseSpacingRaw,+ spacingRaw as unknown as BaseSpacingRaw);const radiusTheme = stylex.createTheme(radiusVars,- radiusRaw as unknown as BaseRadiusRaw,+ radiusRaw as unknown as BaseRadiusRaw);const elevationTheme = stylex.createTheme(elevationVars,- elevationRaw as unknown as BaseElevationRaw,+ elevationRaw as unknown as BaseElevationRaw);const transitionTheme = stylex.createTheme(transitionVars,- transitionRaw as unknown as BaseTransitionRaw,+ transitionRaw as unknown as BaseTransitionRaw);const typographyTheme = stylex.createTheme(typographyVars,- typographyRaw as unknown as BaseTypographyRaw,+ typographyRaw as unknown as BaseTypographyRaw);const textSizeTheme = stylex.createTheme(textSizeVars,- textSizeRaw as unknown as BaseTextSizeRaw,+ textSizeRaw as unknown as BaseTextSizeRaw);const lineHeightTheme = stylex.createTheme(lineHeightVars,- lineHeightRaw as unknown as BaseLineHeightRaw,+ lineHeightRaw as unknown as BaseLineHeightRaw);const fontWeightTheme = stylex.createTheme(fontWeightVars,- fontWeightRaw as unknown as BaseFontWeightRaw,+ fontWeightRaw as unknown as BaseFontWeightRaw);// =============================================================================