Open History to see the last commit
1import {
2 getSharedHighlighter,
3 VirtualizedFile,
4 Virtualizer,
5 type FileContents,
6} from "@pierre/diffs";
7import { Editor, TextDocument } from "@pierre/diffs/edit";
8import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10const renderingManagerUrl = new URL(
11 "./managers/UniversalRenderingManager.js",
12 import.meta.resolve("@pierre/diffs"),
13);
14const { clearRenderQueue } = (await import(/* @vite-ignore */ renderingManagerUrl.href)) as {
15 clearRenderQueue(): void;
16};
17
18class MeasuredElement {
19 static geometryReads = 0;
20 children: MeasuredElement[] = [];
21 dataset: Record<string, string> = {};
22 nextElementSibling: MeasuredElement | null = null;
23 shadowRoot: MeasuredElement | null = null;
24 width = 283;
25
26 constructor(readonly height = 0) {}
27
28 attachShadow() {
29 this.shadowRoot ??= new MeasuredElement();
30 return this.shadowRoot;
31 }
32
33 appendChild(child: MeasuredElement) {
34 this.children.push(child);
35 return child;
36 }
37
38 getBoundingClientRect() {
39 MeasuredElement.geometryReads += 1;
40 return { top: 0, height: this.height, width: this.width };
41 }
42}
43
44class MeasuredCodeElement extends MeasuredElement {
45 readonly tagName = "CODE";
46
47 get firstElementChild() {
48 return this.children[0] ?? null;
49 }
50}
51
52const observers: RecordedResizeObserver[] = [];
53const animationFrames = new Map<number, FrameRequestCallback>();
54let nextFrameId = 0;
55
56class RecordedResizeObserver {
57 readonly targets = new Set<Element>();
58
59 constructor(readonly callback: ResizeObserverCallback) {
60 observers.push(this);
61 }
62
63 observe(target: Element) {
64 this.targets.add(target);
65 }
66
67 unobserve(target: Element) {
68 this.targets.delete(target);
69 }
70
71 disconnect() {
72 this.targets.clear();
73 }
74
75 deliver(target: HTMLElement) {
76 const rect = target.getBoundingClientRect();
77 const size = { inlineSize: rect.width, blockSize: rect.height };
78 this.callback(
79 [
80 {
81 target,
82 contentRect: rect,
83 contentBoxSize: [size],
84 borderBoxSize: [size],
85 devicePixelContentBoxSize: [size],
86 },
87 ],
88 this as unknown as ResizeObserver,
89 );
90 }
91}
92
93function measuredElement(element: MeasuredElement): HTMLElement {
94 return element as unknown as HTMLElement;
95}
96
97class LayoutVirtualizer extends Virtualizer {
98 override getOffsetInScrollContainer(_element: HTMLElement) {
99 return 0;
100 }
101}
102
103class MeasuredFile extends VirtualizedFile {
104 override top = 0;
105 override onRender = () => false;
106
107 override __attachEditor(editor: Parameters<VirtualizedFile["__attachEditor"]>[0]) {
108 this.editor = editor;
109 return () => {
110 this.editor = undefined;
111 };
112 }
113
114 async initialize(file: FileContents) {
115 this.updateCodeViewLayout(file, 0);
116 // Document changes require the session an attached editor installs.
117 (this as unknown as { installEditSession(file: FileContents): void }).installEditSession(file);
118 await this.fileRenderer.initializeHighlighter();
119 expect(
120 this.fileRenderer.renderFile(file, {
121 startingLine: 5950,
122 totalLines: 51,
123 bufferBefore: 0,
124 bufferAfter: 0,
125 }),
126 ).toBeDefined();
127 this.fileContainer = measuredElement(new MeasuredElement());
128 }
129
130 measure(
131 rows: ReadonlyArray<readonly [lineIndex: number, height: number]>,
132 contentWidth = 226.25,
133 ) {
134 const content = new MeasuredElement();
135 content.width = contentWidth;
136 content.children = rows.map(([lineIndex, height]) => {
137 const row = new MeasuredElement(height);
138 row.dataset.lineIndex = String(lineIndex);
139 return row;
140 });
141 const code = new MeasuredCodeElement();
142 code.width = contentWidth + 56.75;
143 code.children = [new MeasuredElement(), content];
144 this.code = measuredElement(code);
145 this.reconcileHeights();
146 }
147
148 resizeContent(contentWidth: number, codeWidth = contentWidth + 56.75) {
149 const code = this.code;
150 const content = code?.children[1];
151 if (!(code instanceof MeasuredElement) || !(content instanceof MeasuredElement)) {
152 throw new Error("Expected measured code and content");
153 }
154 code.width = codeWidth;
155 content.width = contentWidth;
156 }
157
158 observeLayout() {
159 const pre = new MeasuredElement();
160 if (!(this.code instanceof MeasuredElement)) throw new Error("Expected measured code");
161 pre.children = [this.code];
162 this.resizeManager.setup(measuredElement(pre) as HTMLPreElement, {
163 disableAnnotations: true,
164 columnVariables: "measure",
165 });
166 const code = this.code;
167 const observer = observers.find((candidate) => candidate.targets.has(code));
168 if (observer === undefined) throw new Error("The real resize manager did not observe code");
169 return () => observer.deliver(code);
170 }
171
172 dispose() {
173 this.fileContainer = undefined;
174 this.code = undefined;
175 this.cleanUp();
176 }
177}
178
179const instances: MeasuredFile[] = [];
180const editors: Editor<"file", undefined, undefined>[] = [];
181
182beforeAll(async () => {
183 await getSharedHighlighter({
184 themes: ["pierre-dark"],
185 langs: ["text"],
186 preferredHighlighter: "shiki-wasm",
187 });
188});
189
190beforeEach(() => {
191 observers.length = 0;
192 animationFrames.clear();
193 MeasuredElement.geometryReads = 0;
194 vi.stubGlobal("HTMLElement", MeasuredElement);
195 vi.stubGlobal("Document", MeasuredElement);
196 vi.stubGlobal("ResizeObserver", RecordedResizeObserver);
197 vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
198 const id = ++nextFrameId;
199 animationFrames.set(id, callback);
200 return id;
201 });
202 vi.stubGlobal("cancelAnimationFrame", (id: number) => animationFrames.delete(id));
203});
204
205afterEach(() => {
206 for (const editor of editors.splice(0)) editor.cleanUp();
207 for (const instance of instances.splice(0)) instance.dispose();
208 clearRenderQueue();
209 animationFrames.clear();
210 vi.unstubAllGlobals();
211});
212
213async function makeFixture(
214 overflow: "wrap" | "scroll" = "wrap",
215 lineCount = 6001,
216 contentWidth = 226.25,
217) {
218 const contents = Array.from({ length: lineCount }, (_, index) => `line ${index}`).join("\n");
219 const file: FileContents = {
220 name: "wrapped.txt",
221 contents,
222 cacheKey: `wrapped:${overflow}`,
223 lang: "text",
224 };
225 const document = new TextDocument<"file", undefined>(file.name, contents, "text");
226 const instance = new MeasuredFile(
227 {
228 overflow,
229 disableFileHeader: true,
230 theme: "pierre-dark",
231 preferredHighlighter: "shiki-wasm",
232 useTokenTransformer: true,
233 controlledSelection: true,
234 },
235 new LayoutVirtualizer(),
236 );
237 instances.push(instance);
238 await instance.initialize(file);
239 instance.measure(
240 [
241 [0, 80],
242 [120, 60],
243 [4999, 100],
244 [5000, 80],
245 [5999, 100],
246 [6000, 60],
247 ],
248 contentWidth,
249 );
250 const apply = (change: { startLine: number } | undefined, passStartLine = true) => {
251 if (change === undefined) throw new Error("Expected a document change");
252 file.contents = document.getText();
253 instance.applyDocumentChange(
254 document,
255 undefined,
256 false,
257 passStartLine ? change.startLine : undefined,
258 );
259 };
260 const append = () => {
261 const position = document.positionAt(document.getText().length);
262 apply(document.applyEdits([{ range: { start: position, end: position }, newText: "\n" }]));
263 };
264 return { instance, document, file, apply, append };
265}
266
267describe("wrapped editor document changes", () => {
268 it("preserves the position above an EOF insertion across layout checkpoints", async () => {
269 const { instance, document, append } = await makeFixture();
270 const previousLastLine = document.lineCount;
271 const before = instance.getLinePosition(previousLastLine);
272 expect(before).toEqual({ top: 120328, height: 60 });
273 const viewport = { top: before!.top - 100, bottom: before!.top + 80 };
274 expect(instance.getAdvancedStickySpecs(viewport)).toEqual({ topOffset: 118240, height: 2096 });
275
276 append();
277
278 expect(document.lineCount).toBe(previousLastLine + 1);
279 expect(instance.getLinePosition(previousLastLine)).toEqual({ top: before!.top, height: 20 });
280 expect(instance.getLinePosition(document.lineCount)).toEqual({ top: 120348, height: 20 });
281 expect(instance.getVirtualizedHeight()).toBe(120376);
282 expect(instance.getAdvancedStickySpecs(viewport)).toEqual({ topOffset: 118240, height: 2096 });
283 });
284
285 it("invalidates changed and shifted rows after an insertion in the middle", async () => {
286 const { instance, document, apply } = await makeFixture();
287 const before = instance.getLinePosition(5001);
288 const position = { line: 5000, character: 2 };
289 apply(document.applyEdits([{ range: { start: position, end: position }, newText: "\n" }]));
290
291 expect(instance.getLinePosition(5001)).toEqual({ top: before!.top, height: 20 });
292 expect(instance.getLineHeight(4999)).toBe(100);
293 expect(instance.getLineHeight(5000)).toBe(20);
294 expect(instance.getLineHeight(5999)).toBe(20);
295 expect(instance.getLinePosition(document.lineCount)).toEqual({ top: 120208, height: 20 });
296 });
297
298 it("keeps preceding measurements when a deletion crosses a checkpoint", async () => {
299 const { instance, document, apply } = await makeFixture();
300 const before = instance.getLinePosition(5000);
301 apply(
302 document.applyEdits([
303 {
304 range: { start: { line: 4999, character: 2 }, end: { line: 5001, character: 2 } },
305 newText: "",
306 },
307 ]),
308 );
309
310 expect(document.lineCount).toBe(5999);
311 expect(instance.getLinePosition(5000)).toEqual({ top: before!.top, height: 20 });
312 expect(instance.getLineHeight(120)).toBe(60);
313 expect(instance.getLineHeight(4999)).toBe(20);
314 expect(instance.getLineHeight(6000)).toBe(20);
315 expect(instance.getLinePosition(document.lineCount)).toEqual({ top: 120068, height: 20 });
316 });
317
318 it("uses the earliest changed line for edits at multiple selections", async () => {
319 const { instance, document, apply } = await makeFixture();
320 const before = instance.getLinePosition(121);
321 apply(
322 document.applyEdits(
323 [120, 5000].map((line) => ({
324 range: { start: { line, character: 2 }, end: { line, character: 2 } },
325 newText: "\n",
326 })),
327 ),
328 );
329
330 expect(document.lineCount).toBe(6003);
331 expect(instance.getLinePosition(121)).toEqual({ top: before!.top, height: 20 });
332 expect(instance.getLineHeight(0)).toBe(80);
333 expect(instance.getLineHeight(120)).toBe(20);
334 expect(instance.getLineHeight(4999)).toBe(20);
335 });
336
337 it("retains the unchanged prefix through repeated Enter, undo and redo", async () => {
338 const { instance, document, apply, append } = await makeFixture();
339 const before = instance.getLinePosition(6001);
340 for (let count = 0; count < 60; count += 1) append();
341 expect(document.lineCount).toBe(6061);
342 expect(instance.getLinePosition(6001)?.top).toBe(before!.top);
343 apply(document.undo()?.[0]);
344 expect(instance.getLinePosition(6001)?.top).toBe(before!.top);
345 apply(document.redo()?.[0]);
346 expect(document.lineCount).toBe(6061);
347 expect(instance.getLinePosition(6001)?.top).toBe(before!.top);
348 });
349
350 // regression: #10018 retaining wrapped row heights must not shift rows in an unwrapped layout
351 it("keeps unwrapped positions unchanged", async () => {
352 const { instance, append } = await makeFixture("scroll");
353 const before = instance.getLinePosition(6001);
354 append();
355 expect(instance.getLinePosition(6001)).toEqual(before);
356 expect(instance.getLinePosition(6002)).toEqual({ top: 120028, height: 20 });
357 });
358
359 it("fully invalidates measurements when the first changed line is unknown", async () => {
360 const { instance, document, apply } = await makeFixture();
361 const position = document.positionAt(document.getText().length);
362 apply(
363 document.applyEdits([{ range: { start: position, end: position }, newText: "\n" }]),
364 false,
365 );
366 expect(instance.getLinePosition(6001)).toEqual({ top: 120008, height: 20 });
367 expect(instance.getLineHeight(0)).toBe(20);
368 });
369
370 it("still discards all measured rows after a metric change", async () => {
371 const { instance, file, append } = await makeFixture();
372 append();
373 instance.setMetrics({ hunkLineCount: 50, lineHeight: 24, diffHeaderHeight: 44, spacing: 8 });
374 instance.updateCodeViewLayout(file, 0);
375 expect(instance.getLinePosition(6001)).toEqual({ top: 144008, height: 24 });
376 });
377
378 it("still discards all measured rows when annotations change", async () => {
379 const { instance, file, append } = await makeFixture();
380 append();
381 instance.setLineAnnotations([{ lineNumber: 10, metadata: undefined }]);
382 instance.updateCodeViewLayout(file, 0);
383 expect(instance.getLinePosition(6001)).toEqual({ top: 120008, height: 20 });
384 });
385});