An open source design system that's fully customizable and agent ready
TypeScript
fix(TextInput): dispatch changeAction and update optimistic value on clear (#6425)
Manohar Paturibb0786673c00
diff --git a/.changeset/text-input-clear-change-action.md b/.changeset/text-input-clear-change-action.mdnew file mode 100644index 0000000000..842f897dd3--- /dev/null+++ b/.changeset/text-input-clear-change-action.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] TextInput: the clear button now runs `changeAction` with the empty value and shows the optimistic empty value and busy state, as typing does. The clear goes through the input's own change handler, so `onChange` and `changeAction` receive a real change event (before, `onChange` received `null` as its event and `changeAction` did not run), `onChange` runs first, and its `preventDefault()` cancels the Action.++@ManoharPaturi @cixzhangdiff --git a/docs/families/input-fields.md b/docs/families/input-fields.mdindex f4958f353a..9512ae69fb 100644--- a/docs/families/input-fields.md+++ b/docs/families/input-fields.md@@ -371,8 +371,8 @@ DEC-6 does not require unrelated components to add a new floor.options available while input `isLoading` is true, but current empty/no-resultpresentation still treats that flag as option-source pending and neithercomponent has the explicit source-pending API required by AST-001.-- **Transition Action coverage:** current TextInput and FileInput clear- affordances call `onChange` without `changeAction`, and FileInput does not+- **Transition Action coverage:** the current FileInput clear affordance+ calls `onChange` without `changeAction`, and FileInput does notexplicitly hold the proposed controlled files as an optimistic value whileits Action is pending. Other exposed clear paths inspected on current mainroute through their ordinary Action pipeline. These are conformance gapsdiff --git a/docs/specs/components/TextInput/TextInput.spec.md b/docs/specs/components/TextInput/TextInput.spec.mdindex cf73929625..81265924d6 100644--- a/docs/specs/components/TextInput/TextInput.spec.md+++ b/docs/specs/components/TextInput/TextInput.spec.md@@ -35,15 +35,15 @@ system_specs: [spec:AST-082, spec:AST-085, spec:AST-086, spec:AST-102]## Contract at a glance-| Area | Contract |-| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | TextInput is a controlled single-line text field with Field props, `type` (`text`, `password`, `email`, `search`, `tel`, `url`), size, status, clear, start icon, `onChange`, `changeAction`, `isLoading`, disabled and read-only states, the touch-keyboard props `enterKeyHint`, `inputMode`, `autoCapitalize`, `hasAutoCorrect`, and `hasSpellCheck` (FR16), and the input-family part props. |-| Behavior | Typing calls `onChange`, then an optional `changeAction` in a transition with an optimistic value, and a busy Spinner while the shown value differs from `value`. A disabled field stays focusable, read-only, unsubmitted, and inert. |-| End-user impact | People type into a labelled field that shows progress and validation in place. Keyboard and screen-reader users can reach a disabled field and its reason. An error without a message is signalled only by color and an icon. On a phone, a field its caller describes opens the keyboard it needs, such as a phone pad or a number pad, with a Return key that says Next, Go, or Done, and leaves names as typed. |-| Builder impact | Callers can choose the touch keyboard, its Return key label, capitalization, correction, and spell-check marking (FR16); an unset prop leaves the field as it is. |-| Compatibility/readiness | The touch-keyboard props and the `search`, `tel`, and `url` types are additive, a patch `[feat]` (`spec:AST-017` FR5, FR7). Otherwise the record states shipped behavior. The clear action skips `changeAction`, the clear button scales under reduced motion, an error may lack text, the height does not grow with text, a `detached` status without a message is color-only, and a grouped `description` is referenced but not rendered; all are listed under Current-state impact. |-| Review checks | Reject a disabled field that leaves the tab order, submits, or runs caller handlers; an Enter that fires `onEnter` while committing an IME conversion; a busy state without `aria-busy`; root styling props; a keyboard prop that renders an attribute while unset or changes what Enter does; or a keyboard value type that accepts any string. |-| Governing rules | `family:input-fields` FR1, FR2, FR3, FR4, FR6, FR8–FR11; `spec:AST-085` FR1–FR3, FR5–FR7; `spec:AST-086` FR8; `architecture:component-size-cascade` INV3–INV5; `design:reduced-motion` DR1; `spec:AST-102` FR4; `architecture:public-component-api` INV2–INV4, INV25; `spec:AST-082` FR3, DEC-14; `spec:AST-017` FR5, FR7. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | TextInput is a controlled single-line text field with Field props, `type` (`text`, `password`, `email`, `search`, `tel`, `url`), size, status, clear, start icon, `onChange`, `changeAction`, `isLoading`, disabled and read-only states, the touch-keyboard props `enterKeyHint`, `inputMode`, `autoCapitalize`, `hasAutoCorrect`, and `hasSpellCheck` (FR16), and the input-family part props. |+| Behavior | Typing calls `onChange`, then an optional `changeAction` in a transition with an optimistic value, and a busy Spinner while the shown value differs from `value`. A disabled field stays focusable, read-only, unsubmitted, and inert. |+| End-user impact | People type into a labelled field that shows progress and validation in place. Keyboard and screen-reader users can reach a disabled field and its reason. An error without a message is signalled only by color and an icon. On a phone, a field its caller describes opens the keyboard it needs, such as a phone pad or a number pad, with a Return key that says Next, Go, or Done, and leaves names as typed. |+| Builder impact | Callers can choose the touch keyboard, its Return key label, capitalization, correction, and spell-check marking (FR16); an unset prop leaves the field as it is. |+| Compatibility/readiness | The touch-keyboard props and the `search`, `tel`, and `url` types are additive, a patch `[feat]` (`spec:AST-017` FR5, FR7). Otherwise the record states shipped behavior. The clear button scales under reduced motion, an error may lack text, the height does not grow with text, a `detached` status without a message is color-only, and a grouped `description` is referenced but not rendered; all are listed under Current-state impact. |+| Review checks | Reject a disabled field that leaves the tab order, submits, or runs caller handlers; an Enter that fires `onEnter` while committing an IME conversion; a busy state without `aria-busy`; root styling props; a keyboard prop that renders an attribute while unset or changes what Enter does; or a keyboard value type that accepts any string. |+| Governing rules | `family:input-fields` FR1, FR2, FR3, FR4, FR6, FR8–FR11; `spec:AST-085` FR1–FR3, FR5–FR7; `spec:AST-086` FR8; `architecture:component-size-cascade` INV3–INV5; `design:reduced-motion` DR1; `spec:AST-102` FR4; `architecture:public-component-api` INV2–INV4, INV25; `spec:AST-082` FR3, DEC-14; `spec:AST-017` FR5, FR7. |This table is a review projection; the body below is authoritative.@@ -118,7 +118,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR2 | The input is a native `<input>` of the chosen `type` showing the controlled value. `htmlName` becomes `name`, `autoComplete` reaches the input unchanged, and `hasAutoFocus` focuses it on mount. | Current tests || FR3 | Editing calls `onChange(value, event)`. Unless that call prevents default, `changeAction(value, event)` then runs in a transition; the field shows the proposed value while the Action is pending, and the controlled `value` once it settles. | `family:input-fields` FR6; current source || FR4 | While `isLoading` or while the shown value differs from `value`, the input sets `aria-busy`, a decorative small Spinner shows in the end area, and the busy start is announced once (`spec:AST-086` FR8). | `family:input-fields` FR5; `spec:AST-086` FR8; current source |-| FR5 | With `hasClear`, a clear button shows only while `value` is non-empty and the field is editable. Its accessible name is the localized "Clear" phrase with the label. Activating it MUST commit `''` through FR3's pipeline (`onChange`, then the optimistic value and `changeAction`) and moves focus to the input: at once for keyboard activation, and inside the tap without scrolling for pointer activation. The clear button is a ghost small `component:Button`, so its press feedback follows Button FR15, whose press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: it calls only `onChange('')`, with no event, and skips the optimistic value and `changeAction`; and its press scale still applies under reduced motion. | `family:input-fields` FR6, FR11; current tests |+| FR5 | With `hasClear`, a clear button shows only while `value` is non-empty and the field is editable. Its accessible name is the localized "Clear" phrase with the label. Activating it MUST commit `''` through FR3's pipeline (`onChange`, then the optimistic value and `changeAction`) and moves focus to the input: at once for keyboard activation, and inside the tap without scrolling for pointer activation. The clear button is a ghost small `component:Button`, so its press feedback follows Button FR15, whose press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: its press scale still applies under reduced motion. | `family:input-fields` FR6, FR11; current tests || FR6 | TextInput is disabled when its own `isDisabled` or an enclosing InputGroup's `isDisabled` is true; an enabled group never re-enables a field that disables itself (`spec:AST-085` FR7). Disabled: the input exposes `aria-disabled="true"` and `readOnly`, keeps its tab stop, has no `name` (so it does not submit), and never changes value. Caller event handlers other than focus and blur do not run, Enter is cancelled, the clear button hides, the control dims, and keyboard focus paints a ring. | `spec:AST-085` FR1–FR3, FR6; current tests || FR7 | Disabled with `disabledMessage`: a tooltip with the reason opens above the control on hover and keyboard focus, and describes the input. | `family:input-fields` FR4; current tests || FR8 | Read-only: the input is `readOnly`, keeps full opacity, stays focusable, still submits under `name`, never calls `onChange`, and hides the clear button. Disabled wins when both are set. | Current tests |@@ -238,10 +238,6 @@ anatomy-theming map.## Current-state impact-- **Clear skips the Action (FR5).** The clear button calls `onChange('')`- without running `changeAction` or showing the optimistic value, against- `family:input-fields` FR6, and passes no event although the callback type- declares one.- **Error without text (AR4).** TextInput accepts an error status without amessage, so the error is shown only by color and an icon, against WCAG 2.23.3.1. The accessibility suite records this as a known failure.diff --git a/packages/core/src/TextInput/TextInput.test.tsx b/packages/core/src/TextInput/TextInput.test.tsxindex 8823d89b3d..2d89cc26e0 100644--- a/packages/core/src/TextInput/TextInput.test.tsx+++ b/packages/core/src/TextInput/TextInput.test.tsx@@ -11,7 +11,7 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent, waitFor} from '@testing-library/react';+import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import * as stylex from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';@@ -1026,7 +1026,85 @@ describe('TextInput', () => {<TextInput label="Name" value="hello" onChange={onChange} hasClear />,);await user.click(screen.getByRole('button', {name: 'Clear Name'}));- expect(onChange).toHaveBeenCalledWith('', null);+ expect(onChange).toHaveBeenCalledWith(+ '',+ expect.objectContaining({target: screen.getByRole('textbox')}),+ );+ });++ it('calls onChange, then changeAction, with an empty string and the change event when clear is clicked', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const changeAction = vi.fn();+ render(+ <TextInput+ label="Name"+ value="hello"+ onChange={onChange}+ changeAction={changeAction}+ hasClear+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Clear Name'}));+ const input = screen.getByRole('textbox');+ // A real change event, so an Action that reads e.target works on clear.+ expect(onChange).toHaveBeenCalledWith(+ '',+ expect.objectContaining({target: input}),+ );+ expect(changeAction).toHaveBeenCalledWith(+ '',+ expect.objectContaining({target: input}),+ );+ expect(onChange.mock.invocationCallOrder[0]).toBeLessThan(+ changeAction.mock.invocationCallOrder[0],+ );+ });++ it('runs no changeAction on clear when onChange prevents the change event', async () => {+ const user = userEvent.setup();+ const changeAction = vi.fn();+ render(+ <TextInput+ label="Name"+ value="hello"+ onChange={(_value, e) => e.preventDefault()}+ changeAction={changeAction}+ hasClear+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Clear Name'}));+ expect(changeAction).not.toHaveBeenCalled();+ });++ it('presents optimistic empty value and busy state while clear changeAction is pending', async () => {+ const user = userEvent.setup();+ let resolveAction: () => void = () => {};+ const changeAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolveAction = resolve;+ }),+ );+ render(+ <TextInput+ label="Name"+ value="hello"+ onChange={() => {}}+ changeAction={changeAction}+ hasClear+ />,+ );+ const input = screen.getByRole('textbox');+ expect(input).toHaveValue('hello');++ await user.click(screen.getByRole('button', {name: 'Clear Name'}));+ expect(input).toHaveValue('');+ expect(input).toHaveAttribute('aria-busy', 'true');++ await act(async () => {+ resolveAction();+ });});});diff --git a/packages/core/src/TextInput/TextInput.tsx b/packages/core/src/TextInput/TextInput.tsxindex 9f64e3f571..1238f45e2d 100644--- a/packages/core/src/TextInput/TextInput.tsx+++ b/packages/core/src/TextInput/TextInput.tsx@@ -129,6 +129,7 @@ import {themeProps} from '../utils/themeProps';import {useMergedRefs} from '../hooks/useMergedRefs';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';+import {setInputValue} from '../utils/setInputValue';import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';import {registerEnglishFallback,@@ -454,23 +455,25 @@ export function TextInput({}};- // Handle clear button click- const handleClear = useCallback(- (e?: React.MouseEvent<HTMLButtonElement>) => {- onChange?.('', null as unknown as ChangeEvent<HTMLInputElement>);- if (!e || e.detail === 0) {- inputRef.current?.focus();- } else {- // Focus inside the tap: iOS Safari brings up its keyboard only for a- // focus made while handling the touch, so a field the tap reaches- // unfocused gets its keyboard, as UIKit's clear button makes the- // field first responder. `preventScroll` keeps a scrolled page where- // it is.- inputRef.current?.focus({preventScroll: true});- }- },- [onChange],- );+ // A native value set and an `input` event run the input's own change handler.+ // So the clear gets a real change event and the same callback order and+ // cancellation as typing.+ const handleClear = useCallback((e?: React.MouseEvent<HTMLButtonElement>) => {+ const input = inputRef.current;+ if (input != null && input.value !== '') {+ setInputValue(input, '');+ }+ if (!e || e.detail === 0) {+ inputRef.current?.focus();+ } else {+ // Focus inside the tap: iOS Safari brings up its keyboard only for a+ // focus made while handling the touch, so a field the tap reaches+ // unfocused gets its keyboard, as UIKit's clear button makes the+ // field first responder. `preventScroll` keeps a scrolled page where+ // it is.+ inputRef.current?.focus({preventScroll: true});+ }+ }, []);// Focus input when clicking anywhere on the wrapper (icons, padding, etc.)const {onClick: handleWrapperClick, onMouseUp: handleWrapperMouseUp} =diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex 5a55f9159e..3d6c6c775d 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -78,6 +78,7 @@ import {useMergedRefs} from '../hooks/useMergedRefs';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useResolvedRequired} from '../hooks/useResolvedRequired';import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';+import {setInputValue} from '../utils/setInputValue';import {registerEnglishFallback,useComponentTranslator,@@ -513,14 +514,9 @@ export function Typeahead<T extends SearchableItem>({// focus handler sees the label rather than an empty query: an empty one// would open the hasEntriesOnFocus bootstrap entries, and Enter would// commit the first of them instead of the edited value.- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(- window.HTMLInputElement.prototype,- 'value',- )?.set;// eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the base must hold the label as its query before the in-tap focusflushSync(() => {- nativeInputValueSetter?.call(input, value.label);- input.dispatchEvent(new Event('input', {bubbles: true}));+ setInputValue(input, value.label);});input.focus();input.setSelectionRange(0, input.value.length);@@ -588,12 +584,7 @@ export function Typeahead<T extends SearchableItem>({const handleClear = useCallback(() => {const input = inputRef.current;if (input && input.value !== '') {- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(- window.HTMLInputElement.prototype,- 'value',- )?.set;- nativeInputValueSetter?.call(input, '');- input.dispatchEvent(new Event('input', {bubbles: true}));+ setInputValue(input, '');}setIsEditing(false);setEditingValue(null);diff --git a/packages/core/src/utils/setInputValue.ts b/packages/core/src/utils/setInputValue.tsnew file mode 100644index 0000000000..0b9a5ff89c--- /dev/null+++ b/packages/core/src/utils/setInputValue.ts@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file setInputValue.ts+ * @input An input element and a new value+ * @output Sets the value as the user would, so the input's own change handler+ * runs+ * @position Internal utility; used by TextInput's clear and Typeahead's+ * edit and clear paths. Not exported from the utils entry.+ */++/**+ * Set `input`'s value through the native setter and dispatch an `input`+ * event. React tracks the value it last wrote, so a plain assignment fires no+ * `onChange`. The native setter makes React see a real change, and the event+ * reaches the input's own change handler with a real change event.+ */+export function setInputValue(input: HTMLInputElement, value: string): void {+ const setNativeValue = Object.getOwnPropertyDescriptor(+ input.ownerDocument.defaultView?.HTMLInputElement.prototype ??+ HTMLInputElement.prototype,+ 'value',+ )?.set;+ setNativeValue?.call(input, value);+ input.dispatchEvent(new Event('input', {bubbles: true}));+}