An open source design system that's fully customizable and agent ready
TypeScript
fix(Field): hardening — a11y, auto-IDs, disabled styles (#848)
Joeye52b38555d3e
diff --git a/apps/storybook/stories/Field.stories.tsx b/apps/storybook/stories/Field.stories.tsxindex f797ef4f30..e576a1f1bf 100644--- a/apps/storybook/stories/Field.stories.tsx+++ b/apps/storybook/stories/Field.stories.tsx@@ -2,6 +2,7 @@ import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import * as stylex from '@stylexjs/stylex';import {XDSField} from '@xds/core/Field';+import {XDSTextInput} from '@xds/core/TextInput';import {colorVars,spacingVars,@@ -240,45 +241,33 @@ export const StatusVariants: Story = {gap: 24,maxWidth: 400,}}>- <XDSField+ <XDSTextInputlabel="Email"description="Enter your work email"- inputID="s-error"+ value={vals.error}+ onChange={set('error')}status={{type: 'error',message: 'Please enter a valid email address',- }}>- <NativeInput- id="s-error"- value={vals.error}- onChange={set('error')}- />- </XDSField>- <XDSField+ }}+ />+ <XDSTextInputlabel="Username"description="Choose a unique username"- inputID="s-warning"+ value={vals.warning}+ onChange={set('warning')}status={{type: 'warning',message: 'This username is reserved for administrators',- }}>- <NativeInput- id="s-warning"- value={vals.warning}- onChange={set('warning')}- />- </XDSField>- <XDSField+ }}+ />+ <XDSTextInputlabel="API Key"description="Paste your API key"- inputID="s-success"- status={{type: 'success', message: 'API key is valid and active'}}>- <NativeInput- id="s-success"- value={vals.success}- onChange={set('success')}- />- </XDSField>+ value={vals.success}+ onChange={set('success')}+ status={{type: 'success', message: 'API key is valid and active'}}+ /></div>);},diff --git a/packages/core/src/Field/Field.doc.mjs b/packages/core/src/Field/Field.doc.mjsindex 92eaa0d63c..1ab5c07442 100644--- a/packages/core/src/Field/Field.doc.mjs+++ b/packages/core/src/Field/Field.doc.mjs@@ -9,6 +9,8 @@ export const docs = {'Description — optional description text displayed between the label and input','Optional/Required Indicators — display "Optional" or "Required" text with bullet separator','Label Tooltip — optional info icon with tooltip at end of label',+ 'Disabled State — propagates disabled styling to label',+ 'Status Messages — attached/detached validation feedback with role="status" and aria-live="polite"','Accessible — label properly associated with input via htmlFor/id','Styled with StyleX — uses XDS design tokens for consistent styling',],@@ -82,8 +84,11 @@ const bioDescId = useId();'Label is always rendered for accessibility; use isLabelHidden to hide visually.','Hidden label uses a 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 association.',- 'isOptional and isRequired are mutually exclusive; setting both will show "Optional".',+ 'isOptional and isRequired are mutually exclusive; setting both will show "Optional" (dev warning emitted).','Optional/Required text appears on the same line as the label.',+ 'Status messages use role="status" and aria-live="polite" for screen reader announcements.',+ 'Use statusVariant="attached" (default) for bordered inputs; "detached" for checkboxes, switches, sliders.',+ 'isDisabled propagates disabled styling to the label (color + cursor).',],components: [{@@ -126,6 +131,13 @@ const bioDescId = useId();'Visually hide the label (still accessible to screen readers).',default: 'false',},+ {+ name: 'isDisabled',+ type: 'boolean',+ description:+ 'Whether the associated input is disabled. Propagates disabled styling to the label.',+ default: 'false',+ },{name: 'description',type: 'string',@@ -163,12 +175,42 @@ const bioDescId = useId();description:'Tooltip text to display in an info icon at the end of the label.',},+ {+ name: 'status',+ type: 'XDSFieldStatus',+ description:+ 'Status indicator with type and optional message. When message is set, displays a colored status box.',+ },+ {+ name: 'statusVariant',+ type: "'attached' | 'detached'",+ description:+ 'How the status message renders relative to the input. Attached overlaps the input border; detached floats below.',+ default: "'attached'",+ },+ {+ name: 'ref',+ type: 'React.Ref<HTMLDivElement>',+ description: 'Ref forwarded to the root element.',+ },{name: 'xstyle',type: 'StyleXStyles',description:'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value — not an inline style object like style={{}}.',},+ {+ name: 'className',+ type: 'string',+ description:+ 'CSS class name(s) appended to the root element. Prefer xstyle for StyleX deduplication.',+ },+ {+ name: 'style',+ type: 'React.CSSProperties',+ description:+ 'Inline styles applied to the root element. Takes priority over StyleX inline styles.',+ },],},{@@ -280,6 +322,8 @@ export const docsZh = {'描述 - 可选的描述文本,显示在标签和输入框之间','可选/必填指示器 - 显示"Optional"或"Required"文本,带圆点分隔符','标签工具提示 - 可选的信息图标,在标签末尾显示工具提示',+ '禁用状态 - 将禁用样式传递给标签',+ '状态消息 - attached/detached 验证反馈,带 role="status" 和 aria-live="polite"','无障碍 - 通过 htmlFor/id 将标签与输入框正确关联','使用 StyleX 样式 - 使用 XDS 设计令牌实现一致的样式',],@@ -353,8 +397,11 @@ const bioDescId = useId();'标签始终渲染以确保无障碍访问;使用 isLabelHidden 进行视觉隐藏。','隐藏标签使用 CSS 技术,屏幕阅读器仍可访问。','提供 description 时会渲染描述文本;如果同时提供 descriptionID,描述元素会获得该 ID 用于 aria-describedby 关联。',- 'isOptional 和 isRequired 互斥;同时设置两者将显示"Optional"。',+ 'isOptional 和 isRequired 互斥;同时设置两者将显示"Optional"(开发模式下发出警告)。','可选/必填文本与标签显示在同一行。',+ '状态消息使用 role="status" 和 aria-live="polite" 进行屏幕阅读器播报。',+ '使用 statusVariant="attached"(默认)用于带边框的输入框;"detached" 用于复选框、开关、滑块。',+ 'isDisabled 将禁用样式传递给标签(颜色 + 光标)。',],components: [{@@ -397,6 +444,13 @@ const bioDescId = useId();'视觉隐藏标签(屏幕阅读器仍可访问)。',default: 'false',},+ {+ name: 'isDisabled',+ type: 'boolean',+ description:+ '关联的输入框是否禁用。将禁用样式传递给标签。',+ default: 'false',+ },{name: 'description',type: 'string',@@ -434,12 +488,42 @@ const bioDescId = useId();description:'在标签末尾的信息图标中显示的工具提示文本。',},+ {+ name: 'status',+ type: 'XDSFieldStatus',+ description:+ '状态指示器,包含类型和可选消息。设置消息时显示彩色状态框。',+ },+ {+ name: 'statusVariant',+ type: "'attached' | 'detached'",+ description:+ '状态消息相对于输入框的渲染方式。attached 覆盖输入框边框;detached 浮动在下方。',+ default: "'attached'",+ },+ {+ name: 'ref',+ type: 'React.Ref<HTMLDivElement>',+ description: '转发到根元素的 ref。',+ },{name: 'xstyle',type: 'StyleXStyles',description:'用于布局自定义(外边距、定位、尺寸)的 StyleX 样式。必须是 stylex.create() 的值,而非内联样式对象如 style={{}}。',},+ {+ name: 'className',+ type: 'string',+ description:+ '附加到根元素的 CSS 类名。优先使用 xstyle 以获得 StyleX 样式去重。',+ },+ {+ name: 'style',+ type: 'React.CSSProperties',+ description:+ '应用到根元素的内联样式。优先于 StyleX 内联样式。',+ },],},{@@ -550,6 +634,8 @@ export const docsDense = {'Optional description text between label + input','Optional/Required indicators w/ bullet separator','Label tooltip; optional info icon w/ tooltip at end of label',+ 'Disabled state; propagates disabled styling to label',+ 'Status messages; attached/detached validation feedback w/ role="status" + aria-live="polite"','Label properly associated w/ input via htmlFor/id','Styled w/ StyleX; uses XDS design tokens for consistent styling',],@@ -558,8 +644,11 @@ export const docsDense = {'Label always rendered for a11y; use isLabelHidden to hide visually.','Hidden label uses CSS technique accessible to screen readers.','Description rendered when provided; descriptionID sets element ID for aria-describedby.',- 'isOptional + isRequired mutually exclusive; both set shows "Optional".',+ 'isOptional + isRequired mutually exclusive; both set shows "Optional" (dev warning).','Optional/Required text on same line as label.',+ 'Status messages use role="status" + aria-live="polite" for screen reader announcements.',+ 'statusVariant="attached" (default) for bordered inputs; "detached" for checkboxes/switches/sliders.',+ 'isDisabled propagates disabled styling to label (color + cursor).',],components: [{@@ -570,13 +659,19 @@ export const docsDense = {inputID: 'Input element ID (used for label htmlFor).',children: 'Input or control to render.',isLabelHidden: 'Visually hide label (still accessible to screen readers).',+ isDisabled: 'Associated input disabled. Propagates disabled styling to label.',description: 'Description text between label + input.',descriptionID: 'ID for description element (use for aria-describedby on input).',isOptional: 'Field optional (mutually exclusive w/ isRequired).',isRequired: 'Field required (mutually exclusive w/ isOptional).',labelIcon: 'Icon before label text.',labelTooltip: 'Tooltip text in info icon at end of label.',+ status: 'Status indicator w/ type + optional message. Shows colored status box.',+ statusVariant: 'Status render mode; attached overlaps input, detached floats below.',+ ref: 'Ref forwarded to root element.',xstyle: 'StyleX styles for layout customization. Must be stylex.create() value.',+ className: 'CSS class name(s) appended to root element.',+ style: 'Inline styles applied to root element.',},},{diff --git a/packages/core/src/Field/XDSField.test.tsx b/packages/core/src/Field/XDSField.test.tsxindex 54fe995a06..296a212092 100644--- a/packages/core/src/Field/XDSField.test.tsx+++ b/packages/core/src/Field/XDSField.test.tsx@@ -111,7 +111,7 @@ describe('XDSField', () => {);const description = screen.getByText('Description text');expect(description).toBeInTheDocument();- expect(description).not.toHaveAttribute('id');+ expect(description).toHaveAttribute('id', 'email-input-desc');});it('renders Optional text when isOptional is set', () => {@@ -171,7 +171,10 @@ describe('XDSField', () => {</XDSField>,);expect(screen.getByText('Name')).toBeInTheDocument();- expect(screen.getByText(/∙.*Optional/)).toBeInTheDocument();+ expect(+ screen.getByText('∙', {selector: '[aria-hidden="true"]'}),+ ).toBeInTheDocument();+ expect(screen.getByText(/Optional/)).toBeInTheDocument();});it('renders tooltip info icon when labelTooltip is provided', () => {@@ -192,4 +195,69 @@ describe('XDSField', () => {);expect(document.querySelector('svg')).not.toBeInTheDocument();});++ it('status has role="alert" and aria-live="assertive" for error type', () => {+ render(+ <XDSField+ label="Email"+ inputID="email-input"+ status={{type: 'error', message: 'Invalid email'}}>+ <input id="email-input" />+ </XDSField>,+ );+ const status = screen.getByRole('alert');+ expect(status).toHaveTextContent('Invalid email');+ expect(status).toHaveAttribute('aria-live', 'assertive');+ });++ it('status has role="status" and aria-live="polite" for warning type', () => {+ render(+ <XDSField+ label="Email"+ inputID="email-input"+ status={{type: 'warning', message: 'Check this'}}>+ <input id="email-input" />+ </XDSField>,+ );+ const status = screen.getByRole('status');+ expect(status).toHaveTextContent('Check this');+ expect(status).toHaveAttribute('aria-live', 'polite');+ });++ it('auto-generates description ID as {inputID}-desc when descriptionID is not provided', () => {+ render(+ <XDSField label="Email" inputID="my-input" description="Help text">+ <input id="my-input" />+ </XDSField>,+ );+ expect(screen.getByText('Help text')).toHaveAttribute(+ 'id',+ 'my-input-desc',+ );+ });++ it('auto-generates status message ID as {inputID}-status when messageID is not provided', () => {+ render(+ <XDSField+ label="Email"+ inputID="my-input"+ status={{type: 'error', message: 'Required'}}>+ <input id="my-input" />+ </XDSField>,+ );+ expect(screen.getByRole('alert')).toHaveAttribute('id', 'my-input-status');+ });++ it('warns when isOptional and isRequired are both set', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(+ <XDSField label="Name" inputID="name-input" isOptional isRequired>+ <input id="name-input" />+ </XDSField>,+ );+ expect(warnSpy).toHaveBeenCalledWith(+ 'XDSField: isOptional and isRequired are mutually exclusive. isOptional takes precedence.',+ );+ warnSpy.mockRestore();+ });});diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsxindex c509bb2777..bc50966972 100644--- a/packages/core/src/Field/XDSField.tsx+++ b/packages/core/src/Field/XDSField.tsx@@ -13,7 +13,6 @@* - /apps/storybook/stories/Field.stories.tsx (storybook stories)*/-import {type HTMLAttributes, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';@@ -22,6 +21,7 @@ import {XDSFieldStatus} from './XDSFieldStatus';import {colorVars,fontWeightVars,+ lineHeightVars,spacingVars,typographyVars,typeScaleVars,@@ -35,17 +35,6 @@ const styles = stylex.create({flexDirection: 'column',gap: spacingVars['--spacing-1'],},- labelRow: {- display: 'flex',- flexDirection: 'row',- alignItems: 'baseline',- },- label: {- fontFamily: typographyVars['--font-body'],- fontSize: typeScaleVars['--text-body-size'],- fontWeight: fontWeightVars['--font-weight-medium'],- color: colorVars['--color-text-primary'],- },labelHidden: {borderStyle: 'none',clip: 'rect(0, 0, 0, 0)',@@ -64,14 +53,10 @@ const styles = stylex.create({description: {fontFamily: typographyVars['--font-body'],fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: lineHeightVars['--leading-snug'],+ fontWeight: fontWeightVars['--font-weight-normal'],color: colorVars['--color-text-secondary'],},- optionalRequired: {- fontFamily: typographyVars['--font-body'],- fontSize: typeScaleVars['--text-supporting-size'],- color: colorVars['--color-text-secondary'],- marginInlineStart: spacingVars['--spacing-1'],- },inputStatusWrapper: {display: 'flex',flexDirection: 'column',@@ -211,6 +196,17 @@ export function XDSField({ref,...props}: XDSFieldProps) {+ const resolvedDescriptionID =+ descriptionID ?? (description ? `${inputID}-desc` : undefined);+ const resolvedMessageID =+ status?.messageID ?? (status?.message ? `${inputID}-status` : undefined);++ if (isOptional && isRequired) {+ console.warn(+ 'XDSField: isOptional and isRequired are mutually exclusive. isOptional takes precedence.',+ );+ }+return (<divref={ref}@@ -232,7 +228,7 @@ export function XDSField({/>{description && (<span- id={descriptionID}+ id={resolvedDescriptionID}{...stylex.props(styles.description,isLabelHidden && styles.labelHidden,@@ -247,7 +243,7 @@ export function XDSField({<XDSFieldStatustype={status.type}message={status.message}- id={status.messageID}+ id={resolvedMessageID}variant="attached"/>)}@@ -259,7 +255,7 @@ export function XDSField({<XDSFieldStatustype={status.type}message={status.message}- id={status.messageID}+ id={resolvedMessageID}variant="detached"/>)}diff --git a/packages/core/src/Field/XDSFieldLabel.tsx b/packages/core/src/Field/XDSFieldLabel.tsxindex ffd5ca92eb..9d2f4bb541 100644--- a/packages/core/src/Field/XDSFieldLabel.tsx+++ b/packages/core/src/Field/XDSFieldLabel.tsx@@ -30,10 +30,15 @@ const styles = stylex.create({fontFamily: typographyVars['--font-body'],fontSize: typeScaleVars['--text-label-size'],fontWeight: fontWeightVars['--font-weight-medium'],- color: colorVars['--color-text-primary'],- },- labelClickable: {- cursor: 'pointer',+ color: {+ default: colorVars['--color-text-primary'],+ [stylex.when.ancestor(':has(:disabled)')]:+ colorVars['--color-text-disabled'],+ },+ cursor: {+ default: 'pointer',+ [stylex.when.ancestor(':has(:disabled)')]: 'not-allowed',+ },},labelDisabled: {color: colorVars['--color-text-disabled'],@@ -132,29 +137,21 @@ export function XDSFieldLabel({xdsClassName('field-label'),stylex.props(styles.label,- !isDisabled && styles.labelClickable,isDisabled && styles.labelDisabled,isLabelHidden && styles.labelHidden,),)}>- {labelIcon && (- <XDSIcon- icon={labelIcon}- size="sm"- color={isDisabled ? 'disabled' : 'primary'}- />- )}+ {labelIcon && <XDSIcon icon={labelIcon} size="sm" color="inherit" />}{label}{statusText && (- <span {...stylex.props(styles.optionalRequired)}> ∙ {statusText}</span>+ <span {...stylex.props(styles.optionalRequired)}>+ <span aria-hidden="true"> ∙ </span>+ {statusText}+ </span>)}{labelTooltip && (<XDSTooltip content={labelTooltip} placement="above">- <XDSIcon- icon="info"- size="sm"- color={isDisabled ? 'disabled' : 'secondary'}- />+ <XDSIcon icon="info" size="sm" color="inherit" /></XDSTooltip>)}</label>diff --git a/packages/core/src/Field/XDSFieldStatus.tsx b/packages/core/src/Field/XDSFieldStatus.tsxindex ebe5239466..2d4544b77c 100644--- a/packages/core/src/Field/XDSFieldStatus.tsx+++ b/packages/core/src/Field/XDSFieldStatus.tsx@@ -28,9 +28,9 @@ const styles = stylex.create({lineHeight: lineHeightVars['--leading-snug'],},attached: {- marginTop: -6,- paddingBlockStart: 14,- paddingBlockEnd: 8,+ marginTop: `calc(-1 * ${spacingVars['--spacing-1-5']})`,+ paddingBlockStart: `calc(${spacingVars['--spacing-1-5']} + ${spacingVars['--spacing-2']})`,+ paddingBlockEnd: spacingVars['--spacing-2'],paddingInline: spacingVars['--spacing-2'],borderBottomLeftRadius: radiusVars['--radius-2'],borderBottomRightRadius: radiusVars['--radius-2'],@@ -128,6 +128,8 @@ export function XDSFieldStatus({return (<divid={id}+ role={type === 'error' ? 'alert' : 'status'}+ aria-live={type === 'error' ? 'assertive' : 'polite'}{...mergeProps(xdsClassName('field-status', {type, variant}),stylex.props(diff --git a/packages/core/src/Field/inputStyles.stylex.ts b/packages/core/src/Field/inputStyles.stylex.tsindex 8be574be64..6cd02dd2d1 100644--- a/packages/core/src/Field/inputStyles.stylex.ts+++ b/packages/core/src/Field/inputStyles.stylex.ts@@ -47,7 +47,10 @@ export const inputWrapperStyles = stylex.create({borderRadius: 'var(--input-radius)',backgroundColor: colorVars['--color-surface'],transitionProperty: 'border-color, outline, box-shadow',- transitionDuration: durationVars['--duration-fast'],+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },transitionTimingFunction: easeVars['--ease-standard'],boxShadow: {default: 'none',