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

preserveReadingPosition.browser.test.ts

190 lines7.9 KB

1import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
2​
3import { preserveReadingPosition } from "./preserveReadingPosition";
4​
5describe("preserveReadingPosition", () => {
6 it("keeps the reader's line through a resize that lands before the first layout report", async () => {
7 const scroller = document.createElement("div");
8 scroller.style.cssText =
9 "width: 600px; height: 300px; overflow-y: auto; font: 16px/20px serif;";
10 // The marker fits one line at both widths, so whichever caret the probe picks shares its top.
11 scroller.innerHTML = Array.from({ length: 30 }, (_, index) =>
12 index === 15
13 ? "<p>Marker line.</p>"
14 : `<p>${"Filler words that wrap across several lines. ".repeat(8)}</p>`,
15 ).join("");
16 document.body.append(scroller);
17 onTestFinished(() => scroller.remove());
18 const markerText = [...scroller.querySelectorAll("p")][15]!.firstChild!;
19 const markerTop = () => {
20 const range = document.createRange();
21 range.setStart(markerText, 0);
22 range.collapse(true);
23 return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
24 };
25​
26 const stop = preserveReadingPosition(scroller);
27 onTestFinished(stop);
28 scroller.scrollTop += markerTop() - 24;
29 scroller.dispatchEvent(new Event("scroll"));
30 const before = markerTop();
31 scroller.style.width = "300px";
32​
33 await vi.waitFor(() => expect(Math.abs(markerTop() - before)).toBeLessThan(2));
34 });
35 it.each(["input", "textarea"])(
36 "anchors on text below a <%s> under the probe point",
37 async (tag) => {
38 const scroller = document.createElement("div");
39 scroller.style.cssText =
40 "width: 400px; height: 200px; overflow-y: auto; overflow-anchor: none; font: 16px/20px serif;";
41 scroller.innerHTML = `<p style="margin: 0">${"Filler words that wrap across several lines. ".repeat(12)}</p><${tag} style="display: block; width: 350px; height: 40px; margin: 0; box-sizing: border-box"></${tag}><p style="margin: 0">Below the field.</p><div style="height: 400px"></div>`;
42 document.body.append(scroller);
43 onTestFinished(() => scroller.remove());
44 const field = scroller.querySelector<HTMLInputElement | HTMLTextAreaElement>(tag)!;
45 field.value = "hello world from inside a text field";
46 const belowText = scroller.querySelectorAll("p")[1]!.firstChild!;
47 const belowTop = () => {
48 const range = document.createRange();
49 range.setStart(belowText, 0);
50 range.collapse(true);
51 return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
52 };
53 const errors: unknown[] = [];
54 const onError = (event: ErrorEvent) => {
55 errors.push(event.error);
56 event.preventDefault();
57 };
58 window.addEventListener("error", onError);
59 onTestFinished(() => window.removeEventListener("error", onError));
60​
61 const stop = preserveReadingPosition(scroller);
62 onTestFinished(stop);
63 scroller.scrollTop = field.offsetTop - scroller.offsetTop;
64 scroller.dispatchEvent(new Event("scroll"));
65 expect(errors).toEqual([]);
66 const before = belowTop();
67 scroller.style.width = "300px";
68 // Created after the helper's observer, so this delivery runs after its synchronous restore.
69 await new Promise<void>((resolve) => {
70 const observer = new ResizeObserver(() => {
71 observer.disconnect();
72 resolve();
73 });
74 observer.observe(scroller);
75 });
76​
77 expect(scroller.clientWidth).toBeLessThan(400);
78 expect(Math.abs(belowTop() - before)).toBeLessThan(2);
79 expect(errors).toEqual([]);
80 },
81 );
82 it.each([
83 {
84 name: "on a blank paragraph",
85 tailHtml: "<p><br></p>",
86 select: (paragraph: HTMLElement) => ({ node: paragraph, offset: 0 }),
87 target: (paragraph: HTMLElement) => paragraph.firstElementChild!,
88 },
89 {
90 name: "immediately after an inline chip",
91 tailHtml:
92 '<p>Check <span contenteditable="false" style="display: inline-block">README.md</span><img style="display: inline; width: 0; height: 0"><br></p>',
93 select: (paragraph: HTMLElement) => ({ node: paragraph, offset: 2 }),
94 target: (paragraph: HTMLElement) => paragraph.querySelector("span")!,
95 },
96 {
97 name: "after a zero-height separator following wrapped text",
98 tailHtml: `<p>${"Wrapped line words inside the active paragraph. ".repeat(6)}<img style="display: inline; width: 0; height: 0"></p>`,
99 select: (paragraph: HTMLElement) => ({ node: paragraph, offset: 2 }),
100 target: (paragraph: HTMLElement) => {
101 const text = paragraph.firstChild as Text;
102 const end = document.createRange();
103 end.setStart(text, text.data.length);
104 end.collapse(true);
105 return end;
106 },
107 },
108 ])(
109 "keeps a focused composer caret $name visible through a narrowing resize",
110 async ({ tailHtml, select, target }) => {
111 const scroller = document.createElement("div");
112 scroller.contentEditable = "true";
113 scroller.style.cssText =
114 "width: 600px; height: 200px; overflow-y: auto; overflow-anchor: none; font: 16px/20px serif;";
115 scroller.innerHTML = `${Array.from(
116 { length: 8 },
117 () => `<p>${"Filler words that wrap across several lines. ".repeat(4)}</p>`,
118 ).join("")}${tailHtml}`;
119 document.body.append(scroller);
120 onTestFinished(() => scroller.remove());
121​
122 const stop = preserveReadingPosition(scroller);
123 onTestFinished(stop);
124 scroller.focus();
125 const tail = scroller.lastElementChild as HTMLElement;
126 const anchor = target(tail);
127 const { node, offset } = select(tail);
128 const range = document.createRange();
129 range.setStart(node, offset);
130 range.collapse(true);
131 const selection = document.getSelection()!;
132 selection.removeAllRanges();
133 selection.addRange(range);
134 scroller.scrollTop = scroller.scrollHeight;
135 scroller.dispatchEvent(new Event("scroll"));
136​
137 const relTop = () =>
138 anchor.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
139 const before = relTop();
140 expect(before).toBeGreaterThanOrEqual(0);
141 expect(before).toBeLessThan(scroller.clientHeight);
142​
143 scroller.style.width = "320px";
144 await vi.waitFor(() => expect(Math.abs(relTop() - before)).toBeLessThan(2));
145 },
146 );
147 it("ignores a relocated anchor when an anchored text node is replaced before resize", async () => {
148 const scroller = document.createElement("div");
149 scroller.style.cssText =
150 "width: 600px; height: 200px; overflow-x: hidden; overflow-y: auto; overflow-anchor: none; font: 14px/20px monospace;";
151 const pre = document.createElement("pre");
152 pre.style.margin = "0";
153 const code = document.createElement("code");
154 const lines = Array.from(
155 { length: 120 },
156 (_, index) => `const line_${index} = "0123456789abcdefghijklmnopqrstuvwxyz0123456789";`,
157 ).join("\n");
158 code.textContent = lines;
159 pre.append(code);
160 scroller.append(pre);
161 document.body.append(scroller);
162 onTestFinished(() => scroller.remove());
163​
164 const stop = preserveReadingPosition(scroller);
165 onTestFinished(stop);
166 scroller.scrollTop = 1200;
167 scroller.dispatchEvent(new Event("scroll"));
168 const beforeScrollTop = scroller.scrollTop;
169 expect(beforeScrollTop).toBeGreaterThan(1000);
170​
171 // Simulate a syntax-highlighting swap replacing the anchored text node inside <code>.
172 code.innerHTML = lines
173 .split("\n")
174 .map((line) => `<span>${line}</span>`)
175 .join("\n");
176​
177 scroller.style.width = "320px";
178 // Created after the helper's observer, so this delivery runs after its synchronous restore.
179 await new Promise<void>((resolve) => {
180 const observer = new ResizeObserver(() => {
181 observer.disconnect();
182 resolve();
183 });
184 observer.observe(scroller);
185 });
186​
187 expect(scroller.clientWidth).toBeLessThan(600);
188 expect(scroller.scrollTop).toBe(beforeScrollTop);
189 });
190});