Skip to content

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

TypeScript

feat(input): add disabledMessage to text-entry inputs (#3509) (#3510)

Cindy Zhang3f9afb0041a2
diff --git a/.changeset/text-entry-disabled-message.md b/.changeset/text-entry-disabled-message.md
new file mode 100644
index 0000000000..31863f5536
--- /dev/null
+++ b/.changeset/text-entry-disabled-message.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] TextInput/NumberInput/TextArea/FileInput: disabledMessage prop shows a tooltip explaining the disabled state (#3509)
+@cixzhang
diff --git a/apps/storybook/stories/FileInput.stories.tsx b/apps/storybook/stories/FileInput.stories.tsx
index c0a0f24514..0aae44b882 100644
--- a/apps/storybook/stories/FileInput.stories.tsx
+++ b/apps/storybook/stories/FileInput.stories.tsx
@@ -48,6 +48,11 @@ const meta: Meta<typeof FileInput> = {
control: 'boolean',
description: 'Whether the input is disabled',
},
+ disabledMessage: {
+ control: 'text',
+ description:
+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the trigger focusable via aria-disabled (opening the file picker stays blocked). Use this instead of wrapping a disabled FileInput in Tooltip.',
+ },
isLoading: {
control: 'boolean',
description: 'Whether the input is in a loading state',
@@ -169,6 +174,25 @@ export const Disabled: Story = {
},
};
+// Disabled with an explanation tooltip. Hover or keyboard-focus the trigger to
+// see why it's disabled — the reason is announced to assistive tech via
+// aria-describedby, and the trigger stays focusable (opening the picker is
+// still blocked). Use disabledMessage instead of wrapping a disabled FileInput
+// in Tooltip: disabled controls swallow the pointer events a Tooltip wrapper
+// needs.
+export const DisabledWithMessage: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <FileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Resume',
+ isDisabled: true,
+ disabledMessage: 'Uploads are locked until your profile is verified',
+ placeholder: 'Upload is currently disabled',
+ },
+};
+
export const Loading: Story = {
render: args => {
const [value, setValue] = useState<File | File[] | null>(null);
@@ -228,11 +252,7 @@ export const AllVariations: Story = {
gap: '24px',
maxWidth: '400px',
}}>
- <FileInput
- label="Default (input mode)"
- value={v1}
- onChange={setV1}
- />
+ <FileInput label="Default (input mode)" value={v1} onChange={setV1} />
<FileInput
label="Dropzone with constraints"
value={v2}
diff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsx
index 26d3ba3ddd..bbe2f37814 100644
--- a/apps/storybook/stories/NumberInput.stories.tsx
+++ b/apps/storybook/stories/NumberInput.stories.tsx
@@ -50,6 +50,11 @@ const meta: Meta<typeof NumberInput> = {
control: 'boolean',
description: 'Whether the input is disabled',
},
+ disabledMessage: {
+ control: 'text',
+ description:
+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled NumberInput in Tooltip.',
+ },
status: {
control: 'object',
description:
@@ -232,11 +237,7 @@ export const AllVariations: Story = {
onChange={setValue2}
placeholder="Hidden label input"
/>
- <NumberInput
- label="With value"
- value={value3}
- onChange={setValue3}
- />
+ <NumberInput label="With value" value={value3} onChange={setValue3} />
<NumberInput
label="Optional field"
isOptional
@@ -313,6 +314,24 @@ export const Disabled: Story = {
},
};
+// Disabled with an explanation tooltip. Hover or keyboard-focus the input to
+// see why it's disabled — the reason is announced to assistive tech via
+// aria-describedby, and the input stays focusable (editing is still blocked).
+// Use disabledMessage instead of wrapping a disabled NumberInput in Tooltip:
+// disabled controls swallow the pointer events a Tooltip wrapper needs.
+export const DisabledWithMessage: Story = {
+ render: args => {
+ const [value, setValue] = useState<number | null>(args.value ?? 100);
+ return <NumberInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Quantity',
+ isDisabled: true,
+ disabledMessage: 'Editing is locked while the order is processing',
+ value: 100,
+ },
+};
+
export const WithStartIcon: Story = {
render: args => {
const [value, setValue] = useState<number | null>(args.value ?? null);
@@ -516,9 +535,7 @@ export const WithEventHandlers: Story = {
export const Clearable: Story = {
render: args => {
const [value, setValue] = useState<number | null>(args.value ?? 42);
- return (
- <NumberInput {...args} value={value} onChange={setValue} hasClear />
- );
+ return <NumberInput {...args} value={value} onChange={setValue} hasClear />;
},
args: {
label: 'Quantity',
@@ -529,9 +546,7 @@ export const Clearable: Story = {
export const ClearableWithUnits: Story = {
render: args => {
const [value, setValue] = useState<number | null>(args.value ?? 75);
- return (
- <NumberInput {...args} value={value} onChange={setValue} hasClear />
- );
+ return <NumberInput {...args} value={value} onChange={setValue} hasClear />;
},
args: {
label: 'Progress',
diff --git a/apps/storybook/stories/TextArea.stories.tsx b/apps/storybook/stories/TextArea.stories.tsx
index d29fbc85f3..45178076c5 100644
--- a/apps/storybook/stories/TextArea.stories.tsx
+++ b/apps/storybook/stories/TextArea.stories.tsx
@@ -54,6 +54,11 @@ const meta: Meta<typeof TextArea> = {
control: 'boolean',
description: 'Whether the textarea is disabled',
},
+ disabledMessage: {
+ control: 'text',
+ description:
+ 'Explains why the textarea is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the textarea focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled TextArea in Tooltip.',
+ },
status: {
control: 'object',
description:
@@ -277,6 +282,26 @@ export const Disabled: Story = {
},
};
+// Disabled with an explanation tooltip. Hover or keyboard-focus the textarea to
+// see why it's disabled — the reason is announced to assistive tech via
+// aria-describedby, and the textarea stays focusable (editing is still
+// blocked). Use disabledMessage instead of wrapping a disabled TextArea in
+// Tooltip: disabled controls swallow the pointer events a Tooltip wrapper needs.
+export const DisabledWithMessage: Story = {
+ render: args => {
+ const [value, setValue] = useState(
+ args.value ?? 'These notes are locked after submission.',
+ );
+ return <TextArea {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Notes',
+ isDisabled: true,
+ disabledMessage: 'Notes are locked after submission',
+ value: 'These notes are locked after submission.',
+ },
+};
+
export const WithStartIcon: Story = {
render: args => {
const [value, setValue] = useState(args.value ?? '');
diff --git a/apps/storybook/stories/TextInput.stories.tsx b/apps/storybook/stories/TextInput.stories.tsx
index ae3f282e84..4811311a2a 100644
--- a/apps/storybook/stories/TextInput.stories.tsx
+++ b/apps/storybook/stories/TextInput.stories.tsx
@@ -54,6 +54,11 @@ const meta: Meta<typeof TextInput> = {
control: 'boolean',
description: 'Whether the input is disabled',
},
+ disabledMessage: {
+ control: 'text',
+ description:
+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled TextInput in Tooltip.',
+ },
status: {
control: 'object',
description:
@@ -237,6 +242,24 @@ export const Disabled: Story = {
},
};
+// Disabled with an explanation tooltip. Hover or keyboard-focus the input to
+// see why it's disabled — the reason is announced to assistive tech via
+// aria-describedby, and the input stays focusable (editing is still blocked).
+// Use disabledMessage instead of wrapping a disabled TextInput in Tooltip:
+// disabled controls swallow the pointer events a Tooltip wrapper needs.
+export const DisabledWithMessage: Story = {
+ render: args => {
+ const [value, setValue] = useState(args.value ?? '[email protected]');
+ return <TextInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Owner',
+ isDisabled: true,
+ disabledMessage: 'You need the Editor role to change this',
+ value: '[email protected]',
+ },
+};
+
export const WithStartIcon: Story = {
render: args => {
const [value, setValue] = useState(args.value ?? '');
diff --git a/packages/core/src/FileInput/FileInput.doc.mjs b/packages/core/src/FileInput/FileInput.doc.mjs
index 9974c38602..df46dcc624 100644
--- a/packages/core/src/FileInput/FileInput.doc.mjs
+++ b/packages/core/src/FileInput/FileInput.doc.mjs
@@ -88,6 +88,12 @@ export const docs = {
'Disables the input, preventing interaction and dimming the element.',
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 trigger focusable via aria-disabled (opening the file picker stays blocked). Use this instead of wrapping a disabled FileInput in Tooltip — disabled controls swallow the hover events an external Tooltip needs.',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -135,6 +141,7 @@ export const docs = {
{guidance: true, description: 'Use changeAction for immediate upload workflows that benefit from optimistic UI.'},
{guidance: false, description: "Don't use FileInput for directory or folder uploads; that is not supported in v1."},
{guidance: false, description: "Don't avoid dropzone mode unless space is constrained; drag-and-drop is the expected interaction for file uploads."},
+ {guidance: false, description: "Don't wrap a disabled FileInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text that identifies the field. Always rendered for accessibility even when visually hidden.'},
@@ -211,6 +218,12 @@ export const docsZh = {
description: '禁用输入框,阻止交互并使元素变暗。',
default: 'false',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ '说明输入框被禁用的原因。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持触发器可聚焦(打开文件选择器仍被阻止)。请使用此属性,而不是用 Tooltip 包裹已禁用的 FileInput。',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -248,6 +261,7 @@ export const docsZh = {
{guidance: true, description: 'Add a description to communicate constraints.'},
{guidance: false, description: "Don't use FileInput for directory uploads."},
{guidance: false, description: "Don't use mode='input' unless space is constrained; dropzone mode provides a better experience."},
+ {guidance: false, description: "Don't wrap a disabled FileInput in Tooltip to explain the disabled state; use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text identifying the field.'},
@@ -272,6 +286,7 @@ export const docsDense = {
{guidance: true, description: 'Use changeAction for immediate upload workflows that benefit from optimistic UI.'},
{guidance: false, description: "Don't use FileInput for directory uploads."},
{guidance: false, description: "Don't use mode='input' unless space is constrained; dropzone mode provides a better experience."},
+ {guidance: false, description: "Don't wrap a disabled FileInput in Tooltip to explain the disabled state; use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text identifying the field.'},
@@ -295,6 +310,8 @@ export const docsDense = {
isOptional: 'Shows "Optional" indicator.',
isRequired: 'Shows "Required" indicator+sets aria-required.',
isDisabled: 'Disables input, prevents interaction.',
+ disabledMessage:
+ 'Explains why input is disabled. With isDisabled, shows tooltip on hover/focus + keeps trigger focusable via aria-disabled (opening picker stays blocked). Use instead of wrapping a disabled FileInput in Tooltip.',
isLoading: 'Loading state w/ spinner+aria-busy.',
placeholder: 'Placeholder when no files selected.',
mode: "Visual mode: 'input' (compact) or 'dropzone' (drag-and-drop).",
diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsx
index 6ba6ff545f..ce6deceeb5 100644
--- a/packages/core/src/FileInput/FileInput.test.tsx
+++ b/packages/core/src/FileInput/FileInput.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When FileInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, afterEach} from 'vitest';
+import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {FileInput} from './FileInput';
@@ -19,6 +19,43 @@ afterEach(() => {
__resetLiveRegionsForTest();
});
+// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
+// disabledMessage tooltip.
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ // jsdom does not resolve :focus-visible for role="button" divs the way a
+ // browser does after keyboard focus; treat the active element as
+ // focus-visible so the tooltip's keyboard-focus path is exercised.
+ if (selector === ':focus-visible') {
+ return this === document.activeElement;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+// jsdom popover content is in the DOM but may not be "visible" in the
+// accessibility tree. Use hidden: true to find it.
+const h = {hidden: true} as const;
+
function politeRegion(): HTMLElement | null {
return document.querySelector('[data-astryx-live-region="polite"]');
}
@@ -581,4 +618,146 @@ describe('FileInput', () => {
expect(input).toHaveAttribute('data-testid', 'file-upload');
});
});
+
+ describe('disabledMessage', () => {
+ it('shows the reason tooltip on hover when disabled with a reason', async () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const trigger = screen.getByRole('button');
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(tooltip).toHaveTextContent('You need the Editor role');
+
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+
+ fireEvent.mouseLeave(trigger);
+ await waitFor(() => {
+ expect(tooltip).not.toHaveAttribute('popover-open');
+ });
+ });
+
+ it('shows the reason tooltip on keyboard focus', async () => {
+ const user = userEvent.setup();
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const tooltip = screen.getByRole('tooltip', h);
+ await user.tab();
+ expect(screen.getByRole('button')).toHaveFocus();
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+ });
+
+ it('does not render a tooltip when not disabled', () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('does not render a tooltip when disabled without a reason', () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('keeps the trigger focusable via aria-disabled when a reason is provided', () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const trigger = screen.getByRole('button');
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ expect(trigger).toHaveAttribute('tabindex', '0');
+ });
+
+ it('links the reason tooltip from the trigger via aria-describedby', () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const trigger = screen.getByRole('button');
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(trigger.getAttribute('aria-describedby')).toContain(tooltip.id);
+ });
+
+ it('blocks opening the file picker while focusable-disabled', async () => {
+ const user = userEvent.setup();
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const trigger = screen.getByRole('button');
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const clickSpy = vi.spyOn(input, 'click');
+
+ await user.click(trigger);
+ trigger.focus();
+ await user.keyboard('{Enter}');
+ await user.keyboard(' ');
+
+ expect(clickSpy).not.toHaveBeenCalled();
+ });
+
+ it('keeps the trigger non-focusable when disabled without a reason', () => {
+ render(
+ <FileInput
+ label="Resume"
+ value={null}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ const trigger = screen.getByRole('button');
+ expect(trigger).toHaveAttribute('tabindex', '-1');
+ expect(trigger).not.toHaveAttribute('aria-disabled');
+ });
+ });
});
diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsx
index df18e3a5ce..6d92010124 100644
--- a/packages/core/src/FileInput/FileInput.tsx
+++ b/packages/core/src/FileInput/FileInput.tsx
@@ -45,6 +45,7 @@ import {
import {Icon, type IconName} from '../Icon';
import {Spinner} from '../Spinner';
import {useAnnounce} from '../hooks/useAnnounce';
+import {useTooltip} from '../Tooltip';
export type {
InputStatus as FileInputStatus,
@@ -321,6 +322,27 @@ export interface FileInputProps extends Omit<
* @default false
*/
isDisabled?: boolean;
+ /**
+ * Explains why the input is disabled. When set together with `isDisabled`,
+ * the file input shows a tooltip with this text on hover and keyboard focus,
+ * and its trigger stays focusable (via `aria-disabled`) so the reason is
+ * discoverable by keyboard and assistive technology. Opening the file picker
+ * stays blocked.
+ *
+ * Use this instead of wrapping a disabled input in `Tooltip` — disabled
+ * controls don't emit the pointer events an external tooltip needs.
+ *
+ * @example
+ * ```
+ * <FileInput
+ * label="Resume"
+ * value={file}
+ * isDisabled
+ * disabledMessage="Uploads are locked until your profile is verified"
+ * />
+ * ```
+ */
+ disabledMessage?: string;
/**
* Whether the input is required.
* @default false
@@ -387,6 +409,7 @@ export function FileInput({
maxSize,
maxFiles,
isDisabled = false,
+ disabledMessage,
isRequired = false,
isLoading = false,
status: statusProp,
@@ -416,6 +439,18 @@ export function FileInput({
// carries validation errors, so a successful attach was previously silent.
const announce = useAnnounce();
+ // Disabled-reason tooltip. Disabled controls swallow pointer events, so the
+ // tooltip listeners attach to the role="button" trigger (which already
+ // exists) and the trigger stays perceivable via aria-disabled instead of the
+ // native disabled attribute. Opening the picker is blocked by the isDisabled
+ // guards in handleClick / handleKeyDown / handleFiles.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
const status =
statusProp ??
(validationError
@@ -441,6 +476,7 @@ export function FileInput({
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
]
.filter(Boolean)
.join(' ') || undefined;
@@ -684,8 +720,18 @@ export function FileInput({
labelTooltip={labelTooltip}
width={width}>
<div
+ ref={el => {
+ // Anchor + hover/focus listeners for the disabled-message tooltip.
+ // Handlers are gated internally by isEnabled, and anchor names
+ // compose, so attaching unconditionally is safe.
+ disabledMessageTooltip.ref(el);
+ }}
role="button"
- tabIndex={isDisabled ? -1 : 0}
+ // With a disabledMessage the trigger keeps focusability via
+ // aria-disabled so the reason is focus-discoverable; opening the picker
+ // is still blocked by the isDisabled guards in the handlers.
+ tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}
onClick={handleClick}
onKeyDown={handleKeyDown}
aria-label={label}
@@ -738,6 +784,8 @@ export function FileInput({
{...stylex.props(styles.liveRegion)}>
{validationError}
</div>
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
</Field>
);
}
diff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjs
index e358955c73..4802222c61 100644
--- a/packages/core/src/NumberInput/NumberInput.doc.mjs
+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs
@@ -62,6 +62,12 @@ export const docs = {
type: 'boolean',
description: 'Whether the input is disabled.',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled NumberInput in Tooltip.',
+ },
{
name: 'placeholder',
type: 'string',
@@ -166,6 +172,7 @@ export const docs = {
{ guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
{ guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
{ guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
+ { 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." },
],
anatomy: [
{name: 'Label', required: true, description: 'The label for the number input.'},
@@ -236,6 +243,12 @@ export const docsZh = {
type: 'boolean',
description: '输入框是否禁用。',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ '说明输入框被禁用的原因。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持输入框可聚焦(字段变为只读)。请使用此属性,而不是用 Tooltip 包裹已禁用的 NumberInput。',
+ },
{
name: 'placeholder',
type: 'string',
@@ -339,6 +352,7 @@ export const docsZh = {
{ guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
{ guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
{ guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
+ { 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." },
],
anatomy: [
{name: 'Label', required: true, description: 'The label for the number input.'},
@@ -361,6 +375,7 @@ export const docsDense = {
{ guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
{ guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
{ guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
+ { 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." },
],
anatomy: [
{name: 'Label', required: true, description: 'The label for the number input.'},
@@ -380,6 +395,8 @@ export const docsDense = {
isOptional: 'Field optional (mutually exclusive w/ isRequired).',
isRequired: 'Field required (mutually exclusive w/ isOptional).',
isDisabled: 'Input disabled.',
+ 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.',
labelTooltip: 'Tooltip text in info icon at label end.',
startIcon: 'Icon at input start.',
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 62cfa4fcb7..4a7b9d45eb 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -9,12 +9,43 @@
* SYNC: When NumberInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {HashtagIcon} from '@heroicons/react/24/outline';
import {NumberInput} from './NumberInput';
+// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
+// disabledMessage tooltip.
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+// jsdom popover content is in the DOM but may not be "visible" in the
+// accessibility tree. Use hidden: true to find it.
+const h = {hidden: true} as const;
+
describe('NumberInput', () => {
it('renders with label', () => {
render(<NumberInput label="Quantity" value={null} onChange={() => {}} />);
@@ -698,4 +729,141 @@ describe('NumberInput', () => {
expect(input).toHaveFocus();
});
});
+
+ describe('disabledMessage', () => {
+ it('shows the reason tooltip on hover when disabled with a reason', async () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ const container = input.parentElement as HTMLElement;
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(tooltip).toHaveTextContent('You need the Editor role');
+
+ fireEvent.mouseEnter(container);
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+
+ fireEvent.mouseLeave(container);
+ await waitFor(() => {
+ expect(tooltip).not.toHaveAttribute('popover-open');
+ });
+ });
+
+ it('shows the reason tooltip on keyboard focus', async () => {
+ const user = userEvent.setup();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const tooltip = screen.getByRole('tooltip', h);
+ await user.tab();
+ expect(screen.getByRole('spinbutton')).toHaveFocus();
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+ });
+
+ it('does not render a tooltip when not disabled', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('does not render a tooltip when disabled without a reason', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('keeps the input focusable via aria-disabled when a reason is provided', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ expect(input).not.toBeDisabled();
+ expect(input).toHaveAttribute('aria-disabled', 'true');
+ expect(input).toHaveAttribute('readonly');
+ });
+
+ it('links the reason tooltip from the input via aria-describedby', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(input.getAttribute('aria-describedby')).toContain(tooltip.id);
+ });
+
+ it('blocks value changes while focusable-disabled', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={onChange}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.keyboard('9');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('remains natively disabled when disabled without a reason', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ expect(input).toBeDisabled();
+ expect(input).not.toHaveAttribute('aria-disabled');
+ });
+ });
});
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index b11f974deb..8aa7b65686 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -47,6 +47,7 @@ import {
} from '../Field';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {VisuallyHidden} from '../VisuallyHidden';
+import {useTooltip} from '../Tooltip';
import {useSize} from '../SizeContext/SizeContext';
import {useInputContainer} from '../hooks/useInputContainer';
import {useInputGroup} from '../InputGroup/InputGroupContext';
@@ -168,6 +169,27 @@ interface NumberInputPropsBase extends Omit<
* @default false
*/
isDisabled?: boolean;
+ /**
+ * 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
+ * stays focusable (via `aria-disabled`) so the reason is discoverable by
+ * 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.
+ *
+ * @example
+ * ```
+ * <NumberInput
+ * label="Quantity"
+ * value={quantity}
+ * isDisabled
+ * disabledMessage="Editing is locked while the order is processing"
+ * />
+ * ```
+ */
+ disabledMessage?: string;
/**
* Icon to display at the start of the input.
* Accepts a ReactNode (e.g. `<Icon icon={SearchIcon} />`) or an SVG icon component directly.
@@ -347,6 +369,7 @@ export function NumberInput({
isOptional = false,
isRequired = false,
isDisabled = false,
+ disabledMessage,
startIcon,
labelIcon,
status,
@@ -386,6 +409,20 @@ export function NumberInput({
// Pending input while user is typing (null = show formatted value)
const [pendingInput, setPendingInput] = useState<string | null>(null);
+ // 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 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;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ // The container div is not naturally focusable; focusin bubbles up from
+ // the input, so always attach focus listeners.
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
const statusIconMap: Record<InputStatusType, IconName> = {
warning: 'warning',
error: 'error',
@@ -405,6 +442,7 @@ export function NumberInput({
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
]
.filter(Boolean)
.join(' ') || undefined;
@@ -432,6 +470,12 @@ export function NumberInput({
// Handle input text change - update immediately if valid
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
+ // Value can't change while showing a disabled message (the field is
+ // read-only and non-native-disabled), but guard the handler too so the
+ // pending value and onChange never fire.
+ if (isDisabled) {
+ return;
+ }
const newValue = e.target.value;
setPendingInput(newValue);
@@ -441,7 +485,7 @@ export function NumberInput({
onChange(parsed);
}
},
- [value, onChange, min, max, isIntegerOnly],
+ [value, onChange, min, max, isIntegerOnly, isDisabled],
);
// Handle focus
@@ -523,7 +567,13 @@ export function NumberInput({
const inputWrapper = (
<div
- ref={containerRef}
+ ref={el => {
+ containerRef.current = el;
+ // Anchor + hover/focus listeners for the disabled-message tooltip.
+ // Handlers are gated internally by isEnabled, and anchor names
+ // compose, so attaching unconditionally is safe.
+ disabledMessageTooltip.ref(el);
+ }}
onClick={handleWrapperClick}
onMouseUp={handleWrapperMouseUp}
{...mergeProps(
@@ -556,7 +606,12 @@ export function NumberInput({
onBlur={handleBlur}
onKeyDown={handleKeyDown}
placeholder={placeholder}
- disabled={isDisabled}
+ // 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={showsDisabledMessage || undefined}
autoFocus={hasAutoFocus}
data-autofocus={hasAutoFocus || undefined}
min={min ?? undefined}
@@ -603,7 +658,13 @@ export function NumberInput({
);
if (inputGroup) {
- return inputWrapper;
+ return (
+ <>
+ {inputWrapper}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </>
+ );
}
return (
@@ -629,6 +690,8 @@ export function NumberInput({
labelTooltip={labelTooltip}
width={width}>
{inputWrapper}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
</Field>
);
}
diff --git a/packages/core/src/TextArea/TextArea.doc.mjs b/packages/core/src/TextArea/TextArea.doc.mjs
index c1edabbf71..86f2b5c1a1 100644
--- a/packages/core/src/TextArea/TextArea.doc.mjs
+++ b/packages/core/src/TextArea/TextArea.doc.mjs
@@ -70,6 +70,12 @@ export const docs = {
description: 'Disables the textarea, preventing interaction.',
default: 'false',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ 'Explains why the textarea is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the textarea focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled TextArea in Tooltip — disabled controls swallow the hover events an external Tooltip needs.',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -174,6 +180,7 @@ export const docs = {
{ guidance: false, description: 'Avoid using TextArea for short, single-line values like names or emails; use TextInput instead.' },
{ guidance: false, description: 'Don\'t rely solely on placeholder text to communicate the purpose of the field; placeholders disappear on focus and are not accessible labels.' },
{ guidance: false, description: 'Don\'t show a status message without also setting the status type; the colored border and icon are what draw the user\'s attention to the message.' },
+ { guidance: false, description: 'Don\'t wrap a disabled TextArea in Tooltip to explain why it\'s disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.' },
],
},
};
@@ -239,6 +246,12 @@ export const docsZh = {
description: '禁用文本域,阻止交互。',
default: 'false',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ '说明文本域被禁用的原因。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持文本域可聚焦(字段变为只读)。请使用此属性,而不是用 Tooltip 包裹已禁用的 TextArea。',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -336,6 +349,7 @@ export const docsZh = {
{ guidance: false, description: 'Avoid using TextArea for short, single-line values like names or emails; use TextInput instead.' },
{ guidance: false, description: 'Don\'t rely solely on placeholder text to communicate the purpose of the field; placeholders disappear on focus and are not accessible labels.' },
{ guidance: false, description: 'Don\'t show a status message without also setting the status type; the colored border and icon are what draw the user\'s attention to the message.' },
+ { guidance: false, description: 'Don\'t wrap a disabled TextArea in Tooltip to explain why it\'s disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.' },
],
},
};
@@ -354,6 +368,7 @@ export const docsDense = {
{ guidance: false, description: 'Avoid TextArea for single-line values; use TextInput.' },
{ guidance: false, description: 'Don\'t use placeholder as only label; disappears on focus, not accessible.' },
{ guidance: false, description: 'Don\'t show status message without status type; border and icon draw attention.' },
+ { guidance: false, description: 'Don\'t wrap a disabled TextArea in Tooltip to explain the disabled state; use the disabledMessage prop instead.' },
],
},
propDescriptions: {
@@ -367,6 +382,8 @@ export const docsDense = {
isOptional: 'Shows "Optional" indicator. Mutually exclusive w/ isRequired.',
isRequired: 'Shows "Required" indicator+sets aria-required. Mutually exclusive w/ isOptional.',
isDisabled: 'Disables textarea, prevents interaction.',
+ disabledMessage:
+ 'Explains why textarea is disabled. With isDisabled, shows tooltip on hover/focus + keeps textarea focusable via aria-disabled (field becomes read-only). Use instead of wrapping a disabled TextArea in Tooltip.',
isLoading: 'Loading state w/ spinner inside input.',
placeholder: 'Placeholder when textarea empty.',
rows: 'Visible text rows.',
diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsx
index fefdcc7086..48b74783df 100644
--- a/packages/core/src/TextArea/TextArea.test.tsx
+++ b/packages/core/src/TextArea/TextArea.test.tsx
@@ -10,12 +10,43 @@
*/
import {useState} from 'react';
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MagnifyingGlassIcon} from '@heroicons/react/24/outline';
import {TextArea} from './TextArea';
+// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
+// disabledMessage tooltip.
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+// jsdom popover content is in the DOM but may not be "visible" in the
+// accessibility tree. Use hidden: true to find it.
+const h = {hidden: true} as const;
+
describe('TextArea', () => {
it('renders with label', () => {
render(<TextArea label="Description" value="" onChange={() => {}} />);
@@ -39,9 +70,7 @@ describe('TextArea', () => {
it('calls onChange with value and event when typing', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
- render(
- <TextArea label="Description" value="" onChange={handleChange} />,
- );
+ render(<TextArea label="Description" value="" onChange={handleChange} />);
const textarea = screen.getByRole('textbox');
await user.type(textarea, 'Hi');
@@ -73,24 +102,14 @@ describe('TextArea', () => {
it('forwards ref correctly', () => {
const ref = vi.fn();
render(
- <TextArea
- ref={ref}
- label="Description"
- value=""
- onChange={() => {}}
- />,
+ <TextArea ref={ref} label="Description" value="" onChange={() => {}} />,
);
expect(ref).toHaveBeenCalledWith(expect.any(HTMLTextAreaElement));
});
it('visually hides label when isLabelHidden is true', () => {
render(
- <TextArea
- label="Comments"
- isLabelHidden
- value=""
- onChange={() => {}}
- />,
+ <TextArea label="Comments" isLabelHidden value="" onChange={() => {}} />,
);
const label = screen.getByText('Comments');
expect(label).toBeInTheDocument();
@@ -133,12 +152,7 @@ describe('TextArea', () => {
it('is disabled when isDisabled is true', () => {
render(
- <TextArea
- label="Description"
- isDisabled
- value=""
- onChange={() => {}}
- />,
+ <TextArea label="Description" isDisabled value="" onChange={() => {}} />,
);
expect(screen.getByRole('textbox')).toBeDisabled();
});
@@ -150,12 +164,7 @@ describe('TextArea', () => {
it('shows aria-busy when isLoading is true', () => {
render(
- <TextArea
- label="Description"
- isLoading
- value=""
- onChange={() => {}}
- />,
+ <TextArea label="Description" isLoading value="" onChange={() => {}} />,
);
expect(screen.getByRole('textbox')).toHaveAttribute('aria-busy', 'true');
expect(screen.getByRole('textbox')).not.toBeDisabled();
@@ -340,12 +349,7 @@ describe('TextArea', () => {
it('renders with size="lg"', () => {
render(
- <TextArea
- label="Description"
- value=""
- onChange={() => {}}
- size="lg"
- />,
+ <TextArea label="Description" value="" onChange={() => {}} size="lg" />,
);
expect(screen.getByLabelText('Description')).toBeInTheDocument();
});
@@ -595,4 +599,132 @@ describe('TextArea', () => {
expect(textarea).toHaveFocus();
});
});
+
+ describe('disabledMessage', () => {
+ it('shows the reason tooltip on hover when disabled with a reason', async () => {
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const textarea = screen.getByRole('textbox');
+ const container = textarea.parentElement as HTMLElement;
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(tooltip).toHaveTextContent('You need the Editor role');
+
+ fireEvent.mouseEnter(container);
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+
+ fireEvent.mouseLeave(container);
+ await waitFor(() => {
+ expect(tooltip).not.toHaveAttribute('popover-open');
+ });
+ });
+
+ it('shows the reason tooltip on keyboard focus', async () => {
+ const user = userEvent.setup();
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const tooltip = screen.getByRole('tooltip', h);
+ await user.tab();
+ expect(screen.getByRole('textbox')).toHaveFocus();
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+ });
+
+ it('does not render a tooltip when not disabled', () => {
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('does not render a tooltip when disabled without a reason', () => {
+ render(
+ <TextArea label="Notes" value="" onChange={() => {}} isDisabled />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('keeps the textarea focusable via aria-disabled when a reason is provided', () => {
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const textarea = screen.getByRole('textbox');
+ expect(textarea).not.toBeDisabled();
+ expect(textarea).toHaveAttribute('aria-disabled', 'true');
+ expect(textarea).toHaveAttribute('readonly');
+ });
+
+ it('links the reason tooltip from the textarea via aria-describedby', () => {
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const textarea = screen.getByRole('textbox');
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(textarea.getAttribute('aria-describedby')).toContain(tooltip.id);
+ });
+
+ it('blocks value changes while focusable-disabled', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={onChange}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const textarea = screen.getByRole('textbox');
+ await user.click(textarea);
+ await user.keyboard('hello');
+ expect(onChange).not.toHaveBeenCalled();
+ expect(textarea).toHaveValue('');
+ });
+
+ it('remains natively disabled when disabled without a reason', () => {
+ render(
+ <TextArea label="Notes" value="" onChange={() => {}} isDisabled />,
+ );
+ const textarea = screen.getByRole('textbox');
+ expect(textarea).toBeDisabled();
+ expect(textarea).not.toHaveAttribute('aria-disabled');
+ });
+ });
});
diff --git a/packages/core/src/TextArea/TextArea.tsx b/packages/core/src/TextArea/TextArea.tsx
index 7605635ce6..561f0dcf03 100644
--- a/packages/core/src/TextArea/TextArea.tsx
+++ b/packages/core/src/TextArea/TextArea.tsx
@@ -43,6 +43,7 @@ import {
} from '../Field';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
+import {useTooltip} from '../Tooltip';
import {mergeProps, mergeRefs} from '../utils';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -189,6 +190,27 @@ export interface TextAreaProps extends Omit<
* @default false
*/
isDisabled?: boolean;
+ /**
+ * Explains why the textarea is disabled. When set together with
+ * `isDisabled`, the textarea shows a tooltip with this text on hover and
+ * keyboard focus, and stays focusable (via `aria-disabled`) so the reason is
+ * discoverable by keyboard and assistive technology. The field cannot be
+ * edited (it becomes read-only) while disabled.
+ *
+ * Use this instead of wrapping a disabled textarea in `Tooltip` — disabled
+ * controls don't emit the pointer events an external tooltip needs.
+ *
+ * @example
+ * ```
+ * <TextArea
+ * label="Notes"
+ * value={notes}
+ * isDisabled
+ * disabledMessage="Notes are locked after submission"
+ * />
+ * ```
+ */
+ disabledMessage?: string;
/**
* Status indicator for the textarea.
* When set, displays a colored border and status icon.
@@ -274,6 +296,7 @@ export function TextArea({
placeholder,
rows = 3,
isDisabled = false,
+ disabledMessage,
status,
labelTooltip,
startIcon,
@@ -304,6 +327,20 @@ export function TextArea({
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // Disabled-reason tooltip. Disabled controls swallow pointer events, so the
+ // tooltip listeners attach to the textarea container (which already exists)
+ // and the textarea 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 handleChange.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ // The container div is not naturally focusable; focusin bubbles up from
+ // the textarea, so always attach focus listeners.
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
const statusIconMap: Record<TextAreaStatusType, IconName> = {
warning: 'warning',
error: 'error',
@@ -324,11 +361,18 @@ export function TextArea({
description ? descriptionID : null,
status?.message ? statusMessageID : null,
maxLength != null ? counterID : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
]
.filter(Boolean)
.join(' ') || undefined;
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
+ // Value can't change while showing a disabled message (the field is
+ // read-only and non-native-disabled), but guard the handler too so the
+ // optimistic value and callbacks never fire.
+ if (isDisabled) {
+ return;
+ }
const newValue = e.target.value;
onChange?.(newValue, e);
if (changeAction && !e.defaultPrevented) {
@@ -371,7 +415,13 @@ export function TextArea({
labelTooltip={labelTooltip}
width={width}>
<div
- ref={containerRef}
+ ref={el => {
+ containerRef.current = el;
+ // Anchor + hover/focus listeners for the disabled-message tooltip.
+ // Handlers are gated internally by isEnabled, and anchor names
+ // compose, so attaching unconditionally is safe.
+ disabledMessageTooltip.ref(el);
+ }}
onClick={handleWrapperClick}
onMouseUp={handleWrapperMouseUp}
{...mergeProps(
@@ -403,7 +453,12 @@ export function TextArea({
onBlur={onBlur}
placeholder={placeholder}
rows={rows}
- disabled={isDisabled}
+ // With a disabledMessage the textarea keeps focusability via
+ // aria-disabled so the reason is focus-discoverable; readOnly + the
+ // handleChange guard keep the value from changing.
+ disabled={isDisabled && !showsDisabledMessage}
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}
+ readOnly={showsDisabledMessage || undefined}
spellCheck={hasSpellCheck}
autoFocus={hasAutoFocus}
data-autofocus={hasAutoFocus || undefined}
@@ -450,6 +505,8 @@ export function TextArea({
</VisuallyHidden>
</div>
)}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
</Field>
);
}
diff --git a/packages/core/src/TextInput/TextInput.doc.mjs b/packages/core/src/TextInput/TextInput.doc.mjs
index d156a8e460..93d16b8aa0 100644
--- a/packages/core/src/TextInput/TextInput.doc.mjs
+++ b/packages/core/src/TextInput/TextInput.doc.mjs
@@ -78,6 +78,12 @@ export const docs = {
'Disables the input, preventing interaction and dimming the element.',
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 input focusable via aria-disabled (the field becomes read-only). Use this instead of wrapping a disabled TextInput in Tooltip — disabled controls swallow the hover events an external Tooltip needs.',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -144,6 +150,7 @@ export const docs = {
{guidance: false, description: "Don't use placeholder text as a replacement for a label; placeholders disappear on focus and are not reliably read by screen readers."},
{guidance: false, description: "Don't use TextInput for multi-line content like comments or descriptions; use TextArea instead."},
{guidance: false, description: "Don't mark every field as required; only flag mandatory fields so users are not overwhelmed by validation errors."},
+ {guidance: false, description: "Don't wrap a disabled TextInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text that identifies the field. Always rendered for accessibility even when visually hidden.'},
@@ -231,6 +238,12 @@ export const docsZh = {
'禁用输入框,阻止交互并使元素变暗。',
default: 'false',
},
+ {
+ name: 'disabledMessage',
+ type: 'string',
+ description:
+ '说明输入框被禁用的原因。与 isDisabled 一起使用时,在悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持输入框可聚焦(字段变为只读)。请使用此属性,而不是用 Tooltip 包裹已禁用的 TextInput——已禁用的控件会吞掉外部 Tooltip 所需的悬停事件。',
+ },
{
name: 'isLoading',
type: 'boolean',
@@ -296,6 +309,7 @@ export const docsZh = {
{guidance: false, description: "Don't use placeholder text as a replacement for a label; placeholders disappear on focus and are not reliably read by screen readers."},
{guidance: false, description: "Don't use TextInput for multi-line content like comments or descriptions; use TextArea instead."},
{guidance: false, description: "Don't mark every field as required; only flag mandatory fields so users are not overwhelmed by validation errors."},
+ {guidance: false, description: "Don't wrap a disabled TextInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text that identifies the field. Always rendered for accessibility even when visually hidden.'},
@@ -323,6 +337,7 @@ export const docsDense = {
{guidance: false, description: "Don't use placeholder text as a replacement for a label; placeholders disappear on focus and are not reliably read by screen readers."},
{guidance: false, description: "Don't use TextInput for multi-line content like comments or descriptions; use TextArea instead."},
{guidance: false, description: "Don't mark every field as required; only flag mandatory fields so users are not overwhelmed by validation errors."},
+ {guidance: false, description: "Don't wrap a disabled TextInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead."},
],
anatomy: [
{name: 'Label', required: true, description: 'Text that identifies the field. Always rendered for accessibility even when visually hidden.'},
@@ -346,6 +361,8 @@ export const docsDense = {
isOptional: 'Shows "Optional" indicator. Mutually exclusive w/ isRequired.',
isRequired: 'Shows "Required" indicator+sets aria-required. Mutually exclusive w/ isOptional.',
isDisabled: 'Disables input, prevents interaction, dims element.',
+ 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 TextInput in Tooltip.',
isLoading: 'Loading state w/ spinner+aria-busy.',
placeholder: 'Placeholder when input empty.',
labelTooltip: 'Tooltip in info icon at label end.',
diff --git a/packages/core/src/TextInput/TextInput.test.tsx b/packages/core/src/TextInput/TextInput.test.tsx
index 3442c8f3a9..9e50cd1ee7 100644
--- a/packages/core/src/TextInput/TextInput.test.tsx
+++ b/packages/core/src/TextInput/TextInput.test.tsx
@@ -9,12 +9,43 @@
* SYNC: When TextInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MagnifyingGlassIcon} from '@heroicons/react/24/outline';
import {TextInput} from './TextInput';
+// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
+// disabledMessage tooltip.
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+// jsdom popover content is in the DOM but may not be "visible" in the
+// accessibility tree. Use hidden: true to find it.
+const h = {hidden: true} as const;
+
describe('TextInput', () => {
it('renders with label', () => {
render(<TextInput label="Name" value="" onChange={() => {}} />);
@@ -62,31 +93,20 @@ describe('TextInput', () => {
it('displays controlled value', () => {
render(
- <TextInput
- label="Name"
- value="Controlled value"
- onChange={() => {}}
- />,
+ <TextInput label="Name" value="Controlled value" onChange={() => {}} />,
);
expect(screen.getByRole('textbox')).toHaveValue('Controlled value');
});
it('forwards ref correctly', () => {
const ref = vi.fn();
- render(
- <TextInput ref={ref} label="Name" value="" onChange={() => {}} />,
- );
+ render(<TextInput ref={ref} label="Name" value="" onChange={() => {}} />);
expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
});
it('visually hides label when isLabelHidden is true', () => {
render(
- <TextInput
- label="Search"
- isLabelHidden
- value=""
- onChange={() => {}}
- />,
+ <TextInput label="Search" isLabelHidden value="" onChange={() => {}} />,
);
const label = screen.getByText('Search');
expect(label).toBeInTheDocument();
@@ -116,9 +136,7 @@ describe('TextInput', () => {
});
it('sets disabled attribute when isDisabled is true', () => {
- render(
- <TextInput label="Name" isDisabled value="" onChange={() => {}} />,
- );
+ render(<TextInput label="Name" isDisabled value="" onChange={() => {}} />);
expect(screen.getByRole('textbox')).toBeDisabled();
});
@@ -410,12 +428,7 @@ describe('TextInput', () => {
describe('hasClear', () => {
it('shows clear button when hasClear is true and value is non-empty', () => {
render(
- <TextInput
- label="Name"
- value="hello"
- onChange={() => {}}
- hasClear
- />,
+ <TextInput label="Name" value="hello" onChange={() => {}} hasClear />,
);
expect(
screen.getByRole('button', {name: 'Clear Name'}),
@@ -423,9 +436,7 @@ describe('TextInput', () => {
});
it('does not show clear button when value is empty', () => {
- render(
- <TextInput label="Name" value="" onChange={() => {}} hasClear />,
- );
+ render(<TextInput label="Name" value="" onChange={() => {}} hasClear />);
expect(
screen.queryByRole('button', {name: 'Clear Name'}),
).not.toBeInTheDocument();
@@ -457,12 +468,7 @@ describe('TextInput', () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
- <TextInput
- label="Name"
- value="hello"
- onChange={onChange}
- hasClear
- />,
+ <TextInput label="Name" value="hello" onChange={onChange} hasClear />,
);
await user.click(screen.getByRole('button', {name: 'Clear Name'}));
expect(onChange).toHaveBeenCalledWith('', null);
@@ -524,4 +530,132 @@ describe('TextInput', () => {
expect(fieldRoot.getAttribute('style') ?? '').not.toContain('100%');
});
});
+
+ describe('disabledMessage', () => {
+ it('shows the reason tooltip on hover when disabled with a reason', async () => {
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const input = screen.getByRole('textbox');
+ const container = input.parentElement as HTMLElement;
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(tooltip).toHaveTextContent('You need the Editor role');
+
+ fireEvent.mouseEnter(container);
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+
+ fireEvent.mouseLeave(container);
+ await waitFor(() => {
+ expect(tooltip).not.toHaveAttribute('popover-open');
+ });
+ });
+
+ it('shows the reason tooltip on keyboard focus', async () => {
+ const user = userEvent.setup();
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const tooltip = screen.getByRole('tooltip', h);
+ await user.tab();
+ expect(screen.getByRole('textbox')).toHaveFocus();
+ await waitFor(() => {
+ expect(tooltip).toHaveAttribute('popover-open');
+ });
+ });
+
+ it('does not render a tooltip when not disabled', () => {
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={() => {}}
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('does not render a tooltip when disabled without a reason', () => {
+ render(
+ <TextInput label="Owner" value="" onChange={() => {}} isDisabled />,
+ );
+ expect(screen.queryByRole('tooltip', h)).not.toBeInTheDocument();
+ });
+
+ it('keeps the input focusable via aria-disabled when a reason is provided', () => {
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const input = screen.getByRole('textbox');
+ expect(input).not.toBeDisabled();
+ expect(input).toHaveAttribute('aria-disabled', 'true');
+ expect(input).toHaveAttribute('readonly');
+ });
+
+ it('links the reason tooltip from the input via aria-describedby', () => {
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+ const input = screen.getByRole('textbox');
+ const tooltip = screen.getByRole('tooltip', h);
+ expect(input.getAttribute('aria-describedby')).toContain(tooltip.id);
+ });
+
+ it('blocks value changes while focusable-disabled', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <TextInput
+ label="Owner"
+ value=""
+ onChange={onChange}
+ isDisabled
+ disabledMessage="You need the Editor role"
+ />,
+ );
+
+ const input = screen.getByRole('textbox');
+ await user.click(input);
+ await user.keyboard('hello');
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('');
+ });
+
+ it('remains natively disabled when disabled without a reason', () => {
+ render(
+ <TextInput label="Owner" value="" onChange={() => {}} isDisabled />,
+ );
+ const input = screen.getByRole('textbox');
+ expect(input).toBeDisabled();
+ expect(input).not.toHaveAttribute('aria-disabled');
+ });
+ });
});
diff --git a/packages/core/src/TextInput/TextInput.tsx b/packages/core/src/TextInput/TextInput.tsx
index 2fd8df6677..b088d0a0d1 100644
--- a/packages/core/src/TextInput/TextInput.tsx
+++ b/packages/core/src/TextInput/TextInput.tsx
@@ -47,6 +47,7 @@ import {
} from '../Field';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
+import {useTooltip} from '../Tooltip';
const styles = stylex.create({
clearButton: {
@@ -162,6 +163,27 @@ export interface TextInputProps extends Omit<
* @default false
*/
isDisabled?: boolean;
+ /**
+ * 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
+ * stays focusable (via `aria-disabled`) so the reason is discoverable by
+ * 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.
+ *
+ * @example
+ * ```
+ * <TextInput
+ * label="Owner"
+ * value={owner}
+ * isDisabled
+ * disabledMessage="You need the Editor role to change this"
+ * />
+ * ```
+ */
+ disabledMessage?: string;
/**
* Icon to display at the start of the input.
* Accepts a ReactNode (e.g. `<Icon icon={SearchIcon} />`) or an SVG icon component directly.
@@ -252,6 +274,7 @@ export function TextInput({
isOptional = false,
isRequired = false,
isDisabled = false,
+ disabledMessage,
startIcon,
status,
size: sizeProp,
@@ -286,6 +309,20 @@ export function TextInput({
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // 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 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 handleChange.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ // The container div is not naturally focusable; focusin bubbles up from
+ // the input, so always attach focus listeners.
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
const statusIconMap: Record<InputStatusType, IconName> = {
warning: 'warning',
error: 'error',
@@ -305,11 +342,18 @@ export function TextInput({
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
]
.filter(Boolean)
.join(' ') || undefined;
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ // Value can't change while showing a disabled message (the field is
+ // read-only and non-native-disabled), but guard the handler too so the
+ // optimistic value and callbacks never fire.
+ if (isDisabled) {
+ return;
+ }
const newValue = e.target.value;
onChange?.(newValue, e);
if (changeAction && !e.defaultPrevented) {
@@ -336,7 +380,13 @@ export function TextInput({
const inputWrapper = (
<div
- ref={containerRef}
+ ref={el => {
+ containerRef.current = el;
+ // Anchor + hover/focus listeners for the disabled-message tooltip.
+ // Handlers are gated internally by isEnabled, and anchor names
+ // compose, so attaching unconditionally is safe.
+ disabledMessageTooltip.ref(el);
+ }}
onClick={handleWrapperClick}
onMouseUp={handleWrapperMouseUp}
{...mergeProps(
@@ -374,7 +424,12 @@ export function TextInput({
: undefined
}
placeholder={placeholder}
- disabled={isDisabled}
+ // With a disabledMessage the input keeps focusability via aria-disabled
+ // so the reason is focus-discoverable; readOnly + the handleChange guard
+ // keep the value from changing.
+ disabled={isDisabled && !showsDisabledMessage}
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}
+ readOnly={showsDisabledMessage || undefined}
autoFocus={hasAutoFocus}
data-autofocus={hasAutoFocus || undefined}
aria-describedby={ariaDescribedBy}
@@ -405,7 +460,13 @@ export function TextInput({
);
if (inputGroup) {
- return inputWrapper;
+ return (
+ <>
+ {inputWrapper}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </>
+ );
}
return (
@@ -430,6 +491,8 @@ export function TextInput({
labelTooltip={labelTooltip}
width={width}>
{inputWrapper}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
</Field>
);
}