fix(web): discard stale highlights after file edits (#9902)
This commit is contained in:
1 parent
2fb99a7a66
commit
df8e0eb46b
3 files changed
+281
-5
No files matched your search
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
FileRenderer,
|
||||
getSharedHighlighter,
|
||||
type BaseCodeOptions,
|
||||
type DiffsHighlighter,
|
||||
type FileContents,
|
||||
type HighlightedToken,
|
||||
type RenderRange,
|
||||
} from "@pierre/diffs";
|
||||
import { TextDocument } from "@pierre/diffs/editor";
|
||||
import { WorkerPoolManager, type WorkerRequest, type WorkerResponse } from "@pierre/diffs/worker";
|
||||
import * as NodeWorkerThreads from "node:worker_threads";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
type DocumentChange = NonNullable<ReturnType<TextDocument<unknown>["applyEdits"]>>;
|
||||
interface Tokenizer {
|
||||
readonly themeType: "light" | "dark";
|
||||
tokenize(change: DocumentChange, range: RenderRange): Map<number, HighlightedToken[]>;
|
||||
cleanUp(): void;
|
||||
}
|
||||
|
||||
// This dependency-internal tokenizer is the one used by Editor.#rerender.
|
||||
const tokenizerUrl = new URL("./editor/tokenizer.js", import.meta.resolve("@pierre/diffs"));
|
||||
const { EditorTokenizer } = (await import(/* @vite-ignore */ tokenizerUrl.href)) as {
|
||||
EditorTokenizer: new (options: {
|
||||
codeOptions: BaseCodeOptions;
|
||||
highlighter: DiffsHighlighter;
|
||||
textDocument: TextDocument<unknown>;
|
||||
setStyle: (style: string) => void;
|
||||
onDeferTokenize: (lines: Map<number, HighlightedToken[]>, theme: "light" | "dark") => void;
|
||||
}) => Tokenizer;
|
||||
};
|
||||
|
||||
const workerModule = import.meta.resolve("@pierre/diffs/worker/worker.js");
|
||||
const source = Array.from(
|
||||
{ length: 7_000 },
|
||||
(_, index) =>
|
||||
`export const section${index} = <p>Long wrapped source line ${index} for the file editor.</p>;`,
|
||||
).join("\n");
|
||||
const options = {
|
||||
theme: "pierre-dark",
|
||||
themeType: "dark",
|
||||
preferredHighlighter: "shiki-wasm",
|
||||
useTokenTransformer: true,
|
||||
overflow: "wrap",
|
||||
disableFileHeader: true,
|
||||
} as const;
|
||||
const range: RenderRange = {
|
||||
startingLine: 6_950,
|
||||
totalLines: 150,
|
||||
bufferBefore: 0,
|
||||
bufferAfter: 0,
|
||||
};
|
||||
|
||||
interface HeldResponse {
|
||||
data: WorkerResponse;
|
||||
deliver: () => void;
|
||||
}
|
||||
let responses: HeldResponse[];
|
||||
let responseWaiters: ((response: HeldResponse) => void)[];
|
||||
let terminationPromises: Promise<number>[];
|
||||
let pool: WorkerPoolManager;
|
||||
let renderer: FileRenderer;
|
||||
let tokenizer: Tokenizer;
|
||||
let file: FileContents;
|
||||
let document: TextDocument<unknown>;
|
||||
|
||||
function nextResponse(): Promise<HeldResponse> {
|
||||
const response = responses.shift();
|
||||
return response
|
||||
? Promise.resolve(response)
|
||||
: new Promise((resolve) => responseWaiters.push(resolve));
|
||||
}
|
||||
|
||||
class WorkerTransport {
|
||||
private readonly worker = new NodeWorkerThreads.Worker(
|
||||
`const { parentPort, workerData } = require("node:worker_threads");
|
||||
globalThis.self = {
|
||||
addEventListener(type, listener) {
|
||||
if (type === "message") parentPort.on("message", data => listener({ data }));
|
||||
if (type === "error") process.on("uncaughtException", listener);
|
||||
}
|
||||
};
|
||||
globalThis.postMessage = data => parentPort.postMessage(data);
|
||||
import(workerData.moduleUrl);`,
|
||||
{ eval: true, workerData: { moduleUrl: workerModule }, execArgv: [] },
|
||||
);
|
||||
|
||||
addEventListener(
|
||||
type: "message" | "error",
|
||||
listener: (event: { data: WorkerResponse } | Error) => void,
|
||||
) {
|
||||
if (type === "error") {
|
||||
this.worker.on("error", listener);
|
||||
return;
|
||||
}
|
||||
this.worker.on("message", (data: WorkerResponse) => {
|
||||
const response = { data, deliver: () => listener({ data }) };
|
||||
if (data.type !== "success" || data.requestType !== "file") {
|
||||
response.deliver();
|
||||
return;
|
||||
}
|
||||
const waiter = responseWaiters.shift();
|
||||
if (waiter) waiter(response);
|
||||
else responses.push(response);
|
||||
});
|
||||
}
|
||||
|
||||
postMessage(message: WorkerRequest) {
|
||||
this.worker.postMessage(message, []);
|
||||
}
|
||||
|
||||
terminate() {
|
||||
terminationPromises.push(this.worker.terminate());
|
||||
}
|
||||
}
|
||||
|
||||
function applyChange(change: DocumentChange) {
|
||||
// Keep the installed editor's non-DOM order, including the existing contents patch.
|
||||
renderer.updateRenderCache(tokenizer.tokenize(change, range), tokenizer.themeType);
|
||||
file.contents = document.getText();
|
||||
if (change.lineDelta !== 0) renderer.applyDocumentChange(document);
|
||||
}
|
||||
|
||||
function append(text: string) {
|
||||
const position = document.positionAt(document.getText().length);
|
||||
const change = document.applyEdits([
|
||||
{ range: { start: position, end: position }, newText: text },
|
||||
]);
|
||||
expect(change).toBeDefined();
|
||||
applyChange(change!);
|
||||
}
|
||||
|
||||
function undo() {
|
||||
const change = document.undo()?.[0];
|
||||
expect(change).toBeDefined();
|
||||
applyChange(change!);
|
||||
}
|
||||
|
||||
function renderContents() {
|
||||
const result = renderer.renderFile(file, range);
|
||||
expect(result?.totalLines).toBe(document.lineCount);
|
||||
return renderer.renderFullHTML(result!);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
responses = [];
|
||||
responseWaiters = [];
|
||||
terminationPromises = [];
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
|
||||
setImmediate(() => callback(0)),
|
||||
);
|
||||
vi.stubGlobal("cancelAnimationFrame", clearImmediate);
|
||||
vi.stubGlobal("window", { matchMedia: () => ({ matches: true }) });
|
||||
pool = new WorkerPoolManager(
|
||||
// Adapt browser transport only; Pierre's real worker produces each response.
|
||||
{ workerFactory: () => new WorkerTransport() as unknown as globalThis.Worker, poolSize: 1 },
|
||||
options,
|
||||
);
|
||||
await pool.initialize(["tsx"]);
|
||||
const highlighter = await getSharedHighlighter({
|
||||
themes: ["pierre-dark"],
|
||||
langs: ["tsx"],
|
||||
preferredHighlighter: "shiki-wasm",
|
||||
});
|
||||
file = { name: "wrapped.tsx", contents: source, cacheKey: "editable-file" };
|
||||
document = new TextDocument(file.name, source, "tsx");
|
||||
renderer = new FileRenderer(options, () => {}, pool);
|
||||
tokenizer = new EditorTokenizer({
|
||||
codeOptions: options,
|
||||
highlighter,
|
||||
textDocument: document,
|
||||
setStyle: () => {},
|
||||
onDeferTokenize: (lines, theme) => renderer.updateRenderCache(lines, theme),
|
||||
});
|
||||
renderContents();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
tokenizer?.cleanUp();
|
||||
renderer?.cleanUp();
|
||||
pool?.terminate();
|
||||
await Promise.all(terminationPromises);
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("editable file highlighting", () => {
|
||||
it("still accepts an asynchronous highlight when the file has not changed", async () => {
|
||||
expect(renderContents()).not.toContain('style="color:');
|
||||
(await nextResponse()).deliver();
|
||||
expect(renderContents()).toContain('style="color:');
|
||||
expect(pool.getFileResultCache(file)).toBeDefined();
|
||||
});
|
||||
|
||||
it.each([1, 60])(
|
||||
"ignores a dispatched highlight after %i Enter edits and highlights the new version",
|
||||
async (count) => {
|
||||
const oldResponse = await nextResponse();
|
||||
for (let index = 0; index < count; index += 1) append("\n");
|
||||
append("export const EDITED_MARKER = 1;");
|
||||
oldResponse.deliver();
|
||||
expect(renderContents()).toContain("EDITED_MARKER");
|
||||
const currentResponse = await nextResponse();
|
||||
currentResponse.deliver();
|
||||
expect(renderContents()).toContain("EDITED_MARKER");
|
||||
const firstLines = renderer.renderFile(file, { ...range, startingLine: 0, totalLines: 20 });
|
||||
expect(renderer.renderFullHTML(firstLines!)).toContain('style="color:');
|
||||
expect(document.lineCount).toBe(7_000 + count);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not replace a same-line edit with stale tokens", async () => {
|
||||
const oldResponse = await nextResponse();
|
||||
append(" EDITED_MARKER");
|
||||
oldResponse.deliver();
|
||||
expect(renderContents()).toContain("EDITED_MARKER");
|
||||
expect(document.lineCount).toBe(7_000);
|
||||
(await nextResponse()).deliver();
|
||||
expect(renderContents()).toContain("EDITED_MARKER");
|
||||
});
|
||||
|
||||
it("keeps undo edits after an older highlight arrives", async () => {
|
||||
const oldResponse = await nextResponse();
|
||||
append("\nexport const RETAINED_MARKER = 1;");
|
||||
append("\nexport const UNDONE_MARKER = 2;");
|
||||
undo();
|
||||
oldResponse.deliver();
|
||||
const html = renderContents();
|
||||
expect(html).toContain("RETAINED_MARKER");
|
||||
expect(html).not.toContain("UNDONE_MARKER");
|
||||
(await nextResponse()).deliver();
|
||||
expect(renderContents()).toContain("RETAINED_MARKER");
|
||||
undo();
|
||||
expect(document.getText()).toBe(source);
|
||||
expect(renderContents()).not.toContain("RETAINED_MARKER");
|
||||
const redone = document.redo()?.[0];
|
||||
expect(redone).toBeDefined();
|
||||
applyChange(redone!);
|
||||
expect(renderContents()).toContain("RETAINED_MARKER");
|
||||
});
|
||||
|
||||
it("evicts the pre-edit shared cache without losing already-highlighted lines", async () => {
|
||||
(await nextResponse()).deliver();
|
||||
expect(pool.getFileResultCache(file)).toBeDefined();
|
||||
append("\nexport const EDITED_MARKER = 1;");
|
||||
expect(pool.getFileResultCache(file)).toBeUndefined();
|
||||
expect(renderContents()).toContain("EDITED_MARKER");
|
||||
const firstLines = renderer.renderFile(file, { ...range, startingLine: 0, totalLines: 20 });
|
||||
expect(renderer.renderFullHTML(firstLines!)).toContain('style="color:');
|
||||
});
|
||||
|
||||
it("reopens the edited file with the same cache key while an old response is pending", async () => {
|
||||
const oldResponse = await nextResponse();
|
||||
append("\nexport const REOPENED_MARKER = 1;");
|
||||
renderer.cleanUp();
|
||||
renderer = new FileRenderer(options, () => {}, pool);
|
||||
file = { ...file };
|
||||
expect(renderContents()).toContain("REOPENED_MARKER");
|
||||
oldResponse.deliver();
|
||||
(await nextResponse()).deliver();
|
||||
expect(renderContents()).toContain("REOPENED_MARKER");
|
||||
expect(renderContents()).toContain('style="color:');
|
||||
});
|
||||
});
|
||||
@@ -60,6 +60,18 @@ index e9f62f5..af82a46 100644
|
||||
};
|
||||
return merged;
|
||||
}
|
||||
diff --git a/dist/renderers/FileRenderer.js b/dist/renderers/FileRenderer.js
|
||||
--- a/dist/renderers/FileRenderer.js
|
||||
+++ b/dist/renderers/FileRenderer.js
|
||||
@@ -163,6 +163,8 @@
|
||||
if (this.renderCache == null) return;
|
||||
const { file, result } = this.renderCache;
|
||||
if (result == null) return;
|
||||
+ this.workerManager?.cleanUpTasks(this);
|
||||
+ if (file.cacheKey != null) this.workerManager?.evictFileFromCache(file.cacheKey);
|
||||
const lineCache = this.lineCache != null && isLineCacheForFile(this.lineCache, file) ? this.lineCache : void 0;
|
||||
for (const [line, tokens] of dirtyLines) {
|
||||
if (lineCache != null && line < lineCache.lines.length) {
|
||||
diff --git a/package.json b/package.json
|
||||
index ff61c90..1e170e5 100644
|
||||
--- a/package.json
|
||||
|
||||
Generated
+5
-5
@@ -92,7 +92,7 @@ patchedDependencies:
|
||||
'@expo/[email protected]': 96f1a75347e6ea02dc4b7034ace815d8ee39e18b8166ebfb573d9e58328f0dc2
|
||||
'@ff-labs/[email protected]': ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368
|
||||
'@legendapp/[email protected]': 03ec41339cd915ecb9a774a6b90cc2197c29038f7db67c4d2e55cd3971e5be43
|
||||
'@pierre/[email protected]': 7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa
|
||||
'@pierre/[email protected]': c087c47b657c44ddce2b0ec8237d675086414134e91829c4b4edd009ec86893e
|
||||
'@react-native-ai/[email protected]': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
|
||||
'@react-native-menu/[email protected]': f63d256bf6a97a873b5e628eb595bd6ef0075ddd5bdd890fc920f7a6024290dd
|
||||
'@react-navigation/[email protected]': e667c3cef8c78bb9ff4882ee5bd23a432247b843060a9499eb5f07e9e2295552
|
||||
@@ -245,7 +245,7 @@ importers:
|
||||
version: 1.9.1
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
version: 1.3.0-beta.10(patch_hash=c087c47b657c44ddce2b0ec8237d675086414134e91829c4b4edd009ec86893e)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@react-native-ai/apple':
|
||||
specifier: 0.12.0
|
||||
version: 0.12.0(patch_hash=2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))
|
||||
@@ -586,7 +586,7 @@ importers:
|
||||
version: 1.8.0
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
version: 1.3.0-beta.10(patch_hash=c087c47b657c44ddce2b0ec8237d675086414134e91829c4b4edd009ec86893e)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@pierre/trees':
|
||||
specifier: 1.0.0-beta.4
|
||||
version: 1.0.0-beta.4([email protected]([email protected]))([email protected])
|
||||
@@ -13613,7 +13613,7 @@ snapshots:
|
||||
tslib: 2.8.1
|
||||
webcrypto-core: 1.9.2
|
||||
|
||||
'@pierre/[email protected](patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])':
|
||||
'@pierre/[email protected](patch_hash=c087c47b657c44ddce2b0ec8237d675086414134e91829c4b4edd009ec86893e)(@shikijs/[email protected])([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@pierre/theme': 1.1.0
|
||||
'@pierre/theming': 0.0.2(@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
@@ -13627,7 +13627,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- '@shikijs/themes'
|
||||
|
||||
'@pierre/[email protected](patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])':
|
||||
'@pierre/[email protected](patch_hash=c087c47b657c44ddce2b0ec8237d675086414134e91829c4b4edd009ec86893e)(@shikijs/[email protected])([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@pierre/theme': 1.1.0
|
||||
'@pierre/theming': 0.0.2(@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
|
||||
Reference in new issue
Block a user