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

sidebarTree.ts

263 lines9.7 KB

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;
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;
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 focusRow(selected);
124 }
125 if (ownsFocus && !selected && document.activeElement === document.body) root.focus();
126 };
127​
128 // Clicking non-focusable content drops focus to the body without a focusin event.
129 const onPointerDown = (event: PointerEvent) => {
130 if (!root.contains(event.target as Node)) ownsFocus = false;
131 };
132 const onFocus = (event: FocusEvent) => {
133 ownsFocus = root.contains(event.target as Node);
134 if (!ownsFocus || !(event.target instanceof HTMLElement) || !event.target.matches(ROW)) return;
135 setTabStop(event.target);
136 };
137 const onKeyDown = (event: KeyboardEvent) => {
138 const row = event.target;
139 if (
140 !event.defaultPrevented &&
141 !event.isComposing &&
142 !event.altKey &&
143 !event.ctrlKey &&
144 !event.metaKey &&
145 (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) &&
146 row instanceof HTMLElement &&
147 row.matches(ROW)
148 ) {
149 event.preventDefault();
150 event.stopPropagation();
151 contextMenuRow = row;
152 return;
153 }
154 if (
155 event.defaultPrevented ||
156 event.isComposing ||
157 event.altKey ||
158 event.ctrlKey ||
159 event.metaKey ||
160 event.shiftKey
161 )
162 return;
163 if (!(row instanceof HTMLElement) || !row.matches(ROW)) return;
164 const index = rows.indexOf(row);
165 if (index < 0) return;
166 let target: HTMLElement | undefined;
167 switch (event.key) {
168 case "ArrowDown":
169 target = rows[Math.min(index + 1, rows.length - 1)];
170 break;
171 case "ArrowUp":
172 target = rows[Math.max(index - 1, 0)];
173 break;
174 case "Home":
175 target = rows[0];
176 break;
177 case "End":
178 target = rows.at(-1);
179 break;
180 case "ArrowRight":
181 if (row.getAttribute("aria-expanded") === "false") row.click();
182 else
183 target = rows.find(
184 (candidate) => candidate.dataset.sidebarParent === row.dataset.sidebarRow,
185 );
186 break;
187 case "ArrowLeft":
188 if (row.getAttribute("aria-expanded") === "true") row.click();
189 else
190 target = rows.find(
191 (candidate) => candidate.dataset.sidebarRow === row.dataset.sidebarParent,
192 );
193 break;
194 // Row handlers own Enter, Space, F2 rename, and the context menu.
195 default:
196 return;
197 }
198 event.preventDefault();
199 event.stopPropagation();
200 if (target) focusRow(target);
201 };
202 const onKeyUp = (event: KeyboardEvent) => {
203 if (!contextMenuRow || (event.key !== "ContextMenu" && event.key !== "F10")) return;
204 const row = contextMenuRow;
205 contextMenuRow = undefined;
206 event.preventDefault();
207 event.stopPropagation();
208 if (document.activeElement !== row || !row.isConnected) return;
209 const rect = row.getBoundingClientRect();
210 // Like VS Code's list, suppress keydown and open on release. Reuse the row's
211 // selection-aware handler, including its Electron native menu route.
212 row.dispatchEvent(
213 new MouseEvent("contextmenu", {
214 bubbles: true,
215 cancelable: true,
216 clientX: rect.left,
217 clientY: rect.bottom,
218 }),
219 );
220 };
221 refresh();
222 const observer = new MutationObserver((records) => {
223 if (
224 records.some(
225 (record) =>
226 record.type === "attributes" ||
227 [...record.addedNodes, ...record.removedNodes].some(
228 (node) =>
229 node instanceof Element &&
230 (node.matches(`${ROW}, ${CONTROL}`) || node.querySelector(`${ROW}, ${CONTROL}`)),
231 ),
232 )
233 )
234 refresh();
235 });
236 observer.observe(root, {
237 childList: true,
238 subtree: true,
239 attributes: true,
240 attributeFilter: [
241 "data-sidebar-row",
242 "data-sidebar-parent",
243 "aria-expanded",
244 "hidden",
245 "disabled",
246 "inert",
247 "aria-hidden",
248 ],
249 });
250 document.addEventListener("focusin", onFocus);
251 document.addEventListener("pointerdown", onPointerDown, true);
252 root.addEventListener("keydown", onKeyDown, true);
253 root.addEventListener("keyup", onKeyUp, true);
254 return () => {
255 observer.disconnect();
256 // A later install reads these as the controls' own tab indexes.
257 for (const [control, tabIndex] of ownTabIndex) setTabIndex(control, tabIndex);
258 document.removeEventListener("focusin", onFocus);
259 document.removeEventListener("pointerdown", onPointerDown, true);
260 root.removeEventListener("keydown", onKeyDown, true);
261 root.removeEventListener("keyup", onKeyUp, true);
262 };