Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tokenizer-focus-handoffs-in-refs.md
Original file line number Diff line number Diff line change
@@ -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 @duytbp
102 changes: 54 additions & 48 deletions packages/core/src/Tokenizer/Tokenizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand All @@ -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;
}
};
Comment on lines +858 to +862

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only the input or the trigger notes a pending hand-off here. With presentation: 'adaptive', a keyboard user on a token's Remove button or the inline Clear all button loses focus to the page body when the screen turns compact-touch; the base moved it to the trigger, because its flag was set on any focus entry into the field. Noting the hand-off when focus is anywhere inside the detaching field (for example from a cleanup-returning callback ref on the inline wrapper that checks el.contains(el.ownerDocument.activeElement)) would restore that, with swap tests that start on Remove and on Clear all.

}, []);
// 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).
Expand Down Expand Up @@ -947,13 +935,37 @@ 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This cleanup also runs when the same wrapper re-attaches through a new wrapperCallbackRef, which happens whenever disabledMessageTooltip.ref changes identity (for example when isDisabled toggles on a field with disabledMessage). Nothing clears the flag on leave, so after the user blurs to the page, the next attach (a new inline ref on the input, or an adaptive swap) takes focus back, with onFocus suppressed. Clearing isFocusPendingHandOffRef in handleBlurCapture's leave branch and the trigger's onBlur keeps every existing test green and stops it.

}
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).
const triggerMergedRef = useMergedRefs<HTMLButtonElement>(
triggerRef,
ref as React.Ref<HTMLButtonElement> | undefined,
disabledMessageTooltip.ref,
handOffFocusRef,
);

useImperativeHandle(handleRef, () => ({
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand Down
148 changes: 144 additions & 4 deletions packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function Harness({
presentation?: Presentation;
initial?: SearchableItem[];
hasCreate?: boolean;
hasClear?: boolean;
maxEntries?: number;
isDisabled?: boolean;
disabledMessage?: string;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -2550,24 +2553,161 @@ 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);
expect(onBlur).not.toHaveBeenCalled();
// 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', () => {
Expand Down
Loading
Loading