Lutra/ui/tests/editor/highlightPerf.test.ts
danny 6c75c08d70 M2.2: PHP highlighting, syntax colour tokens and editor.reveal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:17:17 +02:00

111 lines
5.1 KiB
TypeScript

/**
* Keystroke-to-highlight on a 1 MB PHP file (budget: < 16 ms, C3 contract).
*
* Opt-in, since it measures rather than checks behaviour: run it with
* `LUTRA_PERF=1 pnpm vitest run tests/editor/highlightPerf.test.ts` on an
* idle machine. It builds a 1 MB PHP file, parses it completely once (as the
* editor does in the background after opening), then types characters into
* a view at the top and in the middle of the file. Each keystroke is one
* `view.dispatch`, which runs the incremental Lezer reparse up to the
* visible range and redraws the highlighted lines; it also times the
* incremental reparse of the whole document after an edit (the background
* work the editor spreads over idle time). jsdom has no layout or paint, so
* the numbers are the JavaScript work of a keystroke, not the frame.
*/
import { ensureSyntaxTree, forceParsing, syntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { describe, expect, it } from "vitest";
import { editorExtensions } from "../../src/components/editor/extensions";
/** One class of the generated file, about 1 KB. */
function chunk(n: number): string {
const i = String(n);
return [
`/** Shop item ${i}. */`,
`final class Item${i} extends Base implements \\JsonSerializable`,
"{",
` public const LIMIT = ${i};`,
" private array $tags = ['otter', \"stone\", 'river'];",
"",
" public function __construct(private int $id, protected ?string $name = null) {}",
"",
" // Sums the price with tax.",
" public function total(float $price, int $count = 1): float",
" {",
" $sum = $price * $count * 1.19;",
" if ($sum > self::LIMIT && $this->name !== null) {",
' return round($sum, 2) + strlen("{$this->name}");',
" }",
" foreach ($this->tags as $k => $tag) { $sum += \\count([$k, $tag]); }",
" return $sum;",
" }",
"",
" public function jsonSerialize(): mixed { return ['id' => $this->id, 'name' => $this->name]; }",
"}",
"",
].join("\n");
}
/** Median and 95th percentile of samples, in ms. */
function stats(samples: number[]): { median: number; p95: number; max: number } {
const sorted = [...samples].sort((a, b) => a - b);
const at = (q: number): number => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
return { median: at(0.5), p95: at(0.95), max: sorted.at(-1) ?? 0 };
}
/**
* Types into a view of the text with the extensions of a path.
*
* @param path - picks the language (`big.php`, or `big.txt` for the plain
* text baseline).
* @param text - the document.
* @returns timings in ms.
*/
function measure(path: string, text: string): Record<string, unknown> {
const view = new EditorView({ state: EditorState.create({ doc: text, extensions: editorExtensions(path) }), parent: document.body });
let started = performance.now();
forceParsing(view, text.length, 60_000);
const fullParseMs = performance.now() - started;
const parsed = syntaxTree(view.state).length;
const typing = (pos: number, count: number): number[] => {
const samples: number[] = [];
view.dispatch({ selection: { anchor: pos }, effects: EditorView.scrollIntoView(pos, { y: "center" }) });
for (let i = 0; i < count; i += 1) {
const at = view.state.selection.main.head;
const t0 = performance.now();
view.dispatch({ changes: { from: at, insert: i % 10 === 9 ? "\n" : "x" }, selection: { anchor: at + 1 }, userEvent: "input.type" });
samples.push(performance.now() - t0);
}
return samples;
};
const lineStart = (n: number): number => view.state.doc.line(n).from + 8;
typing(lineStart(20), 50);
const top = stats(typing(lineStart(30), 300));
const middleLine = Math.floor(view.state.doc.lines / 2);
typing(lineStart(middleLine - 40), 50);
const middle = stats(typing(lineStart(middleLine), 300));
const edited = view.state.update({ changes: { from: lineStart(middleLine), insert: "$" } }).state;
started = performance.now();
ensureSyntaxTree(edited, edited.doc.length, 60_000);
const reparseMs = performance.now() - started;
view.destroy();
return { fullParseMs, keystrokeTop: top, keystrokeMiddle: middle, fullIncrementalReparseMs: reparseMs, parsed };
}
describe.runIf(process.env.LUTRA_PERF)("keystroke to highlight, 1 MB PHP", () => {
it("stays within the frame budget", () => {
Range.prototype.getClientRects = () => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
let text = "<?php\n\nnamespace App\\Shop;\n\n";
for (let i = 0; text.length < 1024 * 1024; i += 1) {
text += chunk(i);
}
const php = measure("big.php", text);
const plain = measure("big.txt", text);
const round = (_k: string, v: unknown): unknown => (typeof v === "number" ? Math.round(v * 100) / 100 : v);
console.log(JSON.stringify({ bytes: text.length, php, plainTextBaseline: plain }, round, 2));
expect(php.parsed).toBe(text.length);
expect((php.keystrokeMiddle as { median: number }).median).toBeLessThan(16);
}, 120_000);
});