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, 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.

@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
56 changes: 34 additions & 22 deletions packages/core/src/utils/useFocusAcrossSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
*
* 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 in an inert region, such as OverflowList's measuring copy, holds
* no focus, so it neither leaves nor takes a handoff. The hook checks this at
* each handoff, because a region can stop being inert.
*/

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

function isInInertRegion(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 +92,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 (!isInInertRegion(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 (!isInInertRegion(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
24 changes: 22 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}
label={reopenLabel}
variant="ghost"
size="sm"
Expand Down Expand Up @@ -485,6 +498,13 @@ export function CommentActions({
presentation="adaptive"
hasChevron={false}
button={{
// While Mark as resolved or Reopen sits in this menu, the
// trigger takes its hand-off, so a pressed control that
// collapses here gives focus to the trigger.
Comment on lines +501 to +503

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 (comment style): this is one 27-word sentence with two topics. Two short sentences read more easily:

              // While Mark as resolved or Reopen sits in this menu, the
              // trigger takes its hand-off. A focused control that collapses
              // here gives focus to the trigger.

ref:
resolveAction != null && collapsed.has(resolveAction.kind)
? resolveAction.controlRef
: undefined,
label: menuLabel,
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 @@ -377,15 +378,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
Loading