Skip to content
Open
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/comments-resolve-focus-handoff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[chore] Internal: the focus hand-off Core runs when it replaces one of a control's elements ignores an element while it is inside an inert region, such as the copy OverflowList renders to measure its items, and Core's internal `@astryxdesign/core/internal/touch` entry re-exports it for Astryx's own packages, so Lab's Comments carries focus from Mark as resolved to Reopen and back while the replacing control shows in the comment's header. It is not part of the public API. Apps see no change.

@ernestt
8 changes: 8 additions & 0 deletions packages/core/src/internal/touch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,14 @@ describe('internal/touch', () => {
);
});

it("re-exports by name the focus hand-off Lab's Comments reads", async () => {
const entry: Record<string, unknown> = await import('./touch');
const swap = await import('../utils/useFocusAcrossSwap');
// Identity alone passes when both sides are undefined.
expect(typeof entry.useFocusAcrossSwap).toBe('function');
expect(entry.useFocusAcrossSwap).toBe(swap.useFocusAcrossSwap);
});

it('attaches no window or document listeners when it loads', async () => {
vi.resetModules();
const onWindow = vi.spyOn(window, 'addEventListener');
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/internal/touch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ export type {ActionGroupTrackingOptions} from '../hooks/useActionGroupTracking';
// Lab's TabBar finds a panel's scroll area with Core's scroll test.
export {measureLogicalScrollAxis} from '../hooks/scrollGeometry';

// Lab's Comments carries focus to the control that replaces a pressed one,
// Mark as resolved and Reopen, with the same focus hand-off as Core.
export {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';

// A Lab group shares Core's group press tracking and the group-item mark.
export {
useGroupPressTracking,
Expand Down
44 changes: 43 additions & 1 deletion packages/core/src/utils/useFocusAcrossSwap.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
useImperativeHandle,
type Ref,
} from 'react';
import {act, render, renderHook, screen} from '@testing-library/react';
import {act, render, renderHook, screen, within} from '@testing-library/react';
import {describe, expect, it, vi} from 'vitest';
import {useFocusAcrossSwap} from './useFocusAcrossSwap';

Expand Down Expand Up @@ -75,6 +75,25 @@ function OptionalContentExample({
);
}

function MeasuredExample({isDisabled}: {isDisabled: boolean}) {
const ref = useFocusAcrossSwap<HTMLElement>();
const Element = isDisabled ? 'div' : 'a';
const control = (
<Element ref={ref} role="button" tabIndex={-1}>
Measured
</Element>
);
// As OverflowList does: an inert copy to measure, then the visible one.
return (
<>
<div inert data-testid="measure">
{control}
</div>
<div data-testid="visible">{control}</div>
</>
);
}

const NEVER = new Promise<never>(() => {});

function Suspender({isSuspended}: {isSuspended: boolean}) {
Expand Down Expand Up @@ -273,6 +292,29 @@ describe('useFocusAcrossSwap', () => {
expect(screen.getByRole('button')).not.toHaveFocus();
});

it('carries focus to the visible replacement past an inert copy of the element', () => {
const {rerender} = render(<MeasuredExample isDisabled={false} />);
within(screen.getByTestId('visible')).getByText('Measured').focus();
rerender(<MeasuredExample isDisabled />);
expect(
within(screen.getByTestId('visible')).getByText('Measured'),
).toHaveFocus();
});

it('keeps the handoff for a control first mounted inside an inert region', () => {
const forwardedRef = createRef<HTMLElement>();
const fixture = (isCovered: boolean, isDisabled: boolean) => (
<div inert={isCovered}>
<DirectExample isDisabled={isDisabled} forwardedRef={forwardedRef} />
</div>
);
const {rerender} = render(fixture(true, false));
rerender(fixture(false, false));
screen.getByRole('button').focus();
rerender(fixture(false, true));
expect(screen.getByRole('button')).toHaveFocus();
});

it('expires a handoff from a descendant ref that detaches while its Effect stays connected', async () => {
const {rerender} = render(
<OptionalContentExample hasContent revision={0} />,
Expand Down
57 changes: 35 additions & 22 deletions packages/core/src/utils/useFocusAcrossSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
*
* React can detach and re-attach the same node, as an Activity boundary does.
* Focus moves only to a different node, and only when focus fell to the page.
* An element inside an inert region, such as the copy OverflowList renders to
* measure its items, can hold no focus, so it neither leaves nor takes a
* handoff. Inertness is read when a handoff is recorded or taken, not when the
* node attaches: a region can stop being inert later.
Comment on lines +17 to +20

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.

Non-blocking (source comments): the header is now 17 lines, and this sentence runs 28 words over two topics. A short comment beside the helper keeps the header near 12 lines:

// An inert element cannot hold focus. It records and takes no handoff.
// OverflowList renders an inert copy of each item to measure it.
// Read inertness at each handoff. A region can stop being inert later.
function isInertCopy(value: unknown): boolean {

The helper matches any element in an inert region, not only a copy, so isInInertRegion would also fit.

*/

import {useCallback, useEffect, useRef, type Ref} from 'react';
Expand All @@ -30,6 +34,10 @@ function isNativeTarget(value: unknown): value is HTMLElement {
);
}

function isInertCopy(value: unknown): boolean {
return isHTMLElement(value) && value.closest('[inert]') != null;
}

function wasHidden(node: HTMLElement): boolean {
// A hidden Activity can commit another change before microtasks run.
for (
Expand Down Expand Up @@ -85,33 +93,38 @@ export function useFocusAcrossSwap<T extends HTMLElement>(
if (node === null) {
return undefined;
}
const outgoing = focusedNodeRef.current;
focusedNodeRef.current = null;
const resolved = getFocusTarget ? getFocusTarget(node) : node;
const target = isNativeTarget(resolved) ? resolved : null;
if (
target?.isConnected &&
outgoing !== null &&
outgoing.target !== target &&
!outgoing.target.isConnected &&
!wasHidden(outgoing.source) &&
isFocusUnclaimed(target)
) {
target.focus({preventScroll: true});
if (!isInertCopy(node)) {
const outgoing = focusedNodeRef.current;
focusedNodeRef.current = null;
if (
target?.isConnected &&
outgoing !== null &&
outgoing.target !== target &&
!outgoing.target.isConnected &&
!wasHidden(outgoing.source) &&
isFocusUnclaimed(target)
) {
target.focus({preventScroll: true});
}
}
const release = mergeRefs<T>(ref)(node);
return () => {
const outgoing =
target && ownsFocus(target) ? {target, source: node} : null;
focusedNodeRef.current = outgoing;
if (outgoing) {
// Descendant refs can detach without disconnecting this hook's Effect.
// Expire the handoff after this commit, but leave newer handoffs intact.
queueMicrotask(() => {
if (focusedNodeRef.current === outgoing) {
focusedNodeRef.current = null;
}
});
if (!isInertCopy(node)) {
const outgoing =
target && ownsFocus(target) ? {target, source: node} : null;
focusedNodeRef.current = outgoing;
if (outgoing) {
// Descendant refs can detach without disconnecting this hook's
// Effect. Expire the handoff after this commit, but leave newer
// handoffs intact.
queueMicrotask(() => {
if (focusedNodeRef.current === outgoing) {
focusedNodeRef.current = null;
}
});
}
}
release?.();
};
Expand Down
17 changes: 15 additions & 2 deletions packages/lab/src/Comments/CommentActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@
* @position Internal parts of a comment row in the Comments family
*/

import {useCallback, useRef, useState, type ReactNode} from 'react';
import {
useCallback,
useRef,
useState,
type ReactNode,
type RefCallback,
} from 'react';
import {flushSync} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {Button} from '@astryxdesign/core/Button';
Expand Down Expand Up @@ -57,7 +63,12 @@ const styles = stylex.create({
export type CommentActionId = 'resolve' | 'reopen' | 'react' | 'reply' | 'link';

/** Mark as resolved on an open thread, Reopen on a resolved one. */
export type ResolveAction = {kind: 'resolve' | 'reopen'; onClick: () => void};
export type ResolveAction = {
kind: 'resolve' | 'reopen';
onClick: () => void;
/** Carries focus to the control that replaces a pressed one. */
controlRef?: RefCallback<HTMLElement>;
};

/** One of a comment's action buttons, as it shows. OverflowList renders a
* hidden copy of every item to measure it; only the copy in the visible list
Expand Down Expand Up @@ -401,6 +412,7 @@ export function CommentActions({
{resolveAction?.kind === 'resolve' ? (
<IconButton
key="resolve"
ref={resolveAction.controlRef}
label={resolveLabel}
tooltip={resolveLabel}
variant="ghost"
Expand All @@ -413,6 +425,7 @@ export function CommentActions({
) : resolveAction?.kind === 'reopen' ? (
<Button
key="reopen"
ref={resolveAction.controlRef}

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.

Miss: this ref hands focus to Reopen, but Reopen (75 px) is wider than the Mark as resolved icon (28 px). OverflowList has no minimum and remeasures when the key changes, so in a narrow header Reopen moves into the more menu one commit later and focus falls to the page body (reproduced locally in the Margin Comment story). The more-menu trigger already keeps focus when the action is picked from the menu, so it is a natural target for that case.

label={reopenLabel}
variant="ghost"
size="sm"
Expand Down
16 changes: 14 additions & 2 deletions packages/lab/src/Comments/CommentRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
useClickableContainer,
useContainerReveal,
} from '@astryxdesign/core/hooks';
import {useFocusAcrossSwap} from '@astryxdesign/core/internal/touch';
import {HStack, StackItem, VStack} from '@astryxdesign/core/Layout';
import {Link} from '@astryxdesign/core/Link';
import {Section} from '@astryxdesign/core/Section';
Expand Down Expand Up @@ -375,15 +376,26 @@ export function CommentRow({
const rowActionsBusy = isBusy || isSubmitting || isComposerActionPending;
const isResolved = thread?.isResolved === true;
const isMuted = isResolved || isParentThreadResolved;
// The host's update replaces Mark as resolved with Reopen, and back.
// The replacement takes focus if the pressed control had it.
const resolveControlRef = useFocusAcrossSwap<HTMLElement>();
const resolveAction: ResolveAction | undefined =
thread == null || thread.canResolve === false || !canMutate
? undefined
: isResolved
? can.reopen
? {kind: 'reopen', onClick: () => scope.reopen(comment)}
? {
kind: 'reopen',
onClick: () => scope.reopen(comment),
controlRef: resolveControlRef,
}
: undefined
: can.resolve
? {kind: 'resolve', onClick: () => scope.resolve(comment)}
? {
kind: 'resolve',
onClick: () => scope.resolve(comment),
controlRef: resolveControlRef,
}
: undefined;
const hasHistory =
comment.isEdited === true &&
Expand Down
88 changes: 88 additions & 0 deletions packages/lab/src/Comments/Comments.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1225,6 +1225,94 @@ describe('Comments resolved and inline threads', () => {
expect(onReopenThread).toHaveBeenCalledWith('done');
});

it('hands focus to Reopen after a keyboard resolve, and back after Reopen', async () => {
const user = userEvent.setup();
function Host() {
const [isResolved, setIsResolved] = useState(false);
return (
<Sized>
<Comments
comments={[
{
id: 'open',
author: OTHER,
body: 'Open thread',
createdAt: '2026-09-30T19:00:00Z',
isResolved,
},
]}
currentUser={VIEWER}
onResolveThread={() => setIsResolved(true)}
onReopenThread={() => setIsResolved(false)}
/>
</Sized>
);
}
render(<Host />);
within(threadSurface('open'))
.getByRole('button', {name: 'Mark as resolved'})
.focus();
await user.keyboard('{Enter}');
await flush();
expect(
within(threadSurface('open')).getByRole('button', {name: 'Reopen'}),
).toHaveFocus();
await user.keyboard('{Enter}');
await flush();
expect(
within(threadSurface('open')).getByRole('button', {
name: 'Mark as resolved',
}),
).toHaveFocus();
});

it('leaves focus where the viewer moved it when the host resolves later', async () => {
const user = userEvent.setup();
let finishResolve = () => {};
function Host() {
const [isResolved, setIsResolved] = useState(false);
return (
<Sized>
<Comments
comments={[
{
id: 'open',
author: OTHER,
body: 'Open thread',
createdAt: '2026-09-30T19:00:00Z',
isResolved,
},
]}
currentUser={VIEWER}
onResolveThread={() =>
new Promise<void>(resolve => {
finishResolve = () => {
setIsResolved(true);
resolve();
};
})
}
onReopenThread={() => {}}
/>
<button type="button">Elsewhere</button>
</Sized>
);
}
render(<Host />);
within(threadSurface('open'))
.getByRole('button', {name: 'Mark as resolved'})
.focus();
await user.keyboard('{Enter}');
const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});
elsewhere.focus();
await act(async () => finishResolve());
await flush();
expect(
within(threadSurface('open')).getByRole('button', {name: 'Reopen'}),
).toBeTruthy();
expect(elsewhere).toHaveFocus();
});

it('quotes anchored passages and marks orphaned ones Outdated', () => {
render(
<Sized>
Expand Down
1 change: 1 addition & 0 deletions scripts/touch-support-bundle.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ const LAB_ONLY_NAMES = [
'useTouchHitArea',
'touchHitAreaStyles',
'measureLogicalScrollAxis',
'useFocusAcrossSwap',
'timing',
'useGroupPressTracking',
'GROUP_PRESS_POINTERS',
Expand Down
Loading