Lutra/ui/tests/editor/engineText.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

81 lines
3 KiB
TypeScript

/**
* Tests for the mapping between engine text (line breaks as on disk) and
* CodeMirror documents (one position per line break).
*/
import { ChangeSet, Text } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { diffDocs, EngineText, positionOf, separatorOf } from "../../src/components/editor/engineText";
describe("EngineText", () => {
it("maps positions past CRLF breaks and keeps mixed endings", () => {
const text = EngineText.fromEngine("a\r\nb\nc\rd\r\n");
expect(text.doc.toString()).toBe("a\nb\nc\nd\n");
expect(text.toEngine(0)).toBe(0);
expect(text.toEngine(2)).toBe(3);
expect(text.toEngine(4)).toBe(5);
expect(text.toEngine(8)).toBe(10);
expect(text.toEngine(99)).toBe(10);
expect(text.engineString()).toBe("a\r\nb\nc\nd\r\n");
});
it("is the identity for text without CRLF", () => {
const text = EngineText.fromEngine("x😀\ny");
expect(text.toEngine(4)).toBe(4);
});
it("turns changes into engine edits with the buffer's line ending", () => {
const text = EngineText.fromEngine("ab\r\ncd\r\n");
const changes = ChangeSet.of(
[
{ from: 1, insert: "\n" },
{ from: 3, to: 5, insert: "X" },
],
text.doc.length,
);
expect(text.edits(changes, "\r\n")).toEqual([
{ from: 1, to: 1, insert: "\r\n" },
{ from: 4, to: 6, insert: "X" },
]);
const after = text.apply(changes, "\r\n");
expect(after.doc.toString()).toBe("a\nb\nX\n");
expect(after.engineString()).toBe("a\r\nb\r\nX\r\n");
});
it("diffs documents into one replacement", () => {
const a = Text.of(["hello", "world"]);
const b = Text.of(["hello", "brave", "world"]);
const diff = diffDocs(a, b);
expect(diff.apply(a).toString()).toBe(b.toString());
expect(diffDocs(a, a).empty).toBe(true);
});
it("names separators", () => {
expect(separatorOf("crlf")).toBe("\r\n");
expect(separatorOf("cr")).toBe("\r");
expect(separatorOf("lf")).toBe("\n");
expect(separatorOf("?")).toBe("\n");
});
});
describe("positionOf", () => {
it("maps engine line and UTF-16 column to the same text in CRLF and LF documents", () => {
for (const engine of ["ab\r\ncd😀e\r\n\r\nf", "ab\ncd😀e\n\nf", "ab\rcd😀e\r\rf"]) {
const text = EngineText.fromEngine(engine);
const pos = positionOf(text.doc, 1, 4);
expect(text.doc.sliceString(pos, pos + 1)).toBe("e");
expect(engine.charAt(text.toEngine(pos))).toBe("e");
const f = positionOf(text.doc, 3, 0);
expect(engine.charAt(text.toEngine(f))).toBe("f");
}
});
it("clamps lines and columns into the document", () => {
const doc = EngineText.fromEngine("ab\r\ncd").doc;
expect(positionOf(doc, 0, 99)).toBe(2);
expect(positionOf(doc, 99, 1)).toBe(4);
expect(positionOf(doc, -3, -1)).toBe(0);
expect(positionOf(doc, 1.8, 1.9)).toBe(4);
expect(positionOf(doc, Number.NaN, Number.POSITIVE_INFINITY)).toBe(0);
expect(positionOf(Text.empty, 4, 4)).toBe(0);
});
});