Skip to content

Commit 22561bb

Browse files
committed
fix(Comments): Mark as resolved and Reopen hand focus to the control that replaces them
Resolving a thread replaces Mark as resolved with Reopen, and reopening it replaces Reopen with Mark as resolved, when the host's update arrives. The pressed control left the page, so keyboard focus fell to the page body. Both controls now take one ref from Core's focus hand-off, useFocusAcrossSwap: when the pressed control leaves while it has focus, the control that replaces it takes focus, unless focus has moved somewhere else. A failed request replaces nothing. OverflowList renders an inert copy of each action to measure it, so the hand-off ignores an element while it is inside an inert region. It reads inertness when it records or takes a hand-off, not when the element attaches, because a region can stop being inert later. Core's internal entry re-exports the hook for Lab. In a narrow panel, Reopen does not fit the actions row and collapses into the more menu right after it takes focus. While the resolve action sits in that menu, the menu's trigger takes the same ref, so focus moves to the trigger.
1 parent e642a67 commit 22561bb

9 files changed

Lines changed: 262 additions & 27 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] 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, or to the more-menu trigger when the replacement collapses into that menu. It is not part of the public API. Apps see no change.
6+
7+
@ernestt

‎packages/core/src/internal/touch.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,14 @@ describe('internal/touch', () => {
210210
);
211211
});
212212

213+
it("re-exports by name the focus hand-off Lab's Comments reads", async () => {
214+
const entry: Record<string, unknown> = await import('./touch');
215+
const swap = await import('../utils/useFocusAcrossSwap');
216+
// Identity alone passes when both sides are undefined.
217+
expect(typeof entry.useFocusAcrossSwap).toBe('function');
218+
expect(entry.useFocusAcrossSwap).toBe(swap.useFocusAcrossSwap);
219+
});
220+
213221
it('attaches no window or document listeners when it loads', async () => {
214222
vi.resetModules();
215223
const onWindow = vi.spyOn(window, 'addEventListener');

‎packages/core/src/internal/touch.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ export type {ActionGroupTrackingOptions} from '../hooks/useActionGroupTracking';
128128
// Lab's TabBar finds a panel's scroll area with Core's scroll test.
129129
export {measureLogicalScrollAxis} from '../hooks/scrollGeometry';
130130

131+
// Lab's Comments carries focus to the control that replaces a pressed one,
132+
// Mark as resolved and Reopen, with the same focus hand-off as Core.
133+
export {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';
134+
131135
// A Lab group shares Core's group press tracking and the group-item mark.
132136
export {
133137
useGroupPressTracking,

‎packages/core/src/utils/useFocusAcrossSwap.test.tsx‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
useImperativeHandle,
1616
type Ref,
1717
} from 'react';
18-
import {act, render, renderHook, screen} from '@testing-library/react';
18+
import {act, render, renderHook, screen, within} from '@testing-library/react';
1919
import {describe, expect, it, vi} from 'vitest';
2020
import {useFocusAcrossSwap} from './useFocusAcrossSwap';
2121

@@ -75,6 +75,25 @@ function OptionalContentExample({
7575
);
7676
}
7777

78+
function MeasuredExample({isDisabled}: {isDisabled: boolean}) {
79+
const ref = useFocusAcrossSwap<HTMLElement>();
80+
const Element = isDisabled ? 'div' : 'a';
81+
const control = (
82+
<Element ref={ref} role="button" tabIndex={-1}>
83+
Measured
84+
</Element>
85+
);
86+
// As OverflowList does: an inert copy to measure, then the visible one.
87+
return (
88+
<>
89+
<div inert data-testid="measure">
90+
{control}
91+
</div>
92+
<div data-testid="visible">{control}</div>
93+
</>
94+
);
95+
}
96+
7897
const NEVER = new Promise<never>(() => {});
7998

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

295+
it('carries focus to the visible replacement past an inert copy of the element', () => {
296+
const {rerender} = render(<MeasuredExample isDisabled={false} />);
297+
within(screen.getByTestId('visible')).getByText('Measured').focus();
298+
rerender(<MeasuredExample isDisabled />);
299+
expect(
300+
within(screen.getByTestId('visible')).getByText('Measured'),
301+
).toHaveFocus();
302+
});
303+
304+
it('keeps the handoff for a control first mounted inside an inert region', () => {
305+
const forwardedRef = createRef<HTMLElement>();
306+
const fixture = (isCovered: boolean, isDisabled: boolean) => (
307+
<div inert={isCovered}>
308+
<DirectExample isDisabled={isDisabled} forwardedRef={forwardedRef} />
309+
</div>
310+
);
311+
const {rerender} = render(fixture(true, false));
312+
rerender(fixture(false, false));
313+
screen.getByRole('button').focus();
314+
rerender(fixture(false, true));
315+
expect(screen.getByRole('button')).toHaveFocus();
316+
});
317+
276318
it('expires a handoff from a descendant ref that detaches while its Effect stays connected', async () => {
277319
const {rerender} = render(
278320
<OptionalContentExample hasContent revision={0} />,

‎packages/core/src/utils/useFocusAcrossSwap.ts‎

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
*
1515
* React can detach and re-attach the same node, as an Activity boundary does.
1616
* Focus moves only to a different node, and only when focus fell to the page.
17+
* An element in an inert region, such as OverflowList's measuring copy, holds
18+
* no focus, so it neither leaves nor takes a handoff. The hook checks this at
19+
* each handoff, because a region can stop being inert.
1720
*/
1821

1922
import {useCallback, useEffect, useRef, type Ref} from 'react';
@@ -30,6 +33,10 @@ function isNativeTarget(value: unknown): value is HTMLElement {
3033
);
3134
}
3235

36+
function isInInertRegion(value: unknown): boolean {
37+
return isHTMLElement(value) && value.closest('[inert]') != null;
38+
}
39+
3340
function wasHidden(node: HTMLElement): boolean {
3441
// A hidden Activity can commit another change before microtasks run.
3542
for (
@@ -85,33 +92,38 @@ export function useFocusAcrossSwap<T extends HTMLElement>(
8592
if (node === null) {
8693
return undefined;
8794
}
88-
const outgoing = focusedNodeRef.current;
89-
focusedNodeRef.current = null;
9095
const resolved = getFocusTarget ? getFocusTarget(node) : node;
9196
const target = isNativeTarget(resolved) ? resolved : null;
92-
if (
93-
target?.isConnected &&
94-
outgoing !== null &&
95-
outgoing.target !== target &&
96-
!outgoing.target.isConnected &&
97-
!wasHidden(outgoing.source) &&
98-
isFocusUnclaimed(target)
99-
) {
100-
target.focus({preventScroll: true});
97+
if (!isInInertRegion(node)) {
98+
const outgoing = focusedNodeRef.current;
99+
focusedNodeRef.current = null;
100+
if (
101+
target?.isConnected &&
102+
outgoing !== null &&
103+
outgoing.target !== target &&
104+
!outgoing.target.isConnected &&
105+
!wasHidden(outgoing.source) &&
106+
isFocusUnclaimed(target)
107+
) {
108+
target.focus({preventScroll: true});
109+
}
101110
}
102111
const release = mergeRefs<T>(ref)(node);
103112
return () => {
104-
const outgoing =
105-
target && ownsFocus(target) ? {target, source: node} : null;
106-
focusedNodeRef.current = outgoing;
107-
if (outgoing) {
108-
// Descendant refs can detach without disconnecting this hook's Effect.
109-
// Expire the handoff after this commit, but leave newer handoffs intact.
110-
queueMicrotask(() => {
111-
if (focusedNodeRef.current === outgoing) {
112-
focusedNodeRef.current = null;
113-
}
114-
});
113+
if (!isInInertRegion(node)) {
114+
const outgoing =
115+
target && ownsFocus(target) ? {target, source: node} : null;
116+
focusedNodeRef.current = outgoing;
117+
if (outgoing) {
118+
// Descendant refs can detach without disconnecting this hook's
119+
// Effect. Expire the handoff after this commit, but leave newer
120+
// handoffs intact.
121+
queueMicrotask(() => {
122+
if (focusedNodeRef.current === outgoing) {
123+
focusedNodeRef.current = null;
124+
}
125+
});
126+
}
115127
}
116128
release?.();
117129
};

‎packages/lab/src/Comments/CommentActions.tsx‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@
1313
* @position Internal parts of a comment row in the Comments family
1414
*/
1515

16-
import {useCallback, useRef, useState, type ReactNode} from 'react';
16+
import {
17+
useCallback,
18+
useRef,
19+
useState,
20+
type ReactNode,
21+
type RefCallback,
22+
} from 'react';
1723
import {flushSync} from 'react-dom';
1824
import * as stylex from '@stylexjs/stylex';
1925
import {Button} from '@astryxdesign/core/Button';
@@ -57,7 +63,12 @@ const styles = stylex.create({
5763
export type CommentActionId = 'resolve' | 'reopen' | 'react' | 'reply' | 'link';
5864

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

6273
/** One of a comment's action buttons, as it shows. OverflowList renders a
6374
* hidden copy of every item to measure it; only the copy in the visible list
@@ -401,6 +412,7 @@ export function CommentActions({
401412
{resolveAction?.kind === 'resolve' ? (
402413
<IconButton
403414
key="resolve"
415+
ref={resolveAction.controlRef}
404416
label={resolveLabel}
405417
tooltip={resolveLabel}
406418
variant="ghost"
@@ -413,6 +425,7 @@ export function CommentActions({
413425
) : resolveAction?.kind === 'reopen' ? (
414426
<Button
415427
key="reopen"
428+
ref={resolveAction.controlRef}
416429
label={reopenLabel}
417430
variant="ghost"
418431
size="sm"
@@ -485,6 +498,13 @@ export function CommentActions({
485498
presentation="adaptive"
486499
hasChevron={false}
487500
button={{
501+
// While Mark as resolved or Reopen sits in this menu, the
502+
// trigger takes its hand-off, so a pressed control that
503+
// collapses here gives focus to the trigger.
504+
ref:
505+
resolveAction != null && collapsed.has(resolveAction.kind)
506+
? resolveAction.controlRef
507+
: undefined,
488508
label: menuLabel,
489509
variant: 'ghost',
490510
size: 'sm',

‎packages/lab/src/Comments/CommentRow.tsx‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
useClickableContainer,
3030
useContainerReveal,
3131
} from '@astryxdesign/core/hooks';
32+
import {useFocusAcrossSwap} from '@astryxdesign/core/internal/touch';
3233
import {HStack, StackItem, VStack} from '@astryxdesign/core/Layout';
3334
import {Link} from '@astryxdesign/core/Link';
3435
import {Section} from '@astryxdesign/core/Section';
@@ -377,15 +378,26 @@ export function CommentRow({
377378
const rowActionsBusy = isBusy || isSubmitting || isComposerActionPending;
378379
const isResolved = thread?.isResolved === true;
379380
const isMuted = isResolved || isParentThreadResolved;
381+
// The host's update replaces Mark as resolved with Reopen, and back.
382+
// The replacement takes focus if the pressed control had it.
383+
const resolveControlRef = useFocusAcrossSwap<HTMLElement>();
380384
const resolveAction: ResolveAction | undefined =
381385
thread == null || thread.canResolve === false || !canMutate
382386
? undefined
383387
: isResolved
384388
? can.reopen
385-
? {kind: 'reopen', onClick: () => scope.reopen(comment)}
389+
? {
390+
kind: 'reopen',
391+
onClick: () => scope.reopen(comment),
392+
controlRef: resolveControlRef,
393+
}
386394
: undefined
387395
: can.resolve
388-
? {kind: 'resolve', onClick: () => scope.resolve(comment)}
396+
? {
397+
kind: 'resolve',
398+
onClick: () => scope.resolve(comment),
399+
controlRef: resolveControlRef,
400+
}
389401
: undefined;
390402
const hasHistory =
391403
comment.isEdited === true &&

0 commit comments

Comments
 (0)