Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
5 changes: 5 additions & 0 deletions .changeset/comments-more-menu-resolve-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astryxdesign/lab': patch
---

[fix] In a narrow comment, Mark as resolved and Reopen keep focus off the page. When the focused button is replaced by an action the header has no room for, focus moves to the comment's more menu button, and the menu stays closed. When one picked from the more menu is replaced by a header button, that button takes focus.
95 changes: 85 additions & 10 deletions packages/lab/src/Comments/CommentActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import {Icon} from '@astryxdesign/core/Icon';
import {useClipboardCopy} from '@astryxdesign/core/internal/clipboard-copy';
import {IconButton} from '@astryxdesign/core/IconButton';
import {isFocusLost} from '@astryxdesign/core/internal/touch';
import {HStack, VStack} from '@astryxdesign/core/Layout';
import {OverflowList, type OverflowItem} from '@astryxdesign/core/OverflowList';
import {Popover} from '@astryxdesign/core/Popover';
Expand Down Expand Up @@ -84,6 +85,13 @@ export function visibleCommentAction(
);
}

/** Whether focus is on `node` or inside it, in its own document or shadow root. */
function holdsFocus(node: HTMLElement): boolean {
const root = node.getRootNode() as Document | ShadowRoot;
const active = root.activeElement ?? null;
return active != null && node.contains(active);
}

export function commentMoreMenuTrigger(
root: HTMLElement | null,
): HTMLElement | null {
Expand Down Expand Up @@ -281,6 +289,31 @@ export function CommentActions({
const [isPickerOpen, setIsPickerOpen] = useState(false);
const [collapsed, setCollapsed] = useState(NO_COLLAPSED_ACTIONS);
const clusterRef = useRef<HTMLElement | null>(null);
// True from the commit that removed a focused Mark as resolved or Reopen
// until the end of that commit's work.
const resolveFocusDroppedRef = useRef(false);
// True from that overflow report until the more menu's trigger takes focus,
// at most until the end of that commit's work.
const isMoreFocusPendingRef = useRef(false);
const resolveControlRef = resolveAction?.controlRef;
const trackResolveControl = useCallback(
(node: HTMLElement | null) => {
const release = resolveControlRef?.(node);
if (node == null) {
return undefined;
}
return () => {
if (holdsFocus(node)) {
resolveFocusDroppedRef.current = true;
queueMicrotask(() => {
resolveFocusDroppedRef.current = false;
});
}
release?.();
};
},
[resolveControlRef],
);
const href = `#${commentAnchorId(comment.id)}`;
const linkLabel = isLinkCopyFailed
? linkCopyFailedLabel
Expand Down Expand Up @@ -318,15 +351,56 @@ export function CommentActions({
)?.focus();
};
const changeOverflow = useCallback((items: OverflowItem[]) => {
setCollapsed(
new Set(
items.flatMap(item => {
const action = commentActionOf(item);
return action == null ? [] : [action];
}),
),
const next = new Set(
items.flatMap(item => {
const action = commentActionOf(item);
return action == null ? [] : [action];
}),
);
setCollapsed(next);
// A Mark as resolved or Reopen that had focus was replaced by its other
// action, and the header had no room for it. The more menu now holds it,
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
// so its trigger takes focus (the docs promise focus never drops to the
// page). The menu stays closed. The cluster's ref, which attaches after
// this list's layout, moves the focus.
if (
resolveFocusDroppedRef.current &&
(next.has('resolve') || next.has('reopen'))
) {
resolveFocusDroppedRef.current = false;
isMoreFocusPendingRef.current = true;
queueMicrotask(() => {
isMoreFocusPendingRef.current = false;
});
}
}, []);
// Moves focus to the more menu's trigger once it is in the document.
const takeMoreFocus = useCallback((root: HTMLElement | null) => {
if (!isMoreFocusPendingRef.current || root == null) {
return;
}
const trigger = commentMoreMenuTrigger(root);
if (trigger == null) {
return;
}
isMoreFocusPendingRef.current = false;
if (isFocusLost(null, root.ownerDocument)) {
trigger.focus({preventScroll: true});
}
}, []);
// The more menu takes part in the resolve control's focus swap: when an
// action picked from it is replaced by a header button and the emptied
// menu goes, that button takes focus.
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const attachMoreMenu = useCallback(
(element: HTMLElement | null) => {
const release = resolveControlRef?.(element);
if (element != null) {
takeMoreFocus(clusterRef.current ?? element);
}
return release;
},
[resolveControlRef, takeMoreFocus],
);

const collapsedItems: DropdownMenuOption[] = [];
if (resolveAction != null && collapsed.has(resolveAction.kind)) {
Expand Down Expand Up @@ -397,6 +471,7 @@ export function CommentActions({
ref={(element: HTMLElement | null) => {
clusterRef.current = element;
anchorRef?.(element);
takeMoreFocus(element);
}}
gap={0.5}
align="center"
Expand All @@ -412,7 +487,7 @@ export function CommentActions({
{resolveAction?.kind === 'resolve' ? (
<IconButton
key="resolve"
ref={resolveAction.controlRef}
ref={trackResolveControl}
label={resolveLabel}
tooltip={resolveLabel}
variant="ghost"
Expand All @@ -425,7 +500,7 @@ export function CommentActions({
) : resolveAction?.kind === 'reopen' ? (
<Button
key="reopen"
ref={resolveAction.controlRef}
ref={trackResolveControl}
label={reopenLabel}
variant="ghost"
size="sm"
Expand Down Expand Up @@ -490,7 +565,7 @@ export function CommentActions({
</OverflowList>
{additionalActions}
{items.length > 0 && (
<HStack data-comment-more-menu="true">
<HStack ref={attachMoreMenu} data-comment-more-menu="true">
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
<DropdownMenu
items={items}
menuWidth={MORE_MENU_MIN_WIDTH}
Expand Down
13 changes: 12 additions & 1 deletion packages/lab/src/Comments/CommentRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,15 @@ const INSTANT_REVEAL_STYLE = {transition: 'none'} as const;
* the accessible name and pressed state. Selection paints the container's own
* muted fill, so no selectable component is restyled.
*/

// The resolve control's focus swap includes the comment's more menu, whose
// focus target is its trigger button.
function resolveFocusTarget(node: HTMLElement): HTMLElement | null {
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
return node.matches('[data-comment-more-menu]')
? node.querySelector<HTMLElement>('button')
: node;
}

function ThreadSurface({
children,
dividers,
Expand Down Expand Up @@ -389,7 +398,9 @@ export function CommentRow({
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 resolveControlRef = useFocusAcrossSwap<HTMLElement>(undefined, {
getFocusTarget: resolveFocusTarget,
});
const resolveAction: ResolveAction | undefined =
thread == null || thread.canResolve === false || !canMutate
? undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/lab/src/Comments/Comments.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export const docs = {
category: 'Keyboard',
criterion: '2.4.3 Focus Order',
description:
'Focus never drops to the page. After a delete it moves to the next thread, or to the thread when a reply was deleted. Load earlier comments keeps focus on itself, or on the Retry that replaces it when loading fails. A thread selected when the panel mounts opens without taking focus.',
'Focus never drops to the page. Mark as resolved and Reopen hand focus to each other. When the header has no room for the one that replaces it, focus goes to the more menu button that holds it; when one picked from the more menu is replaced by a header button, that button takes focus. After a delete it moves to the next thread, or to the thread when a reply was deleted. Load earlier comments keeps focus on itself, or on the Retry that replaces it when loading fails. A thread selected when the panel mounts opens without taking focus.',
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
},
{
name: 'Busy actions',
Expand Down
196 changes: 196 additions & 0 deletions packages/lab/src/Comments/Comments.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1266,6 +1266,202 @@ describe('Comments resolved and inline threads', () => {
).toHaveFocus();
});

it('hands focus to the more menu trigger when Reopen collapses into it', async () => {
overflowControl.collapsed = new Set(['reopen', 'reply', 'link']);
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 />);
const surface = threadSurface('open');
within(surface).getByRole('button', {name: 'Mark as resolved'}).focus();
await user.keyboard('{Enter}');
await flush();
expect(within(surface).queryByRole('button', {name: 'Reopen'})).toBeNull();
const more = surface.querySelector<HTMLElement>(
'[data-comment-more-menu] button',
);
expect(more).not.toBeNull();
expect(more).toHaveFocus();
expect(more).toHaveAttribute('aria-expanded', 'false');
});

it('hands focus to Mark as resolved after Reopen is picked from the more menu', async () => {
// Only Reopen collapses, so the more menu empties and unmounts once Mark
// as resolved replaces it in the header.
overflowControl.collapsed = new Set(['reopen']);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const user = userEvent.setup();
function Host() {
const [isResolved, setIsResolved] = useState(true);
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 />);
const surface = threadSurface('open');
const more = surface.querySelector<HTMLElement>(
'[data-comment-more-menu] button',
);
expect(more).not.toBeNull();
await user.click(more!);
await user.click(
await screen.findByRole('menuitem', {name: 'Reopen', hidden: true}),
);
await flush();
expect(surface.querySelector('[data-comment-more-menu]')).toBeNull();
expect(
within(surface).getByRole('button', {name: 'Mark as resolved'}),
).toHaveFocus();
});

it('returns focus to the more menu trigger when the menu stays after a pick', async () => {
overflowControl.collapsed = new Set(['reopen', 'reply', 'link']);
const user = userEvent.setup();
function Host() {
const [isResolved, setIsResolved] = useState(true);
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 />);
const surface = threadSurface('open');
const more = surface.querySelector<HTMLElement>(
'[data-comment-more-menu] button',
);
await user.click(more!);
await user.click(
await screen.findByRole('menuitem', {name: 'Reopen', hidden: true}),
);
await flush();
expect(more).toHaveFocus();
});

it('hands focus to the more menu trigger inside a shadow root', async () => {
overflowControl.collapsed = new Set(['reopen', 'reply', 'link']);
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>
);
}
const shadowHost = document.createElement('div');
document.body.append(shadowHost);
const shadow = shadowHost.attachShadow({mode: 'open'});
const container = document.createElement('div');
shadow.append(container);
render(<Host />, {container});
const resolve = within(container).getByRole('button', {
name: 'Mark as resolved',
});
resolve.focus();
expect(shadow.activeElement).toBe(resolve);
fireEvent.click(resolve);
await flush();
const more = container.querySelector<HTMLElement>(
'[data-comment-more-menu] button',
);
expect(more).not.toBeNull();
expect(shadow.activeElement).toBe(more);
shadowHost.remove();
});

it('moves no focus when the host resolves a thread whose control did not have focus', async () => {
overflowControl.collapsed = new Set(['reopen', 'reply', 'link']);
let resolve = () => {};
function Host() {
const [isResolved, setIsResolved] = useState(false);
resolve = () => setIsResolved(true);
return (
<Sized>
<Comments
comments={[
{
id: 'open',
author: OTHER,
body: 'Open thread',
createdAt: '2026-09-30T19:00:00Z',
isResolved,
},
]}
currentUser={VIEWER}
onResolveThread={() => {}}
onReopenThread={() => {}}
/>
</Sized>
);
}
render(<Host />);
expect(document.body).toHaveFocus();
await act(async () => {
resolve();
});
await flush();
expect(document.body).toHaveFocus();
});

it('leaves focus where the viewer moved it when the host resolves later', async () => {
const user = userEvent.setup();
let finishResolve = () => {};
Expand Down