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

workspaceFocus.ts

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