Skip to content

Commit b735ef0

Browse files
fix(Tokenizer): focus hand-offs live in the controls' callback refs and the confirmation's close handler (#9162)
fix(Tokenizer): focus hand-offs live in the controls' callback refs and the confirmation's close handler Co-authored-by: imdreamrunner <imdreamrunner@users.noreply.github.com>
1 parent 94eb29b commit b735ef0

4 files changed

Lines changed: 213 additions & 66 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[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).
6+
7+
@cixzhang @duytbp

‎packages/core/src/Tokenizer/Tokenizer.tsx‎

Lines changed: 54 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import {
8888
import type {SearchableItem, SearchSource} from '../Typeahead/types';
8989
import {composeEventHandlers, mergeProps} from '../utils';
9090
import {joinAriaIDs} from '../utils/inputAria';
91+
import {isFocusDetached} from '../utils/focusReturn';
9192
import {themeProps} from '../utils/themeProps';
9293
import {useTranslator} from '../i18n';
9394
import type {TokenizerBottomSheetProps} from './TokenizerBottomSheet';
@@ -823,14 +824,6 @@ export function Tokenizer<T extends SearchableItem>({
823824
},
824825
[onChangeQuery],
825826
);
826-
// Whether the field's control — the inline input or the trigger — holds
827-
// focus. Kept in a ref by the focus and blur handlers of both, because a
828-
// control unmounted while focused fires no blur: when a presentation swap
829-
// removes the focused control (the latch releasing into the popover, or
830-
// `adaptive` changing while the sheet is closed), the new presentation's
831-
// control takes the focus over once it has mounted, so focus never lands on
832-
// the page body (`component:Tokenizer` FR16, `spec:AST-085` FR4).
833-
const isControlFocusedRef = useRef(false);
834827
// Set around a focus move the field makes itself — a presentation swap
835828
// handing focus from one control to the other — so the receiving control
836829
// does not report it as focus entering from outside.
@@ -841,38 +834,33 @@ export function Tokenizer<T extends SearchableItem>({
841834
// entry, and the one focus the trigger then gets — BottomSheet's return
842835
// focus — is the entry to report.
843836
const hasReportedFocusRef = useRef(false);
844-
// A control can hold focus without the field having seen a focus event:
845-
// the inline input server-rendered with `autofocus` (`hasAutoFocus`) is
846-
// focused before hydration, and the swap to the trigger in the first
847-
// render after it removes that input. React detaches the old control
848-
// before any effect of the swapping commit runs, so the live focus is
849-
// read during that render, while the control is still in the document —
850-
// a read of `document.activeElement` only, with no update made in render.
851-
const previousPresentationRef = useRef(isSheetPresentation);
852-
if (previousPresentationRef.current !== isSheetPresentation) {
853-
previousPresentationRef.current = isSheetPresentation;
854-
if (typeof document !== 'undefined') {
855-
const active = document.activeElement;
856-
if (
857-
active != null &&
858-
(active === inputRef.current || active === triggerRef.current)
859-
) {
860-
isControlFocusedRef.current = true;
861-
}
862-
}
863-
}
864-
useEffect(() => {
865-
if (!isControlFocusedRef.current) {
837+
// When a presentation swap removes the focused control (the latch
838+
// releasing into the popover, or `adaptive` changing while the sheet is
839+
// closed), the new presentation's control takes the focus over, so focus
840+
// never lands on the page body (`component:Tokenizer` FR16, `spec:AST-085`
841+
// FR4). Both controls' callback refs own the hand-off
842+
// (`architecture:react-component-runtime` INV6): the detaching control
843+
// notes that it held focus — it is still in the document then, so this also
844+
// covers a control focused before hydration (`hasAutoFocus`), which no focus
845+
// event reported — and the attaching control takes it.
846+
const isFocusPendingHandOffRef = useRef(false);
847+
const handOffFocusRef = useCallback((node: HTMLElement | null) => {
848+
if (node == null) {
866849
return;
867850
}
868-
const active = document.activeElement;
869-
if (active != null && active !== document.body) {
870-
return;
851+
const takesFocus = isFocusPendingHandOffRef.current;
852+
isFocusPendingHandOffRef.current = false;
853+
if (takesFocus && isFocusDetached(node.ownerDocument)) {
854+
isHandingOffFocusRef.current = true;
855+
node.focus();
856+
isHandingOffFocusRef.current = false;
871857
}
872-
isHandingOffFocusRef.current = true;
873-
(isSheetPresentation ? triggerRef.current : inputRef.current)?.focus();
874-
isHandingOffFocusRef.current = false;
875-
}, [isSheetPresentation]);
858+
return () => {
859+
if (node.ownerDocument.activeElement === node) {
860+
isFocusPendingHandOffRef.current = true;
861+
}
862+
};
863+
}, []);
876864
// The trigger's accessible description names the selected tokens: the
877865
// button's children are tokens whose own content assistive technology
878866
// leaves out of a button's name (`spec:AST-020` FR1).
@@ -947,13 +935,37 @@ export function Tokenizer<T extends SearchableItem>({
947935
focusTrigger: 'always',
948936
isEnabled: showsDisabledMessage,
949937
});
938+
// The inline field's wrapper holds every control a swap removes with the
939+
// input — a token's Remove button, the inline Clear all — so it notes focus
940+
// anywhere inside it for the hand-off above. It also anchors the
941+
// disabled-message tooltip, whose handlers are gated internally by
942+
// isEnabled, so attaching unconditionally is safe.
943+
const tooltipAnchorRef = disabledMessageTooltip.ref;
944+
const wrapperCallbackRef = useCallback(
945+
(el: HTMLDivElement | null) => {
946+
wrapperRef.current = el;
947+
tooltipAnchorRef(el);
948+
if (el == null) {
949+
return;
950+
}
951+
return () => {
952+
if (el.contains(el.ownerDocument.activeElement)) {
953+
isFocusPendingHandOffRef.current = true;
954+
}
955+
wrapperRef.current = null;
956+
tooltipAnchorRef(null);
957+
};
958+
},
959+
[tooltipAnchorRef],
960+
);
950961

951962
// The sheet presentation has no input; the public ref reaches the trigger,
952963
// the control it stands for (`family:input-fields` FR10).
953964
const triggerMergedRef = useMergedRefs<HTMLButtonElement>(
954965
triggerRef,
955966
ref as React.Ref<HTMLButtonElement> | undefined,
956967
disabledMessageTooltip.ref,
968+
handOffFocusRef,
957969
);
958970

959971
useImperativeHandle(handleRef, () => ({
@@ -1034,7 +1046,6 @@ export function Tokenizer<T extends SearchableItem>({
10341046
layer.show();
10351047
}
10361048
if (comingFromOutside) {
1037-
isControlFocusedRef.current = true;
10381049
if (!isHandingOffFocusRef.current) {
10391050
hasReportedFocusRef.current = true;
10401051
onFocus?.(e);
@@ -1052,8 +1063,9 @@ export function Tokenizer<T extends SearchableItem>({
10521063
const handleBlurCapture = useCallback(
10531064
(e: React.FocusEvent) => {
10541065
if (!isFocusInTokenizer(e.relatedTarget)) {
1055-
isControlFocusedRef.current = false;
10561066
hasReportedFocusRef.current = false;
1067+
// Focus left the field: no hand-off is owed any more.
1068+
isFocusPendingHandOffRef.current = false;
10571069
setIsFocusedWithin(false);
10581070
onBlur?.(e);
10591071
if (isLayerMode) {
@@ -1327,13 +1339,7 @@ export function Tokenizer<T extends SearchableItem>({
13271339

13281340
const wrapperContent = (
13291341
<div
1330-
ref={el => {
1331-
wrapperRef.current = el;
1332-
// Anchor + hover/focus listeners for the disabled-message tooltip.
1333-
// Handlers are gated internally by isEnabled, so attaching
1334-
// unconditionally is safe.
1335-
disabledMessageTooltip.ref(el);
1336-
}}
1342+
ref={wrapperCallbackRef}
13371343
role="group"
13381344
aria-label={label}
13391345
onClick={handleWrapperClick}
@@ -1399,6 +1405,7 @@ export function Tokenizer<T extends SearchableItem>({
13991405
// With `experimental`, the ref type admits the trigger too; in
14001406
// this presentation it receives the input.
14011407
ref as React.Ref<HTMLInputElement> | undefined,
1408+
handOffFocusRef,
14021409
)}
14031410
searchSource={isAtMax ? emptySource : filteredSource}
14041411
value={null}
@@ -1533,7 +1540,6 @@ export function Tokenizer<T extends SearchableItem>({
15331540
React.MouseEventHandler<HTMLButtonElement> | undefined,
15341541
)}
15351542
onFocus={event => {
1536-
isControlFocusedRef.current = true;
15371543
// BottomSheet focuses the trigger only after its exit completes;
15381544
// that focus is the signal that the retained sheet can leave. If
15391545
// the resolution moved to the popover meanwhile, the inline input
@@ -1562,8 +1568,8 @@ export function Tokenizer<T extends SearchableItem>({
15621568
if (isSheetOpen) {
15631569
return;
15641570
}
1565-
isControlFocusedRef.current = false;
15661571
hasReportedFocusRef.current = false;
1572+
isFocusPendingHandOffRef.current = false;
15671573
onBlur?.(event);
15681574
}}
15691575
onKeyDown={onKeyDown}

‎packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx‎

Lines changed: 144 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ function Harness({
7272
presentation?: Presentation;
7373
initial?: SearchableItem[];
7474
hasCreate?: boolean;
75+
hasClear?: boolean;
7576
maxEntries?: number;
7677
isDisabled?: boolean;
7778
disabledMessage?: string;
@@ -1806,7 +1807,9 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {
18061807
// changes until the sheet closes.
18071808
compact = false;
18081809
act(() => {
1809-
for (const cb of listeners) {cb();}
1810+
for (const cb of listeners) {
1811+
cb();
1812+
}
18101813
});
18111814
expect(screen.getByRole('dialog', {name: 'Tags'})).toBe(dialog);
18121815
expect(trigger).toBeInTheDocument();
@@ -2550,24 +2553,161 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {
25502553
// the hand-off inside the field reports neither a blur nor a focus.
25512554
compact = false;
25522555
act(() => {
2553-
for (const cb of listeners) {cb();}
2556+
for (const cb of listeners) {
2557+
cb();
2558+
}
25542559
});
25552560
expect(screen.getByRole('combobox')).toHaveFocus();
25562561
expect(onFocus).toHaveBeenCalledTimes(1);
25572562
expect(onBlur).not.toHaveBeenCalled();
25582563
// And back: the input focused, the screen becomes compact again.
25592564
compact = true;
25602565
act(() => {
2561-
for (const cb of listeners) {cb();}
2566+
for (const cb of listeners) {
2567+
cb();
2568+
}
25622569
});
25632570
expect(openTrigger()).toHaveFocus();
25642571
// Unfocused, a change moves nothing.
25652572
openTrigger().blur();
25662573
compact = false;
25672574
act(() => {
2568-
for (const cb of listeners) {cb();}
2575+
for (const cb of listeners) {
2576+
cb();
2577+
}
2578+
});
2579+
expect(document.body).toHaveFocus();
2580+
});
2581+
2582+
it('hands focus to the trigger when a swap removes a focused Remove button or Clear all (FR16)', () => {
2583+
let compact = false;
2584+
const listeners = new Set<() => void>();
2585+
vi.stubGlobal(
2586+
'matchMedia',
2587+
vi.fn().mockImplementation((query: string) => ({
2588+
get matches() {
2589+
return query === COMPACT_TOUCH_QUERY ? compact : false;
2590+
},
2591+
media: query,
2592+
onchange: null,
2593+
addEventListener: (_: string, cb: () => void) => listeners.add(cb),
2594+
removeEventListener: (_: string, cb: () => void) =>
2595+
listeners.delete(cb),
2596+
addListener: vi.fn(),
2597+
removeListener: vi.fn(),
2598+
dispatchEvent: vi.fn(),
2599+
})),
2600+
);
2601+
const turn = (next: boolean) => {
2602+
compact = next;
2603+
act(() => {
2604+
for (const cb of listeners) {
2605+
cb();
2606+
}
2607+
});
2608+
};
2609+
render(<Harness presentation="adaptive" hasClear />);
2610+
// Inline: a token's Remove button holds focus, then the screen turns
2611+
// compact-touch.
2612+
// Enter the field first: focus arriving from the page is redirected to
2613+
// the input, so a Remove button only holds focus once inside.
2614+
screen.getByRole('combobox').focus();
2615+
const remove = screen.getByRole('button', {name: 'Remove Design'});
2616+
remove.focus();
2617+
expect(remove).toHaveFocus();
2618+
turn(true);
2619+
expect(openTrigger()).toHaveFocus();
2620+
// Back to inline, then the inline Clear all holds focus.
2621+
turn(false);
2622+
const clearAll = screen.getByRole('button', {name: 'Clear all'});
2623+
clearAll.focus();
2624+
expect(clearAll).toHaveFocus();
2625+
turn(true);
2626+
expect(openTrigger()).toHaveFocus();
2627+
});
2628+
2629+
it('owes no hand-off once focus has left the field, even after the wrapper re-attached while focused (FR16)', () => {
2630+
const onFocus = vi.fn();
2631+
const stableRef = () => {};
2632+
const field = (isDisabled: boolean, ref: () => void = stableRef) => (
2633+
<TokenizerWithPresentation
2634+
label="Tags"
2635+
searchSource={source}
2636+
value={[]}
2637+
onChange={() => {}}
2638+
onFocus={onFocus}
2639+
isDisabled={isDisabled}
2640+
disabledMessage="You need the Editor role"
2641+
ref={ref}
2642+
experimental={{presentation: 'popover'}}
2643+
/>
2644+
);
2645+
const {rerender} = render(field(false));
2646+
const input = screen.getByRole('combobox');
2647+
input.focus();
2648+
expect(onFocus).toHaveBeenCalledTimes(1);
2649+
// Toggling isDisabled re-attaches the field's wrapper, not the input,
2650+
// while the input holds focus, which notes a hand-off.
2651+
rerender(field(true));
2652+
rerender(field(false));
2653+
expect(input).toHaveFocus();
2654+
// The user leaves the field.
2655+
act(() => {
2656+
input.blur();
25692657
});
25702658
expect(document.body).toHaveFocus();
2659+
// A later re-attach of the input (a new inline ref) must not pull focus
2660+
// back.
2661+
rerender(field(false, () => {}));
2662+
expect(document.body).toHaveFocus();
2663+
expect(onFocus).toHaveBeenCalledTimes(1);
2664+
});
2665+
2666+
it('moves no focus when a control re-attaches without a swap, such as a new ref callback (FR16; react-component-runtime INV6)', () => {
2667+
const onFocus = vi.fn();
2668+
const {rerender} = render(
2669+
<TokenizerWithPresentation
2670+
label="Tags"
2671+
searchSource={source}
2672+
value={[]}
2673+
onChange={() => {}}
2674+
onFocus={onFocus}
2675+
ref={() => {}}
2676+
experimental={{presentation: 'popover'}}
2677+
/>,
2678+
);
2679+
const input = screen.getByRole('combobox');
2680+
input.focus();
2681+
expect(onFocus).toHaveBeenCalledTimes(1);
2682+
// A new inline ref detaches and re-attaches the same input while it
2683+
// holds focus: nothing is handed off, and no focus is reported again.
2684+
rerender(
2685+
<TokenizerWithPresentation
2686+
label="Tags"
2687+
searchSource={source}
2688+
value={[]}
2689+
onChange={() => {}}
2690+
onFocus={onFocus}
2691+
ref={() => {}}
2692+
experimental={{presentation: 'popover'}}
2693+
/>,
2694+
);
2695+
expect(input).toHaveFocus();
2696+
expect(onFocus).toHaveBeenCalledTimes(1);
2697+
// Focus elsewhere: a later re-attach takes nothing back.
2698+
input.blur();
2699+
rerender(
2700+
<TokenizerWithPresentation
2701+
label="Tags"
2702+
searchSource={source}
2703+
value={[]}
2704+
onChange={() => {}}
2705+
onFocus={onFocus}
2706+
ref={() => {}}
2707+
experimental={{presentation: 'popover'}}
2708+
/>,
2709+
);
2710+
expect(document.body).toHaveFocus();
25712711
});
25722712

25732713
it('carries hidden form inputs and the field chrome in the sheet presentation', () => {

0 commit comments

Comments
 (0)