Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(NumberInput): a disabled field stays in the tab order (#8099)

Cindy Zhang92697387b225
diff --git a/.changeset/number-input-focusable-disabled.md b/.changeset/number-input-focusable-disabled.md
new file mode 100644
index 0000000000..63b2d6745f
--- /dev/null
+++ b/.changeset/number-input-focusable-disabled.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] NumberInput: a disabled field now keeps its place in the tab order, so keyboard and screen-reader users can reach it and hear that it is unavailable (WCAG 2.2 SC 2.1.1 Keyboard, 4.1.2 Name, Role, Value and 2.4.7 Focus Visible; `spec:AST-085` FR1–FR3 and FR6). It exposes `aria-disabled="true"` and is read-only instead of carrying the native `disabled` attribute, as it already did with a `disabledMessage`; it is still dimmed, cannot be edited or stepped, and is left out of form submission. Like a natively disabled field, it runs no caller event handler other than focus and blur, and Enter does not submit its form. Its number steppers expose `aria-disabled` too, and under keyboard focus the field shows its focus ring, dimmed with the rest of the field. The Pagination page box follows.
+
+Part of #7814.
+
+@cixzhang
diff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsx
index 95ce1162d0..f2ddd7a254 100644
--- a/apps/storybook/stories/NumberInput.stories.tsx
+++ b/apps/storybook/stories/NumberInput.stories.tsx
@@ -54,7 +54,7 @@ const meta: Meta<typeof NumberInput> = {
isReadOnly: {
control: 'boolean',
description:
- 'Whether the input is read-only. The value still submits with the form but cannot be edited. Unlike isDisabled it is not dimmed and stays in the tab order.',
+ 'Whether the input is read-only. The value still submits with the form but cannot be edited. Unlike isDisabled it is not dimmed and keeps its form value.',
},
disabledMessage: {
control: 'text',
@@ -428,7 +428,7 @@ export const RequiredField: Story = {
};
// Read-only shows a value the user should see and send but not change. Unlike
-// a disabled field it is not dimmed, stays in the tab order, and still submits.
+// a disabled field it is not dimmed and still submits.
export const ReadOnly: Story = {
render: args => {
const [value, setValue] = useState<number | null>(args.value ?? 1024);
diff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjs
index 544d59628f..eb33db907e 100644
--- a/packages/core/src/NumberInput/NumberInput.doc.mjs
+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs
@@ -81,7 +81,7 @@ export const docs = {
name: 'isReadOnly',
type: 'boolean',
description:
- 'Makes the input read-only: the value is shown at full opacity and still submits with the form, but cannot be edited. Unlike isDisabled, a read-only input is not dimmed and stays in the tab order. Stepping is off in every form while read-only: arrow keys, the wheel, and the number steppers. isDisabled takes precedence when both are set.',
+ 'Makes the input read-only: the value is shown at full opacity and still submits with the form, but cannot be edited. Unlike isDisabled, a read-only input is not dimmed and keeps its form value. Stepping is off in every form while read-only: arrow keys, the wheel, and the number steppers. isDisabled takes precedence when both are set.',
default: 'false',
},
{
@@ -308,7 +308,7 @@ export const docs = {
{
guidance: false,
description:
- "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled. Use the disabledMessage prop, which attaches the reason to the field itself.",
},
],
anatomy: [
@@ -401,7 +401,7 @@ export const docsZh = {
name: 'isReadOnly',
type: 'boolean',
description:
- '将输入框设为只读:值以完整不透明度显示并仍随表单提交,但无法编辑。与 isDisabled 不同,只读输入框不会变暗,并保留在 Tab 顺序中。只读时所有步进方式均被禁用:方向键、滚轮和步进按钮。同时设置时 isDisabled 优先。',
+ '将输入框设为只读:值以完整不透明度显示并仍随表单提交,但无法编辑。与 isDisabled 不同,只读输入框不会变暗,并保留其表单值。只读时所有步进方式均被禁用:方向键、滚轮和步进按钮。同时设置时 isDisabled 优先。',
default: 'false',
},
{
@@ -613,7 +613,7 @@ export const docsZh = {
{
guidance: false,
description:
- "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled. Use the disabledMessage prop, which attaches the reason to the field itself.",
},
],
anatomy: [
@@ -687,7 +687,7 @@ export const docsDense = {
{
guidance: false,
description:
- "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled. Use the disabledMessage prop, which attaches the reason to the field itself.",
},
],
anatomy: [
@@ -737,7 +737,7 @@ export const docsDense = {
isRequired: 'Field required (mutually exclusive w/ isOptional).',
isDisabled: 'Input disabled.',
isReadOnly:
- 'Read-only: value visible + still submits, but not editable. Unlike isDisabled: not dimmed, stays in tab order.',
+ 'Read-only: value visible + still submits, but not editable. Unlike isDisabled: not dimmed.',
disabledMessage:
'Explains why input is disabled. With isDisabled, shows tooltip on hover/focus + keeps input focusable via aria-disabled (field becomes read-only). Use instead of wrapping a disabled NumberInput in Tooltip.',
placeholder: 'Placeholder text.',
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 48cd494556..0badae9747 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -13,6 +13,8 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {act, useState} from 'react';
import {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 {TestIcon} from '../__tests__/TestIcon';
import {InternationalizationProvider} from '../i18n';
import {registerIcons, resetIcons} from '../Icon';
@@ -22,6 +24,21 @@ import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+// jsdom cannot match `:focus-visible`: compare the ring's StyleX class hash.
+const RING = stylex
+ .props(
+ stylex.create({
+ ring: {
+ boxShadow: {
+ default: null,
+ ':has(> [aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,
+ },
+ },
+ }).ring,
+ )
+ .className!.split(' ')
+ .pop()!;
+
// FieldStatus announces status messages through the persistent useAnnounce
// singletons; remove them between tests so role/aria-live queries in this
// file never match a leftover region.
@@ -149,7 +166,7 @@ describe('NumberInput', () => {
expect(screen.getByRole('spinbutton')).not.toHaveAttribute('aria-required');
});
- it('sets disabled attribute when isDisabled is true', () => {
+ it('exposes aria-disabled, not native disabled, when isDisabled is true (spec:AST-085)', () => {
render(
<NumberInput
label="Quantity"
@@ -158,7 +175,76 @@ describe('NumberInput', () => {
onChange={() => {}}
/>,
);
- expect(screen.getByRole('spinbutton')).toBeDisabled();
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+
+ it('keeps a disabled input in the tab order and rings it (spec:AST-085 FR1, FR6)', async () => {
+ const user = userEvent.setup();
+ render(
+ <>
+ <NumberInput label="First" value={1} onChange={() => {}} />
+ <NumberInput label="Second" value={2} onChange={() => {}} isDisabled />
+ </>,
+ );
+ await user.tab();
+ await user.tab();
+ const input = screen.getByRole('spinbutton', {name: 'Second'});
+ expect(input).toHaveFocus();
+ expect(input.parentElement).toHaveClass(RING);
+ });
+
+ it('runs no caller handler, steps nothing and submits no form while disabled (spec:AST-085 FR2)', async () => {
+ const user = userEvent.setup();
+ const handlers = {
+ onChange: vi.fn(),
+ onEnter: vi.fn(),
+ onKeyDown: vi.fn(),
+ onPaste: vi.fn(),
+ };
+ const onSubmit = vi.fn((e: React.FormEvent) => e.preventDefault());
+ render(
+ <form onSubmit={onSubmit}>
+ <NumberInput
+ label="Quantity"
+ value={5}
+ isDisabled
+ hasNumberSteppers
+ {...handlers}
+ />
+ </form>,
+ );
+ await user.click(screen.getByRole('spinbutton'));
+ await user.keyboard('{ArrowUp}{ArrowDown}{Enter}');
+ await user.paste('9');
+ await user.click(screen.getByRole('button', {name: 'Increment Quantity'}));
+ for (const handler of [...Object.values(handlers), onSubmit]) {
+ expect(handler).not.toHaveBeenCalled();
+ }
+ });
+
+ it('commits nothing when a field disabled mid-entry loses focus (spec:AST-085 FR2)', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const field = (isDisabled: boolean) => (
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={onChange}
+ isDisabled={isDisabled}
+ />
+ );
+ const {rerender} = render(field(false));
+ const input = screen.getByRole('spinbutton');
+ await user.clear(input);
+ await user.type(input, '8');
+ onChange.mockClear();
+ rerender(field(true));
+ await user.tab();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('5');
});
it('does not fire onChange when disabled', async () => {
@@ -1424,10 +1510,10 @@ describe('NumberInput', () => {
const increment = screen.getByRole('button', {
name: 'Increment Quantity',
});
- expect(increment).toBeDisabled();
+ expect(increment).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', {name: 'Decrement Quantity'}),
- ).toBeDisabled();
+ ).toHaveAttribute('aria-disabled', 'true');
fireEvent.click(increment);
expect(handleChange).not.toHaveBeenCalled();
@@ -1446,7 +1532,10 @@ describe('NumberInput', () => {
/>
</form>,
);
- expect(screen.getByRole('spinbutton')).toBeDisabled();
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
expect([
...new FormData(container.querySelector('form')!).keys(),
]).toEqual([]);
@@ -1693,7 +1782,7 @@ describe('NumberInput', () => {
expect(onChange).not.toHaveBeenCalled();
});
- it('remains natively disabled when disabled without a reason', () => {
+ it('stays focusable when disabled without a reason', () => {
render(
<NumberInput
label="Quantity"
@@ -1703,8 +1792,8 @@ describe('NumberInput', () => {
/>,
);
const input = screen.getByRole('spinbutton');
- expect(input).toBeDisabled();
- expect(input).not.toHaveAttribute('aria-disabled');
+ expect(input).not.toBeDisabled();
+ expect(input).toHaveAttribute('aria-disabled', 'true');
});
});
});
@@ -2006,14 +2095,14 @@ describe('NumberInput stepping', () => {
const input = screen.getByRole('spinbutton');
const increment = screen.getByRole('button', {name: 'Increment Amount'});
- expect(increment).toBeEnabled();
+ expect(increment).not.toHaveAttribute('aria-disabled');
fireEvent.click(increment);
expect(input).toHaveValue('99.99');
expect(input).toHaveAttribute('aria-valuenow', '99.99');
expect(input).not.toHaveAttribute('aria-invalid');
- expect(increment).toBeDisabled();
+ expect(increment).toHaveAttribute('aria-disabled', 'true');
});
it('allows wheel stepping by default and consumes the focused gesture', () => {
@@ -2259,10 +2348,33 @@ describe('NumberInput stepping', () => {
);
expect(
screen.getByRole('button', {name: 'Increment Quantity'}),
- ).toBeDisabled();
+ ).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', {name: 'Decrement Quantity'}),
- ).not.toBeDisabled();
+ ).not.toHaveAttribute('aria-disabled');
+ });
+
+ it('commits nothing from a click on the stepper at the reached boundary (spec:AST-085 FR2)', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={onChange}
+ min={0}
+ max={10}
+ hasNumberSteppers
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ await user.clear(input);
+ await user.type(input, '10');
+ onChange.mockClear();
+ await user.click(
+ screen.getByRole('button', {name: 'Increment Quantity'}),
+ );
+ expect(onChange).not.toHaveBeenCalled();
});
it('disables both steppers with the input', () => {
@@ -2277,10 +2389,10 @@ describe('NumberInput stepping', () => {
);
expect(
screen.getByRole('button', {name: 'Increment Quantity'}),
- ).toBeDisabled();
+ ).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', {name: 'Decrement Quantity'}),
- ).toBeDisabled();
+ ).toHaveAttribute('aria-disabled', 'true');
});
});
});
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index af9cb5e135..e3e8fc0f9f 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -53,6 +53,7 @@ import {useTooltip} from '../Tooltip';
import {getInputARIA} from '../utils';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
+import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';
import {useSize} from '../SizeContext/SizeContext';
import {useInputContainer} from '../hooks/useInputContainer';
import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
@@ -261,7 +262,7 @@ interface NumberInputPropsBase extends Omit<
* Whether the input is read-only.
* The value is shown at full opacity and still submits with the form, but
* cannot be edited. Unlike `isDisabled`, a read-only input is not dimmed and
- * stays in the tab order — use it for a value the user should see and send
+ * keeps its form value — use it for a value the user should see and send
* but not change. Stepping is off in every form while read-only: arrow keys,
* the wheel, and the number steppers. `isDisabled` takes precedence when both
* are set.
@@ -275,8 +276,8 @@ interface NumberInputPropsBase extends Omit<
* keyboard and assistive technology. The field cannot be edited (it becomes
* read-only) while disabled.
*
- * 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 attached to the field itself.
*
* @example
* ```
@@ -600,12 +601,20 @@ export function NumberInput({
const [pendingInput, setPendingInput] = useState<string | null>(null);
const [isFocused, setIsFocused] = useState(false);
- // Disabled-reason tooltip. Disabled controls swallow pointer events, so the
- // tooltip listeners attach to the input container (which already exists) and
+ // Disabled-reason tooltip. The tooltip listeners attach to the input container (which already exists) and
// the input stays perceivable via aria-disabled instead of the native
// disabled attribute. The field is made read-only so it can't be typed into,
// and value mutation is blocked by the isDisabled guard in the handlers.
const showsDisabledMessage = isDisabled && !!disabledMessage;
+ // A disabled field keeps its tab stop but, like a natively disabled one,
+ // runs no caller event handler other than focus and blur (`spec:AST-085` FR2).
+ const fieldProps = isDisabled
+ ? Object.fromEntries(
+ Object.entries(rest).filter(
+ ([key]) => !/^on[A-Z]/.test(key) || /^on(Focus|Blur)/.test(key),
+ ),
+ )
+ : rest;
const disabledMessageTooltip = useTooltip({
placement: 'above',
// The container div is not naturally focusable; focusin bubbles up from
@@ -699,6 +708,12 @@ export function NumberInput({
if (pendingInput === null) {
return;
}
+ if (isDisabled) {
+ // A field disabled mid-entry commits nothing; its draft is dropped, as
+ // a natively disabled field's was (spec:AST-085 FR2).
+ setPendingInput(null);
+ return;
+ }
const decision = resolveNumberInputCommit(pendingInput, {
min,
@@ -722,7 +737,17 @@ export function NumberInput({
onChange(decision.value);
}
},
- [hasClear, isIntegerOnly, locale, max, min, onChange, pendingInput, value],
+ [
+ hasClear,
+ isDisabled,
+ isIntegerOnly,
+ locale,
+ max,
+ min,
+ onChange,
+ pendingInput,
+ value,
+ ],
);
// Blur ends the edit and displays the resulting committed value.
@@ -780,6 +805,13 @@ export function NumberInput({
// Handle keyboard events
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLInputElement>) => {
+ if (isDisabled) {
+ // A read-only field still submits its form on Enter.
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ }
+ return;
+ }
// The field is type="text" for formatted display, so an IME can compose
// into it: Enter commits the candidate and the arrows walk the candidate
// window. The composing keydown fires before compositionend, so without
@@ -804,7 +836,7 @@ export function NumberInput({
}
onKeyDown?.(e);
},
- [commitPendingInput, onEnter, onKeyDown, stepValue],
+ [commitPendingInput, isDisabled, onEnter, onKeyDown, stepValue],
);
// React's delegated wheel listener can be passive, so use a native,
@@ -902,6 +934,7 @@ export function NumberInput({
hasNumberSteppers && styles.wrapperWithNumberSteppers,
sizeStyles[size],
isDisabled && inputWrapperStyles.disabled,
+ isDisabled && inputDisabledFocusStyles.ring,
status && inputStatusBorderStyles[status.type],
status && !isDisabled && inputStatusHoverShadowStyles[status.type],
status && inputStatusFocusWithinStyles[status.type],
@@ -914,7 +947,7 @@ export function NumberInput({
{startIcon && renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
{inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
<input
- {...rest}
+ {...fieldProps}
ref={mergedInputRef}
id={id}
name={isDisabled || formatValue ? undefined : htmlName}
@@ -928,12 +961,11 @@ export function NumberInput({
onBlur={handleBlur}
onKeyDown={handleKeyDown}
placeholder={placeholder}
- // With a disabledMessage the input keeps focusability via aria-disabled
- // so the reason is focus-discoverable; readOnly + the handler guards
- // keep the value from changing.
- disabled={isDisabled && !showsDisabledMessage}
- aria-disabled={showsDisabledMessage ? 'true' : undefined}
- readOnly={isReadOnly || showsDisabledMessage || undefined}
+ // A disabled input keeps its place in the tab order (spec:AST-085):
+ // aria-disabled instead of the native attribute, with readOnly + the
+ // handler guards keeping the value from changing.
+ aria-disabled={isDisabled ? 'true' : undefined}
+ readOnly={isReadOnly || isDisabled || undefined}
autoFocus={hasAutoFocus}
data-autofocus={hasAutoFocus || undefined}
aria-valuemin={min ?? undefined}
@@ -992,10 +1024,17 @@ export function NumberInput({
type="button"
tabIndex={-1}
{...pressable}
- disabled={isDisabled || isReadOnly || !canIncrement}
+ aria-disabled={
+ isDisabled || isReadOnly || !canIncrement || undefined
+ }
aria-label={t('@astryx.numberInput.incrementLabel', {label})}
onPointerDown={event => event.preventDefault()}
onClick={() => {
+ // An aria-disabled stepper does nothing, as a natively disabled
+ // one did (spec:AST-085 FR2).
+ if (isDisabled || isReadOnly || !canIncrement) {
+ return;
+ }
inputRef.current?.focus();
stepValue(1);
}}
@@ -1016,10 +1055,17 @@ export function NumberInput({
type="button"
tabIndex={-1}
{...pressable}
- disabled={isDisabled || isReadOnly || !canDecrement}
+ aria-disabled={
+ isDisabled || isReadOnly || !canDecrement || undefined
+ }
aria-label={t('@astryx.numberInput.decrementLabel', {label})}
onPointerDown={event => event.preventDefault()}
onClick={() => {
+ // An aria-disabled stepper does nothing, as a natively disabled
+ // one did (spec:AST-085 FR2).
+ if (isDisabled || isReadOnly || !canDecrement) {
+ return;
+ }
inputRef.current?.focus();
stepValue(-1);
}}
diff --git a/packages/core/src/Pagination/Pagination.test.tsx b/packages/core/src/Pagination/Pagination.test.tsx
index 1ade0a0e55..d3727e54d1 100644
--- a/packages/core/src/Pagination/Pagination.test.tsx
+++ b/packages/core/src/Pagination/Pagination.test.tsx
@@ -965,7 +965,7 @@ describe('Pagination', () => {
/>,
);
const box = screen.getByRole('spinbutton', {name: 'Go to page'});
- expect(box).toBeDisabled();
+ expect(box).toHaveAttribute('aria-disabled', 'true');
// Disabled input never fires a change.
await user.type(box, '5{Enter}');
expect(onChange).not.toHaveBeenCalled();
@@ -999,7 +999,7 @@ describe('Pagination', () => {
// editable box is inert rather than accepting entries it can't resolve.
expect(
screen.getByRole('spinbutton', {name: 'Go to page'}),
- ).toBeDisabled();
+ ).toHaveAttribute('aria-disabled', 'true');
});
it('renders the localized "Page" label by default and a custom pageLabel', () => {