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

sourceSelection.ts

275 lines9.7 KB

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