An open source design system that's fully customizable and agent ready
TypeScript
fix(Tokenizer): focus hand-offs live in the controls' callback refs and the confirmation's close handler (#9162)
Cindy Zhangb735ef052b36
diff --git a/.changeset/tokenizer-focus-handoffs-in-refs.md b/.changeset/tokenizer-focus-handoffs-in-refs.mdnew file mode 100644index 0000000000..72b9474d99--- /dev/null+++ b/.changeset/tokenizer-focus-handoffs-in-refs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] `Tokenizer` hands focus between its controls from callback refs and the Clear all confirmation's close handler, not from effects, as `architecture:react-component-runtime` INV2 and INV6 require. Where focus lands is unchanged. The presentation swap and the sheet are internal (not yet public). Thanks @imdreamrunner (#7977).++@cixzhang @duytbpdiff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex 8c914bb3b4..a14058602f 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -88,6 +88,7 @@ import {import type {SearchableItem, SearchSource} from '../Typeahead/types';import {composeEventHandlers, mergeProps} from '../utils';import {joinAriaIDs} from '../utils/inputAria';+import {isFocusDetached} from '../utils/focusReturn';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';import type {TokenizerBottomSheetProps} from './TokenizerBottomSheet';@@ -823,14 +824,6 @@ export function Tokenizer<T extends SearchableItem>({},[onChangeQuery],);- // Whether the field's control — the inline input or the trigger — holds- // focus. Kept in a ref by the focus and blur handlers of both, because a- // control unmounted while focused fires no blur: when a presentation swap- // removes the focused control (the latch releasing into the popover, or- // `adaptive` changing while the sheet is closed), the new presentation's- // control takes the focus over once it has mounted, so focus never lands on- // the page body (`component:Tokenizer` FR16, `spec:AST-085` FR4).- const isControlFocusedRef = useRef(false);// Set around a focus move the field makes itself — a presentation swap// handing focus from one control to the other — so the receiving control// does not report it as focus entering from outside.@@ -841,38 +834,33 @@ export function Tokenizer<T extends SearchableItem>({// entry, and the one focus the trigger then gets — BottomSheet's return// focus — is the entry to report.const hasReportedFocusRef = useRef(false);- // A control can hold focus without the field having seen a focus event:- // the inline input server-rendered with `autofocus` (`hasAutoFocus`) is- // focused before hydration, and the swap to the trigger in the first- // render after it removes that input. React detaches the old control- // before any effect of the swapping commit runs, so the live focus is- // read during that render, while the control is still in the document —- // a read of `document.activeElement` only, with no update made in render.- const previousPresentationRef = useRef(isSheetPresentation);- if (previousPresentationRef.current !== isSheetPresentation) {- previousPresentationRef.current = isSheetPresentation;- if (typeof document !== 'undefined') {- const active = document.activeElement;- if (- active != null &&- (active === inputRef.current || active === triggerRef.current)- ) {- isControlFocusedRef.current = true;- }- }- }- useEffect(() => {- if (!isControlFocusedRef.current) {+ // When a presentation swap removes the focused control (the latch+ // releasing into the popover, or `adaptive` changing while the sheet is+ // closed), the new presentation's control takes the focus over, so focus+ // never lands on the page body (`component:Tokenizer` FR16, `spec:AST-085`+ // FR4). Both controls' callback refs own the hand-off+ // (`architecture:react-component-runtime` INV6): the detaching control+ // notes that it held focus — it is still in the document then, so this also+ // covers a control focused before hydration (`hasAutoFocus`), which no focus+ // event reported — and the attaching control takes it.+ const isFocusPendingHandOffRef = useRef(false);+ const handOffFocusRef = useCallback((node: HTMLElement | null) => {+ if (node == null) {return;}- const active = document.activeElement;- if (active != null && active !== document.body) {- return;+ const takesFocus = isFocusPendingHandOffRef.current;+ isFocusPendingHandOffRef.current = false;+ if (takesFocus && isFocusDetached(node.ownerDocument)) {+ isHandingOffFocusRef.current = true;+ node.focus();+ isHandingOffFocusRef.current = false;}- isHandingOffFocusRef.current = true;- (isSheetPresentation ? triggerRef.current : inputRef.current)?.focus();- isHandingOffFocusRef.current = false;- }, [isSheetPresentation]);+ return () => {+ if (node.ownerDocument.activeElement === node) {+ isFocusPendingHandOffRef.current = true;+ }+ };+ }, []);// The trigger's accessible description names the selected tokens: the// button's children are tokens whose own content assistive technology// leaves out of a button's name (`spec:AST-020` FR1).@@ -947,6 +935,29 @@ export function Tokenizer<T extends SearchableItem>({focusTrigger: 'always',isEnabled: showsDisabledMessage,});+ // The inline field's wrapper holds every control a swap removes with the+ // input — a token's Remove button, the inline Clear all — so it notes focus+ // anywhere inside it for the hand-off above. It also anchors the+ // disabled-message tooltip, whose handlers are gated internally by+ // isEnabled, so attaching unconditionally is safe.+ const tooltipAnchorRef = disabledMessageTooltip.ref;+ const wrapperCallbackRef = useCallback(+ (el: HTMLDivElement | null) => {+ wrapperRef.current = el;+ tooltipAnchorRef(el);+ if (el == null) {+ return;+ }+ return () => {+ if (el.contains(el.ownerDocument.activeElement)) {+ isFocusPendingHandOffRef.current = true;+ }+ wrapperRef.current = null;+ tooltipAnchorRef(null);+ };+ },+ [tooltipAnchorRef],+ );// The sheet presentation has no input; the public ref reaches the trigger,// the control it stands for (`family:input-fields` FR10).@@ -954,6 +965,7 @@ export function Tokenizer<T extends SearchableItem>({triggerRef,ref as React.Ref<HTMLButtonElement> | undefined,disabledMessageTooltip.ref,+ handOffFocusRef,);useImperativeHandle(handleRef, () => ({@@ -1034,7 +1046,6 @@ export function Tokenizer<T extends SearchableItem>({layer.show();}if (comingFromOutside) {- isControlFocusedRef.current = true;if (!isHandingOffFocusRef.current) {hasReportedFocusRef.current = true;onFocus?.(e);@@ -1052,8 +1063,9 @@ export function Tokenizer<T extends SearchableItem>({const handleBlurCapture = useCallback((e: React.FocusEvent) => {if (!isFocusInTokenizer(e.relatedTarget)) {- isControlFocusedRef.current = false;hasReportedFocusRef.current = false;+ // Focus left the field: no hand-off is owed any more.+ isFocusPendingHandOffRef.current = false;setIsFocusedWithin(false);onBlur?.(e);if (isLayerMode) {@@ -1327,13 +1339,7 @@ export function Tokenizer<T extends SearchableItem>({const wrapperContent = (<div- ref={el => {- wrapperRef.current = el;- // Anchor + hover/focus listeners for the disabled-message tooltip.- // Handlers are gated internally by isEnabled, so attaching- // unconditionally is safe.- disabledMessageTooltip.ref(el);- }}+ ref={wrapperCallbackRef}role="group"aria-label={label}onClick={handleWrapperClick}@@ -1399,6 +1405,7 @@ export function Tokenizer<T extends SearchableItem>({// With `experimental`, the ref type admits the trigger too; in// this presentation it receives the input.ref as React.Ref<HTMLInputElement> | undefined,+ handOffFocusRef,)}searchSource={isAtMax ? emptySource : filteredSource}value={null}@@ -1533,7 +1540,6 @@ export function Tokenizer<T extends SearchableItem>({React.MouseEventHandler<HTMLButtonElement> | undefined,)}onFocus={event => {- isControlFocusedRef.current = true;// BottomSheet focuses the trigger only after its exit completes;// that focus is the signal that the retained sheet can leave. If// the resolution moved to the popover meanwhile, the inline input@@ -1562,8 +1568,8 @@ export function Tokenizer<T extends SearchableItem>({if (isSheetOpen) {return;}- isControlFocusedRef.current = false;hasReportedFocusRef.current = false;+ isFocusPendingHandOffRef.current = false;onBlur?.(event);}}onKeyDown={onKeyDown}diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsxindex fe866a5208..9abd8f8d36 100644--- a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx@@ -72,6 +72,7 @@ function Harness({presentation?: Presentation;initial?: SearchableItem[];hasCreate?: boolean;+ hasClear?: boolean;maxEntries?: number;isDisabled?: boolean;disabledMessage?: string;@@ -1806,7 +1807,9 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// changes until the sheet closes.compact = false;act(() => {- for (const cb of listeners) {cb();}+ for (const cb of listeners) {+ cb();+ }});expect(screen.getByRole('dialog', {name: 'Tags'})).toBe(dialog);expect(trigger).toBeInTheDocument();@@ -2550,7 +2553,9 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// the hand-off inside the field reports neither a blur nor a focus.compact = false;act(() => {- for (const cb of listeners) {cb();}+ for (const cb of listeners) {+ cb();+ }});expect(screen.getByRole('combobox')).toHaveFocus();expect(onFocus).toHaveBeenCalledTimes(1);@@ -2558,16 +2563,151 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// And back: the input focused, the screen becomes compact again.compact = true;act(() => {- for (const cb of listeners) {cb();}+ for (const cb of listeners) {+ cb();+ }});expect(openTrigger()).toHaveFocus();// Unfocused, a change moves nothing.openTrigger().blur();compact = false;act(() => {- for (const cb of listeners) {cb();}+ for (const cb of listeners) {+ cb();+ }+ });+ expect(document.body).toHaveFocus();+ });++ it('hands focus to the trigger when a swap removes a focused Remove button or Clear all (FR16)', () => {+ let compact = false;+ const listeners = new Set<() => void>();+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ get matches() {+ return query === COMPACT_TOUCH_QUERY ? compact : false;+ },+ media: query,+ onchange: null,+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),+ removeEventListener: (_: string, cb: () => void) =>+ listeners.delete(cb),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const turn = (next: boolean) => {+ compact = next;+ act(() => {+ for (const cb of listeners) {+ cb();+ }+ });+ };+ render(<Harness presentation="adaptive" hasClear />);+ // Inline: a token's Remove button holds focus, then the screen turns+ // compact-touch.+ // Enter the field first: focus arriving from the page is redirected to+ // the input, so a Remove button only holds focus once inside.+ screen.getByRole('combobox').focus();+ const remove = screen.getByRole('button', {name: 'Remove Design'});+ remove.focus();+ expect(remove).toHaveFocus();+ turn(true);+ expect(openTrigger()).toHaveFocus();+ // Back to inline, then the inline Clear all holds focus.+ turn(false);+ const clearAll = screen.getByRole('button', {name: 'Clear all'});+ clearAll.focus();+ expect(clearAll).toHaveFocus();+ turn(true);+ expect(openTrigger()).toHaveFocus();+ });++ it('owes no hand-off once focus has left the field, even after the wrapper re-attached while focused (FR16)', () => {+ const onFocus = vi.fn();+ const stableRef = () => {};+ const field = (isDisabled: boolean, ref: () => void = stableRef) => (+ <TokenizerWithPresentation+ label="Tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ onFocus={onFocus}+ isDisabled={isDisabled}+ disabledMessage="You need the Editor role"+ ref={ref}+ experimental={{presentation: 'popover'}}+ />+ );+ const {rerender} = render(field(false));+ const input = screen.getByRole('combobox');+ input.focus();+ expect(onFocus).toHaveBeenCalledTimes(1);+ // Toggling isDisabled re-attaches the field's wrapper, not the input,+ // while the input holds focus, which notes a hand-off.+ rerender(field(true));+ rerender(field(false));+ expect(input).toHaveFocus();+ // The user leaves the field.+ act(() => {+ input.blur();});expect(document.body).toHaveFocus();+ // A later re-attach of the input (a new inline ref) must not pull focus+ // back.+ rerender(field(false, () => {}));+ expect(document.body).toHaveFocus();+ expect(onFocus).toHaveBeenCalledTimes(1);+ });++ it('moves no focus when a control re-attaches without a swap, such as a new ref callback (FR16; react-component-runtime INV6)', () => {+ const onFocus = vi.fn();+ const {rerender} = render(+ <TokenizerWithPresentation+ label="Tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ onFocus={onFocus}+ ref={() => {}}+ experimental={{presentation: 'popover'}}+ />,+ );+ const input = screen.getByRole('combobox');+ input.focus();+ expect(onFocus).toHaveBeenCalledTimes(1);+ // A new inline ref detaches and re-attaches the same input while it+ // holds focus: nothing is handed off, and no focus is reported again.+ rerender(+ <TokenizerWithPresentation+ label="Tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ onFocus={onFocus}+ ref={() => {}}+ experimental={{presentation: 'popover'}}+ />,+ );+ expect(input).toHaveFocus();+ expect(onFocus).toHaveBeenCalledTimes(1);+ // Focus elsewhere: a later re-attach takes nothing back.+ input.blur();+ rerender(+ <TokenizerWithPresentation+ label="Tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ onFocus={onFocus}+ ref={() => {}}+ experimental={{presentation: 'popover'}}+ />,+ );+ expect(document.body).toHaveFocus();});it('carries hidden form inputs and the field chrome in the sheet presentation', () => {diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsxindex 0538c5dd31..1f73054805 100644--- a/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx@@ -35,6 +35,7 @@ import {type ReactNode,type RefObject,} from 'react';+import {flushSync} from 'react-dom';import * as stylex from '@stylexjs/stylex';import {AlertDialog} from '../AlertDialog/AlertDialog';import {BottomSheet} from '../BottomSheet/BottomSheet';@@ -328,8 +329,9 @@ function TokenizerSheetContent<T extends SearchableItem>({// trigger's press — so an open sheet with no confirmation pending carries// no closed dialog (`architecture:component-style-authoring` INV7). Dialog// has an entrance animation and no exit, so a close is its unmount; the- // sheet then places focus itself, in the Effect below, once the modal is- // gone and the sheet's content can take focus again: on the search field+ // close handler commits that unmount at once and then places focus itself,+ // now that the modal is gone and the sheet's content can take focus again+ // (`architecture:react-component-runtime` INV2): on the search field// after a confirmed clear — the clear is spent, and the search field is// where the next selection starts (FR24, `spec:AST-085` FR4) — and back on// Clear all after a cancel. A confirmed clear is announced there too — a@@ -341,25 +343,17 @@ function TokenizerSheetContent<T extends SearchableItem>({// dialog, so FR14 routes the words into it while the sheet is open.const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);const clearAllRef = useRef<HTMLButtonElement>(null);- const afterConfirmationRef = useRef<'search' | 'clear-all' | null>(null);const announce = useAnnounce();const closeClearConfirmation = (confirmed: boolean) => {- afterConfirmationRef.current = confirmed ? 'search' : 'clear-all';- setIsClearConfirmationOpen(false);- };- useEffect(() => {- if (isClearConfirmationOpen || afterConfirmationRef.current == null) {- return;- }- const destination = afterConfirmationRef.current;- afterConfirmationRef.current = null;- if (destination === 'search') {+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the confirmation must be gone before focus moves into the sheet and the words are routed into it+ flushSync(() => setIsClearConfirmationOpen(false));+ if (confirmed) {searchRef.current?.focus();announce(t('@astryx.tokenizer.allRemoved'));} else {clearAllRef.current?.focus();}- }, [announce, isClearConfirmationOpen, t]);+ };const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);// ---- sheet session ----