Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workspaceFocus.ts

470 lines20.5 KB

1import type { AnyRouter } from "@tanstack/react-router";
2import { dismissContextMenu } from "../contextMenuFallback";
3import { useRightPanelStore } from "../rightPanelStore";
4​
5const AREA_SELECTOR = "[data-workspace-area]";
6const FOCUS_BOUNDARY_SELECTOR =
7 '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], [data-slot$="-popup"]:not([data-slot="tooltip-popup"]):not([role="tooltip"])';
8const 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. */
12export 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;
20​
21export interface WorkspaceFocusTarget {
22 area: string;
23 selector?: string;
24 restore?: boolean;
26​
27function 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;
33​
34function 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);
53​
54function 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;
66​
67function 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 });
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 */
79export function canReturnFocusTo(element: HTMLElement) {
80 return (
81 workspaceArea(element) !== null && isWorkspaceElementVisible(element) && isInScrollView(element)
82 );
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 */
89function 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 }
97​
98/** Keeps area focus local, like VS Code's layout service focusPart/visible-neighbour actions. */
99export 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, keepScroll = false) => {
140 const key = area.dataset.workspaceFocusKey ?? area.dataset.workspaceArea!;
141 const previous = restore ? lastFocused.get(key) : undefined;
142 // Recovering from a removed row lands on a control already in view instead of
143 // scrolling the list back to its first one.
144 const usable = (element: HTMLElement) =>
145 isWorkspaceElementVisible(element) &&
146 !element.matches(":disabled") &&
147 (!keepScroll || element === area || isInScrollView(element));
148 const belongs = (element: HTMLElement) => workspaceArea(element) === area && usable(element);
149 // A side chat's message input sits in its own area inside the panel. Opening the
150 // panel focuses it, but F6 visits that area on its own, so it moves past it here.
151 // A nested timeline stands in only for its own area, never ahead of that input.
152 const preferred = Array.from(
153 area.querySelectorAll<HTMLElement>(
154 '[data-workspace-focus-default], [data-sidebar-row][aria-current="page"], [data-settings-section][aria-current="page"], .xterm-helper-textarea, [contenteditable="true"]',
155 ),
156 ).find((element) =>
157 nested && !standsInFor(element, area) ? usable(element) : belongs(element),
158 );
159 const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
160 (element) => element.tabIndex >= 0 && belongs(element),
161 );
162 // Panel surfaces may unmount when hidden. Recover the same named control when
163 // it mounts again, without sharing focus history between different surface tabs.
164 const restored =
165 previous && !previous.isConnected
166 ? Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
167 (element) =>
168 belongs(element) &&
169 element.tagName === previous.tagName &&
170 ((previous.id && element.id === previous.id) ||
171 (previous.getAttribute("aria-label") &&
172 element.getAttribute("aria-label") === previous.getAttribute("aria-label")) ||
173 (previous.matches("button") &&
174 previous.textContent?.trim() &&
175 element.textContent === previous.textContent)),
176 )
177 : undefined;
178 const surface = area.querySelector<HTMLElement>("[data-right-panel-surface-content]");
179 const surfaceControl = surface
180 ? Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
181 (element) => belongs(element) && element.tabIndex >= 0,
182 )
183 : undefined;
184 // Moving the timeline to an old control would also stop it following a running turn,
185 // so the conversation reuses a control only while it is still in view. A remembered
186 // area is only the fallback it was then, so controls mounted since take precedence.
187 const isConversation = area.dataset.workspaceArea === "conversation";
188 const targets = new Set([
189 previous &&
190 previous !== area &&
191 belongs(previous) &&
192 (!isConversation || isInScrollView(previous))
193 ? previous
194 : undefined,
195 isConversation ? undefined : restored,
196 preferred,
197 surfaceControl,
198 isConversation ? undefined : fallback,
199 area,
200 ]);
201 for (const target of targets) {
202 if (!target) continue;
203 target.focus({ preventScroll: true });
204 const root = target.getRootNode();
205 const active = root instanceof ShadowRoot ? root.activeElement : doc.activeElement;
206 if (active === target || (active && target.contains(active))) {
207 if (target !== area && !isConversation && !keepScroll) revealInScrollers(target);
208 // Focusing the already focused area fires no focusin, as when F6 has nowhere else to go.
209 if (standsInFor(target, area)) markKeyboardArea(target);
210 return true;
211 }
212 }
213 return false;
214 };
215 const focus = (name: string, restore = true, selector?: string, keepScroll = false) => {
216 const areas = Array.from(doc.querySelectorAll<HTMLElement>(AREA_SELECTOR)).filter(
217 isWorkspaceElementVisible,
218 );
219 const area =
220 name === "content"
221 ? (areas.find((element) => element.dataset.workspaceArea === "composer") ??
222 areas.find(
223 (element) =>
224 element.dataset.workspaceArea === "pull-requests" || element.matches("main"),
225 ) ??
226 areas.find((element) => element.dataset.workspaceArea === "conversation") ??
227 areas.find((element) => element.dataset.workspaceArea === "panel"))
228 : areas.find((element) => element.dataset.workspaceArea === name);
229 if (!area) return false;
230 const surface = area.querySelector("[data-right-panel-surface-content]");
231 // A lazy surface's Suspense fallback is empty. Wait for its content instead
232 // of claiming focus on the tab strip before the useful controls mount.
233 if (surface && !surface.hasChildNodes()) return false;
234 if (!selector && surface?.contains(doc.activeElement)) return true;
235 if (selector) {
236 const target = area.querySelector<HTMLElement>(selector);
237 if (!target || !isWorkspaceElementVisible(target)) return false;
238 target.focus({ preventScroll: true });
239 return doc.activeElement === target;
240 }
241 return focusArea(area, restore, true, keepScroll);
242 };
243 const move = (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
244 // HTML context menus close on blur, unlike modal dialogs and Base UI popups.
245 dismissContextMenu(false);
246 // A palette closes before running its command. Other popups keep their focus boundary.
247 // Inline listboxes (such as Settings search) belong to their workspace area, while
248 // portalled listboxes and menus can also supply a boundary without a popup data-slot.
249 const activePopup = doc.activeElement?.closest<HTMLElement>('[role="menu"], [role="listbox"]');
250 // Settings opens as a route modal with its own areas; navigation stays inside it.
251 const appModal = Array.from(doc.querySelectorAll<HTMLElement>("[data-app-modal]")).find(
252 isWorkspaceElementVisible,
253 );
254 const boundaries = Array.from(
255 doc.querySelectorAll<HTMLElement>(FOCUS_BOUNDARY_SELECTOR),
256 ).filter((boundary) => boundary !== appModal);
257 if (activePopup && !activePopup.closest(AREA_SELECTOR)) boundaries.push(activePopup);
258 // A modal keeps focus wherever it is; any other popup only while it holds focus,
259 // so hover popups and notifications never swallow the key.
260 if (
261 boundaries.some(
262 (boundary) =>
263 !(closingPalette && boundary.closest("[data-command-palette]")) &&
264 (boundary.matches('[aria-modal="true"]') || boundary.contains(doc.activeElement)) &&
265 isWorkspaceElementVisible(boundary),
266 )
267 )
268 return false;
269 const areas = Array.from((appModal ?? doc).querySelectorAll<HTMLElement>(AREA_SELECTOR))
270 .filter(isWorkspaceElementVisible)
271 .sort(
272 (left, right) => Number(left.dataset.workspaceOrder) - Number(right.dataset.workspaceOrder),
273 );
274 if (areas.length === 0) return false;
275 const activeArea = doc.activeElement?.closest<HTMLElement>(AREA_SELECTOR);
276 const currentId = fromArea ?? activeArea?.dataset.workspaceArea ?? lastArea;
277 // A side chat nests areas with the main chat's names, so prefer the focused element.
278 const activeIndex = fromArea || !activeArea ? -1 : areas.indexOf(activeArea);
279 const current =
280 activeIndex === -1
281 ? areas.findIndex((area) => area.dataset.workspaceArea === currentId)
282 : activeIndex;
283 const index =
284 current === -1
285 ? direction === 1
286 ? 0
287 : areas.length - 1
288 : (current + direction + areas.length) % areas.length;
289 const area = areas[index]!;
290 return focusArea(area, true, false);
291 };
292​
293 // Focus that drops to the body because its element was hidden, made inert, disabled, or removed
294 // returns to a remounted control, else its area, or the composer for a finished timeline prompt.
295 const recover = (event: FocusEvent) => {
296 const lost = event.target;
297 if (!(lost instanceof HTMLElement) || event.relatedTarget) return;
298 const areaName = workspaceArea(lost)?.dataset.workspaceArea;
299 const recoveryArea = areaName === "conversation" ? "composer" : areaName;
300 const label = lost.getAttribute("aria-label");
301 // Removal fires focusout while the row is still laid out, so its list and place are known.
302 const list = scrollingAncestors(lost)[0];
303 const lostTop = lost.getBoundingClientRect().top;
304 requestAnimationFrame(() => {
305 if (
306 doc.activeElement !== doc.body ||
307 !doc.hasFocus() ||
308 // Scrolling swaps these out; focusing elsewhere would pull a screen reader's cursor along.
309 lost.closest("[inert][data-workspace-scroll-swap]") ||
310 (isWorkspaceElementVisible(lost) && !lost.matches(":disabled"))
311 )
312 return;
313 const remounted = Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
314 (element) =>
315 element.tagName === lost.tagName &&
316 ((lost.id && element.id === lost.id) ||
317 (label && element.getAttribute("aria-label") === label)) &&
318 isWorkspaceElementVisible(element) &&
319 !element.matches(":disabled"),
320 );
321 const distance = (element: HTMLElement) =>
322 Math.abs(element.getBoundingClientRect().top - lostTop);
323 const neighbour =
324 !lost.isConnected && list?.isConnected && recoveryArea === areaName
325 ? Array.from(list.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
326 .filter(
327 (element) =>
328 element.tabIndex >= 0 &&
329 isWorkspaceElementVisible(element) &&
330 isInScrollView(element),
331 )
332 .reduce<HTMLElement | undefined>(
333 (best, element) => (!best || distance(element) < distance(best) ? element : best),
334 undefined,
335 )
336 : undefined;
337 if (remounted) remounted.focus({ preventScroll: true });
338 else if (neighbour) neighbour.focus({ preventScroll: true });
339 else if (!recoveryArea || !focus(recoveryArea, true, undefined, true)) focus("content");
340 });
341 };
342 doc.addEventListener("focusout", recover);
343​
344 // A request names a destination React has not committed yet, so it retries as the
345 // DOM changes. User input cancels it, and it gives up after two seconds.
346 let pending: WorkspaceFocusTarget | undefined;
347 let frame = 0;
348 let deadline = 0;
349 let cancelOnInput = false;
350 const observer = new MutationObserver(() => schedule());
351 const cancelRequest = () => {
352 pending = undefined;
353 cancelOnInput = false;
354 observer.disconnect();
355 cancelAnimationFrame(frame);
356 clearTimeout(deadline);
357 };
358 const schedule = () => {
359 cancelAnimationFrame(frame);
360 frame = requestAnimationFrame(() => {
361 if (pending && focus(pending.area, pending.restore, pending.selector)) cancelRequest();
362 });
363 };
364 const request = (target: WorkspaceFocusTarget) => {
365 cancelRequest();
366 pending = target;
367 // The key or click that made the request may still be propagating.
368 queueMicrotask(() => {
369 if (pending === target) cancelOnInput = true;
370 });
371 observer.observe(doc.body, {
372 childList: true,
373 subtree: true,
374 attributes: true,
375 attributeFilter: ["inert", "aria-hidden", "data-workspace-unavailable"],
376 });
377 deadline = window.setTimeout(cancelRequest, 2000);
378 schedule();
379 };
380 const onUserInput = () => {
381 if (cancelOnInput) cancelRequest();
382 };
383 const onPointerDown = () => {
384 unmarkKeyboardArea();
385 onUserInput();
386 };
387 doc.addEventListener("pointerdown", onPointerDown, true);
388 doc.addEventListener("keydown", onUserInput, true);
389​
390 return {
391 move: (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
392 cancelRequest();
393 return move(direction, fromArea, closingPalette);
394 },
395 focus,
396 request,
397 dispose: () => {
398 cancelRequest();
399 unmarkKeyboardArea();
400 doc.removeEventListener("focusin", remember);
401 doc.removeEventListener("focusout", recover);
402 doc.removeEventListener("pointerdown", onPointerDown, true);
403 doc.removeEventListener("keydown", onUserInput, true);
404 },
405 };
407​
408let controller: ReturnType<typeof createWorkspaceFocusController> | undefined;
409let focusRequestVersion = 0;
410export const getWorkspaceFocusRequestVersion = () => focusRequestVersion;
411​
412/**
413 * Starts workspace focus for the app: F6 area moves, focus requests, focus-loss recovery,
414 * focus into a panel the user opens, and focus into the Pull Requests page on entry.
415 */
416export function startWorkspaceFocus(router: AnyRouter): () => void {
417 const active = createWorkspaceFocusController(document);
418 controller = active;
419 const stopPanels = useRightPanelStore.subscribe((state, previous) => {
420 if (state.userActionRevisionByThreadKey === previous.userActionRevisionByThreadKey) return;
421 for (const [threadKey, revision] of Object.entries(state.userActionRevisionByThreadKey)) {
422 if (previous.userActionRevisionByThreadKey[threadKey] === revision) continue;
423 const next = state.byThreadKey[threadKey];
424 const before = previous.byThreadKey[threadKey];
425 if (next?.isOpen && (!before?.isOpen || next.activeSurfaceId !== before.activeSurfaceId))
426 requestWorkspaceFocus({ area: "panel" });
427 }
428 });
429 const stopRoute = router.subscribe("onResolved", ({ fromLocation, toLocation }) => {
430 if (toLocation.pathname === "/pull-requests" && fromLocation?.pathname !== "/pull-requests")
431 requestWorkspaceFocus({ area: "pull-requests" });
432 });
433 return () => {
434 stopPanels();
435 stopRoute();
436 active.dispose();
437 if (controller === active) controller = undefined;
438 };
440​
441/** Moves to the next or previous visible area. `fromArea` overrides the focused area. */
442export function moveWorkspaceFocus(direction: 1 | -1, fromArea?: string): boolean {
443 return controller?.move(direction, fromArea) ?? false;
445​
446/** Explicit user actions request focus after React has committed the destination. */
447export function requestWorkspaceFocus(target: WorkspaceFocusTarget) {
448 focusRequestVersion++;
449 controller?.request(target);
451​
452export function requestWorkspaceContentFocus() {
453 // Resolve after the layout commits: closing a maximized panel makes the
454 // composer available again, while hiding a sidebar may leave only the panel.
455 requestWorkspaceFocus({ area: "content" });
457​
458let pendingPaletteDirection: 1 | -1 | undefined;
459export function queueWorkspaceFocusFromPalette(direction: 1 | -1) {
460 pendingPaletteDirection = direction;
462​
463/** Runs at the palette's normal focus restoration milestone, after its focus trap closes. */
464export function restoreWorkspaceFocusFromPalette(): boolean {
465 if (pendingPaletteDirection === undefined) return false;
466 const direction = pendingPaletteDirection;
467 pendingPaletteDirection = undefined;
468 window.requestAnimationFrame(() => controller?.move(direction, undefined, true));
469 return true;