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

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