Open History to see the last commit
1const ROW = "[data-sidebar-row]";
2const CONTROL = 'button, a[href], input, textarea, select, [contenteditable="true"], [tabindex]';
3const TEXT_ENTRY = 'input, textarea, select, [contenteditable="true"]';
4
5function setAttribute(element: Element, name: string, value: string) {
6 if (element.getAttribute(name) !== value) element.setAttribute(name, value);
7}
8
9function setTabIndex(element: HTMLElement, value: number) {
10 if (element.tabIndex !== value) element.tabIndex = value;
11}
12
13export const SIDEBAR_TREE_PROPS = { role: "tree", "aria-label": "Threads" } as const;
14
15/** Ref callback for a sidebar list; installs the tree and returns its cleanup. */
16export function attachSidebarTree(element: HTMLElement | null) {
17 return element ? installSidebarTree(element) : undefined;
18}
19
20/** A roving DOM focus, separate from thread activation, as in VS Code's list commands. */
21export function installSidebarTree(root: HTMLElement) {
22 let rows: HTMLElement[] = [];
23 let focusedId: string | undefined;
24 let ownsFocus = false;
25 let tabStop: HTMLElement | undefined;
26 let contextMenuRow: HTMLElement | undefined;
27 // A control's own tab index, restored while its row holds the Tab stop and on uninstall.
28 const ownTabIndex = new Map<HTMLElement, number>();
29
30 const rowControls = (row: HTMLElement) => {
31 const id = row.dataset.sidebarRow;
32 const linked = id
33 ? root.querySelectorAll<HTMLElement>(`[data-sidebar-action-for="${CSS.escape(id)}"]`)
34 : [];
35 return [...row.querySelectorAll<HTMLElement>(CONTROL), ...linked].filter(
36 (control) => !control.matches(ROW) && !control.matches(TEXT_ENTRY),
37 );
38 };
39 // Tab reaches the buttons of the focused row only, so the tree stays one stop for the rest.
40 const setRowControlsReachable = (row: HTMLElement, reachable: boolean) => {
41 for (const control of rowControls(row)) {
42 if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);
43 setTabIndex(control, reachable ? ownTabIndex.get(control)! : -1);
44 }
45 };
46
47 const setTabStop = (row: HTMLElement) => {
48 if (tabStop === row) return;
49 if (tabStop) {
50 setTabIndex(tabStop, -1);
51 setRowControlsReachable(tabStop, false);
52 }
53 setTabIndex(row, 0);
54 setRowControlsReachable(row, true);
55 tabStop = row;
56 focusedId = row.dataset.sidebarRow;
57 };
58
59 const focusRow = (row: HTMLElement) => {
60 setTabStop(row);
61 // Revealing before focusing also materializes content-visibility:auto descendants.
62 row.scrollIntoView({ block: "nearest" });
63 row.focus({ preventScroll: true });
64 };
65
66 const refresh = () => {
67 const previousRows = rows;
68 const previousIndex = previousRows.findIndex((row) => row.dataset.sidebarRow === focusedId);
69 const previous = previousRows[previousIndex];
70 rows = Array.from(root.querySelectorAll<HTMLElement>(ROW)).filter((row) => {
71 const hidden = row.closest('[hidden], [inert], [aria-hidden="true"]');
72 // A dialog can temporarily make the whole workspace inert. Keep the tree's
73 // Tab stop ready for its return while still excluding exiting row clones.
74 return (!hidden || !root.contains(hidden)) && !row.matches(":disabled");
75 });
76 let selected =
77 rows.find((row) => row.dataset.sidebarRow === focusedId) ??
78 rows.find((row) => row === document.activeElement);
79 if (!selected) {
80 selected =
81 rows.find((row) => row.dataset.sidebarRow === previous?.dataset.sidebarParent) ??
82 (previousIndex === -1 ? rows.find((row) => row.hasAttribute("aria-current")) : undefined) ??
83 rows[Math.min(Math.max(previousIndex, 0), rows.length - 1)];
84 }
85 focusedId = selected?.dataset.sidebarRow;
86 tabStop = selected;
87 setTabIndex(root, selected ? -1 : 0);
88 const siblings = new Map<string, HTMLElement[]>();
89 for (const row of rows) {
90 const parent = row.dataset.sidebarParent ?? "";
91 const group = siblings.get(parent) ?? [];
92 group.push(row);
93 siblings.set(parent, group);
94 setAttribute(row, "aria-level", parent ? "2" : "1");
95 setTabIndex(row, row === selected ? 0 : -1);
96 }
97 const byId = new Map(rows.map((row) => [row.dataset.sidebarRow, row]));
98 for (const control of ownTabIndex.keys()) if (!control.isConnected) ownTabIndex.delete(control);
99 for (const control of root.querySelectorAll<HTMLElement>(CONTROL)) {
100 if (control.matches(ROW) || control.matches(TEXT_ENTRY)) continue;
101 const linked = control.dataset.sidebarActionFor;
102 const owner = control.closest<HTMLElement>(ROW) ?? (linked ? byId.get(linked) : undefined);
103 if (!owner) continue;
104 if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);
105 setTabIndex(control, owner === selected ? ownTabIndex.get(control)! : -1);
106 }
107 for (const group of siblings.values())
108 group.forEach((row, index) => {
109 setAttribute(row, "aria-posinset", String(index + 1));
110 setAttribute(row, "aria-setsize", String(group.length));
111 });
112 for (const listItem of root.querySelectorAll("li:not([role])"))
113 listItem.setAttribute("role", "presentation");
114 if (
115 ownsFocus &&
116 selected &&
117 (document.activeElement === document.body ||
118 document.activeElement === root ||
119 (root.contains(document.activeElement) &&
120 !rows.includes(document.activeElement as HTMLElement) &&
121 document.activeElement?.matches(ROW)))
122 ) {
123 // A settled row moves to the bottom shelf; scrolling after it fights the route reveal.
124 selected.focus({ preventScroll: true });
125 }
126 if (ownsFocus && !selected && document.activeElement === document.body) root.focus();
127 };
128
129 // Clicking non-focusable content drops focus to the body without a focusin event.
130 const onPointerDown = (event: PointerEvent) => {
131 if (!root.contains(event.target as Node)) ownsFocus = false;
132 };
133 const onFocus = (event: FocusEvent) => {
134 ownsFocus = root.contains(event.target as Node);
135 if (!ownsFocus || !(event.target instanceof HTMLElement) || !event.target.matches(ROW)) return;
136 setTabStop(event.target);
137 };
138 const onKeyDown = (event: KeyboardEvent) => {
139 const row = event.target;
140 if (
141 !event.defaultPrevented &&
142 !event.isComposing &&
143 !event.altKey &&
144 !event.ctrlKey &&
145 !event.metaKey &&
146 (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) &&
147 row instanceof HTMLElement &&
148 row.matches(ROW)
149 ) {
150 event.preventDefault();
151 event.stopPropagation();
152 contextMenuRow = row;
153 return;
154 }
155 if (
156 event.defaultPrevented ||
157 event.isComposing ||
158 event.altKey ||
159 event.ctrlKey ||
160 event.metaKey ||
161 event.shiftKey
162 )
163 return;
164 if (!(row instanceof HTMLElement) || !row.matches(ROW)) return;
165 const index = rows.indexOf(row);
166 if (index < 0) return;
167 let target: HTMLElement | undefined;
168 switch (event.key) {
169 case "ArrowDown":
170 target = rows[Math.min(index + 1, rows.length - 1)];
171 break;
172 case "ArrowUp":
173 target = rows[Math.max(index - 1, 0)];
174 break;
175 case "Home":
176 target = rows[0];
177 break;
178 case "End":
179 target = rows.at(-1);
180 break;
181 case "ArrowRight":
182 if (row.getAttribute("aria-expanded") === "false") row.click();
183 else
184 target = rows.find(
185 (candidate) => candidate.dataset.sidebarParent === row.dataset.sidebarRow,
186 );
187 break;
188 case "ArrowLeft":
189 if (row.getAttribute("aria-expanded") === "true") row.click();
190 else
191 target = rows.find(
192 (candidate) => candidate.dataset.sidebarRow === row.dataset.sidebarParent,
193 );
194 break;
195 // Row handlers own Enter, Space, F2 rename, and the context menu.
196 default:
197 return;
198 }
199 event.preventDefault();
200 event.stopPropagation();
201 if (target) focusRow(target);
202 };
203 const onKeyUp = (event: KeyboardEvent) => {
204 if (!contextMenuRow || (event.key !== "ContextMenu" && event.key !== "F10")) return;
205 const row = contextMenuRow;
206 contextMenuRow = undefined;
207 event.preventDefault();
208 event.stopPropagation();
209 if (document.activeElement !== row || !row.isConnected) return;
210 const rect = row.getBoundingClientRect();
211 // Like VS Code's list, suppress keydown and open on release. Reuse the row's
212 // selection-aware handler, including its Electron native menu route.
213 row.dispatchEvent(
214 new MouseEvent("contextmenu", {
215 bubbles: true,
216 cancelable: true,
217 clientX: rect.left,
218 clientY: rect.bottom,
219 }),
220 );
221 };
222 refresh();
223 const observer = new MutationObserver((records) => {
224 if (
225 records.some(
226 (record) =>
227 record.type === "attributes" ||
228 [...record.addedNodes, ...record.removedNodes].some(
229 (node) =>
230 node instanceof Element &&
231 (node.matches(`${ROW}, ${CONTROL}`) || node.querySelector(`${ROW}, ${CONTROL}`)),
232 ),
233 )
234 )
235 refresh();
236 });
237 observer.observe(root, {
238 childList: true,
239 subtree: true,
240 attributes: true,
241 attributeFilter: [
242 "data-sidebar-row",
243 "data-sidebar-parent",
244 "aria-expanded",
245 "hidden",
246 "disabled",
247 "inert",
248 "aria-hidden",
249 ],
250 });
251 document.addEventListener("focusin", onFocus);
252 document.addEventListener("pointerdown", onPointerDown, true);
253 root.addEventListener("keydown", onKeyDown, true);
254 root.addEventListener("keyup", onKeyUp, true);
255 return () => {
256 observer.disconnect();
257 // A later install reads these as the controls' own tab indexes.
258 for (const [control, tabIndex] of ownTabIndex) setTabIndex(control, tabIndex);
259 document.removeEventListener("focusin", onFocus);
260 document.removeEventListener("pointerdown", onPointerDown, true);
261 root.removeEventListener("keydown", onKeyDown, true);
262 root.removeEventListener("keyup", onKeyUp, true);
263 };
264}