From 701363517f25957453acfc733346db281c6e140f Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Sat, 31 Oct 2026 09:33:19 -0700 Subject: [PATCH 1/3] fix(Tokenizer): focus hand-offs live in the controls' callback refs and the confirmation's close handler From the raw-effects audit (architecture:react-component-runtime INV2, INV6). The presentation-swap hand-off was an effect fed by a read of document.activeElement during render; both controls' callback refs now own it: the detaching control notes it held focus (still in the document then, which also covers a control focused before hydration), and the attaching control takes it. The Clear all confirmation's close handler commits the unmount with flushSync and then moves focus and announces, instead of an effect waiting for the next render. Existing FR16 and FR24 focus tests fail with either move removed; a new test shows a re-attach without a swap moves no focus. Co-authored-by: imdreamrunner --- .../tokenizer-focus-handoffs-in-refs.md | 7 ++ packages/core/src/Tokenizer/Tokenizer.tsx | 68 ++++++++----------- .../Tokenizer/TokenizerBottomSheet.test.tsx | 63 +++++++++++++++-- .../src/Tokenizer/TokenizerBottomSheet.tsx | 22 +++--- 4 files changed, 101 insertions(+), 59 deletions(-) create mode 100644 .changeset/tokenizer-focus-handoffs-in-refs.md diff --git a/.changeset/tokenizer-focus-handoffs-in-refs.md b/.changeset/tokenizer-focus-handoffs-in-refs.md new file mode 100644 index 0000000000000..8b9f7baf5f0e2 --- /dev/null +++ b/.changeset/tokenizer-focus-handoffs-in-refs.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] `Tokenizer` hands focus to the new control when a presentation swap removes the focused one, through the controls' callback refs instead of a read of the focused element during render. A render React discards, as concurrent rendering can, no longer drops a keyboard user's focus to the page. After the sheet's Clear all confirmation closes, focus moves, and the clear is announced, in the confirm or cancel handler itself. Thanks @imdreamrunner (#7977). + +@cixzhang @duytbp diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx index 8c914bb3b4878..61570af299fca 100644 --- a/packages/core/src/Tokenizer/Tokenizer.tsx +++ b/packages/core/src/Tokenizer/Tokenizer.tsx @@ -823,14 +823,6 @@ export function Tokenizer({ }, [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 +833,34 @@ export function Tokenizer({ // 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; + const active = node.ownerDocument.activeElement; + if (takesFocus && (active == null || active === node.ownerDocument.body)) { + 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). @@ -954,6 +942,7 @@ export function Tokenizer({ triggerRef, ref as React.Ref | undefined, disabledMessageTooltip.ref, + handOffFocusRef, ); useImperativeHandle(handleRef, () => ({ @@ -1034,7 +1023,6 @@ export function Tokenizer({ layer.show(); } if (comingFromOutside) { - isControlFocusedRef.current = true; if (!isHandingOffFocusRef.current) { hasReportedFocusRef.current = true; onFocus?.(e); @@ -1052,7 +1040,6 @@ export function Tokenizer({ const handleBlurCapture = useCallback( (e: React.FocusEvent) => { if (!isFocusInTokenizer(e.relatedTarget)) { - isControlFocusedRef.current = false; hasReportedFocusRef.current = false; setIsFocusedWithin(false); onBlur?.(e); @@ -1399,6 +1386,7 @@ export function Tokenizer({ // With `experimental`, the ref type admits the trigger too; in // this presentation it receives the input. ref as React.Ref | undefined, + handOffFocusRef, )} searchSource={isAtMax ? emptySource : filteredSource} value={null} @@ -1533,7 +1521,6 @@ export function Tokenizer({ React.MouseEventHandler | 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,7 +1549,6 @@ export function Tokenizer({ if (isSheetOpen) { return; } - isControlFocusedRef.current = false; hasReportedFocusRef.current = false; onBlur?.(event); }} diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx index fe866a5208906..8e2d8b0884f75 100644 --- a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx +++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx @@ -1806,7 +1806,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 +2552,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,18 +2562,69 @@ 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('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( + {}} + 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( + {}} + 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( + {}} + onFocus={onFocus} + ref={() => {}} + experimental={{presentation: 'popover'}} + />, + ); + expect(document.body).toHaveFocus(); + }); + it('carries hidden form inputs and the field chrome in the sheet presentation', () => { const {container} = render( ({ // 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({ // dialog, so FR14 routes the words into it while the sheet is open. const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false); const clearAllRef = useRef(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 ---- From ecdd14cb45d445ec717904facd696e0bc423662f Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Sat, 31 Oct 2026 10:45:27 -0700 Subject: [PATCH 2/3] fix(Tokenizer): the swap hand-off also covers focus on a Remove button or Clear all; changeset says the change is internal Review follow-up: only the input and the trigger noted a pending hand-off, so with adaptive presentation, focus on a token's Remove button or the inline Clear all fell to the body on a swap to the sheet, where the base moved it to the trigger. The inline wrapper's callback ref (now stable) notes focus anywhere inside it on detach, with a swap test from each. The body check uses isFocusDetached. The changeset is a [chore] that says the change sits inside the not-yet-public sheet presentation. --- .../tokenizer-focus-handoffs-in-refs.md | 2 +- packages/core/src/Tokenizer/Tokenizer.tsx | 35 ++++++++++++---- .../Tokenizer/TokenizerBottomSheet.test.tsx | 41 +++++++++++++++++++ 3 files changed, 68 insertions(+), 10 deletions(-) diff --git a/.changeset/tokenizer-focus-handoffs-in-refs.md b/.changeset/tokenizer-focus-handoffs-in-refs.md index 8b9f7baf5f0e2..9dc767a41602b 100644 --- a/.changeset/tokenizer-focus-handoffs-in-refs.md +++ b/.changeset/tokenizer-focus-handoffs-in-refs.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] `Tokenizer` hands focus to the new control when a presentation swap removes the focused one, through the controls' callback refs instead of a read of the focused element during render. A render React discards, as concurrent rendering can, no longer drops a keyboard user's focus to the page. After the sheet's Clear all confirmation closes, focus moves, and the clear is announced, in the confirm or cancel handler itself. Thanks @imdreamrunner (#7977). +[chore] Inside `Tokenizer`'s internal sheet presentation (not yet public), focus hand-offs move from effects into callback refs and the Clear all confirmation's close handler. Public fields, which render only the popover, are unchanged. Thanks @imdreamrunner (#7977). @cixzhang @duytbp diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx index 61570af299fca..0e253f686fc5e 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'; @@ -849,8 +850,7 @@ export function Tokenizer({ } const takesFocus = isFocusPendingHandOffRef.current; isFocusPendingHandOffRef.current = false; - const active = node.ownerDocument.activeElement; - if (takesFocus && (active == null || active === node.ownerDocument.body)) { + if (takesFocus && isFocusDetached(node.ownerDocument)) { isHandingOffFocusRef.current = true; node.focus(); isHandingOffFocusRef.current = false; @@ -935,6 +935,29 @@ export function Tokenizer({ 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). @@ -1314,13 +1337,7 @@ export function Tokenizer({ const wrapperContent = (
{ - 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} diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx index 8e2d8b0884f75..82bc9d34ac9b3 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; @@ -2578,6 +2579,46 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => { 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(); + // Inline: a token's Remove button holds focus, then the screen turns + // compact-touch. + screen.getByRole('button', {name: 'Remove Design'}).focus(); + turn(true); + expect(openTrigger()).toHaveFocus(); + // Back to inline, then the inline Clear all holds focus. + turn(false); + screen.getByRole('button', {name: 'Clear all'}).focus(); + turn(true); + expect(openTrigger()).toHaveFocus(); + }); + 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( From 8573c1477b0d3f82cd42f5437846e180359c8c5d Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Sat, 31 Oct 2026 14:00:18 -0700 Subject: [PATCH 3/3] fix(Tokenizer): leaving the field clears a pending hand-off; the changeset calls this a conformance change Review follow-up: a wrapper re-attached while focused (an isDisabled toggle with disabledMessage) left the hand-off pending, so after the user left the field a new inline ref or a swap pulled focus back. The blur-capture leave branch and the trigger's onBlur now clear it, with a regression test that fails without the clear. The Remove/Clear all swap test enters the field first, so it tests the Remove path. The changeset is a [chore] conformance note: where focus lands is unchanged. --- .../tokenizer-focus-handoffs-in-refs.md | 2 +- packages/core/src/Tokenizer/Tokenizer.tsx | 3 ++ .../Tokenizer/TokenizerBottomSheet.test.tsx | 48 ++++++++++++++++++- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/.changeset/tokenizer-focus-handoffs-in-refs.md b/.changeset/tokenizer-focus-handoffs-in-refs.md index 9dc767a41602b..72b9474d99a93 100644 --- a/.changeset/tokenizer-focus-handoffs-in-refs.md +++ b/.changeset/tokenizer-focus-handoffs-in-refs.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Inside `Tokenizer`'s internal sheet presentation (not yet public), focus hand-offs move from effects into callback refs and the Clear all confirmation's close handler. Public fields, which render only the popover, are unchanged. Thanks @imdreamrunner (#7977). +[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 @duytbp diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx index 0e253f686fc5e..a14058602fdde 100644 --- a/packages/core/src/Tokenizer/Tokenizer.tsx +++ b/packages/core/src/Tokenizer/Tokenizer.tsx @@ -1064,6 +1064,8 @@ export function Tokenizer({ (e: React.FocusEvent) => { if (!isFocusInTokenizer(e.relatedTarget)) { hasReportedFocusRef.current = false; + // Focus left the field: no hand-off is owed any more. + isFocusPendingHandOffRef.current = false; setIsFocusedWithin(false); onBlur?.(e); if (isLayerMode) { @@ -1567,6 +1569,7 @@ export function Tokenizer({ return; } 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.tsx index 82bc9d34ac9b3..9abd8f8d36994 100644 --- a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx +++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx @@ -2609,16 +2609,60 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => { render(); // Inline: a token's Remove button holds focus, then the screen turns // compact-touch. - screen.getByRole('button', {name: 'Remove Design'}).focus(); + // 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); - screen.getByRole('button', {name: 'Clear all'}).focus(); + 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) => ( + {}} + 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(