@devries-cameron20 / t3code-1 / commits / 350ecd63be
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): closing the right panel returns focus to where it was (#32569)

Julius Marminge committed Nov 10, 2026 at 10:00 UTC 350ecd63bea523195765f36d0a51753557937eac
3 files changed +221 -10
apps/web/src/components/preview/PreviewPanelShell.browser.test.tsx new
+168
@@ -0,0 +1,168 @@
1 +import type { ReactNode } from "react";
2 +import { createPortal } from "react-dom";
3 +import { describe, expect, it } from "vite-plus/test";
4 +import { page, userEvent } from "vite-plus/test/browser";
5 +
6 +import { act, render, type Screen } from "../../../test/render";
7 +import { PreviewPanelShell } from "./PreviewPanelShell";
8 +
9 +function Workspace(props: { open: boolean; present?: boolean; children?: ReactNode }) {
10 + return (
11 + <div>
12 + <div data-workspace-area="composer">
13 + <input aria-label="Message New thread" />
14 + </div>
15 + <button type="button" aria-label="Toggle right panel" data-right-panel-toggle />
16 + {(props.present ?? true) ? (
17 + <PreviewPanelShell mode="inline" open={props.open}>
18 + {props.children ?? <div role="region" aria-label="Open a surface" tabIndex={-1} />}
19 + </PreviewPanelShell>
20 + ) : null}
21 + </div>
22 + );
23 +}
24 +
25 +// Mirrors rightPanel.toggle from the composer: the panel opens and the shortcut focuses its content.
26 +async function openPanelFromComposer(screen: Screen) {
27 + await userEvent.click(screen.getByRole("textbox", { name: "Message New thread" }));
28 + await screen.rerender(<Workspace open />);
29 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
30 +}
31 +
32 +describe("PreviewPanelShell focus", () => {
33 + it("returns focus to the composer when a panel opened from it collapses", async () => {
34 + await using screen = await render(<Workspace open={false} />);
35 + await openPanelFromComposer(screen);
36 +
37 + await screen.rerender(<Workspace open={false} />);
38 +
39 + await expect.element(screen.getByRole("textbox", { name: "Message New thread" })).toHaveFocus();
40 + });
41 +
42 + it("returns focus to the composer when a panel opened from it unmounts", async () => {
43 + await using screen = await render(<Workspace open={false} />);
44 + await openPanelFromComposer(screen);
45 +
46 + await screen.rerender(<Workspace open={false} present={false} />);
47 +
48 + await expect.element(screen.getByRole("textbox", { name: "Message New thread" })).toHaveFocus();
49 + });
50 +
51 + it("returns focus to the composer when the panel's content takes focus as it mounts", async () => {
52 + // A terminal surface focuses itself from its ref callback, before the shell's own ref attaches.
53 + const focusOnMount = (element: HTMLElement | null) => element?.focus();
54 + const panel = (present: boolean) => (
55 + <Workspace open present={present}>
56 + <div role="region" aria-label="Terminal" tabIndex={-1} ref={focusOnMount} />
57 + </Workspace>
58 + );
59 + await using screen = await render(panel(false));
60 + await userEvent.click(screen.getByRole("textbox", { name: "Message New thread" }));
61 + await screen.rerender(panel(true));
62 + await expect.element(screen.getByRole("region", { name: "Terminal" })).toHaveFocus();
63 +
64 + await screen.rerender(panel(false));
65 +
66 + await expect.element(screen.getByRole("textbox", { name: "Message New thread" })).toHaveFocus();
67 + });
68 +
69 + it("keeps the composer as the origin after focus visits a menu portalled from the panel", async () => {
70 + const panel = (open: boolean) => (
71 + <Workspace open={open}>
72 + <div role="region" aria-label="Open a surface" tabIndex={-1} />
73 + {createPortal(<button type="button">Add panel surface</button>, document.body)}
74 + </Workspace>
75 + );
76 + await using screen = await render(panel(false));
77 + await userEvent.click(screen.getByRole("textbox", { name: "Message New thread" }));
78 + await screen.rerender(panel(true));
79 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
80 + await act(() => page.getByRole("button", { name: "Add panel surface" }).element().focus());
81 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
82 +
83 + await screen.rerender(panel(false));
84 +
85 + await expect.element(screen.getByRole("textbox", { name: "Message New thread" })).toHaveFocus();
86 + });
87 +
88 + it("falls back to the toggle without scrolling when the origin has scrolled out of view", async () => {
89 + const layout = (open: boolean) => (
90 + <div>
91 + <div
92 + data-testid="timeline"
93 + data-workspace-area="conversation"
94 + style={{ height: 100, overflowY: "auto" }}
95 + >
96 + <button type="button">Copy message</button>
97 + <div style={{ height: 2000 }} />
98 + </div>
99 + <button type="button" aria-label="Toggle right panel" data-right-panel-toggle />
100 + <PreviewPanelShell mode="inline" open={open}>
101 + <div role="region" aria-label="Open a surface" tabIndex={-1} />
102 + </PreviewPanelShell>
103 + </div>
104 + );
105 + await using screen = await render(layout(false));
106 + await userEvent.click(screen.getByRole("button", { name: "Copy message" }));
107 + await screen.rerender(layout(true));
108 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
109 + const timeline = screen.getByTestId("timeline").element();
110 + timeline.scrollTop = 1500;
111 +
112 + await screen.rerender(layout(false));
113 +
114 + await expect.element(screen.getByRole("button", { name: "Toggle right panel" })).toHaveFocus();
115 + expect(timeline.scrollTop).toBe(1500);
116 + });
117 +
118 + it("falls back to the toggle when the origin's drawer is closing", async () => {
119 + // A closing drawer stays mounted for its exit animation but is no longer a workspace area.
120 + const layout = (open: boolean, drawerOpen: boolean) => (
121 + <div>
122 + <div data-workspace-area={drawerOpen ? "terminal" : undefined}>
123 + <input aria-label="Terminal input" />
124 + </div>
125 + <button type="button" aria-label="Toggle right panel" data-right-panel-toggle />
126 + <PreviewPanelShell mode="inline" open={open}>
127 + <div role="region" aria-label="Open a surface" tabIndex={-1} />
128 + </PreviewPanelShell>
129 + </div>
130 + );
131 + await using screen = await render(layout(false, true));
132 + await userEvent.click(screen.getByRole("textbox", { name: "Terminal input" }));
133 + await screen.rerender(layout(true, true));
134 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
135 + await screen.rerender(layout(true, false));
136 +
137 + await screen.rerender(layout(false, false));
138 +
139 + await expect.element(screen.getByRole("button", { name: "Toggle right panel" })).toHaveFocus();
140 + });
141 +
142 + it("does not return focus to the origin of an earlier open", async () => {
143 + await using screen = await render(<Workspace open={false} />);
144 + await openPanelFromComposer(screen);
145 + await screen.rerender(<Workspace open={false} />);
146 + const composer = screen.getByRole("textbox", { name: "Message New thread" });
147 + await expect.element(composer).toHaveFocus();
148 + await act(() => composer.element().blur());
149 + await screen.rerender(<Workspace open />);
150 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
151 +
152 + await screen.rerender(<Workspace open={false} />);
153 +
154 + await expect.element(screen.getByRole("button", { name: "Toggle right panel" })).toHaveFocus();
155 + });
156 +
157 + it("returns focus to the toggle when a panel opened from it collapses", async () => {
158 + await using screen = await render(<Workspace open={false} />);
159 + await userEvent.click(screen.getByRole("textbox", { name: "Message New thread" }));
160 + await userEvent.click(screen.getByRole("button", { name: "Toggle right panel" }));
161 + await screen.rerender(<Workspace open />);
162 + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus());
163 +
164 + await screen.rerender(<Workspace open={false} />);
165 +
166 + await expect.element(screen.getByRole("button", { name: "Toggle right panel" })).toHaveFocus();
167 + });
168 +});
apps/web/src/components/preview/PreviewPanelShell.tsx
+43 -10
@@ -1,10 +1,17 @@
1 -import { type CSSProperties, type ReactNode, useLayoutEffect, useRef, useState } from "react";
1 +import {
2 + type CSSProperties,
3 + type FocusEvent,
4 + type ReactNode,
5 + useLayoutEffect,
6 + useRef,
7 + useState,
8 +} from "react";
9 import {
10 type PreviewPanelInlineSize,
11 usePreviewPanelInlineSize,
12 } from "~/hooks/usePreviewPanelInlineSize";
13 import { RESIZABLE_WIDTH_PROPERTY } from "~/hooks/useResizableWidth";
7 -import { workspaceAreaProps } from "../../lib/workspaceFocus";
14 +import { canReturnFocusTo, workspaceAreaProps } from "../../lib/workspaceFocus";
15 import { cn } from "~/lib/utils";
16
17 import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
@@ -42,6 +49,19 @@ function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
49 return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} />;
50 }
51
52 +// Prefers the element focus entered the panel from, falling back to the panel toggle.
53 +function returnFocus(host: HTMLElement, origin: HTMLElement | null) {
54 + const { ownerDocument } = host;
55 + // focus() is a no-op on a disabled origin, so activeElement says whether it took.
56 + if (origin?.isConnected && !host.contains(origin) && canReturnFocusTo(origin)) {
57 + origin.focus({ preventScroll: true });
58 + if (ownerDocument.activeElement === origin) return true;
59 + }
60 + const toggle = ownerDocument.querySelector<HTMLButtonElement>("[data-right-panel-toggle]");
61 + toggle?.focus();
62 + return toggle !== null && ownerDocument.activeElement === toggle;
63 +}
64 +
65 function PreviewPanelShellFrame(
66 props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
67 ) {
@@ -52,6 +72,8 @@ function PreviewPanelShellFrame(
72 const maximized = props.maximized ?? false;
73 const hostRef = useRef<HTMLDivElement | null>(null);
74 const returnedFocus = useRef(false);
75 + const focusOrigin = useRef<HTMLElement | null>(null);
76 + const lastBlurred = useRef<EventTarget | null>(null);
77 const { width, handlers, observeRow } = props.inlineSize;
78 // Width animates only for an open or close. Any other width change disables
79 // the transition in the same commit that changes the width, so the browser
@@ -84,21 +106,30 @@ function PreviewPanelShellFrame(
106 stopObservingRow();
107 };
108 };
87 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- on unmount, returns DOM focus to the panel toggle if removal dropped it on the body
109 + // React focus events, unlike a listener added in attachHost, also see content that focuses
110 + // itself while mounting (a terminal does, from a ref that attaches before the host's).
111 + // Focus moving within the panel, portalled menus included, first blurs an element of it.
112 + const rememberFocusOrigin = (event: FocusEvent<HTMLDivElement>) => {
113 + const from = event.relatedTarget;
114 + if (from === null || from === lastBlurred.current) return;
115 + focusOrigin.current = from instanceof HTMLElement ? from : null;
116 + };
117 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- on unmount, returns DOM focus to where it came from if removal dropped it on the body
118 useLayoutEffect(() => {
119 const host = hostRef.current;
120 if (!host || !collapsible) return;
121 return () => {
122 if (!host.contains(host.ownerDocument.activeElement) && !returnedFocus.current) return;
123 + const origin = focusOrigin.current;
124 // Unmount moves the toggle; restore focus at its committed location if removal sent focus to body.
125 queueMicrotask(() => {
126 if (host.ownerDocument.activeElement === host.ownerDocument.body) {
96 - host.ownerDocument.querySelector<HTMLButtonElement>("[data-right-panel-toggle]")?.focus();
127 + returnFocus(host, origin);
128 }
129 });
130 };
131 }, [collapsible, hostRef]);
101 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves focus to the toggle and sets inert on the host DOM node before a collapse paints
132 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves focus out of the host and sets inert on it before a collapse paints
133 useLayoutEffect(() => {
134 const host = hostRef.current;
135 if (!host) return;
@@ -106,17 +137,19 @@ function PreviewPanelShellFrame(
137 if (!collapsed) returnedFocus.current = false;
138 // Move focus before making its current owner inert, while the toggle is reachable.
139 if (collapsed && host.contains(host.ownerDocument.activeElement)) {
109 - const toggle = host.ownerDocument.querySelector<HTMLButtonElement>(
110 - "[data-right-panel-toggle]",
111 - );
112 - toggle?.focus();
113 - returnedFocus.current = toggle !== null && host.ownerDocument.activeElement === toggle;
140 + returnedFocus.current = returnFocus(host, focusOrigin.current);
141 }
142 + // An origin belongs to one open; the next one records its own.
143 + if (collapsed) focusOrigin.current = null;
144 host.toggleAttribute("inert", collapsed);
145 }, [collapsible, open, hostRef]);
146 return (
147 <div
148 ref={attachHost}
149 + onFocus={rememberFocusOrigin}
150 + onBlur={(event) => {
151 + lastBlurred.current = event.target;
152 + }}
153 {...(props.workspaceArea ? panelArea : {})}
154 data-workspace-focus-key={props.workspaceFocusKey}
155 data-workspace-unavailable={collapsible && !open ? "true" : undefined}
apps/web/src/lib/workspaceFocus.ts
+10
@@ -73,6 +73,16 @@ function isInScrollView(target: HTMLElement) {
73 });
74 }
75
76 +/**
77 + * Whether focus can go back to an element without surprising the user: it is still in a
78 + * visible workspace area (a closing drawer drops its area) and in view, so no list scrolls.
79 + */
80 +export function canReturnFocusTo(element: HTMLElement) {
81 + return (
82 + workspaceArea(element) !== null && isWorkspaceElementVisible(element) && isInScrollView(element)
83 + );
84 +}
85 +
86 /**
87 * Brings a restored control into view, innermost scrolling list first.
88 * scrollIntoView would also scroll overflow-hidden layout containers out of place.