@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 302 lines 10.8 KB
Raw
1 interface Point {
2 readonly node: Node;
3 readonly offset: number;
4 }
5
6 interface Ends {
7 readonly anchor: number;
8 readonly focus: number;
9 }
10
11 /** The rows the virtualizer has mounted, as offsets into the file's text. */
12 interface Mounted {
13 readonly rows: NodeListOf<HTMLElement>;
14 readonly firstLine: number;
15 readonly start: number;
16 readonly end: number;
17 }
18
19 /** Lines break where the renderer breaks them: at `\n`, `\r\n`, and a lone `\r`. */
20 function lineStarts(text: string) {
21 const starts = [0];
22 for (const match of text.matchAll(/\r\n|\r|\n/g)) starts.push(match.index + match[0].length);
23 return starts;
24 }
25
26 function sameRange(a: StaticRange | undefined, b: StaticRange | undefined) {
27 if (!a || !b) return a === b;
28 return (
29 a.startContainer === b.startContainer &&
30 a.startOffset === b.startOffset &&
31 a.endContainer === b.endContainer &&
32 a.endOffset === b.endOffset
33 );
34 }
35
36 function rowOf(node: Node) {
37 const element = node instanceof Element ? node : node.parentElement;
38 return element?.closest<HTMLElement>("[data-line]") ?? null;
39 }
40
41 /**
42 * A text selection in a virtualized file, kept as offsets into the file's text.
43 * The browser's own selection can only reach mounted rows: an end whose row unmounts
44 * collapses onto whatever is still there, so the offsets outlive it and are drawn back
45 * onto the rows after every render.
46 */
47 export class SourceSelection {
48 #text = "";
49 #lineStarts: number[] | undefined;
50 #ends: Ends | undefined;
51 #pressed = false;
52 /** A press that places a caret, where a collapsed selection is the click's and never a kept one. */
53 #clicking = false;
54 /**
55 * The browser's selection as last left: by a render during a press when nothing was drawn over it,
56 * or (`clippedByRender`) as drawn clipped to the mounted rows, which must not be read back as the ends.
57 */
58 #parked:
59 | { readonly range: StaticRange | undefined; readonly clippedByRender: boolean }
60 | undefined;
61
62 #use(text: string) {
63 if (text === this.#text) return;
64 this.#text = text;
65 this.#lineStarts = undefined;
66 this.#ends = undefined;
67 this.#parked = undefined;
68 }
69
70 get #starts() {
71 return (this.#lineStarts ??= lineStarts(this.#text));
72 }
73
74 #lineEnd(line: number) {
75 const next = this.#starts[line + 1];
76 if (next === undefined) return this.#text.length;
77 return this.#text.startsWith("\r\n", next - 2) ? next - 2 : next - 1;
78 }
79
80 #lineAt(offset: number) {
81 let low = 0;
82 let high = this.#starts.length - 1;
83 while (low < high) {
84 const middle = (low + high + 1) >> 1;
85 if (this.#starts[middle]! <= offset) low = middle;
86 else high = middle - 1;
87 }
88 return low;
89 }
90
91 #mounted(root: ShadowRoot): Mounted | undefined {
92 const rows = root.querySelectorAll<HTMLElement>("[data-line]");
93 const first = rows[0];
94 const last = rows[rows.length - 1];
95 if (!first || !last) return undefined;
96 const firstLine = Number(first.dataset.line) - 1;
97 const start = this.#starts[firstLine];
98 if (start === undefined) return undefined;
99 return { rows, firstLine, start, end: this.#lineEnd(Number(last.dataset.line) - 1) };
100 }
101
102 /** `inRow` is false for a point between rows, which is where an unmounted row leaves one. */
103 #offsetOf(point: Point, side: "start" | "end", mounted: Mounted) {
104 const row = rowOf(point.node);
105 const range = document.createRange();
106 if (row) {
107 const line = Number(row.dataset.line) - 1;
108 range.setStart(row, 0);
109 range.setEnd(point.node, point.offset);
110 const start = this.#starts[line] ?? this.#text.length;
111 return {
112 inRow: true,
113 offset: Math.min(start + range.toString().length, this.#lineEnd(line)),
114 };
115 }
116 range.setStart(point.node, point.offset);
117 const rows = [...mounted.rows];
118 const near =
119 side === "start"
120 ? rows.find((candidate) => range.comparePoint(candidate, 0) >= 0)
121 : rows.findLast(
122 (candidate) => range.comparePoint(candidate, candidate.childNodes.length) <= 0,
123 );
124 const offset = near
125 ? side === "start"
126 ? this.#starts[Number(near.dataset.line) - 1]!
127 : this.#lineEnd(Number(near.dataset.line) - 1)
128 : side === "start"
129 ? mounted.end
130 : mounted.start;
131 return { inRow: false, offset };
132 }
133
134 #pointAt(offset: number, mounted: Mounted): Point {
135 const clamped = Math.max(mounted.start, Math.min(offset, mounted.end));
136 const line = this.#lineAt(clamped);
137 const row = mounted.rows[line - mounted.firstLine];
138 if (!row) return { node: mounted.rows[0]!, offset: 0 };
139 let column = clamped - this.#starts[line]!;
140 const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
141 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
142 const length = node.nodeValue?.length ?? 0;
143 if (column <= length) return { node, offset: column };
144 column -= length;
145 }
146 return { node: row, offset: row.childNodes.length };
147 }
148
149 /**
150 * Reads the browser's selection into the offsets. An end resting on the edge of the
151 * mounted rows keeps its offset when that offset lies past the edge, and a render
152 * (`afterRender`) keeps every end its unmounted row left between rows.
153 */
154 #read(root: ShadowRoot, afterRender: boolean) {
155 const selection = document.getSelection();
156 let range: StaticRange | undefined;
157 try {
158 range = selection?.getComposedRanges({ shadowRoots: [root] })[0];
159 } catch {
160 // Engines without composed ranges keep their own selection and copy.
161 this.#ends = undefined;
162 return undefined;
163 }
164 const parked = this.#parked;
165 if (
166 parked?.clippedByRender &&
167 (sameRange(range, parked.range) || (afterRender && !this.#pressed))
168 ) {
169 return this.#mounted(root);
170 }
171 if (parked?.clippedByRender) this.#parked = undefined;
172 if (range && !(root.contains(range.startContainer) && root.contains(range.endContainer))) {
173 this.#ends = undefined;
174 return undefined;
175 }
176 const mounted = this.#mounted(root);
177 if (!mounted) return undefined;
178 if (!afterRender && this.#parked && sameRange(range, this.#parked.range)) return mounted;
179 if (!selection || !range) {
180 if (!afterRender) this.#ends = undefined;
181 return mounted;
182 }
183 const start = this.#offsetOf(
184 { node: range.startContainer, offset: range.startOffset },
185 "start",
186 mounted,
187 );
188 const end = this.#offsetOf(
189 { node: range.endContainer, offset: range.endOffset },
190 "end",
191 mounted,
192 );
193 const backward = selection.direction === "backward";
194 const previous = this.#ends;
195 // Select All spans the shadow tree, so it holds every mounted row from outside them.
196 const holdsEveryRow =
197 !start.inRow && !end.inRow && start.offset === mounted.start && end.offset === mounted.end;
198 if (!afterRender && holdsEveryRow) {
199 this.#ends = { anchor: 0, focus: this.#text.length };
200 return mounted;
201 }
202 const keeps = (now: typeof start, was: number | undefined) =>
203 was !== undefined &&
204 (now.inRow
205 ? (now.offset === mounted.start && was < mounted.start) ||
206 (now.offset === mounted.end && was > mounted.end)
207 : afterRender);
208 const anchor = backward ? end : start;
209 const focus = backward ? start : end;
210 const keepsAnchor = keeps(anchor, previous?.anchor);
211 const keepsFocus = keeps(focus, previous?.focus);
212 // A click collapses the selection, and it is a new one unless both ends were already there.
213 const collapsed = start.offset === end.offset && start.inRow && end.inRow;
214 if (collapsed && (this.#clicking || !(keepsAnchor && keepsFocus))) {
215 this.#ends = { anchor: start.offset, focus: start.offset };
216 return mounted;
217 }
218 this.#ends = {
219 anchor: keepsAnchor ? previous!.anchor : anchor.offset,
220 focus: keepsFocus ? previous!.focus : focus.offset,
221 };
222 return mounted;
223 }
224
225 /** Call when the browser's selection changes. */
226 sync(root: ShadowRoot, text: string) {
227 this.#use(text);
228 this.#read(root, false);
229 }
230
231 #draw(root: ShadowRoot, mounted: Mounted | undefined) {
232 this.#parked = undefined;
233 if (!mounted || !this.#ends) return;
234 const anchor = this.#pointAt(this.#ends.anchor, mounted);
235 const focus = this.#pointAt(this.#ends.focus, mounted);
236 const selection = document.getSelection();
237 const range = selection?.getComposedRanges({ shadowRoots: [root] })[0];
238 const { anchor: anchorOffset, focus: focusOffset } = this.#ends;
239 const clipped =
240 anchorOffset !== focusOffset &&
241 (Math.min(anchorOffset, focusOffset) < mounted.start ||
242 Math.max(anchorOffset, focusOffset) > mounted.end);
243 if (this.#pressed && anchor.node === focus.node && anchor.offset === focus.offset) {
244 // Chromium stops extending a drag once a script collapses its selection, so a drag whose
245 // ends are both unmounted keeps what the browser has left of it.
246 this.#parked = { range, clippedByRender: false };
247 return;
248 }
249 const [start, end] = selection?.direction === "backward" ? [focus, anchor] : [anchor, focus];
250 if (
251 range?.startContainer === start.node &&
252 range.startOffset === start.offset &&
253 range.endContainer === end.node &&
254 range.endOffset === end.offset
255 ) {
256 if (clipped) this.#parked = { range, clippedByRender: true };
257 return;
258 }
259 selection?.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
260 if (clipped) {
261 // A projected endpoint can become an interior point when its DOM row survives the next render.
262 this.#parked = {
263 range: selection?.getComposedRanges({ shadowRoots: [root] })[0],
264 clippedByRender: true,
265 };
266 }
267 }
268
269 /** Call after rows mount or unmount, to draw the selection onto the rows now there. */
270 render(root: ShadowRoot, text: string) {
271 this.#use(text);
272 if (this.#ends) this.#draw(root, this.#read(root, true));
273 }
274
275 press(extending: boolean) {
276 this.#pressed = true;
277 this.#clicking = !extending;
278 if (!extending) this.#parked = undefined;
279 }
280
281 release(root: ShadowRoot, text: string) {
282 if (!this.#pressed) return;
283 this.#use(text);
284 const mounted = this.#read(root, false);
285 this.#pressed = false;
286 this.#clicking = false;
287 this.#draw(root, mounted);
288 }
289
290 /** The text to copy when the browser's own copy would miss part of it, else `undefined`. */
291 copy(root: ShadowRoot, text: string) {
292 this.#use(text);
293 const mounted = this.#read(root, false);
294 if (!mounted || !this.#ends) return undefined;
295 const start = Math.min(this.#ends.anchor, this.#ends.focus);
296 const end = Math.max(this.#ends.anchor, this.#ends.focus);
297 if (start === end) return undefined;
298 const whole = start === 0 && end === text.length;
299 if (!whole && start >= mounted.start && end <= mounted.end) return undefined;
300 return text.slice(start, end);
301 }
302 }