An open source design system that's fully customizable and agent ready
TypeScript
fix(core): taps that start typing raise the touch keyboard (#8158)
Christopher Chedeauad8af75abef8
diff --git a/.changeset/typeahead-edit-focus-in-tap.md b/.changeset/typeahead-edit-focus-in-tap.mdnew file mode 100644index 0000000000..009f0567bd--- /dev/null+++ b/.changeset/typeahead-edit-focus-in-tap.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Taps that start typing in a search field raise the touch keyboard. A tap on a Typeahead's selected value (edit mode) and a tap on the clear button of a Selector or MultiSelector search row now focus the input inside the tap itself instead of one frame later; iOS raises its keyboard only for a focus made while the browser is still handling the tap, so the deferred focus left a caret with no keyboard until a second tap. A clear tapped while the keyboard is already up keeps it up, as before.++@vjeuxdiff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsxindex a87492350e..db80f72646 100644--- a/packages/core/src/Field/PanelSearchInput.tsx+++ b/packages/core/src/Field/PanelSearchInput.tsx@@ -232,19 +232,18 @@ export function PanelSearchInput({(e?: React.MouseEvent<HTMLButtonElement>) => {onValueChange('');// Clearing puts the caret back where the user was typing, matching- // TextInput's built-in clear. Defer focus restoration past the button's- // unmount task so touch browsers don't jump page scroll on tap, while- // preserving synchronous focus for keyboard users.- if (!e || e.detail === 0) {- if (typeof ref === 'object' && ref?.current) {- ref.current.focus();- }- } else {- requestAnimationFrame(() => {- if (typeof ref === 'object' && ref?.current) {- ref.current.focus({preventScroll: true});- }- });+ // TextInput's built-in clear, and it does so inside the tap: iOS raises+ // the software keyboard only for a focus made while the browser is+ // still dispatching the person's tap, and a UIKit search field's clear+ // button makes the field first responder, keyboard and all (measured on+ // iOS 26.2). A frame later the focus came with no keyboard. When the+ // input already has focus, the clear button's pressed state never takes+ // it, so this is a no-op and the keyboard stays where it is.+ // `preventScroll` keeps a pointer tap from scrolling the page.+ if (typeof ref === 'object' && ref?.current) {+ ref.current.focus(+ e == null || e.detail === 0 ? undefined : {preventScroll: true},+ );}},[onValueChange, ref],diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex cb402c8a43..3c90bded7f 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -3829,6 +3829,50 @@ describe('Selector search affordances', () => {expect(search).toHaveFocus();});+ // iOS raises the software keyboard only for a focus made while the browser+ // still dispatches the tap, and a UIKit search field's clear button makes+ // the field first responder even when it was not editing.+ it('puts focus back in the search input inside the tap on clear, after the input lost focus', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ const search = screen.getByRole<HTMLInputElement>('combobox', {+ hidden: true,+ });+ await user.type(search, 'ap');+ const clear = screen.getByRole('button', {+ name: 'Clear Search options',+ hidden: true,+ });+ // The person dismissed the keyboard: the input no longer has focus.+ act(() => search.blur());+ expect(search).not.toHaveFocus();++ const focusedDuring: (string | undefined)[] = [];+ const focus = HTMLElement.prototype.focus;+ Object.defineProperty(search, 'focus', {+ configurable: true,+ value(options?: FocusOptions) {+ focusedDuring.push(window.event?.type);+ focus.call(search, options);+ },+ });+ fireEvent.click(clear, {detail: 1});++ // No frame has run: the focus is in place when the tap's dispatch returns.+ expect(search).toHaveValue('');+ expect(search).toHaveFocus();+ expect(focusedDuring).toEqual(['click']);+ });+it('does not render the clear button when the query is empty', async () => {const user = userEvent.setup();render(diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 67e7d6fa12..afa2393dc6 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -1613,6 +1613,86 @@ describe('BaseTypeahead popover after selection', () => {});describe('Typeahead edit mode', () => {+ // iOS raises the software keyboard only for a focus made while the browser+ // still dispatches the person's tap, so the focus must not wait for a frame.+ it.each([+ ['the token', () => screen.getByText(fruits[0].label)],+ [+ 'the field around it',+ () => screen.getByText(fruits[0].label).closest('div')!,+ ],+ ])(+ 'focuses the input with the label selected inside the tap on %s',+ (_name, target) => {+ const onChangeQuery = vi.fn();+ render(+ <Typeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[0]}+ onChange={vi.fn()}+ onChangeQuery={onChangeQuery}+ />,+ );+ const input = screen.getByRole<HTMLInputElement>('combobox');+ // The event the browser is dispatching when focus() runs.+ const focusedDuring: (string | undefined)[] = [];+ // An own property: some test setups make `focus` an accessor on the+ // prototype, which a plain assignment cannot shadow.+ const focus = HTMLElement.prototype.focus;+ Object.defineProperty(input, 'focus', {+ configurable: true,+ value(options?: FocusOptions) {+ focusedDuring.push(window.event?.type);+ focus.call(input, options);+ },+ });++ fireEvent.click(target());++ // No frame has run: the focus, the text and its selection are all in+ // place by the time the tap's own dispatch returns.+ expect(input).toHaveFocus();+ expect(input.value).toBe(fruits[0].label);+ expect(input.selectionStart).toBe(0);+ expect(input.selectionEnd).toBe(fruits[0].label.length);+ expect(focusedDuring.length).toBeGreaterThan(0);+ expect(focusedDuring.every(type => type === 'click')).toBe(true);+ expect(onChangeQuery).toHaveBeenLastCalledWith(fruits[0].label);+ },+ );++ // The base sees the label as its query by the time the focus lands, so a+ // hasEntriesOnFocus field searches the label instead of opening its+ // bootstrap entries, and Enter cannot commit a bootstrap item.+ it('with hasEntriesOnFocus, editing the value searches its label instead of opening the bootstrap entries', async () => {+ const onChange = vi.fn();+ render(+ <Typeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[3]}+ onChange={onChange}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole<HTMLInputElement>('combobox');++ fireEvent.click(screen.getByText(fruits[3].label));++ expect(input).toHaveFocus();+ expect(input.value).toBe(fruits[3].label);+ // Let any bootstrap or search settle (debounceMs is 0).+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20));+ });++ // Apple is the first bootstrap entry, which the label does not match.+ fireEvent.keyDown(input, {key: 'Enter'});+ expect(onChange).not.toHaveBeenCalledWith(fruits[0]);+ });+it('enters edit mode on token container click', () => {const onChange = vi.fn();render(diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex 1d8d71653d..9e3254431f 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -27,6 +27,7 @@ import React, {type ReactNode,type RefObject,} from 'react';+import {flushSync} from 'react-dom';import * as stylex from '@stylexjs/stylex';import {BusyIndicatorLaneProvider,@@ -462,7 +463,14 @@ export function Typeahead<T extends SearchableItem>({// Show token when value is selected and not in edit modeconst showToken = value != null && !isEditing;- // Enter edit mode: remove token visually, populate input with value label+ // Enter edit mode: remove token visually, populate input with value label.+ //+ // Everything happens inside the tap or click that asked for it, never a+ // frame later: iOS raises the software keyboard only for a focus made while+ // the browser is still dispatching the person's own tap (or when the+ // keyboard is already up). Deferred to an animation frame, the focus landed+ // with no keyboard, so a tap on the selected value showed a caret and+ // nothing to type with until a second tap.const handleEnterEditMode = useCallback(() => {if (isDisabled || !value) {return;@@ -471,21 +479,26 @@ export function Typeahead<T extends SearchableItem>({setIsEditing(true);// The base will receive onChangeQuery with the value's labelonChangeQuery?.(value.label);- requestAnimationFrame(() => {- const input = inputRef.current;- if (input) {- // Set the input value directly since the base manages its own query state- // We trigger a synthetic change to sync the base's internal state- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(- window.HTMLInputElement.prototype,- 'value',- )?.set;+ const input = inputRef.current;+ if (input) {+ // Set the input value directly since the base manages its own query+ // state, and trigger a synthetic change to sync the base's internal+ // state. flushSync commits that query before the focus, so the base's+ // 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 focus+ flushSync(() => {nativeInputValueSetter?.call(input, value.label);input.dispatchEvent(new Event('input', {bubbles: true}));- input.focus();- input.setSelectionRange(0, input.value.length);- }- });+ });+ input.focus();+ input.setSelectionRange(0, input.value.length);+ }}, [isDisabled, value, onChangeQuery]);// Handle blur: restore token if editing and no selection was made