Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
---

[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).

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.

The public Tokenizer offers no presentation option and renders only the popover, so it has no presentation swap or sheet, and on the base a discarded render only affected the hasAutoFocus hydration focus. As written, the release note tells consumers a public focus bug was fixed. Suggest wording that says the change is inside the internal sheet presentation (not yet public) and that public fields are unchanged.


@cixzhang @duytbp
68 changes: 27 additions & 41 deletions packages/core/src/Tokenizer/Tokenizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -823,14 +823,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 +833,34 @@ 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;
const active = node.ownerDocument.activeElement;
if (takesFocus && (active == null || active === node.ownerDocument.body)) {

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 is isFocusDetached(node.ownerDocument) from utils/focusReturn.ts, which also treats documentElement as detached. Calling it keeps one definition of "focus is on nothing".

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 @@ -954,6 +942,7 @@ export function Tokenizer<T extends SearchableItem>({
triggerRef,
ref as React.Ref<HTMLButtonElement> | undefined,
disabledMessageTooltip.ref,
handOffFocusRef,
);

useImperativeHandle(handleRef, () => ({
Expand Down Expand Up @@ -1034,7 +1023,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,7 +1040,6 @@ export function Tokenizer<T extends SearchableItem>({
const handleBlurCapture = useCallback(
(e: React.FocusEvent) => {
if (!isFocusInTokenizer(e.relatedTarget)) {
isControlFocusedRef.current = false;
hasReportedFocusRef.current = false;
setIsFocusedWithin(false);
onBlur?.(e);
Expand Down Expand Up @@ -1399,6 +1386,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 +1521,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,7 +1549,6 @@ export function Tokenizer<T extends SearchableItem>({
if (isSheetOpen) {
return;
}
isControlFocusedRef.current = false;
hasReportedFocusRef.current = false;
onBlur?.(event);
}}
Expand Down
63 changes: 59 additions & 4 deletions packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -2550,26 +2552,79 @@ 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('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', () => {
const {container} = render(
<TokenizerWithPresentation
Expand Down
22 changes: 8 additions & 14 deletions packages/core/src/Tokenizer/TokenizerBottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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 ----
Expand Down
Loading