Open History to see the last commit
1import type { AnyRouter } from "@tanstack/react-router";
2import { dismissContextMenu } from "../contextMenuFallback";
3import { useRightPanelStore } from "../rightPanelStore";
4
5const AREA_SELECTOR = "[data-workspace-area]";
6// Excludes non-modal notifications and non-dialog popups; recovery focuses only open dialogs.
7const DIALOG_SELECTOR =
8 '[role="dialog"]:not([aria-modal="false"]), [role="alertdialog"]:not([aria-modal="false"]), [aria-modal="true"], dialog[open]';
9const FOCUS_BOUNDARY_SELECTOR =
10 '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], [data-slot$="-popup"]:not([data-slot="tooltip-popup"]):not([role="tooltip"])';
11const FOCUSABLE_SELECTOR =
12 'button:not(:disabled), a[href], input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [contenteditable="true"], [tabindex]';
13
14/** Props that make an element one stop in the F6 cycle; `order` sets its place in the cycle. */
15export function workspaceAreaProps(name: string, order: number, label?: string) {
16 return {
17 "data-workspace-area": name,
18 "data-workspace-order": order,
19 ...(label ? { "aria-label": label, role: "region" } : {}),
20 tabIndex: -1,
21 } as const;
22}
23
24export interface WorkspaceFocusTarget {
25 area: string;
26 selector?: string;
27 restore?: boolean;
28}
29
30function workspaceArea(element: Element): HTMLElement | null {
31 const area = element.closest<HTMLElement>(AREA_SELECTOR);
32 if (area) return area;
33 const root = element.getRootNode();
34 return root instanceof ShadowRoot ? workspaceArea(root.host) : null;
35}
36
37function isWorkspaceElementVisible(element: HTMLElement): boolean {
38 if (
39 !element.isConnected ||
40 element.closest(
41 '[hidden], [inert], [data-closed], [aria-hidden="true"], [data-chat-column-maximized-away="true"], [data-slot="sidebar"][data-state="collapsed"], [data-workspace-unavailable="true"]',
42 )
43 )
44 return false;
45 const style = getComputedStyle(element);
46 if (style.display === "none" || style.visibility === "hidden") return false;
47 const root = element.getRootNode();
48 if (
49 root instanceof ShadowRoot &&
50 root.host instanceof HTMLElement &&
51 !isWorkspaceElementVisible(root.host)
52 )
53 return false;
54 return Array.from(element.getClientRects()).some((rect) => rect.width > 0 && rect.height > 0);
55}
56
57function scrollingAncestors(target: HTMLElement) {
58 const scrollers: HTMLElement[] = [];
59 for (let element = target.parentElement; element; element = element.parentElement) {
60 const { overflowY } = getComputedStyle(element);
61 if (
62 (overflowY === "auto" || overflowY === "scroll") &&
63 element.scrollHeight > element.clientHeight
64 )
65 scrollers.push(element);
66 }
67 return scrollers;
68}
69
70function isInScrollView(target: HTMLElement) {
71 const rect = target.getBoundingClientRect();
72 return scrollingAncestors(target).every((scroller) => {
73 const box = scroller.getBoundingClientRect();
74 return rect.bottom > box.top && rect.top < box.bottom;
75 });
76}
77
78/**
79 * Whether focus can go back to an element without surprising the user: it is still in a
80 * visible workspace area (a closing drawer drops its area) and in view, so no list scrolls.
81 */
82export function canReturnFocusTo(element: HTMLElement) {
83 return (
84 workspaceArea(element) !== null && isWorkspaceElementVisible(element) && isInScrollView(element)
85 );
86}
87
88/**
89 * Brings a restored control into view, innermost scrolling list first.
90 * scrollIntoView would also scroll overflow-hidden layout containers out of place.
91 */
92function revealInScrollers(target: HTMLElement) {
93 for (const scroller of scrollingAncestors(target)) {
94 const box = scroller.getBoundingClientRect();
95 const rect = target.getBoundingClientRect();
96 if (rect.top < box.top) scroller.scrollTop -= box.top - rect.top;
97 else if (rect.bottom > box.bottom) scroller.scrollTop += rect.bottom - box.bottom;
98 }
99}
100
101/** Keeps area focus local, like VS Code's layout service focusPart/visible-neighbour actions. */
102export function createWorkspaceFocusController(doc: Document) {
103 const lastFocused = new Map<string, HTMLElement>();
104 let lastArea: string | undefined;
105 // An area that took focus itself from the keyboard, or the non-tabbable default (the
106 // conversation's scroller) standing in for it. Chromium's :focus-visible also matches a
107 // clicked area after any later key press, so the ring and window return read this mark.
108 let keyboardArea: HTMLElement | undefined;
109 let previousTarget: EventTarget | null = null;
110 const unmarkKeyboardArea = () => {
111 keyboardArea?.removeAttribute("data-workspace-keyboard-focus");
112 keyboardArea = undefined;
113 };
114 const standsInFor = (element: HTMLElement, area: HTMLElement) =>
115 element === area ||
116 (element.tabIndex < 0 && element.hasAttribute("data-workspace-focus-default"));
117 const markKeyboardArea = (target: HTMLElement) => {
118 if (!target.matches(":focus-visible")) return;
119 keyboardArea = target;
120 target.setAttribute("data-workspace-keyboard-focus", "");
121 };
122 const remember = (event: FocusEvent) => {
123 if (event.target !== keyboardArea) unmarkKeyboardArea();
124 // Window activation refocuses the same element; only focus arriving from elsewhere counts.
125 const arrived = event.target !== previousTarget;
126 previousTarget = event.target;
127 if (!(event.target instanceof HTMLElement)) return;
128 const area = workspaceArea(event.target);
129 if (!area?.dataset.workspaceArea) return;
130 if (arrived && standsInFor(event.target, area)) markKeyboardArea(event.target);
131 lastArea = area.dataset.workspaceArea;
132 const key = area.dataset.workspaceFocusKey ?? lastArea;
133 lastFocused.delete(key);
134 // Custom file trees retarget focusin to their nonfocusable shadow host.
135 const target = event.composedPath().find((element) => element instanceof HTMLElement);
136 lastFocused.set(key, target instanceof HTMLElement ? target : event.target);
137 // Surface history must not retain an unbounded number of detached panel trees.
138 if (lastFocused.size > 64) lastFocused.delete(lastFocused.keys().next().value!);
139 };
140 doc.addEventListener("focusin", remember);
141
142 const focusArea = (area: HTMLElement, restore = true, nested = true, keepScroll = false) => {
143 const key = area.dataset.workspaceFocusKey ?? area.dataset.workspaceArea!;
144 const previous = restore ? lastFocused.get(key) : undefined;
145 // Recovering from a removed row lands on a control already in view instead of
146 // scrolling the list back to its first one.
147 const usable = (element: HTMLElement) =>
148 isWorkspaceElementVisible(element) &&
149 !element.matches(":disabled") &&
150 (!keepScroll || element === area || isInScrollView(element));
151 const belongs = (element: HTMLElement) => workspaceArea(element) === area && usable(element);
152 // A side chat's message input sits in its own area inside the panel. Opening the
153 // panel focuses it, but F6 visits that area on its own, so it moves past it here.
154 // A nested timeline stands in only for its own area, never ahead of that input.
155 const preferred = Array.from(
156 area.querySelectorAll<HTMLElement>(
157 '[data-workspace-focus-default], [data-sidebar-row][aria-current="page"], [data-settings-section][aria-current="page"], .xterm-helper-textarea, [contenteditable="true"]',
158 ),
159 ).find((element) =>
160 nested && !standsInFor(element, area) ? usable(element) : belongs(element),
161 );
162 const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
163 (element) => element.tabIndex >= 0 && belongs(element),
164 );
165 // Panel surfaces may unmount when hidden. Recover the same named control when
166 // it mounts again, without sharing focus history between different surface tabs.
167 const restored =
168 previous && !previous.isConnected
169 ? Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
170 (element) =>
171 belongs(element) &&
172 element.tagName === previous.tagName &&
173 ((previous.id && element.id === previous.id) ||
174 (previous.getAttribute("aria-label") &&
175 element.getAttribute("aria-label") === previous.getAttribute("aria-label")) ||
176 (previous.matches("button") &&
177 previous.textContent?.trim() &&
178 element.textContent === previous.textContent)),
179 )
180 : undefined;
181 const surface = area.querySelector<HTMLElement>("[data-right-panel-surface-content]");
182 const surfaceControl = surface
183 ? Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
184 (element) => belongs(element) && element.tabIndex >= 0,
185 )
186 : undefined;
187 // Moving the timeline to an old control would also stop it following a running turn,
188 // so the conversation reuses a control only while it is still in view. A remembered
189 // area is only the fallback it was then, so controls mounted since take precedence.
190 const isConversation = area.dataset.workspaceArea === "conversation";
191 const targets = new Set([
192 previous &&
193 previous !== area &&
194 belongs(previous) &&
195 (!isConversation || isInScrollView(previous))
196 ? previous
197 : undefined,
198 isConversation ? undefined : restored,
199 preferred,
200 surfaceControl,
201 isConversation ? undefined : fallback,
202 area,
203 ]);
204 for (const target of targets) {
205 if (!target) continue;
206 target.focus({ preventScroll: true });
207 const root = target.getRootNode();
208 const active = root instanceof ShadowRoot ? root.activeElement : doc.activeElement;
209 if (active === target || (active && target.contains(active))) {
210 if (target !== area && !isConversation && !keepScroll) revealInScrollers(target);
211 // Focusing the already focused area fires no focusin, as when F6 has nowhere else to go.
212 if (standsInFor(target, area)) markKeyboardArea(target);
213 return true;
214 }
215 }
216 return false;
217 };
218 const focus = (name: string, restore = true, selector?: string, keepScroll = false) => {
219 const areas = Array.from(doc.querySelectorAll<HTMLElement>(AREA_SELECTOR)).filter(
220 isWorkspaceElementVisible,
221 );
222 const area =
223 name === "content"
224 ? (areas.find((element) => element.dataset.workspaceArea === "composer") ??
225 areas.find(
226 (element) =>
227 element.dataset.workspaceArea === "pull-requests" || element.matches("main"),
228 ) ??
229 areas.find((element) => element.dataset.workspaceArea === "conversation") ??
230 areas.find((element) => element.dataset.workspaceArea === "panel"))
231 : areas.find((element) => element.dataset.workspaceArea === name);
232 if (!area) return false;
233 const surface = area.querySelector("[data-right-panel-surface-content]");
234 // A lazy surface's Suspense fallback is empty. Wait for its content instead
235 // of claiming focus on the tab strip before the useful controls mount.
236 if (surface && !surface.hasChildNodes()) return false;
237 if (!selector && surface?.contains(doc.activeElement)) return true;
238 if (selector) {
239 const target = area.querySelector<HTMLElement>(selector);
240 if (!target || !isWorkspaceElementVisible(target)) return false;
241 target.focus({ preventScroll: true });
242 return doc.activeElement === target;
243 }
244 return focusArea(area, restore, true, keepScroll);
245 };
246 const move = (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
247 // HTML context menus close on blur, unlike modal dialogs and Base UI popups.
248 dismissContextMenu(false);
249 // A palette closes before running its command. Other popups keep their focus boundary.
250 // Inline listboxes (such as Settings search) belong to their workspace area, while
251 // portalled listboxes and menus can also supply a boundary without a popup data-slot.
252 const activePopup = doc.activeElement?.closest<HTMLElement>('[role="menu"], [role="listbox"]');
253 // Settings opens as a route modal with its own areas; navigation stays inside it.
254 const appModal = Array.from(doc.querySelectorAll<HTMLElement>("[data-app-modal]")).find(
255 isWorkspaceElementVisible,
256 );
257 const boundaries = Array.from(
258 doc.querySelectorAll<HTMLElement>(FOCUS_BOUNDARY_SELECTOR),
259 ).filter((boundary) => boundary !== appModal);
260 if (activePopup && !activePopup.closest(AREA_SELECTOR)) boundaries.push(activePopup);
261 // A modal keeps focus wherever it is; any other popup only while it holds focus,
262 // so hover popups and notifications never swallow the key.
263 if (
264 boundaries.some(
265 (boundary) =>
266 !(closingPalette && boundary.closest("[data-command-palette]")) &&
267 (boundary.matches('[aria-modal="true"]') || boundary.contains(doc.activeElement)) &&
268 isWorkspaceElementVisible(boundary),
269 )
270 )
271 return false;
272 const areas = Array.from((appModal ?? doc).querySelectorAll<HTMLElement>(AREA_SELECTOR))
273 .filter(isWorkspaceElementVisible)
274 .sort(
275 (left, right) => Number(left.dataset.workspaceOrder) - Number(right.dataset.workspaceOrder),
276 );
277 if (areas.length === 0) return false;
278 const activeArea = doc.activeElement?.closest<HTMLElement>(AREA_SELECTOR);
279 const currentId = fromArea ?? activeArea?.dataset.workspaceArea ?? lastArea;
280 // A side chat nests areas with the main chat's names, so prefer the focused element.
281 const activeIndex = fromArea || !activeArea ? -1 : areas.indexOf(activeArea);
282 const current =
283 activeIndex === -1
284 ? areas.findIndex((area) => area.dataset.workspaceArea === currentId)
285 : activeIndex;
286 const index =
287 current === -1
288 ? direction === 1
289 ? 0
290 : areas.length - 1
291 : (current + direction + areas.length) % areas.length;
292 const area = areas[index]!;
293 return focusArea(area, true, false);
294 };
295
296 // Focus that drops to the body because its element was hidden, made inert, disabled, or removed
297 // returns to a remounted control, else its area, or the composer for a finished timeline prompt.
298 const recover = (event: FocusEvent) => {
299 const lost = event.target;
300 if (!(lost instanceof HTMLElement) || event.relatedTarget) return;
301 const dialog = lost.closest<HTMLElement>(DIALOG_SELECTOR);
302 const areaName = workspaceArea(lost)?.dataset.workspaceArea;
303 const recoveryArea = areaName === "conversation" ? "composer" : areaName;
304 const label = lost.getAttribute("aria-label");
305 // Removal fires focusout while the row is still laid out, so its list and place are known.
306 const list = scrollingAncestors(lost)[0];
307 const lostTop = lost.getBoundingClientRect().top;
308 requestAnimationFrame(() => {
309 if (
310 doc.activeElement !== doc.body ||
311 !doc.hasFocus() ||
312 // Scrolling swaps these out; focusing elsewhere would pull a screen reader's cursor along.
313 lost.closest("[inert][data-workspace-scroll-swap]") ||
314 (isWorkspaceElementVisible(lost) && !lost.matches(":disabled"))
315 )
316 return;
317 const remounted = Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
318 (element) =>
319 element.tagName === lost.tagName &&
320 ((lost.id && element.id === lost.id) ||
321 (label && element.getAttribute("aria-label") === label)) &&
322 isWorkspaceElementVisible(element) &&
323 !element.matches(":disabled"),
324 );
325 const distance = (element: HTMLElement) =>
326 Math.abs(element.getBoundingClientRect().top - lostTop);
327 const neighbour =
328 !lost.isConnected && list?.isConnected && recoveryArea === areaName
329 ? Array.from(list.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
330 .filter(
331 (element) =>
332 element.tabIndex >= 0 &&
333 isWorkspaceElementVisible(element) &&
334 isInScrollView(element),
335 )
336 .reduce<HTMLElement | undefined>(
337 (best, element) => (!best || distance(element) < distance(best) ? element : best),
338 undefined,
339 )
340 : undefined;
341 if (remounted) remounted.focus({ preventScroll: true });
342 else if (neighbour) neighbour.focus({ preventScroll: true });
343 else if (!recoveryArea || !focus(recoveryArea, true, undefined, true)) {
344 if (dialog && isWorkspaceElementVisible(dialog)) dialog.focus({ preventScroll: true });
345 // A dialog without a tabindex cannot take focus.
346 if (doc.activeElement !== dialog) focus("content");
347 }
348 });
349 };
350 doc.addEventListener("focusout", recover);
351
352 // A request names a destination React has not committed yet, so it retries as the
353 // DOM changes. User input cancels it, and it gives up after two seconds.
354 let pending: WorkspaceFocusTarget | undefined;
355 let frame = 0;
356 let deadline = 0;
357 let cancelOnInput = false;
358 const observer = new MutationObserver(() => schedule());
359 const cancelRequest = () => {
360 pending = undefined;
361 cancelOnInput = false;
362 observer.disconnect();
363 cancelAnimationFrame(frame);
364 clearTimeout(deadline);
365 };
366 const schedule = () => {
367 cancelAnimationFrame(frame);
368 frame = requestAnimationFrame(() => {
369 if (pending && focus(pending.area, pending.restore, pending.selector)) cancelRequest();
370 });
371 };
372 const request = (target: WorkspaceFocusTarget) => {
373 cancelRequest();
374 pending = target;
375 // The key or click that made the request may still be propagating.
376 queueMicrotask(() => {
377 if (pending === target) cancelOnInput = true;
378 });
379 observer.observe(doc.body, {
380 childList: true,
381 subtree: true,
382 attributes: true,
383 attributeFilter: ["inert", "aria-hidden", "data-workspace-unavailable"],
384 });
385 deadline = window.setTimeout(cancelRequest, 2000);
386 schedule();
387 };
388 const onUserInput = () => {
389 if (cancelOnInput) cancelRequest();
390 };
391 const onPointerDown = () => {
392 unmarkKeyboardArea();
393 onUserInput();
394 };
395 doc.addEventListener("pointerdown", onPointerDown, true);
396 doc.addEventListener("keydown", onUserInput, true);
397
398 return {
399 move: (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
400 cancelRequest();
401 return move(direction, fromArea, closingPalette);
402 },
403 focus,
404 request,
405 dispose: () => {
406 cancelRequest();
407 unmarkKeyboardArea();
408 doc.removeEventListener("focusin", remember);
409 doc.removeEventListener("focusout", recover);
410 doc.removeEventListener("pointerdown", onPointerDown, true);
411 doc.removeEventListener("keydown", onUserInput, true);
412 },
413 };
414}
415
416let controller: ReturnType<typeof createWorkspaceFocusController> | undefined;
417let focusRequestVersion = 0;
418export const getWorkspaceFocusRequestVersion = () => focusRequestVersion;
419
420/**
421 * Starts workspace focus for the app: F6 area moves, focus requests, focus-loss recovery,
422 * focus into a panel the user opens, and focus into the Pull Requests page on entry.
423 */
424export function startWorkspaceFocus(router: AnyRouter): () => void {
425 const active = createWorkspaceFocusController(document);
426 controller = active;
427 const stopPanels = useRightPanelStore.subscribe((state, previous) => {
428 if (state.userActionRevisionByThreadKey === previous.userActionRevisionByThreadKey) return;
429 for (const [threadKey, revision] of Object.entries(state.userActionRevisionByThreadKey)) {
430 if (previous.userActionRevisionByThreadKey[threadKey] === revision) continue;
431 const next = state.byThreadKey[threadKey];
432 const before = previous.byThreadKey[threadKey];
433 if (next?.isOpen && (!before?.isOpen || next.activeSurfaceId !== before.activeSurfaceId))
434 requestWorkspaceFocus({ area: "panel" });
435 }
436 });
437 const stopRoute = router.subscribe("onResolved", ({ fromLocation, toLocation }) => {
438 if (toLocation.pathname === "/pull-requests" && fromLocation?.pathname !== "/pull-requests")
439 requestWorkspaceFocus({ area: "pull-requests" });
440 });
441 return () => {
442 stopPanels();
443 stopRoute();
444 active.dispose();
445 if (controller === active) controller = undefined;
446 };
447}
448
449/** Moves to the next or previous visible area. `fromArea` overrides the focused area. */
450export function moveWorkspaceFocus(direction: 1 | -1, fromArea?: string): boolean {
451 return controller?.move(direction, fromArea) ?? false;
452}
453
454/** Explicit user actions request focus after React has committed the destination. */
455export function requestWorkspaceFocus(target: WorkspaceFocusTarget) {
456 focusRequestVersion++;
457 controller?.request(target);
458}
459
460export function requestWorkspaceContentFocus() {
461 // Resolve after the layout commits: closing a maximized panel makes the
462 // composer available again, while hiding a sidebar may leave only the panel.
463 requestWorkspaceFocus({ area: "content" });
464}
465
466let pendingPaletteDirection: 1 | -1 | undefined;
467export function queueWorkspaceFocusFromPalette(direction: 1 | -1) {
468 pendingPaletteDirection = direction;
469}
470
471/** Runs at the palette's normal focus restoration milestone, after its focus trap closes. */
472export function restoreWorkspaceFocusFromPalette(): boolean {
473 if (pendingPaletteDirection === undefined) return false;
474 const direction = pendingPaletteDirection;
475 pendingPaletteDirection = undefined;
476 window.requestAnimationFrame(() => controller?.move(direction, undefined, true));
477 return true;
478}