diff --git a/.changeset/comments-more-menu-resolve-focus.md b/.changeset/comments-more-menu-resolve-focus.md new file mode 100644 index 0000000000000..bc2990b8e2b74 --- /dev/null +++ b/.changeset/comments-more-menu-resolve-focus.md @@ -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; if the menu still holds other actions, focus returns to the more menu button. diff --git a/packages/lab/src/Comments/CommentActions.tsx b/packages/lab/src/Comments/CommentActions.tsx index 57f1e16a119d2..b6f328b1a9367 100644 --- a/packages/lab/src/Comments/CommentActions.tsx +++ b/packages/lab/src/Comments/CommentActions.tsx @@ -5,7 +5,7 @@ /** * @file CommentActions.tsx * @input Uses React, React DOM flushSync, StyleX, Core's internal - * useClipboardCopy, IconButton, + * useClipboardCopy and isFocusLost, IconButton, * Button, Tooltip, ToggleButton, OverflowList, DropdownMenu, Popover, Text * @output Exports CommentActions (a comment's header actions), ReactionSummary * (its reaction toggles), and the action-lookup helpers rows use for focus @@ -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'; @@ -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 { @@ -281,6 +289,31 @@ export function CommentActions({ const [isPickerOpen, setIsPickerOpen] = useState(false); const [collapsed, setCollapsed] = useState(NO_COLLAPSED_ACTIONS); const clusterRef = useRef(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 @@ -318,15 +351,74 @@ 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, + // so its trigger takes focus (the docs promise focus never drops to the + // page). 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; + }); + } }, []); + 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. + const attachMoreMenu = useCallback( + (element: HTMLElement | null) => { + const release = resolveControlRef?.(element); + if (element == null) { + return release; + } + takeMoreFocus(clusterRef.current ?? element); + return () => { + const heldFocus = holdsFocus(element); + release?.(); + if (heldFocus) { + // The header can show the replacing action one commit before the + // emptied menu goes, so no node attaches after it. The visible + // replacing control then takes focus. + queueMicrotask(() => { + const root = clusterRef.current; + if (root == null || !isFocusLost(null, root.ownerDocument)) { + return; + } + ( + visibleCommentAction(root, 'resolve') ?? + visibleCommentAction(root, 'reopen') + )?.focus({preventScroll: true}); + }); + } + }; + }, + [resolveControlRef, takeMoreFocus], + ); const collapsedItems: DropdownMenuOption[] = []; if (resolveAction != null && collapsed.has(resolveAction.kind)) { @@ -397,6 +489,7 @@ export function CommentActions({ ref={(element: HTMLElement | null) => { clusterRef.current = element; anchorRef?.(element); + takeMoreFocus(element); }} gap={0.5} align="center" @@ -412,7 +505,7 @@ export function CommentActions({ {resolveAction?.kind === 'resolve' ? ( {additionalActions} {items.length > 0 && ( - + ('button') + : node; +} + /** * A thread surface (a basic Card or Section) made selectable with * `useClickableContainer`: surface clicks toggle selection while inner @@ -187,6 +195,7 @@ 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. */ + function ThreadSurface({ children, dividers, @@ -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(); + const resolveControlRef = useFocusAcrossSwap(undefined, { + getFocusTarget: resolveFocusTarget, + }); const resolveAction: ResolveAction | undefined = thread == null || thread.canResolve === false || !canMutate ? undefined diff --git a/packages/lab/src/Comments/Comments.doc.mjs b/packages/lab/src/Comments/Comments.doc.mjs index bdc8ca1b735d9..21dd360524a9e 100644 --- a/packages/lab/src/Comments/Comments.doc.mjs +++ b/packages/lab/src/Comments/Comments.doc.mjs @@ -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; if the menu still holds other actions, focus returns to the more menu button. 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.', }, { name: 'Busy actions', diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsx index 39f4b562aa0ac..599f6a6ca992f 100644 --- a/packages/lab/src/Comments/Comments.test.tsx +++ b/packages/lab/src/Comments/Comments.test.tsx @@ -23,7 +23,11 @@ import { // jsdom has no layout, so the measuring OverflowList is replaced by one that // collapses exactly the comment actions a test names. -const overflowControl = vi.hoisted(() => ({collapsed: new Set()})); +const overflowControl = vi.hoisted(() => ({ + collapsed: new Set(), + // Reports in a later commit, as the real OverflowList measures first. + reportsLate: false, +})); const announce = vi.hoisted(() => vi.fn()); // Records each announcement and still speaks it through the real channel, which // other tests here read back. @@ -75,7 +79,12 @@ vi.mock('@astryxdesign/core/OverflowList', async () => { ); const collapsedKey = collapsed.map(actionOf).join(','); React.useLayoutEffect(() => { - if (collapsed.length > 0) { + if (collapsed.length === 0) { + return; + } + if (overflowControl.reportsLate) { + setTimeout(() => onOverflowChange?.(collapsed), 0); + } else { onOverflowChange?.(collapsed); } // Re-run only when the collapsed set changes. @@ -293,6 +302,7 @@ afterAll(() => { beforeEach(() => { announce.mockClear(); overflowControl.collapsed = new Set(); + overflowControl.reportsLate = false; writeText.mockReset(); writeText.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', ResizeObserverStub); @@ -1266,6 +1276,247 @@ 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 ( + + setIsResolved(true)} + onReopenThread={() => setIsResolved(false)} + /> + + ); + } + render(); + 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( + '[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']); + const user = userEvent.setup(); + function Host() { + const [isResolved, setIsResolved] = useState(true); + return ( + + setIsResolved(true)} + onReopenThread={() => setIsResolved(false)} + /> + + ); + } + render(); + const surface = threadSurface('open'); + const more = surface.querySelector( + '[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('hands focus to Mark as resolved after a menu pick when the list reports a commit later', 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']); + overflowControl.reportsLate = true; + const user = userEvent.setup(); + function Host() { + const [isResolved, setIsResolved] = useState(true); + return ( + + setIsResolved(true)} + onReopenThread={() => setIsResolved(false)} + /> + + ); + } + render(); + await flush(); + const surface = threadSurface('open'); + const more = surface.querySelector( + '[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 ( + + setIsResolved(true)} + onReopenThread={() => setIsResolved(false)} + /> + + ); + } + render(); + const surface = threadSurface('open'); + const more = surface.querySelector( + '[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 ( + + setIsResolved(true)} + onReopenThread={() => setIsResolved(false)} + /> + + ); + } + const shadowHost = document.createElement('div'); + document.body.append(shadowHost); + const shadow = shadowHost.attachShadow({mode: 'open'}); + const container = document.createElement('div'); + shadow.append(container); + render(, {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( + '[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 ( + + {}} + onReopenThread={() => {}} + /> + + ); + } + render(); + 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 = () => {};