Skip to content

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

TypeScript

refactor(NumberInput): re-select the editable text in the focus handler (#9150)

Cindy Zhang67613a7ea1c0
diff --git a/.changeset/numberinput-focus-reselect-in-handler.md b/.changeset/numberinput-focus-reselect-in-handler.md
new file mode 100644
index 0000000000..e3a3672dcd
--- /dev/null
+++ b/.changeset/numberinput-focus-reselect-in-handler.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: when Tab moves focus into a NumberInput with `formatValue`, the focus handler itself puts the editable text in the input and selects it, instead of a layout effect that waited for the next render. Behavior is unchanged: typing still replaces the whole number.
+
+@HelloOjasMutreja
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 1630864ff0..dc87c7dcc6 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -381,6 +381,34 @@ describe('NumberInput', () => {
expect(input.selectionEnd).toBe('1500000'.length);
});
+ it('selects the editable text when Tab moves focus into the field', async () => {
+ const user = userEvent.setup();
+ const onFocus = vi.fn();
+ render(
+ <>
+ <button type="button">Before</button>
+ <NumberInput
+ label="Amount"
+ value={1500000}
+ onChange={() => {}}
+ onFocus={onFocus}
+ formatValue={number => number.toLocaleString('en-US')}
+ />
+ </>,
+ );
+ const input = screen.getByRole<HTMLInputElement>('spinbutton');
+ await user.click(screen.getByRole('button', {name: 'Before'}));
+ await user.tab();
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue('1500000');
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('1500000'.length);
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // Typing replaces the whole number.
+ await user.keyboard('42');
+ expect(input).toHaveValue('42');
+ });
+
it('does not swallow keystrokes when focus swaps no text', async () => {
const user = userEvent.setup();
function Controlled() {
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index 81e208dc0b..43003dbeae 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -24,12 +24,12 @@ import {
useState,
useMemo,
useCallback,
- useLayoutEffect,
useRef,
type FocusEvent,
type KeyboardEvent,
type ReactNode,
} from 'react';
+import {flushSync} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -723,39 +723,32 @@ export function NumberInput({
// `formatValue` the text at rest differs from the editable text, and putting
// the editable text in the input after focus collapses that selection to the
// end, so typing would append. When focus arrives with the text selected,
- // select the swapped-in text too.
- const reselectOnFocusRef = useRef(false);
-
+ // the focus handler commits the swap and selects the swapped-in text itself:
+ // the work one event causes stays in its handler
+ // (architecture:react-component-runtime/INV2).
const handleFocus = useCallback(
(e: FocusEvent<HTMLInputElement>) => {
const input = e.currentTarget;
- // Only when focusing swaps the text: otherwise no render follows to
- // consume the flag, and the first keystroke would.
const editableText =
pendingInput ??
(value == null ? '' : formatEditableNumber(value, locale));
- reselectOnFocusRef.current =
+ const shouldReselect =
input.value.length > 0 &&
input.value !== editableText &&
input.selectionStart === 0 &&
input.selectionEnd === input.value.length;
setIsFocused(true);
onFocus?.(e);
+ if (shouldReselect) {
+ // Commit the swap now, so the editable text is in the input to select.
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the editable text must be in the input before the focus event selects it
+ flushSync(() => {});
+ input.setSelectionRange(0, input.value.length);
+ }
},
[onFocus, pendingInput, value, locale],
);
- useLayoutEffect(() => {
- if (!reselectOnFocusRef.current) {
- return;
- }
- reselectOnFocusRef.current = false;
- const input = inputRef.current;
- if (input != null && input === document.activeElement) {
- input.setSelectionRange(0, input.value.length);
- }
- }, [displayValue]);
-
const commitPendingInput = useCallback(
(trigger: 'blur' | 'Enter') => {
if (pendingInput === null) {