An open source design system that's fully customizable and agent ready
TypeScript
feat(NumberInput): a held stepper repeats into the draft, commits once (#8205)
Christopher Chedeau57aa93cb4e8e
diff --git a/.changeset/number-input-stepper-hold.md b/.changeset/number-input-stepper-hold.mdnew file mode 100644index 0000000000..c8853532ce--- /dev/null+++ b/.changeset/number-input-stepper-hold.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feature] Holding a NumberInput stepper with a mouse or a pen repeats the step: the first repeat comes after 0.5 s, and later ones come faster. The field shows each repeated value as its draft and calls `onChange` once, when the hold ends by release or pointer cancel. A click still steps and commits at once.++@vjeuxdiff --git a/docs/specs/components/NumberInput/NumberInput.spec.md b/docs/specs/components/NumberInput/NumberInput.spec.mdindex 65126a1a7c..a6349fa58f 100644--- a/docs/specs/components/NumberInput/NumberInput.spec.md+++ b/docs/specs/components/NumberInput/NumberInput.spec.md@@ -117,21 +117,21 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |-| FR1 | The input is a native text input with `role="spinbutton"`, `inputMode` `numeric` when integer-only and `decimal` otherwise, `aria-valuemin` and `aria-valuemax` from the range, `aria-valuenow` from the committed `value`, and `aria-valuetext` set to the formatted value when `formatValue` is supplied. | Current tests |-| FR2 | Typing changes only a draft; `onChange` is not called while typing. A draft is valid when it parses for the active locale (grouping, decimal separator, digit script, and sign) and, for validity display, lies within the range and meets integer-only. An invalid draft colors the text secondary, sets `aria-invalid`, and fills a persistent assertive region with the localized invalid-number message. | `spec:AST-086` FR3; `architecture:internationalization`; current tests |-| FR3 | On blur the draft resolves once and ends: an empty draft clears (`onChange(null)` when clearable and a value exists) or reverts; an unparsable or wrong-kind draft reverts; otherwise the number clamps to the range and commits with `onChange(number)` when it differs from `value`. Enter resolves a valid draft the same way and clears an empty draft when clearable. Enter commits nothing for an empty draft without `hasClear`, which stays in the field and is not marked invalid, or for an unparsable or wrong-kind draft, which stays in the field and stays invalid. Enter ends the draft only when its commit clamped. In a field that is not disabled, every Enter outside composition then calls `onEnter`, whatever it committed. | Current tests |-| FR4 | ArrowUp and ArrowDown without modifiers, the wheel over the focused input (when `isWheelEnabled`), and the steppers step by one grid position and commit at once. The grid starts at `min` (when it suits integer-only) or 0. From an empty field or an emptied draft, up goes to `min` or 0 and down to `max` or 0. Results round to the finer of the step's and the grid start's precision (at most 12 decimal places), clamp to the range, and never leave integer-only; a stepper that cannot move does nothing, while an arrow or wheel step that cannot move still ends the draft, committing a valid draft's number and dropping an unparsable one. A caller `onKeyDown` that prevents an arrow cancels that step. A wheel step stops the page from scrolling; otherwise the page scrolls. | Current tests |-| FR5 | With `hasNumberSteppers`, increment and decrement buttons render at the end of the control unless the primary pointer is coarse. On coarse primary pointers the buttons are hidden from layout and the accessibility tree at every viewport width, with no opt-out; the control restores its normal themed end padding. Direct numeric entry and keyboard stepping remain available. When shown, the buttons are outside the tab order, are named with the localized increment and decrement phrases and the label, keep focus on the input when pressed, and expose `aria-disabled` when stepping that way cannot move or the field is disabled or read-only. | `spec:AST-085` FR1, FR2; current tests |-| FR6 | With `formatValue`, the input shows the formatted committed value at rest and the plain locale-formatted number while focused. The form value is then submitted from a hidden input carrying the raw number, and the visible input has no `name`; without `formatValue` the visible input carries `name`. | Current tests |-| FR7 | `units` renders as secondary text after the input and is part of the input's description. | Current tests |-| FR8 | With `hasClear`, a clear button shows while `value` is not `null` and the field is editable. Activating it calls `onChange(null)`, drops the draft, and focuses the input as TextInput's clear does. The clear button is a ghost small `component:Button`, so its press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: it still scales under reduced motion. | `family:input-fields` FR11; current tests |-| FR9 | NumberInput 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: `aria-disabled="true"` and `readOnly` on the input, a kept tab stop, no submitted value, no draft commit (a draft in progress is dropped), no stepping by any route, no caller handlers other than focus and blur, Enter cancelled, the clear button hidden, the control dimmed, and a keyboard focus ring. With `disabledMessage`, a reason tooltip opens on hover and keyboard focus and describes the input. | `spec:AST-085` FR1–FR3, FR6; `family:input-fields` FR4; current tests |-| FR10 | Read-only: `readOnly`, full opacity, still submitted, no edits, and no stepping by keyboard, wheel, or steppers; the wheel then scrolls the page. Disabled wins when both are set. | Current tests |-| FR11 | Arrow and Enter keys that belong to an IME composition neither step nor commit. | Current tests |-| FR12 | Field composition, InputGroup adaptation, status presentation, start icon, click-to-focus, size and iOS text floor, and the prop targets match `component:TextInput` FR1, FR9, FR11–FR13, including its implementation gaps (the fixed height against `spec:AST-102` FR4, an error status without text, the color-only `detached` status, and the grouped description), plus a `labelIcon` passed to Field. | `family:input-fields` FR3, FR8–FR10; current tests |-| FR13 | The control box carries `astryx-number-input` with `data-size`, `data-status`, `data-disabled`, and `data-readonly`. A theme `padding` in any spelling on `number-input` pads the control box and the stepper column together. | `architecture:component-theming-surface`; current tests |+| ID | Invariant | Basis |+| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |+| FR1 | The input is a native text input with `role="spinbutton"`, `inputMode` `numeric` when integer-only and `decimal` otherwise, `aria-valuemin` and `aria-valuemax` from the range, `aria-valuenow` from the committed `value`, and `aria-valuetext` set to the formatted value when `formatValue` is supplied. | Current tests |+| FR2 | Typing changes only a draft; `onChange` is not called while typing. A draft is valid when it parses for the active locale (grouping, decimal separator, digit script, and sign) and, for validity display, lies within the range and meets integer-only. An invalid draft colors the text secondary, sets `aria-invalid`, and fills a persistent assertive region with the localized invalid-number message. | `spec:AST-086` FR3; `architecture:internationalization`; current tests |+| FR3 | On blur the draft resolves once and ends: an empty draft clears (`onChange(null)` when clearable and a value exists) or reverts; an unparsable or wrong-kind draft reverts; otherwise the number clamps to the range and commits with `onChange(number)` when it differs from `value`. Enter resolves a valid draft the same way and clears an empty draft when clearable. Enter commits nothing for an empty draft without `hasClear`, which stays in the field and is not marked invalid, or for an unparsable or wrong-kind draft, which stays in the field and stays invalid. Enter ends the draft only when its commit clamped. In a field that is not disabled, every Enter outside composition then calls `onEnter`, whatever it committed. | Current tests |+| FR4 | ArrowUp and ArrowDown without modifiers, the wheel over the focused input (when `isWheelEnabled`), and the steppers step by one grid position and commit at once. The grid starts at `min` (when it suits integer-only) or 0. From an empty field or an emptied draft, up goes to `min` or 0 and down to `max` or 0. Results round to the finer of the step's and the grid start's precision (at most 12 decimal places), clamp to the range, and never leave integer-only; a stepper that cannot move does nothing, while an arrow or wheel step that cannot move still ends the draft, committing a valid draft's number and dropping an unparsable one. A caller `onKeyDown` that prevents an arrow cancels that step. A wheel step stops the page from scrolling; otherwise the page scrolls. | Current tests |+| FR5 | With `hasNumberSteppers`, increment and decrement buttons render at the end of the control unless the primary pointer is coarse. On coarse primary pointers the buttons are hidden from layout and the accessibility tree at every viewport width, with no opt-out; the control restores its normal themed end padding. Direct numeric entry and keyboard stepping remain available. When shown, the buttons are outside the tab order, are named with the localized increment and decrement phrases and the label, keep focus on the input when pressed, and expose `aria-disabled` when stepping that way cannot move or the field is disabled or read-only. Holding a stepper with a mouse or a pen repeats the step, the first repeat after 0.5 s and then faster; each repeated value shows as the field's draft, and the field commits once, through `onChange`, when the hold ends by release or pointer cancel. A single click steps and commits at once. | `spec:AST-085` FR1, FR2; current tests |+| FR6 | With `formatValue`, the input shows the formatted committed value at rest and the plain locale-formatted number while focused. The form value is then submitted from a hidden input carrying the raw number, and the visible input has no `name`; without `formatValue` the visible input carries `name`. | Current tests |+| FR7 | `units` renders as secondary text after the input and is part of the input's description. | Current tests |+| FR8 | With `hasClear`, a clear button shows while `value` is not `null` and the field is editable. Activating it calls `onChange(null)`, drops the draft, and focuses the input as TextInput's clear does. The clear button is a ghost small `component:Button`, so its press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: it still scales under reduced motion. | `family:input-fields` FR11; current tests |+| FR9 | NumberInput 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: `aria-disabled="true"` and `readOnly` on the input, a kept tab stop, no submitted value, no draft commit (a draft in progress is dropped), no stepping by any route, no caller handlers other than focus and blur, Enter cancelled, the clear button hidden, the control dimmed, and a keyboard focus ring. With `disabledMessage`, a reason tooltip opens on hover and keyboard focus and describes the input. | `spec:AST-085` FR1–FR3, FR6; `family:input-fields` FR4; current tests |+| FR10 | Read-only: `readOnly`, full opacity, still submitted, no edits, and no stepping by keyboard, wheel, or steppers; the wheel then scrolls the page. Disabled wins when both are set. | Current tests |+| FR11 | Arrow and Enter keys that belong to an IME composition neither step nor commit. | Current tests |+| FR12 | Field composition, InputGroup adaptation, status presentation, start icon, click-to-focus, size and iOS text floor, and the prop targets match `component:TextInput` FR1, FR9, FR11–FR13, including its implementation gaps (the fixed height against `spec:AST-102` FR4, an error status without text, the color-only `detached` status, and the grouped description), plus a `labelIcon` passed to Field. | `family:input-fields` FR3, FR8–FR10; current tests |+| FR13 | The control box carries `astryx-number-input` with `data-size`, `data-status`, `data-disabled`, and `data-readonly`. A theme `padding` in any spelling on `number-input` pads the control box and the stepper column together. | `architecture:component-theming-surface`; current tests |### Allowed variation@@ -221,6 +221,7 @@ anatomy-theming map.| AR5 | `NumberInput.a11y.chromium.spec.ts` with its recorded known failure | Read-only | The known failure stops matching when the gap closes. | `audit:NumberInput/accessibility` || FR11 | `NumberInput.test.tsx` "does not step or commit on a composing keydown (IME)" and "waits for IME composition to finish before committing" | Composing arrows and Enter | A step or commit during composition fails. | `audit:NumberInput/behavior` || FR5, FR13, AR4 | `NumberInput.coarse-pointer.a11y.chromium.spec.ts` | Coarse/non-coarse pointers at 390 and 1280 px, LTR/RTL, non-default themed end padding | Visible coarse-pointer steppers, hidden fine-pointer steppers, wrong end padding, or lost direct/keyboard entry fail. | `audit:NumberInput/behavior` |+| FR5 | `NumberInput.test.tsx` "a held stepper" suite | Hold and release; pointer cancel; a bound; clicks; a finger press | A commit per repeat, a repeat after the release, or a step after the field turns disabled or read-only fails. | `audit:NumberInput/behavior` |## Current-state impactdiff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjsindex 45f325779e..984ee9aea4 100644--- a/packages/core/src/NumberInput/NumberInput.doc.mjs+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs@@ -160,7 +160,7 @@ export const docs = {name: 'hasNumberSteppers',type: 'boolean',description:- 'Shows increment and decrement buttons at the end of the input on fine pointers. Hidden on coarse pointers (such as touch screens); text entry and keyboard stepping remain available.',+ 'Shows increment and decrement buttons at the end of the input on fine pointers. Hidden on coarse pointers (such as touch screens); text entry and keyboard stepping remain available. Holding a button with a mouse or a pen repeats the step and commits once, when the hold ends.',default: 'false',},{diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsxindex dc87c7dcc6..19e88bc345 100644--- a/packages/core/src/NumberInput/NumberInput.test.tsx+++ b/packages/core/src/NumberInput/NumberInput.test.tsx@@ -2527,6 +2527,481 @@ describe('NumberInput stepping', () => {expect(onChange).not.toHaveBeenCalled();});+ describe('a held stepper', () => {+ const mousePress = {button: 0, pointerId: 1, pointerType: 'mouse'};++ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ function Controlled({+ onChange,+ initial = 5,+ isReadOnly,+ isDisabled,+ hasNumberSteppers = true,+ }: {+ onChange: (value: number | null) => void;+ initial?: number;+ isReadOnly?: boolean;+ isDisabled?: boolean;+ hasNumberSteppers?: boolean;+ }) {+ const [value, setValue] = useState<number | null>(initial);+ return (+ <NumberInput+ label="Quantity"+ value={value}+ max={10}+ isReadOnly={isReadOnly}+ isDisabled={isDisabled}+ hasNumberSteppers={hasNumberSteppers}+ onChange={next => {+ onChange(next);+ setValue(next);+ }}+ />+ );+ }++ it('repeats into the draft and commits once, on release', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const input = screen.getByRole('spinbutton');+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(499);+ });+ expect(input).toHaveValue('5');+ // The first repeat comes at 0.5 s, the next two 250 ms and 225 ms+ // later.+ act(() => {+ vi.advanceTimersByTime(1 + 250 + 225);+ });+ expect(input).toHaveValue('8');+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(8);+ expect(input).toHaveValue('8');+ expect(input).toHaveFocus();+ });++ it('commits once when the pointer is canceled', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });++ fireEvent.pointerDown(decrement, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ fireEvent.pointerCancel(decrement, mousePress);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(3);+ expect(screen.getByRole('spinbutton')).toHaveValue('3');+ });++ it('stops repeating at a bound and commits the bound once', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} initial={9} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(3000);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('10');+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(10);+ });++ it('steps and commits at once for each click', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });++ for (const expected of [6, 7]) {+ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(100);+ });+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).toHaveBeenLastCalledWith(expected);+ }+ expect(onChange).toHaveBeenCalledTimes(2);+ act(() => {+ vi.advanceTimersByTime(3000);+ });+ expect(onChange).toHaveBeenCalledTimes(2);+ expect(screen.getByRole('spinbutton')).toHaveValue('7');+ });++ it('steps for a click with no pointer after a hold, such as a screen reader activation', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500);+ });+ // The release's click lands elsewhere, so the button gets none.+ fireEvent.pointerUp(increment, mousePress);+ expect(onChange).toHaveBeenLastCalledWith(6);+ fireEvent.click(increment, {detail: 0});+ expect(onChange).toHaveBeenLastCalledWith(7);+ expect(onChange).toHaveBeenCalledTimes(2);+ });++ it.each([+ ['read-only', {isReadOnly: true}],+ ['disabled', {isDisabled: true}],+ ])(+ 'commits nothing when the field becomes %s during the hold',+ (_state, props) => {+ const onChange = vi.fn();+ const {rerender} = render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('7');+ rerender(<Controlled onChange={onChange} {...props} />);+ // The hold ends at once: the draft drops and stops moving.+ expect(screen.getByRole('spinbutton')).toHaveValue('5');+ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('5');+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByRole('spinbutton')).toHaveValue('5');+ },+ );++ it('ends the hold with no commit when the steppers go away', () => {+ const onChange = vi.fn();+ const {rerender} = render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const input = screen.getByRole('spinbutton');++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(input).toHaveValue('7');+ rerender(<Controlled onChange={onChange} hasNumberSteppers={false} />);+ expect(input).toHaveValue('5');+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(input).toHaveValue('5');+ fireEvent.blur(input);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('holds a pen press with no text selection or callout, until it ends', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const penPress = {...mousePress, pointerType: 'pen'};+ const refused = (type: string) =>+ !increment.dispatchEvent(+ new Event(type, {bubbles: true, cancelable: true}),+ );++ fireEvent.pointerDown(increment, penPress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('7');+ expect(refused('selectstart')).toBe(true);+ expect(refused('contextmenu')).toBe(true);+ fireEvent.pointerUp(increment, penPress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(7);+ expect(refused('selectstart')).toBe(false);+ expect(refused('contextmenu')).toBe(false);+ });++ it("lets a second pointer's press replace a running hold", () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });+ const penPress = {...mousePress, pointerId: 2, pointerType: 'pen'};++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ fireEvent.pointerDown(decrement, penPress);+ fireEvent.pointerUp(decrement, penPress);+ fireEvent.click(decrement, {detail: 1});+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ const shown = screen.getByRole<HTMLInputElement>('spinbutton').value;+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ // Nothing keeps stepping once both pointers are up.+ expect(screen.getByRole('spinbutton')).toHaveValue(shown);+ });++ it('lets only the holding pointer end a replaced hold', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });+ const input = screen.getByRole('spinbutton');+ const penPress = {...mousePress, pointerId: 2, pointerType: 'pen'};++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ fireEvent.pointerDown(decrement, penPress);+ // The mouse lifts first; the pen's hold goes on.+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(input).toHaveValue('3');+ fireEvent.pointerUp(decrement, penPress);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(3);+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(input).toHaveValue('3');+ });++ it('ends a mouse hold with no commit when a finger taps a stepper', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });+ const fingerPress = {...mousePress, pointerId: 3, pointerType: 'touch'};++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('7');+ fireEvent.pointerDown(decrement, fingerPress);+ fireEvent.pointerUp(decrement, fingerPress);+ fireEvent.click(decrement, {detail: 1});+ // The tap steps from the committed value; the hold's line is gone.+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(4);+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('spinbutton')).toHaveValue('4');+ });++ it('shows no held value again when the field turns editable mid-hold', () => {+ const onChange = vi.fn();+ const {rerender} = render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const input = screen.getByRole('spinbutton');++ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(input).toHaveValue('7');+ rerender(<Controlled onChange={onChange} isReadOnly />);+ rerender(<Controlled onChange={onChange} />);+ expect(input).toHaveValue('5');+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).not.toHaveBeenCalled();+ expect(input).toHaveValue('5');+ });++ it('keeps a typed draft when the field turns read-only mid-hold', () => {+ const onChange = vi.fn();+ const {rerender} = render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const input = screen.getByRole('spinbutton');++ fireEvent.change(input, {target: {value: '6'}});+ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(input).toHaveValue('8');+ rerender(<Controlled onChange={onChange} isReadOnly />);+ fireEvent.pointerUp(increment, mousePress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).not.toHaveBeenCalled();+ expect(input).toHaveValue('6');+ });++ it('ends a mouse hold with no commit at a context request, and opens the menu', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });+ const input = screen.getByRole('spinbutton');++ // A macOS Control-click is a primary-button press.+ fireEvent.pointerDown(decrement, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(input).toHaveValue('3');+ // fireEvent returns false when a handler refuses the event.+ expect(fireEvent.contextMenu(decrement)).toBe(true);+ expect(input).toHaveValue('5');+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ fireEvent.pointerUp(decrement, mousePress);+ fireEvent.click(decrement, {detail: 1});+ expect(onChange).not.toHaveBeenCalled();+ expect(input).toHaveValue('5');+ });++ it('steps nothing on a click after a context request ends a hold', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });++ fireEvent.pointerDown(decrement, mousePress);+ expect(fireEvent.contextMenu(decrement)).toBe(true);+ fireEvent.click(decrement, {detail: 1});+ fireEvent.pointerUp(decrement, mousePress);+ fireEvent.click(decrement, {detail: 1});+ // The menu may take the pointer's capture before its click.+ fireEvent.pointerDown(decrement, mousePress);+ expect(fireEvent.contextMenu(decrement)).toBe(true);+ fireEvent.lostPointerCapture(decrement, mousePress);+ fireEvent.click(decrement, {detail: 1});+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByRole('spinbutton')).toHaveValue('5');+ });++ it('shows a held value as valid after an invalid typed draft', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const input = screen.getByRole('spinbutton');++ fireEvent.change(input, {target: {value: 'abc'}});+ expect(input).toHaveAttribute('aria-invalid', 'true');+ fireEvent.pointerDown(increment, mousePress);+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(input).toHaveValue('6');+ expect(input).not.toHaveAttribute('aria-invalid');+ fireEvent.pointerUp(increment, mousePress);+ expect(onChange).toHaveBeenCalledWith(6);+ });++ it('enables the other stepper as a hold leaves a bound', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} initial={10} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const decrement = screen.getByRole('button', {+ name: 'Decrement Quantity',+ });++ expect(increment).toHaveAttribute('aria-disabled', 'true');+ fireEvent.pointerDown(decrement, mousePress);+ act(() => {+ vi.advanceTimersByTime(500 + 250);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('8');+ expect(increment).not.toHaveAttribute('aria-disabled');+ fireEvent.pointerUp(decrement, mousePress);+ expect(onChange).toHaveBeenCalledWith(8);+ });++ it('keeps the single step of a finger press', () => {+ const onChange = vi.fn();+ render(<Controlled onChange={onChange} />);+ const increment = screen.getByRole('button', {+ name: 'Increment Quantity',+ });+ const fingerPress = {...mousePress, pointerType: 'touch'};++ fireEvent.pointerDown(increment, fingerPress);+ act(() => {+ vi.advanceTimersByTime(3000);+ });+ expect(screen.getByRole('spinbutton')).toHaveValue('5');+ fireEvent.pointerUp(increment, fingerPress);+ fireEvent.click(increment, {detail: 1});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(6);+ });+ });+it('disables both steppers with the input', () => {render(<NumberInputdiff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsxindex e2c8e8233d..54bfd1cae9 100644--- a/packages/core/src/NumberInput/NumberInput.tsx+++ b/packages/core/src/NumberInput/NumberInput.tsx@@ -4,8 +4,8 @@/*** @file NumberInput.tsx- * @input Uses React, useId, useState, useMemo, useCallback, Field, Icon, InputGroupContext- * @output Exports NumberInput component, NumberInputProps; optional steppers are hidden on coarse pointers+ * @input Uses React, useId, useState, useMemo, useCallback, useEffect, Field, Icon, InputGroupContext+ * @output Exports NumberInput component, NumberInputProps; optional steppers are hidden on coarse pointers, and a held one repeats into the draft* @position Core implementation; consumed by index.ts, tested by NumberInput.test.tsx** SYNC: When modified, update these files to stay in sync:@@ -24,9 +24,12 @@ import {useState,useMemo,useCallback,+ useEffect,useRef,type FocusEvent,type KeyboardEvent,+ type MouseEvent,+ type PointerEvent,type ReactNode,} from 'react';import {flushSync} from 'react-dom';@@ -56,6 +59,7 @@ import {joinAriaIDs} from '../utils/inputAria';import {withholdCallerHandlers} from '../utils/disabledInteraction';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';+import {lockSelection, locksSelectionFor} from '../utils/selectionLock';import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import {useSize} from '../SizeContext/SizeContext';import {useInputContainer} from '../hooks/useInputContainer';@@ -403,6 +407,8 @@ interface NumberInputPropsBase extends Omit</*** Whether to show increment and decrement buttons at the end of the input.* The buttons are hidden on coarse pointers (such as touch screens).+ * Holding a button with a mouse or a pen repeats the step and commits once,+ * when the hold ends.* Direct text entry and keyboard stepping remain available.* @default false*/@@ -460,6 +466,32 @@ export type NumberInputProps =type StepDirection = -1 | 1;+/**+ * A held stepper's timing: the first repeat comes `delayMs` after the press.+ * Each later interval is `acceleration` times the one before, from+ * `firstIntervalMs` down to `minIntervalMs`.+ */+const STEPPER_HOLD = {+ delayMs: 500,+ firstIntervalMs: 250,+ acceleration: 0.9,+ minIntervalMs: 50,+} as const;++/**+ * A held stepper press: its pointer, its next repeat, the value its repeats+ * reached, whether the field stopped taking them, and the release of its+ * selection lock.+ */+type StepperHold = {+ pointerId: number;+ timer: ReturnType<typeof setTimeout> | null;+ held: number | null;+ intervalMs: number;+ isFrozen: boolean;+ unlockSelection: (() => void) | null;+};+function getDecimalPlaces(value: number): number {const [coefficient, exponentText] = String(value).toLowerCase().split('e');const fractionLength = coefficient.split('.')[1]?.length ?? 0;@@ -625,6 +657,13 @@ export function NumberInput({// Pending input while user is typing (null = show formatted value)const [pendingInput, setPendingInput] = useState<string | null>(null);+ // The value a held stepper's repeats reached, shown until the hold ends.+ const [holdDraft, setHoldDraft] = useState<number | null>(null);+ // A field that turns disabled or read-only drops the held value during+ // render, so no commit shows a value that the release does not commit.+ if (holdDraft !== null && (isDisabled || isReadOnly)) {+ setHoldDraft(null);+ }const [isFocused, setIsFocused] = useState(false);// Disabled-reason tooltip. The tooltip listeners attach to the input container (which already exists) and@@ -689,6 +728,9 @@ export function NumberInput({// Preserve pending text while editing. Otherwise show the formatted value// at rest and the raw numeric value while focused so it remains editable.const displayValue = useMemo(() => {+ if (holdDraft !== null) {+ return formatEditableNumber(holdDraft, locale);+ }if (pendingInput !== null) {return pendingInput;}@@ -696,15 +738,19 @@ export function NumberInput({return '';}return isFocused ? formatEditableNumber(value, locale) : formattedValue;- }, [formattedValue, isFocused, locale, pendingInput, value]);+ }, [formattedValue, holdDraft, isFocused, locale, pendingInput, value]);// Check if current pending input is valid (for styling purposes)const isInputValid = useMemo(() => {+ // A held value is a step on the grid, so it is always valid.+ if (holdDraft !== null) {+ return true;+ }if (pendingInput === null || !pendingInput.trim()) {return true;}return parseInput(pendingInput) !== null;- }, [pendingInput, parseInput]);+ }, [holdDraft, pendingInput, parseInput]);// Keep the whole text edit as a draft until an explicit commit boundary.const handleInputChange = useCallback(@@ -850,6 +896,167 @@ export function NumberInput({[getNextValue, isDisabled, isReadOnly, onChange, value],);+ // A held stepper repeats into its own draft and commits once, when the hold+ // ends.+ const stepperHoldRef = useRef<StepperHold | null>(null);+ const isClickAfterHoldRef = useRef(false);+ // The pointer of a repeated hold that another press cancelled. Its own+ // release still swallows the click that follows.+ const cancelledHoldPointerRef = useRef<number | null>(null);++ // Ends a hold with no commit, and drops the draft its repeats wrote.+ const cancelStepperHold = useCallback(() => {+ const hold = stepperHoldRef.current;+ if (hold == null) {+ return;+ }+ stepperHoldRef.current = null;+ cancelledHoldPointerRef.current = hold.held != null ? hold.pointerId : null;+ if (hold.timer != null) {+ clearTimeout(hold.timer);+ }+ hold.unlockSelection?.();+ setHoldDraft(null);+ }, []);++ // Syncs the held stepper's repeat timer with the field's editability: a+ // field that turns disabled or read-only stops the repeats, and the release+ // commits nothing.+ useEffect(() => {+ const hold = stepperHoldRef.current;+ if (hold == null || !(isDisabled || isReadOnly)) {+ return;+ }+ hold.isFrozen = true;+ if (hold.timer != null) {+ clearTimeout(hold.timer);+ hold.timer = null;+ }+ }, [isDisabled, isReadOnly]);++ // The stepper column's removal or unmount ends the hold with no commit, as+ // its buttons can no longer hear the release.+ const stepperColumnRef = useCallback(+ () => () => {+ cancelStepperHold();+ },+ [cancelStepperHold],+ );++ const startStepperHold = (+ direction: StepDirection,+ canStep: boolean,+ event: PointerEvent<HTMLButtonElement>,+ ) => {+ isClickAfterHoldRef.current = false;+ if (cancelledHoldPointerRef.current === event.pointerId) {+ cancelledHoldPointerRef.current = null;+ }+ // Any new press ends a running hold, whichever pointer made it.+ cancelStepperHold();+ // Steppers render only under a non-coarse primary pointer, so a hold is a+ // mouse or pen press. A finger keeps the single step of its click.+ if (+ event.button !== 0 ||+ event.pointerType === 'touch' ||+ !canStep ||+ isDisabled ||+ isReadOnly+ ) {+ return;+ }+ const first = getNextValue(direction);+ if (first == null) {+ return;+ }+ // The release ends the hold wherever the pointer is by then.+ event.currentTarget.setPointerCapture?.(event.pointerId);+ const grid = {direction, min, max, step, isIntegerOnly};+ const hold: StepperHold = {+ pointerId: event.pointerId,+ timer: null,+ held: null,+ intervalMs: STEPPER_HOLD.firstIntervalMs,+ isFrozen: false,+ // A pen's hold starts no text selection or callout.+ unlockSelection: locksSelectionFor(event.pointerType)+ ? lockSelection([event.currentTarget], event.target)+ : null,+ };+ const repeat = () => {+ const next =+ hold.held == null+ ? first+ : getSteppedValue({currentValue: hold.held, ...grid});+ // At a bound the repeats stop, and the release still commits.+ if (next == null || next === hold.held) {+ hold.timer = null;+ return;+ }+ hold.held = next;+ setHoldDraft(next);+ hold.timer = setTimeout(repeat, hold.intervalMs);+ hold.intervalMs = Math.max(+ STEPPER_HOLD.minIntervalMs,+ hold.intervalMs * STEPPER_HOLD.acceleration,+ );+ };+ hold.timer = setTimeout(repeat, STEPPER_HOLD.delayMs);+ stepperHoldRef.current = hold;+ };++ const handleStepperContextMenu = (event: MouseEvent<HTMLButtonElement>) => {+ const hold = stepperHoldRef.current;+ if (hold == null) {+ return;+ }+ // A pen's hold opens no callout menu. A mouse's context request, such as+ // a Control-click, ends its hold with no commit and opens the menu.+ if (hold.unlockSelection != null) {+ event.preventDefault();+ return;+ }+ cancelStepperHold();+ // A click that follows the menu steps nothing, as after any ended hold.+ cancelledHoldPointerRef.current = hold.pointerId;+ isClickAfterHoldRef.current = true;+ };++ const endStepperHold = (end: 'release' | 'cancel', pointerId: number) => {+ const hold = stepperHoldRef.current;+ // Only the pointer that holds can end the hold.+ if (hold == null || hold.pointerId !== pointerId) {+ if (cancelledHoldPointerRef.current === pointerId) {+ cancelledHoldPointerRef.current = null;+ // Only arm the swallow here: a lost capture must not clear it.+ if (end === 'release') {+ isClickAfterHoldRef.current = true;+ }+ }+ return;+ }+ stepperHoldRef.current = null;+ if (hold.timer != null) {+ clearTimeout(hold.timer);+ }+ hold.unlockSelection?.();+ // A press released before its first repeat is a click, and its click+ // steps.+ if (hold.held == null) {+ return;+ }+ isClickAfterHoldRef.current = end === 'release';+ setHoldDraft(null);+ // A frozen hold commits nothing, so a typed draft under it stays.+ if (hold.isFrozen || isDisabled || isReadOnly) {+ return;+ }+ setPendingInput(null);+ if (hold.held !== value) {+ onChange(hold.held);+ }+ };+// Handle keyboard eventsconst handleKeyDown = useCallback((e: KeyboardEvent<HTMLInputElement>) => {@@ -927,8 +1134,15 @@ export function NumberInput({[ref, wheelListenerRef],);- const canIncrement = getNextValue(1) !== valueForStepping;- const canDecrement = getNextValue(-1) !== valueForStepping;+ // While a hold runs, the steppers follow the value that it shows.+ const {canIncrement, canDecrement} = useMemo(() => {+ const base = holdDraft ?? valueForStepping;+ const grid = {currentValue: base, min, max, step, isIntegerOnly};+ return {+ canIncrement: getSteppedValue({...grid, direction: 1}) !== base,+ canDecrement: getSteppedValue({...grid, direction: -1}) !== base,+ };+ }, [holdDraft, isIntegerOnly, max, min, step, valueForStepping]);// Handle clear button clickconst handleClear = useCallback(@@ -1069,7 +1283,7 @@ export function NumberInput({)}{statusIcon}{hasNumberSteppers && (- <div {...stylex.props(styles.numberSteppers)}>+ <div ref={stepperColumnRef} {...stylex.props(styles.numberSteppers)}><buttontype="button"tabIndex={-1}@@ -1078,8 +1292,25 @@ export function NumberInput({isDisabled || isReadOnly || !canIncrement || undefined}aria-label={t('@astryx.numberInput.incrementLabel', {label})}- onPointerDown={event => event.preventDefault()}- onClick={() => {+ onPointerDown={event => {+ event.preventDefault();+ startStepperHold(1, canIncrement, event);+ }}+ onContextMenu={handleStepperContextMenu}+ onPointerUp={event => endStepperHold('release', event.pointerId)}+ onPointerCancel={event => endStepperHold('cancel', event.pointerId)}+ onLostPointerCapture={event =>+ endStepperHold('cancel', event.pointerId)+ }+ onClick={event => {+ const isAfterHold = isClickAfterHoldRef.current;+ isClickAfterHoldRef.current = false;+ // A pointer's click after a held press's release steps nothing.+ // A click with no pointer, such as a screen reader's, steps.+ if (isAfterHold && event.detail > 0) {+ inputRef.current?.focus();+ return;+ }// An aria-disabled stepper does nothing, as a natively disabled// one did (spec:AST-085 FR2).if (isDisabled || isReadOnly || !canIncrement) {@@ -1109,8 +1340,25 @@ export function NumberInput({isDisabled || isReadOnly || !canDecrement || undefined}aria-label={t('@astryx.numberInput.decrementLabel', {label})}- onPointerDown={event => event.preventDefault()}- onClick={() => {+ onPointerDown={event => {+ event.preventDefault();+ startStepperHold(-1, canDecrement, event);+ }}+ onContextMenu={handleStepperContextMenu}+ onPointerUp={event => endStepperHold('release', event.pointerId)}+ onPointerCancel={event => endStepperHold('cancel', event.pointerId)}+ onLostPointerCapture={event =>+ endStepperHold('cancel', event.pointerId)+ }+ onClick={event => {+ const isAfterHold = isClickAfterHoldRef.current;+ isClickAfterHoldRef.current = false;+ // A pointer's click after a held press's release steps nothing.+ // A click with no pointer, such as a screen reader's, steps.+ if (isAfterHold && event.detail > 0) {+ inputRef.current?.focus();+ return;+ }// An aria-disabled stepper does nothing, as a natively disabled// one did (spec:AST-085 FR2).if (isDisabled || isReadOnly || !canDecrement) {