An open source design system that's fully customizable and agent ready
TypeScript
fix(TimeInput): disabled fields stay focusable (#7898)
Cindy Zhang6e266c28d6c6
diff --git a/.changeset/time-input-focusable-disabled.md b/.changeset/time-input-focusable-disabled.mdnew file mode 100644index 0000000000..c0542c40c2--- /dev/null+++ b/.changeset/time-input-focusable-disabled.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] TimeInput: a disabled field, or a busy bottom-sheet field, no longer renders native `disabled` on its typed, native-picker or touch input or its picker button. They keep their place in the focus order and expose `aria-disabled`, while typing, arrow-key adjustment, opening, submitting a surrounding form with Enter, and a caller's `onClick` stay blocked, a draft typed before the field became disabled is dropped, and a focused disabled field shows its focus ring. This meets the focusable-disabled requirement in spec:AST-085 (FR1, FR2, FR6). Tests that query a disabled or busy TimeInput with `toBeDisabled()` or `:disabled` should check `aria-disabled="true"` instead.++@cixzhangdiff --git a/apps/storybook/stories/TimeInput.stories.tsx b/apps/storybook/stories/TimeInput.stories.tsxindex 98d6a1c7e8..eaa0b16fd3 100644--- a/apps/storybook/stories/TimeInput.stories.tsx+++ b/apps/storybook/stories/TimeInput.stories.tsx@@ -47,7 +47,7 @@ const meta: Meta<typeof TimeInput> = {disabledMessage: {control: 'text',description:- 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the field focusable via aria-disabled (activation stays blocked). Use this instead of wrapping a disabled TimeInput in Tooltip.',+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and describes the input (activation stays blocked). Use this instead of wrapping a disabled TimeInput in Tooltip.',},size: {control: 'radio',@@ -277,9 +277,9 @@ export const Disabled: Story = {// Disabled with an explanation tooltip. Hover or keyboard-focus the field to// see why it's disabled — the reason is announced to assistive tech via-// aria-describedby, and the field stays focusable (activation is still-// blocked). Use disabledMessage instead of wrapping a disabled TimeInput in Tooltip:-// disabled controls swallow the pointer events a Tooltip wrapper needs.+// aria-describedby (activation is still blocked). Use disabledMessage instead+// of wrapping a disabled TimeInput in Tooltip, so the reason is tied to the+// field.export const DisabledWithMessage: Story = {render: args => {const [value, setValue] = useState<ISOTimeString | undefined>(undefined);diff --git a/packages/core/src/TimeInput/NativeTimeInput.test.tsx b/packages/core/src/TimeInput/NativeTimeInput.test.tsxindex c66a7f0d4a..b25abd871d 100644--- a/packages/core/src/TimeInput/NativeTimeInput.test.tsx+++ b/packages/core/src/TimeInput/NativeTimeInput.test.tsx@@ -241,6 +241,28 @@ describe('TimeInput nativePicker', () => {expect(input.getAttribute('aria-describedby')).toContain(tooltip?.id);});+ it('keeps a disabled native field focusable without native disabled (AST-085 FR1, FR2)', () => {+ stubPointer(true);+ const onClick = vi.fn();+ render(+ <TimeInput+ label="Start time"+ nativePicker="always"+ isDisabled+ onClick={onClick}+ onChange={() => {}}+ />,+ );+ const input = getNativeTimeInput();+ expect(input).not.toHaveAttribute('disabled');+ expect(input).toHaveAttribute('aria-disabled', 'true');+ expect(input).toHaveAttribute('readonly');+ input.focus();+ expect(input).toHaveFocus();+ fireEvent.click(input);+ expect(onClick).not.toHaveBeenCalled();+ });+it('forwards refs and autofocus to the native input', () => {stubPointer(true);const ref = vi.fn();diff --git a/packages/core/src/TimeInput/Presentation.test.tsx b/packages/core/src/TimeInput/Presentation.test.tsxindex 0875e367c5..48f6bef723 100644--- a/packages/core/src/TimeInput/Presentation.test.tsx+++ b/packages/core/src/TimeInput/Presentation.test.tsx@@ -96,6 +96,29 @@ describe('TimeInput presentation', () => {expect(screen.getByRole('listbox', {name: 'Minute'})).toBeInTheDocument();});+ it('bottom-sheet: a disabled field stays focusable and inert (AST-085 FR1, FR2)', () => {+ stubPointer(false);+ const onClick = vi.fn();+ render(+ <TimeInput+ label="Start"+ presentation="bottom-sheet"+ isDisabled+ onClick={onClick}+ onChange={() => {}}+ />,+ );+ const input = screen.getByRole('combobox', {name: 'Start'});+ expect(input).not.toHaveAttribute('disabled');+ expect(input).toHaveAttribute('aria-disabled', 'true');+ input.focus();+ expect(input).toHaveFocus();+ fireEvent.click(input);+ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('listbox', {name: 'Hour'})).toBeNull();+ expect(onClick).not.toHaveBeenCalled();+ });+it('adaptive-bottom-sheet: typed on fine, sheet on coarse', () => {stubPointer(false);const {unmount} = render(diff --git a/packages/core/src/TimeInput/TimeInput.doc.mjs b/packages/core/src/TimeInput/TimeInput.doc.mjsindex 5622fa0623..4554cbe21e 100644--- a/packages/core/src/TimeInput/TimeInput.doc.mjs+++ b/packages/core/src/TimeInput/TimeInput.doc.mjs@@ -71,7 +71,7 @@ export const docs = {{guidance: false,description:- 'Wrap a disabled TimeInput in Tooltip to explain why it is disabled; disabled triggers swallow the hover events the wrapper needs. Use the disabledMessage prop instead.',+ 'Wrap a disabled TimeInput in Tooltip to explain why it is disabled. Use the disabledMessage prop instead, which ties the reason to the field.',},],anatomy: [@@ -144,14 +144,15 @@ export const docs = {{name: 'isDisabled',type: 'boolean',- description: 'Disables the input and suppresses interactions.',+ description:+ 'Disables the input and suppresses interactions. The input stays focusable and exposes `aria-disabled`.',default: 'false',},{name: 'disabledMessage',type: 'string',description:- 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the field focusable via aria-disabled (activation stays blocked). Use this instead of wrapping a disabled TimeInput in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and describes the input (activation stays blocked). Use this instead of wrapping a disabled TimeInput in Tooltip.',},{name: 'value',@@ -329,14 +330,14 @@ export const docsZh = {{name: 'isDisabled',type: 'boolean',- description: '禁用输入框并抑制交互。',+ description: '禁用输入框并抑制交互。输入框仍可聚焦并暴露 `aria-disabled`。',default: 'false',},{name: 'disabledMessage',type: 'string',description:- '说明输入框为何被禁用。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示提示,并通过 aria-disabled 保持输入框可聚焦(仍阻止输入和调整)。请使用此属性,而不是用 Tooltip 包裹已禁用的 TimeInput。',+ '说明输入框为何被禁用。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示提示,并描述输入框(仍阻止输入和调整)。请使用此属性,而不是用 Tooltip 包裹已禁用的 TimeInput。',},{name: 'value',@@ -510,7 +511,7 @@ export const docsZh = {{guidance: false,description:- 'Wrap a disabled TimeInput in Tooltip to explain why it is disabled; disabled triggers swallow the hover events the wrapper needs. Use the disabledMessage prop instead.',+ 'Wrap a disabled TimeInput in Tooltip to explain why it is disabled. Use the disabledMessage prop instead, which ties the reason to the field.',},],anatomy: [@@ -612,7 +613,7 @@ export const docsDense = {'Marks required+sets aria-required. Mutually exclusive w/ isOptional.',isDisabled: 'Disables input, suppresses interactions.',disabledMessage:- 'Reason shown in a tooltip on hover/focus when disabled; keeps input focusable via aria-disabled.',+ 'Reason shown in a tooltip on hover/focus when disabled; describes the input.',value: 'Controlled time in ISO format (HH:MM or HH:MM:SS).',onChange: 'Fired on time change. Receives undefined when cleared.',changeAction:diff --git a/packages/core/src/TimeInput/TimeInput.test.tsx b/packages/core/src/TimeInput/TimeInput.test.tsxindex 99449d21c7..8f869f5790 100644--- a/packages/core/src/TimeInput/TimeInput.test.tsx+++ b/packages/core/src/TimeInput/TimeInput.test.tsx@@ -10,8 +10,10 @@*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {render, screen, fireEvent, waitFor} from '@testing-library/react';+import {act, render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';+import {colorVars} from '../theme/tokens.stylex';import {TimeInput} from './TimeInput';import {InputGroup, InputGroupText} from '../InputGroup';import {InternationalizationProvider} from '../i18n';@@ -141,9 +143,41 @@ describe('TimeInput', () => {);});- it('disables input when isDisabled is true', () => {+ it('keeps a disabled input focusable without native disabled (AST-085 FR1)', () => {render(<TimeInput label="Time" isDisabled onChange={() => {}} />);- expect(screen.getByRole('textbox')).toBeDisabled();+ const input = screen.getByRole('textbox');+ expect(input).not.toHaveAttribute('disabled');+ expect(input).toHaveAttribute('aria-disabled', 'true');+ expect(input).toHaveAttribute('readonly');+ input.focus();+ expect(input).toHaveFocus();+ });++ it('restores the focus ring on a focused disabled field (AST-085 FR6)', () => {+ // The same declarations as the field's ring style compile to the same+ // atomic classes; the shared disabled style alone drops them.+ const ringClasses = stylex+ .props(+ stylex.create({+ ring: {+ borderColor: {+ default: colorVars['--color-border-emphasized'],+ ':focus-within': colorVars['--color-accent'],+ },+ boxShadow: {+ default: 'none',+ ':focus-within': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },+ }).ring,+ )+ .className!.split(' ')+ .filter(name => !name.includes('__'));+ render(<TimeInput label="Time" isDisabled onChange={() => {}} />);+ const wrapper = screen.getByRole('textbox').closest('.astryx-time-input')!;+ for (const name of ringClasses) {+ expect(wrapper).toHaveClass(name);+ }});it('shows clear button when hasClear is true and value exists', () => {@@ -645,11 +679,89 @@ describe('TimeInput', () => {expect(onChange).not.toHaveBeenCalled();});- it('remains natively disabled when disabled without a reason', () => {- render(<TimeInput label="Time" isDisabled />);+ it('blocks typing, arrows and a caller onClick when disabled without a reason (AST-085 FR2)', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const onClick = vi.fn();+ render(+ <TimeInput+ label="Time"+ value={'09:00' as ISOTimeString}+ onChange={onChange}+ onClick={onClick}+ isDisabled+ />,+ );+ const input = screen.getByLabelText('Time');+ await user.click(input);+ await user.type(input, '1');+ await user.keyboard('{ArrowUp}');+ await user.tab();+ expect(onChange).not.toHaveBeenCalled();+ expect(onClick).not.toHaveBeenCalled();+ });++ it.each([+ ['text-input', false, {isDisabled: true}],+ ['native', true, {isDisabled: true}],+ ['bottom-sheet', true, {isDisabled: true}],+ ['bottom-sheet', true, {isLoading: true}],+ ] as const)(+ 'does not submit a surrounding form on Enter: %s (coarse %s) %o (AST-085 FR2)',+ async (presentation, isCoarse, state) => {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: /pointer:\s*coarse/.test(query)+ ? isCoarse+ : /pointer:\s*fine/.test(query) && !isCoarse,+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ }));+ const user = userEvent.setup();+ const onSubmit = vi.fn((e: React.FormEvent) => e.preventDefault());+ render(+ <form onSubmit={onSubmit}>+ <TimeInput+ label="Time"+ presentation={presentation}+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ {...state}+ />+ <button type="submit">Save</button>+ </form>,+ );+ try {+ const input = document.querySelector<HTMLInputElement>(+ '.astryx-time-input input:not([type=hidden])',+ )!;+ act(() => input.focus());+ await user.keyboard('{Enter}');+ expect(onSubmit).not.toHaveBeenCalled();+ } finally {+ vi.unstubAllGlobals();+ }+ },+ );++ it('drops a draft instead of committing it when the field becomes disabled (AST-085 FR2)', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const value = '09:00' as ISOTimeString;+ const {rerender} = render(+ <TimeInput label="Time" value={value} onChange={onChange} />,+ );const input = screen.getByLabelText('Time');- expect(input).toBeDisabled();- expect(input).not.toHaveAttribute('aria-disabled');+ await user.click(input);+ await user.clear(input);+ onChange.mockClear();+ rerender(+ <TimeInput label="Time" value={value} onChange={onChange} isDisabled />,+ );+ await user.tab();+ expect(onChange).not.toHaveBeenCalled();});it('does not swap in the format-hint placeholder on focus while disabled', () => {diff --git a/packages/core/src/TimeInput/TimeInput.tsx b/packages/core/src/TimeInput/TimeInput.tsxindex 9408403c21..d0e3531ea8 100644--- a/packages/core/src/TimeInput/TimeInput.tsx+++ b/packages/core/src/TimeInput/TimeInput.tsx@@ -93,6 +93,18 @@ import {useDevWarning} from '../hooks/useDevWarning';const TOUCH_POINTER_QUERY = '(pointer: coarse)';const styles = stylex.create({+ // The shared disabled style drops the focus ring; restore it while a+ // control inside the field holds focus (spec:AST-085 FR6). Defaults repeat it.+ disabledFocusRing: {+ borderColor: {+ default: colorVars['--color-border-emphasized'],+ ':focus-within': colorVars['--color-accent'],+ },+ boxShadow: {+ default: 'none',+ ':focus-within': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },icon: {display: 'flex',alignItems: 'center',@@ -207,12 +219,12 @@ export interface TimeInputProps extends Omit</*** Explains why the input is disabled. When set together with* `isDisabled`, the input shows a tooltip with this text on hover and- * keyboard focus, and the field stays focusable (via `aria-disabled`)- * so the reason is discoverable by keyboard and assistive technology.- * Typing and arrow-key adjustment stay blocked.+ * keyboard focus, and the input is described by it, so the reason is+ * discoverable by keyboard and assistive technology. Typing and arrow-key+ * adjustment stay blocked.*- * Use this instead of wrapping a disabled input in `Tooltip` — disabled- * controls don't emit the pointer events an external tooltip needs.+ * Use this instead of wrapping a disabled input in `Tooltip`, so the+ * reason is tied to the field.** @example* ```@@ -479,10 +491,10 @@ function TimeField({}}, [announce, inputGroup, status?.message, status?.type]);- // Disabled-reason tooltip. Disabled controls swallow pointer events, so the- // tooltip listeners attach to the input container (which already exists) and- // the input stays perceivable via aria-disabled instead of the disabled- // attribute. Typing is blocked with readOnly and value mutation guards.+ // A disabled field never renders native `disabled` (spec:AST-085 FR1): the+ // input stays focusable via aria-disabled, and readOnly plus the value+ // mutation guards block typing. The disabled-reason tooltip's listeners+ // attach to the input container.const showsDisabledMessage = isDisabled && !!disabledMessage;const disabledMessageTooltip = useTooltip({placement: 'above',@@ -577,8 +589,8 @@ function TimeField({// Handle input text change - update immediately if validconst handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {- // With a disabledMessage the input drops `disabled` for focusability, so- // guard value mutation explicitly (readOnly also blocks typing).+ // The input is never natively disabled (spec:AST-085 FR1), so guard+ // value mutation explicitly (readOnly also blocks typing).if (isDisabled) {return;}@@ -613,6 +625,11 @@ function TimeField({if (pendingInput === null) {return;}+ // Disabled: keep the value, drop the draft (spec:AST-085 FR2).+ if (isDisabled) {+ setPendingInput(null);+ return;+ }if (!pendingInput.trim()) {// Empty input clears the value@@ -633,10 +650,17 @@ function TimeField({// Clear pending input - display will revert to formatted valuesetPendingInput(null);},- [pendingInput, value, fireChange, hasSeconds, min, max],+ [pendingInput, isDisabled, value, fireChange, hasSeconds, min, max],);// Handle keyboard navigation on input+ // Enter in a focused disabled field would submit a surrounding form (FR2).+ const preventDisabledEnter = (e: KeyboardEvent<HTMLInputElement>) => {+ if (isDisabled && e.key === 'Enter') {+ e.preventDefault();+ }+ };+const handleInputKeyDown = useCallback((e: KeyboardEvent<HTMLInputElement>) => {// ArrowUp/ArrowDown step the time and preventDefault; an IME candidate@@ -646,8 +670,7 @@ function TimeField({if (isImeKeyEvent(e.nativeEvent)) {return;}- // Arrow-key adjustment mutates the value; block it while showing a- // disabled reason (the input keeps focusability via aria-disabled).+ // Arrow-key adjustment mutates the value; block it while disabled.if (isDisabled) {return;}@@ -744,6 +767,7 @@ function TimeField({inputWrapperStyles.base,sizeStyles[size],isDisabled && inputWrapperStyles.disabled,+ isDisabled && styles.disabledFocusRing,status && inputStatusBorderStyles[status.type],status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],@@ -778,7 +802,7 @@ function TimeField({max={max}hourFormat={hourFormat}isEffectivelyDisabled={isDisabled}- isFocusableDisabled={showsDisabledMessage}+ isFocusableDisabledisEffectivelyRequired={isEffectivelyRequired}isBusy={isBusy}statusType={status?.type}@@ -787,7 +811,8 @@ function TimeField({...controlProps,onFocus: onFocusProp,onBlur: onBlurProp,- onKeyDown: onKeyDownProp,+ onKeyDown: chainEventHandlers(preventDisabledEnter, onKeyDownProp),+ onClick: isDisabled ? undefined : controlProps.onClick,}}/>) : (@@ -804,14 +829,17 @@ function TimeField({onChange={handleInputChange}onFocus={chainEventHandlers(handleFocus, onFocusProp)}onBlur={chainEventHandlers(handleBlur, onBlurProp)}- onKeyDown={chainEventHandlers(handleInputKeyDown, onKeyDownProp)}+ onKeyDown={chainEventHandlers(+ preventDisabledEnter,+ handleInputKeyDown,+ onKeyDownProp,+ )}placeholder={displayPlaceholder}- // With a disabledMessage the input keeps focusability via- // aria-disabled so the reason is focus-discoverable; typing and- // arrow-key adjustment are blocked with readOnly and the guards.- disabled={isDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}- readOnly={showsDisabledMessage || undefined}+ aria-disabled={isDisabled ? 'true' : undefined}+ readOnly={isDisabled || undefined}+ // The browser still dispatches a click on an aria-disabled input,+ // so a caller's onClick is skipped too (spec:AST-085 FR2).+ onClick={isDisabled ? undefined : controlProps.onClick}autoFocus={hasAutoFocus}data-autofocus={hasAutoFocus || undefined}aria-describedby={ariaDescribedBy}diff --git a/packages/core/src/TimeInput/TouchTimeField.tsx b/packages/core/src/TimeInput/TouchTimeField.tsxindex 7e858ef983..69461ba520 100644--- a/packages/core/src/TimeInput/TouchTimeField.tsx+++ b/packages/core/src/TimeInput/TouchTimeField.tsx@@ -24,6 +24,7 @@ import {useRef,useState,useTransition,+ type KeyboardEvent,} from 'react';import * as stylex from '@stylexjs/stylex';import {BottomSheet} from '../BottomSheet';@@ -45,7 +46,7 @@ import {useMergedRefs} from '../hooks/useMergedRefs';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {Icon} from '../Icon';import {useTranslator} from '../i18n';-import {sizeVars, spacingVars} from '../theme/tokens.stylex';+import {colorVars, sizeVars, spacingVars} from '../theme/tokens.stylex';import {useSize} from '../SizeContext/SizeContext';import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';@@ -74,6 +75,17 @@ const sizeStyles = stylex.create({});const styles = stylex.create({+ // Same as TimeInput's: the focus ring for a focused disabled field.+ disabledFocusRing: {+ borderColor: {+ default: colorVars['--color-border-emphasized'],+ ':focus-within': colorVars['--color-accent'],+ },+ boxShadow: {+ default: 'none',+ ':focus-within': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },iconButton: {display: 'flex',alignItems: 'center',@@ -447,6 +459,7 @@ export function TouchTimeField({inputWrapperStyles.base,sizeStyles[size],isDisabled && inputWrapperStyles.disabled,+ isDisabled && styles.disabledFocusRing,status && inputStatusBorderStyles[status.type],status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],@@ -459,7 +472,7 @@ export function TouchTimeField({<buttontype="button"onClick={openSheet}- disabled={isEffectivelyDisabled}+ aria-disabled={isEffectivelyDisabled || undefined}aria-label={t('@astryx.timeInput.openPicker', {label})}tabIndex={-1}{...stylex.props(focusOutlineStyles.focusVisible, styles.iconButton)}>@@ -475,10 +488,19 @@ export function TouchTimeField({readOnlyinputMode="none"onChange={() => {}}- onClick={chainEventHandlers(openSheet, onClickProp)}+ onClick={+ isEffectivelyDisabled+ ? undefined+ : chainEventHandlers(openSheet, onClickProp)+ }+ // Enter would submit a surrounding form while disabled (FR2).+ onKeyDown={chainEventHandlers((e: KeyboardEvent<HTMLInputElement>) => {+ if (isEffectivelyDisabled && e.key === 'Enter') {+ e.preventDefault();+ }+ }, controlProps.onKeyDown)}placeholder={placeholder}- disabled={isEffectivelyDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}+ aria-disabled={isEffectivelyDisabled ? 'true' : undefined}aria-describedby={ariaDescribedBy}aria-required={isEffectivelyRequired ? 'true' : undefined}aria-invalid={status?.type === 'error' ? 'true' : undefined}