Skip to content

Commit 56a2469

Browse files
saphidgithub-actions[bot]
authored andcommitted
fix(web): move keyboard interaction out of the closing right panel
1 parent 8fb068c commit 56a2469

5 files changed

Lines changed: 336 additions & 0 deletions

File tree

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// @vitest-environment jsdom
2+
3+
import { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6+
7+
import { RightPanelTabs } from "./RightPanelTabs";
8+
import type { PreviewPanelMode } from "./preview/PreviewPanelShell";
9+
10+
let root: Root;
11+
let container: HTMLDivElement;
12+
const originalGetAnimations = Object.getOwnPropertyDescriptor(Element.prototype, "getAnimations");
13+
14+
beforeEach(() => {
15+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
16+
Object.defineProperty(Element.prototype, "getAnimations", {
17+
configurable: true,
18+
value: () => [],
19+
});
20+
vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame"] });
21+
vi.stubGlobal(
22+
"ResizeObserver",
23+
class {
24+
observe() {}
25+
unobserve() {}
26+
disconnect() {}
27+
},
28+
);
29+
container = document.createElement("div");
30+
document.body.append(container);
31+
root = createRoot(container);
32+
});
33+
34+
afterEach(async () => {
35+
await act(async () => root.unmount());
36+
container.remove();
37+
if (originalGetAnimations) {
38+
Object.defineProperty(Element.prototype, "getAnimations", originalGetAnimations);
39+
} else {
40+
Reflect.deleteProperty(Element.prototype, "getAnimations");
41+
}
42+
vi.unstubAllGlobals();
43+
vi.useRealTimers();
44+
});
45+
46+
async function renderTabs(open: boolean, mode: PreviewPanelMode = "inline") {
47+
await act(async () => {
48+
root.render(
49+
<RightPanelTabs
50+
mode={mode}
51+
open={open}
52+
surfaces={[{ id: "diff", kind: "diff" }]}
53+
environmentId={null}
54+
activeSurfaceId="diff"
55+
pendingSurfaceIds={new Set()}
56+
previewSessions={{}}
57+
desktopByTabId={{}}
58+
terminalLabelsById={new Map()}
59+
onActivate={() => undefined}
60+
onCloseSurface={() => undefined}
61+
onCloseOtherSurfaces={() => undefined}
62+
onCloseSurfacesToRight={() => undefined}
63+
onCloseAllSurfaces={() => undefined}
64+
onCopyFilePath={() => undefined}
65+
onAddBrowser={() => undefined}
66+
onAddBrowserInProfile={() => undefined}
67+
onAddTerminal={() => undefined}
68+
onAddPullRequest={() => undefined}
69+
onAddPullRequests={() => undefined}
70+
onAddDiff={() => undefined}
71+
onAddFiles={() => undefined}
72+
onAddDevice={() => undefined}
73+
browserAvailable={false}
74+
terminalAvailable
75+
diffAvailable={false}
76+
filesAvailable={false}
77+
pullRequestAvailable={false}
78+
pullRequestsAvailable={false}
79+
deviceAvailable={false}
80+
>
81+
<div>content</div>
82+
</RightPanelTabs>,
83+
);
84+
});
85+
await act(async () => vi.advanceTimersToNextFrame());
86+
}
87+
88+
async function openMenu() {
89+
const trigger = document.querySelector<HTMLButtonElement>('[aria-label="Add panel surface"]')!;
90+
await act(async () => {
91+
trigger.focus();
92+
trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
93+
});
94+
await act(async () => vi.advanceTimersToNextFrame());
95+
const menu = document.querySelector<HTMLElement>('[role="menu"]')!;
96+
expect(menu).not.toBeNull();
97+
expect(container.contains(menu)).toBe(false);
98+
return menu;
99+
}
100+
101+
describe("collapsed panel portaled menu", () => {
102+
it.each(["sheet", "sidebar", "embedded"] as const)(
103+
"keeps the menu available in %s mode when open is false",
104+
async (mode) => {
105+
await renderTabs(true, mode);
106+
const menu = await openMenu();
107+
await renderTabs(false, mode);
108+
expect(document.querySelector('[role="menu"]')).toBe(menu);
109+
},
110+
);
111+
112+
it("closes the menu on collapse and does not reopen it with the panel", async () => {
113+
await renderTabs(true);
114+
await openMenu();
115+
await renderTabs(false);
116+
expect(document.querySelector('[role="menu"]')).toBeNull();
117+
await renderTabs(true);
118+
expect(document.querySelector('[role="menu"]')).toBeNull();
119+
await openMenu();
120+
});
121+
});

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
795795
const tabListRef = useRef<HTMLDivElement>(null);
796796
const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
797797
const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
798+
// The menu portal sits outside the collapsed shell's inert subtree.
799+
if (props.mode === "inline" && props.open === false && addSurfaceMenuOpen) {
800+
setAddSurfaceMenuOpen(false);
801+
}
798802
const [tabScrollState, setTabScrollState] = useState({
799803
hasOverflow: false,
800804
canScrollLeft: false,

‎apps/web/src/components/chat/PanelLayoutControls.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
121121
pressed={rightPanelOpen}
122122
onPressedChange={onToggleRightPanel}
123123
aria-label="Toggle right panel"
124+
data-right-panel-toggle
124125
variant="ghost"
125126
size="sm"
126127
disabled={!rightPanelAvailable}
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// @vitest-environment jsdom
2+
3+
import { Dialog } from "@base-ui/react/dialog";
4+
import { act } from "react";
5+
import { createRoot, type Root } from "react-dom/client";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7+
8+
import { PanelLayoutControls } from "../chat/PanelLayoutControls";
9+
import { PreviewPanelShell, type PreviewPanelMode } from "./PreviewPanelShell";
10+
11+
let root: Root;
12+
let container: HTMLDivElement;
13+
14+
beforeEach(() => {
15+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
16+
vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame"] });
17+
vi.stubGlobal(
18+
"ResizeObserver",
19+
class {
20+
observe() {}
21+
unobserve() {}
22+
disconnect() {}
23+
},
24+
);
25+
container = document.createElement("div");
26+
document.body.append(container);
27+
root = createRoot(container);
28+
});
29+
30+
afterEach(async () => {
31+
await act(async () => root.unmount());
32+
container.remove();
33+
vi.unstubAllGlobals();
34+
vi.useRealTimers();
35+
});
36+
37+
async function renderPanel(
38+
open: boolean | undefined,
39+
mode: PreviewPanelMode = "inline",
40+
present = true,
41+
) {
42+
await act(async () => {
43+
root.render(
44+
<Dialog.Root open>
45+
<Dialog.Portal>
46+
<Dialog.Popup aria-label="Workspace" finalFocus={false}>
47+
{present ? (
48+
<PreviewPanelShell mode={mode} {...(open === undefined ? {} : { open })}>
49+
<input aria-label="Preview URL" />
50+
<button type="button">Reload preview</button>
51+
</PreviewPanelShell>
52+
) : null}
53+
<button type="button" data-testid="outside">
54+
Send message
55+
</button>
56+
<div key={present ? "root-controls" : "header-controls"}>
57+
<PanelLayoutControls
58+
showTerminalControl={false}
59+
showThreadPanelControl={false}
60+
terminalAvailable={false}
61+
terminalOpen={false}
62+
terminalShortcutLabel={null}
63+
threadPanelOpen={false}
64+
threadPanelPresentation="inline"
65+
threadPanelShortcutLabel={null}
66+
threadPanelHasAttention={false}
67+
rightPanelAvailable
68+
rightPanelOpen={open ?? true}
69+
rightPanelShortcutLabel={null}
70+
onToggleTerminal={() => {}}
71+
onToggleThreadPanel={() => {}}
72+
onToggleRightPanel={() => {}}
73+
/>
74+
</div>
75+
</Dialog.Popup>
76+
</Dialog.Portal>
77+
</Dialog.Root>,
78+
);
79+
});
80+
await act(async () => vi.advanceTimersToNextFrame());
81+
}
82+
83+
async function enterFocusScope() {
84+
// Base UI's focus guard models Tab wrapping into the scope. Its production
85+
// focus manager chooses the first tabbable descendant, including inert rules
86+
// that jsdom's native focus() does not implement.
87+
const guards = document.querySelectorAll<HTMLElement>("[data-base-ui-focus-guard]");
88+
expect(guards.length).toBe(2);
89+
await act(async () => guards[1]!.focus());
90+
await act(async () => vi.advanceTimersToNextFrame());
91+
}
92+
93+
describe("right panel keyboard access", () => {
94+
it("skips collapsed controls and restores access after reopening", async () => {
95+
await renderPanel(false);
96+
const outside = document.querySelector<HTMLElement>('[data-testid="outside"]')!;
97+
expect(document.activeElement).toBe(outside);
98+
await enterFocusScope();
99+
expect(document.activeElement).toBe(outside);
100+
101+
await renderPanel(true);
102+
await enterFocusScope();
103+
expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
104+
105+
await renderPanel(false);
106+
await enterFocusScope();
107+
expect(document.activeElement).toBe(outside);
108+
});
109+
110+
it("returns focus to the right-panel toggle when a focused panel closes", async () => {
111+
await renderPanel(true);
112+
const input = document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!;
113+
await act(async () => input.focus());
114+
await renderPanel(false);
115+
expect(document.activeElement).toBe(
116+
document.querySelector('[aria-label="Toggle right panel"]'),
117+
);
118+
await renderPanel(true);
119+
await enterFocusScope();
120+
expect(document.activeElement).toBe(input);
121+
});
122+
123+
it("retains focus after the closing animation relocates the toggle", async () => {
124+
await renderPanel(true);
125+
await act(async () => {
126+
document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
127+
});
128+
await renderPanel(false);
129+
const closingToggle = document.querySelector('[aria-label="Toggle right panel"]');
130+
expect(document.activeElement).toBe(closingToggle);
131+
await renderPanel(false, "inline", false);
132+
const settledToggle = document.querySelector('[aria-label="Toggle right panel"]');
133+
expect(settledToggle).not.toBe(closingToggle);
134+
expect(document.activeElement).toBe(settledToggle);
135+
});
136+
137+
it("returns focus when the panel closes without an animation", async () => {
138+
await renderPanel(true);
139+
await act(async () => {
140+
document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
141+
});
142+
await renderPanel(false, "inline", false);
143+
expect(document.activeElement).toBe(
144+
document.querySelector('[aria-label="Toggle right panel"]'),
145+
);
146+
});
147+
148+
it("preserves focus moved outside while the closing animation settles", async () => {
149+
await renderPanel(true);
150+
await act(async () => {
151+
document.querySelector<HTMLInputElement>('[aria-label="Preview URL"]')!.focus();
152+
});
153+
await renderPanel(false);
154+
const outside = document.querySelector<HTMLButtonElement>('[data-testid="outside"]')!;
155+
await act(async () => outside.focus());
156+
await renderPanel(false, "inline", false);
157+
expect(document.activeElement).toBe(outside);
158+
});
159+
160+
it("preserves focus outside the panel when it closes", async () => {
161+
await renderPanel(true);
162+
const outside = document.querySelector<HTMLButtonElement>('[data-testid="outside"]')!;
163+
await act(async () => outside.focus());
164+
await renderPanel(false);
165+
expect(document.activeElement).toBe(outside);
166+
});
167+
168+
it.each(["sheet", "sidebar", "embedded"] as const)(
169+
"keeps %s controls reachable when the inline open flag is false",
170+
async (mode) => {
171+
await renderPanel(false, mode);
172+
expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
173+
},
174+
);
175+
176+
it("keeps non-collapsible inline controls reachable", async () => {
177+
await renderPanel(undefined);
178+
expect(document.activeElement).toBe(document.querySelector('[aria-label="Preview URL"]'));
179+
});
180+
});

‎apps/web/src/components/preview/PreviewPanelShell.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ function PreviewPanelShellFrame(
6767
const maximized = props.maximized ?? false;
6868
const localHostRef = useRef<HTMLDivElement | null>(null);
6969
const hostRef = props.hostRef ?? localHostRef;
70+
const returnedFocus = useRef(false);
7071
const { width, handlers } = props.inlineSize;
7172
// Derive suppression before the layout commits so the browser never creates
7273
// a width transition for resize or maximize changes.
@@ -105,6 +106,35 @@ function PreviewPanelShellFrame(
105106
window.cancelAnimationFrame(restoreFrame);
106107
};
107108
}, [suppressWidthTransition]);
109+
useLayoutEffect(() => {
110+
const host = hostRef.current;
111+
if (!host || !collapsible) return;
112+
return () => {
113+
if (!host.contains(host.ownerDocument.activeElement) && !returnedFocus.current) return;
114+
// The toggle moves when the shell unmounts, after an animation or immediately.
115+
// Restore focus at its committed location if removal cleared focus to body.
116+
queueMicrotask(() => {
117+
if (host.ownerDocument.activeElement === host.ownerDocument.body) {
118+
host.ownerDocument.querySelector<HTMLButtonElement>("[data-right-panel-toggle]")?.focus();
119+
}
120+
});
121+
};
122+
}, [collapsible, hostRef]);
123+
useLayoutEffect(() => {
124+
const host = hostRef.current;
125+
if (!host) return;
126+
const collapsed = collapsible && !open;
127+
if (!collapsed) returnedFocus.current = false;
128+
// Move focus before making its current owner inert, while the toggle is reachable.
129+
if (collapsed && host.contains(host.ownerDocument.activeElement)) {
130+
const toggle = host.ownerDocument.querySelector<HTMLButtonElement>(
131+
"[data-right-panel-toggle]",
132+
);
133+
toggle?.focus();
134+
returnedFocus.current = toggle !== null && host.ownerDocument.activeElement === toggle;
135+
}
136+
host.toggleAttribute("inert", collapsed);
137+
}, [collapsible, open, hostRef]);
108138
return (
109139
<div
110140
ref={hostRef}

0 commit comments

Comments
 (0)