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

workspaceFocus.ts

386 lines16.2 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 const remember = (event: FocusEvent) => {
94 if (!(event.target instanceof HTMLElement)) return;
95 const area = workspaceArea(event.target);
96 if (!area?.dataset.workspaceArea) return;
97 lastArea = area.dataset.workspaceArea;
98 const key = area.dataset.workspaceFocusKey ?? lastArea;
99 lastFocused.delete(key);
100 // Custom file trees retarget focusin to their nonfocusable shadow host.
101 const target = event.composedPath().find((element) => element instanceof HTMLElement);
102 lastFocused.set(key, target instanceof HTMLElement ? target : event.target);
103 // Surface history must not retain an unbounded number of detached panel trees.
104 if (lastFocused.size > 64) lastFocused.delete(lastFocused.keys().next().value!);
105 };
106 doc.addEventListener("focusin", remember);
107​
108 const focusArea = (area: HTMLElement, restore = true) => {
109 const key = area.dataset.workspaceFocusKey ?? area.dataset.workspaceArea!;
110 const previous = restore ? lastFocused.get(key) : undefined;
111 const belongs = (element: HTMLElement) =>
112 workspaceArea(element) === area &&
113 isWorkspaceElementVisible(element) &&
114 !element.matches(":disabled");
115 const preferred = Array.from(
116 area.querySelectorAll<HTMLElement>(
117 '[data-workspace-focus-default], [role="treeitem"][tabindex="0"], [data-settings-section][tabindex="0"], .xterm-helper-textarea, [contenteditable="true"]',
118 ),
119 ).find(belongs);
120 const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
121 (element) => element.tabIndex >= 0 && belongs(element),
122 );
123 // Panel surfaces may unmount when hidden. Recover the same named control when
124 // it mounts again, without sharing focus history between different surface tabs.
125 const restored =
126 previous && !previous.isConnected
127 ? Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
128 (element) =>
129 belongs(element) &&
130 element.tagName === previous.tagName &&
131 ((previous.id && element.id === previous.id) ||
132 (previous.getAttribute("aria-label") &&
133 element.getAttribute("aria-label") === previous.getAttribute("aria-label")) ||
134 (previous.matches("button") &&
135 previous.textContent?.trim() &&
136 element.textContent === previous.textContent)),
137 )
138 : undefined;
139 const surface = area.querySelector<HTMLElement>("[data-right-panel-surface-content]");
140 const surfaceControl = surface
141 ? Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
142 (element) => belongs(element) && element.tabIndex >= 0,
143 )
144 : undefined;
145 // Moving the timeline to an old control would also stop it following a running turn,
146 // so the conversation reuses a control only while it is still in view.
147 const isConversation = area.dataset.workspaceArea === "conversation";
148 const targets = new Set([
149 previous && belongs(previous) && (!isConversation || isInScrollView(previous))
150 ? previous
151 : undefined,
152 isConversation ? undefined : restored,
153 preferred,
154 surfaceControl,
155 isConversation ? undefined : fallback,
156 area,
157 ]);
158 for (const target of targets) {
159 if (!target) continue;
160 target.focus({ preventScroll: true });
161 const root = target.getRootNode();
162 const active = root instanceof ShadowRoot ? root.activeElement : doc.activeElement;
163 if (active === target || (active && target.contains(active))) {
164 if (target !== area && !isConversation) revealInScrollers(target);
165 return true;
166 }
167 }
168 return false;
169 };
170 const focus = (name: string, restore = true, selector?: string) => {
171 const areas = Array.from(doc.querySelectorAll<HTMLElement>(AREA_SELECTOR)).filter(
172 isWorkspaceElementVisible,
173 );
174 const area =
175 name === "content"
176 ? (areas.find((element) => element.dataset.workspaceArea === "composer") ??
177 areas.find(
178 (element) =>
179 element.dataset.workspaceArea === "pull-requests" || element.matches("main"),
180 ) ??
181 areas.find((element) => element.dataset.workspaceArea === "conversation") ??
182 areas.find((element) => element.dataset.workspaceArea === "panel"))
183 : areas.find((element) => element.dataset.workspaceArea === name);
184 if (!area) return false;
185 const surface = area.querySelector("[data-right-panel-surface-content]");
186 // A lazy surface's Suspense fallback is empty. Wait for its content instead
187 // of claiming focus on the tab strip before the useful controls mount.
188 if (surface && !surface.hasChildNodes()) return false;
189 if (selector) {
190 const target = area.querySelector<HTMLElement>(selector);
191 if (!target || !isWorkspaceElementVisible(target)) return false;
192 target.focus({ preventScroll: true });
193 return doc.activeElement === target;
194 }
195 return focusArea(area, restore);
196 };
197 const move = (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
198 // HTML context menus close on blur, unlike modal dialogs and Base UI popups.
199 dismissContextMenu(false);
200 // A palette closes before running its command. Other popups keep their focus boundary.
201 // Inline listboxes (such as Settings search) belong to their workspace area, while
202 // portalled listboxes and menus can also supply a boundary without a popup data-slot.
203 const activePopup = doc.activeElement?.closest<HTMLElement>('[role="menu"], [role="listbox"]');
204 // Settings opens as a route modal with its own areas; navigation stays inside it.
205 const appModal = Array.from(doc.querySelectorAll<HTMLElement>("[data-app-modal]")).find(
206 isWorkspaceElementVisible,
207 );
208 const boundaries = Array.from(
209 doc.querySelectorAll<HTMLElement>(FOCUS_BOUNDARY_SELECTOR),
210 ).filter((boundary) => boundary !== appModal);
211 if (activePopup && !activePopup.closest(AREA_SELECTOR)) boundaries.push(activePopup);
212 // A modal keeps focus wherever it is; any other popup only while it holds focus,
213 // so hover popups and notifications never swallow the key.
214 if (
215 boundaries.some(
216 (boundary) =>
217 !(closingPalette && boundary.closest("[data-command-palette]")) &&
218 (boundary.matches('[aria-modal="true"]') || boundary.contains(doc.activeElement)) &&
219 isWorkspaceElementVisible(boundary),
220 )
221 )
222 return false;
223 const areas = Array.from((appModal ?? doc).querySelectorAll<HTMLElement>(AREA_SELECTOR))
224 .filter(isWorkspaceElementVisible)
225 .sort(
226 (left, right) => Number(left.dataset.workspaceOrder) - Number(right.dataset.workspaceOrder),
227 );
228 if (areas.length === 0) return false;
229 const activeArea = doc.activeElement?.closest<HTMLElement>(AREA_SELECTOR);
230 const currentId = fromArea ?? activeArea?.dataset.workspaceArea ?? lastArea;
231 const current = areas.findIndex((area) => area.dataset.workspaceArea === currentId);
232 const index =
233 current === -1
234 ? direction === 1
235 ? 0
236 : areas.length - 1
237 : (current + direction + areas.length) % areas.length;
238 const area = areas[index]!;
239 return focusArea(area);
240 };
241​
242 // Focus that drops to the body because its element was hidden, made inert, or removed
243 // returns to the same control when React remounted it, else to its area, else the content.
244 const recover = (event: FocusEvent) => {
245 const lost = event.target;
246 if (!(lost instanceof HTMLElement) || event.relatedTarget) return;
247 const areaName = workspaceArea(lost)?.dataset.workspaceArea;
248 const label = lost.getAttribute("aria-label");
249 requestAnimationFrame(() => {
250 if (doc.activeElement !== doc.body || !doc.hasFocus() || isWorkspaceElementVisible(lost))
251 return;
252 const remounted = Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
253 (element) =>
254 element.tagName === lost.tagName &&
255 ((lost.id && element.id === lost.id) ||
256 (label && element.getAttribute("aria-label") === label)) &&
257 isWorkspaceElementVisible(element),
258 );
259 if (remounted) remounted.focus({ preventScroll: true });
260 else if (!areaName || !focus(areaName)) focus("content");
261 });
262 };
263 doc.addEventListener("focusout", recover);
264​
265 // A request names a destination React has not committed yet, so it retries as the
266 // DOM changes. User input cancels it, and it gives up after two seconds.
267 let pending: WorkspaceFocusTarget | undefined;
268 let frame = 0;
269 let deadline = 0;
270 let cancelOnInput = false;
271 const observer = new MutationObserver(() => schedule());
272 const cancelRequest = () => {
273 pending = undefined;
274 cancelOnInput = false;
275 observer.disconnect();
276 cancelAnimationFrame(frame);
277 clearTimeout(deadline);
278 };
279 const schedule = () => {
280 cancelAnimationFrame(frame);
281 frame = requestAnimationFrame(() => {
282 if (pending && focus(pending.area, pending.restore, pending.selector)) cancelRequest();
283 });
284 };
285 const request = (target: WorkspaceFocusTarget) => {
286 cancelRequest();
287 pending = target;
288 // The key or click that made the request may still be propagating.
289 queueMicrotask(() => {
290 if (pending === target) cancelOnInput = true;
291 });
292 observer.observe(doc.body, {
293 childList: true,
294 subtree: true,
295 attributes: true,
296 attributeFilter: ["inert", "aria-hidden", "data-workspace-unavailable"],
297 });
298 deadline = window.setTimeout(cancelRequest, 2000);
299 schedule();
300 };
301 const onUserInput = () => {
302 if (cancelOnInput) cancelRequest();
303 };
304 doc.addEventListener("pointerdown", onUserInput, true);
305 doc.addEventListener("keydown", onUserInput, true);
306​
307 return {
308 move: (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
309 cancelRequest();
310 return move(direction, fromArea, closingPalette);
311 },
312 focus,
313 request,
314 dispose: () => {
315 cancelRequest();
316 doc.removeEventListener("focusin", remember);
317 doc.removeEventListener("focusout", recover);
318 doc.removeEventListener("pointerdown", onUserInput, true);
319 doc.removeEventListener("keydown", onUserInput, true);
320 },
321 };
323​
324let controller: ReturnType<typeof createWorkspaceFocusController> | undefined;
325let focusRequestVersion = 0;
326export const getWorkspaceFocusRequestVersion = () => focusRequestVersion;
327​
328/**
329 * Starts workspace focus for the app: F6 area moves, focus requests, focus-loss recovery,
330 * focus into a panel the user opens, and focus into the Pull Requests page on entry.
331 */
332export function startWorkspaceFocus(router: AnyRouter): () => void {
333 const active = createWorkspaceFocusController(document);
334 controller = active;
335 const stopPanels = useRightPanelStore.subscribe((state, previous) => {
336 if (state.userActionRevisionByThreadKey === previous.userActionRevisionByThreadKey) return;
337 for (const [threadKey, revision] of Object.entries(state.userActionRevisionByThreadKey)) {
338 if (previous.userActionRevisionByThreadKey[threadKey] === revision) continue;
339 const next = state.byThreadKey[threadKey];
340 const before = previous.byThreadKey[threadKey];
341 if (next?.isOpen && (!before?.isOpen || next.activeSurfaceId !== before.activeSurfaceId))
342 requestWorkspaceFocus({ area: "panel" });
343 }
344 });
345 const stopRoute = router.subscribe("onResolved", ({ fromLocation, toLocation }) => {
346 if (toLocation.pathname === "/pull-requests" && fromLocation?.pathname !== "/pull-requests")
347 requestWorkspaceFocus({ area: "pull-requests" });
348 });
349 return () => {
350 stopPanels();
351 stopRoute();
352 active.dispose();
353 if (controller === active) controller = undefined;
354 };
356​
357/** Moves to the next or previous visible area. `fromArea` overrides the focused area. */
358export function moveWorkspaceFocus(direction: 1 | -1, fromArea?: string): boolean {
359 return controller?.move(direction, fromArea) ?? false;
361​
362/** Explicit user actions request focus after React has committed the destination. */
363export function requestWorkspaceFocus(target: WorkspaceFocusTarget) {
364 focusRequestVersion++;
365 controller?.request(target);
367​
368export function requestWorkspaceContentFocus() {
369 // Resolve after the layout commits: closing a maximized panel makes the
370 // composer available again, while hiding a sidebar may leave only the panel.
371 requestWorkspaceFocus({ area: "content" });
373​
374let pendingPaletteDirection: 1 | -1 | undefined;
375export function queueWorkspaceFocusFromPalette(direction: 1 | -1) {
376 pendingPaletteDirection = direction;
378​
379/** Runs at the palette's normal focus restoration milestone, after its focus trap closes. */
380export function restoreWorkspaceFocusFromPalette(): boolean {
381 if (pendingPaletteDirection === undefined) return false;
382 const direction = pendingPaletteDirection;
383 pendingPaletteDirection = undefined;
384 window.requestAnimationFrame(() => controller?.move(direction, undefined, true));
385 return true;