The best way to control Claude Code, Codex and more from any computer or phone
fix(web): copying a file preview selection returns the selected lines after scrolling (#36466)
Julius Marminge committed
Nov 13, 2026 at 17:33 UTC
a9fd0b2511a863f642dc52d9c0607ff9be537b50
3 files changed
+463
-32
apps/web/src/components/files/ReadOnlySourcePreview.browser.test.tsx
+142
-1
@@ -1,6 +1,6 @@
1
import type { ReactNode } from "react";
2
import { describe, expect, it, vi } from "vite-plus/test";
3
-import { userEvent } from "vite-plus/test/browser";
3
+import { cdp, userEvent } from "vite-plus/test/browser";
4
import "~/index.css";
5
6
import { render } from "../../../test/render";
@@ -64,4 +64,145 @@ describe("ReadOnlySourcePreview", () => {
64
document.getSelection()!.setBaseAndExtent(firstText, 4, pre, pre.childNodes.length);
65
expect(copiedText(rows()[0]!)).toBeNull();
66
});
67
+
68
+ it.each([
69
+ ["a lone carriage return", "\r"],
70
+ ["a carriage return and line feed", "\r\n"],
71
+ ])("copies the whole of a file whose lines end in %s", async (_name, ending) => {
72
+ const contents = text.replaceAll("\n", ending);
73
+ await getSyntaxHighlighterPromise("text");
74
+ await using screen = await render(
75
+ <div className="flex h-[400px] flex-col">
76
+ <ReadOnlySourcePreview name="notes.txt" text={contents} wordWrap={false} />
77
+ </div>,
78
+ );
79
+ const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
80
+ const rows = () => root.querySelectorAll("[data-line]");
81
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
82
+
83
+ await userEvent.click(rows()[0]!);
84
+ await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
85
+ const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
86
+ scroller.scrollTop = scroller.scrollHeight;
87
+ await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
88
+ expect(copiedText(rows()[0]!)).toBe(contents);
89
+ });
90
+
91
+ it("copies a partial selection after its rows scroll out of the mounted window", async () => {
92
+ await getSyntaxHighlighterPromise("text");
93
+ await using screen = await render(
94
+ <div className="flex h-[400px] flex-col">
95
+ <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
96
+ </div>,
97
+ );
98
+ const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
99
+ const rows = () => root.querySelectorAll("[data-line]");
100
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
101
+
102
+ const rowText = (line: number) =>
103
+ [...rows()].find((row) => row.textContent === `line ${line}`)!.querySelector("span")!
104
+ .firstChild!;
105
+ document.getSelection()!.setBaseAndExtent(rowText(5), 0, rowText(20), "line 20".length);
106
+ const selected = Array.from({ length: 16 }, (_, index) => `line ${index + 5}`).join("\n");
107
+
108
+ const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
109
+ scroller.scrollTop = scroller.scrollHeight;
110
+ await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
111
+ scroller.scrollTop = 0;
112
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
113
+
114
+ expect(copiedText(rows()[0]!) ?? document.getSelection()!.toString()).toBe(selected);
115
+ });
116
+
117
+ it("drops a selection scrolled out of the mounted window when a click lands on its edge", async () => {
118
+ await getSyntaxHighlighterPromise("text");
119
+ await using screen = await render(
120
+ <div className="flex h-[400px] flex-col">
121
+ <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
122
+ </div>,
123
+ );
124
+ const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
125
+ const rows = () => root.querySelectorAll("[data-line]");
126
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
127
+
128
+ const rowText = (index: number) => rows()[index]!.querySelector("span")!.firstChild!;
129
+ document.getSelection()!.setBaseAndExtent(rowText(4), 0, rowText(19), 4);
130
+ const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
131
+ scroller.scrollTop = scroller.scrollHeight;
132
+ await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
133
+ expect(copiedText(rows()[0]!)).toContain("line 5\n");
134
+
135
+ // The first mounted row is where the scrolled-out selection is parked, far above the viewport.
136
+ rows()[0]!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true }));
137
+ document.getSelection()!.collapse(rowText(0), 0);
138
+ expect(copiedText(rows()[0]!)).toBeNull();
139
+ });
140
+
141
+ it("copies a drag that autoscrolls past the edge of the preview", async () => {
142
+ await getSyntaxHighlighterPromise("text");
143
+ await using screen = await render(
144
+ <div className="flex h-[400px] flex-col">
145
+ <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
146
+ </div>,
147
+ );
148
+ const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
149
+ const rows = () => root.querySelectorAll("[data-line]");
150
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
151
+
152
+ const start = rows()[4]!.querySelector("span")!.getBoundingClientRect();
153
+ const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
154
+ const edge = scroller.getBoundingClientRect().bottom;
155
+ const frame = window.frameElement?.getBoundingClientRect();
156
+ const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
157
+ cdp().send("Input.dispatchMouseEvent", {
158
+ type,
159
+ x: x + (frame?.left ?? 0),
160
+ y: y + (frame?.top ?? 0),
161
+ button: "left",
162
+ buttons: type === "mouseReleased" ? 0 : 1,
163
+ clickCount: 1,
164
+ });
165
+ await mouse("mousePressed", start.left + 1, start.top + 5);
166
+ await mouse("mouseMoved", start.left + 30, edge - 5);
167
+ // Held below the preview, the pointer is over no row while the browser scrolls the drag on.
168
+ await mouse("mouseMoved", start.left + 30, edge + 60);
169
+ await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"), { timeout: 10_000 });
170
+ await mouse("mouseReleased", start.left + 30, edge + 60);
171
+
172
+ const copied = copiedText(rows()[0]!)!;
173
+ const from = text.indexOf("line 5\n");
174
+ expect(copied).toBe(text.slice(from, from + copied.length));
175
+ // The drag ends in the rows on screen, short of the last mounted one.
176
+ const lastLine = 4 + copied.split("\n").length;
177
+ expect(lastLine).toBeGreaterThan(50);
178
+ expect(lastLine).toBeLessThan(Number(rows()[rows().length - 1]!.getAttribute("data-line")));
179
+ });
180
+
181
+ it("extends a selection with Shift+click after its anchor scrolls out of the mounted window", async () => {
182
+ await getSyntaxHighlighterPromise("text");
183
+ await using screen = await render(
184
+ <div className="flex h-[400px] flex-col">
185
+ <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
186
+ </div>,
187
+ );
188
+ const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
189
+ const rows = () => root.querySelectorAll("[data-line]");
190
+ await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
191
+
192
+ await userEvent.click(rows()[2]!.querySelector("span")!, { position: { x: 1, y: 5 } });
193
+ const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
194
+ scroller.scrollTop = scroller.scrollHeight;
195
+ await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
196
+ await userEvent.click(rows()[rows().length - 1]!.querySelector("span")!, {
197
+ position: { x: 1, y: 5 },
198
+ modifiers: ["Shift"],
199
+ });
200
+
201
+ const clicked = document.getSelection()!.getComposedRanges({ shadowRoots: [root] })[0]!;
202
+ const lastLine = clicked.endContainer.textContent!;
203
+ expect(Number(lastLine.replace("line ", ""))).toBeGreaterThan(250);
204
+ expect(copiedText(rows()[0]!)).toBe(
205
+ text.slice(text.indexOf("line 3\n"), text.indexOf(`${lastLine}\n`)),
206
+ );
207
+ });
208
});
apps/web/src/components/files/ReadOnlySourcePreview.tsx
+46
-31
@@ -1,5 +1,5 @@
1
import { File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
2
-import type { ClipboardEvent } from "react";
2
+import { type ClipboardEvent, useEffect, useRef, useState } from "react";
3
4
import { DiffWorkerPoolProvider } from "~/components/DiffWorkerPoolProvider";
5
import { useClientSettings } from "~/hooks/useSettings";
@@ -8,31 +8,7 @@ import { resolveDiffThemeName } from "~/lib/diffRendering";
8
import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
9
10
import { FILE_LINK_REVEAL_UNSAFE_CSS } from "./fileSurfaceChrome";
11
-
12
-/** Select All spans the file's shadow tree, where the virtualizer mounts only rows near the viewport. */
13
-function selectsEveryMountedRow(root: ShadowRoot) {
14
- const rows = root.querySelectorAll("[data-line]");
15
- const first = rows[0];
16
- const last = rows[rows.length - 1];
17
- if (!first || !last) return false;
18
- try {
19
- const selected = document.getSelection()?.getComposedRanges({ shadowRoots: [root] })[0];
20
- if (!selected) return false;
21
- if (!root.contains(selected.startContainer) || !root.contains(selected.endContainer)) {
22
- return false;
23
- }
24
- const range = document.createRange();
25
- range.setStart(selected.startContainer, selected.startOffset);
26
- range.setEnd(selected.endContainer, selected.endOffset);
27
- // A dragged selection ends inside rows, so it never holds a row's own boundaries.
28
- return (
29
- range.comparePoint(first, 0) === 0 && range.comparePoint(last, last.childNodes.length) === 0
30
- );
31
- } catch {
32
- // Engines without composed ranges keep their own copy.
33
- return false;
34
- }
35
-}
11
+import { SourceSelection } from "./sourceSelection";
12
13
export default function ReadOnlySourcePreview(props: {
14
readonly name: string;
@@ -45,15 +21,54 @@ export default function ReadOnlySourcePreview(props: {
21
const resolvedTheme = useRenderedAppearance();
22
const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
23
const wordWrap = props.wordWrap ?? defaultWordWrap;
48
- const copyWholeFile = (event: ClipboardEvent<HTMLDivElement>) => {
24
+ const { text, onPostRender } = props;
25
+ const wrapper = useRef<HTMLDivElement>(null);
26
+ const [selection] = useState(() => new SourceSelection());
27
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- follows the document's selection, which only it reports
28
+ useEffect(() => {
29
+ const root = () => wrapper.current?.querySelector("diffs-container")?.shadowRoot;
30
+ const sync = () => {
31
+ const shadowRoot = root();
32
+ if (shadowRoot) selection.sync(shadowRoot, text);
33
+ };
34
+ // A drag that autoscrolls is usually released outside the preview.
35
+ const release = () => {
36
+ const shadowRoot = root();
37
+ if (shadowRoot) selection.release(shadowRoot, text);
38
+ };
39
+ document.addEventListener("selectionchange", sync);
40
+ window.addEventListener("pointerup", release, true);
41
+ window.addEventListener("pointercancel", release, true);
42
+ return () => {
43
+ document.removeEventListener("selectionchange", sync);
44
+ window.removeEventListener("pointerup", release, true);
45
+ window.removeEventListener("pointercancel", release, true);
46
+ };
47
+ }, [selection, text]);
48
+ const copySelection = (event: ClipboardEvent<HTMLDivElement>) => {
49
const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot;
50
- if (!root || !selectsEveryMountedRow(root)) return;
51
- event.clipboardData.setData("text/plain", props.text);
50
+ const copied = root ? selection.copy(root, text) : undefined;
51
+ if (copied === undefined) return;
52
+ event.clipboardData.setData("text/plain", copied);
53
event.preventDefault();
54
};
55
+ const drawSelection: NonNullable<typeof onPostRender> = (node, instance, phase) => {
56
+ if (phase !== "unmount" && node.shadowRoot) selection.render(node.shadowRoot, text);
57
+ return onPostRender?.(node, instance, phase);
58
+ };
59
return (
60
<DiffWorkerPoolProvider>
56
- <div className="contents" onCopy={copyWholeFile}>
61
+ <div
62
+ ref={wrapper}
63
+ className="contents"
64
+ onCopy={copySelection}
65
+ onPointerDown={(event) => selection.press(event.button !== 0 || event.shiftKey)}
66
+ // Scrolling unmounts rows, and a selection made in the same task has not been reported yet.
67
+ onScrollCapture={(event) => {
68
+ const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot;
69
+ if (root) selection.sync(root, text);
70
+ }}
71
+ >
72
<Virtualizer
73
key={`${props.name}:${resolvedTheme}:${props.text.length}`}
74
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
@@ -72,7 +87,7 @@ export default function ReadOnlySourcePreview(props: {
87
preferredHighlighter: PREFERRED_HIGHLIGHTER,
88
themeType: resolvedTheme,
89
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
75
- ...(props.onPostRender ? { onPostRender: props.onPostRender } : {}),
90
+ onPostRender: drawSelection,
91
}}
92
className="min-h-full"
93
/>
apps/web/src/components/files/sourceSelection.ts
new
+275
@@ -0,0 +1,275 @@
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
+ /** 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
+ }
275
+}