M1.6: tabs and CodeMirror editor

- Editor area with tab bar, CodeMirror 6 view, close question and notices
  (ui/src/components/editor/, ui/src/stores/editor.ts), mounted in App.vue;
  the project tree opens files through the editor store.
- BufferSync: local edits to buffer.edit against the confirmed version,
  one call in flight, resync on stale_version or newer bufferChanged with
  rebase of unsent changes; EngineText maps CodeMirror positions to engine
  UTF-16 offsets for CRLF text.
- Save, save all and close from engine default shortcuts via listCommands.
- Dirty marker, Save / Don't Save / Cancel, non-blocking notice when a
  dirty file changes or disappears on disk.
- Vitest: keystroke bursts with stale versions and remote edits (LF and
  CRLF), mapping, store and component tests against a fake engine.
- Progress docs: Editor core 8% (est.), depth ~1.4%, G2, ui-parity tabs,
  M1 row, architecture, README status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-15 18:26:32 +02:00
parent 0fb7e33fc7
commit 9fa6028335
25 changed files with 2958 additions and 22 deletions

View file

@ -18,7 +18,13 @@ describe("App", () => {
});
it("shows name and version in the status bar", async () => {
invoke.mockResolvedValue({ name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" });
invoke.mockImplementation((command: string) =>
Promise.resolve(
command === "engine_list_commands"
? []
: { name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" },
),
);
const wrapper = mount(App);
await flushPromises();
expect(wrapper.get("[data-test=status-bar]").text()).toBe("Lutra 0.0.0");

View file

@ -0,0 +1,430 @@
/**
* Tests for the editor area and the editor store: opening tabs (from the
* tree and from engine events), editing through CodeMirror into
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
* Save / Don't Save / Cancel question), saving through shortcuts loaded
* from the engine's command list, and the notice for files changed on disk.
* The engine is a fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { EditorView } from "@codemirror/view";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import EditorArea from "../../src/components/editor/EditorArea.vue";
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import { useEditorStore } from "../../src/stores/editor";
/** A buffer of the fake engine. */
interface FakeBuffer {
path: string;
text: string;
version: number;
saved: number;
}
/** Fake engine state. */
let buffers: Map<number, FakeBuffer>;
/** Files on the fake disk. */
let disk: Record<string, string>;
/** Next buffer id. */
let nextId: number;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/**
* Describes a buffer as `file.open` and `buffer.get` do.
*
* @param id - buffer id.
*/
function describeBuffer(id: number): unknown {
const b = buffers.get(id);
return b
? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: "lf" }
: null;
}
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
*/
function fail(code: string): Promise<never> {
return Promise.reject(Object.assign(new Error(code), { code, message: code }));
}
/**
* The fake engine's command handler.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const id = typeof p.id === "number" ? p.id : -1;
const b = buffers.get(id);
switch (command) {
case "file.open": {
const path = String(p.path);
for (const [existing, buffer] of buffers) {
if (buffer.path === path) {
return Promise.resolve(describeBuffer(existing));
}
}
const text = disk[path];
if (text === undefined) {
return fail("not_found");
}
const newId = nextId++;
buffers.set(newId, { path, text, version: 1, saved: 1 });
return Promise.resolve(describeBuffer(newId));
}
case "buffer.get":
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
case "buffer.edit": {
if (!b) {
return fail("failed");
}
if (p.baseVersion !== b.version) {
return fail("stale_version");
}
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += b.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
const wasDirty = b.version !== b.saved;
b.text = out + b.text.slice(pos);
b.version += 1;
emitEditorEvent({ kind: "bufferChanged", id, version: b.version });
if (!wasDirty) {
emitEditorEvent({ kind: "dirtyChanged", id, dirty: true });
}
return Promise.resolve({ id, version: b.version, dirty: true });
}
case "file.save":
if (!b) {
return fail("failed");
}
disk[b.path] = b.text;
b.saved = b.version;
emitEditorEvent({ kind: "dirtyChanged", id, dirty: false });
return Promise.resolve({ id, version: b.version });
case "file.saveAll": {
const saved: number[] = [];
for (const [bid, buffer] of buffers) {
if (buffer.version !== buffer.saved) {
disk[buffer.path] = buffer.text;
buffer.saved = buffer.version;
saved.push(bid);
}
}
return Promise.resolve({ saved, failed: [] });
}
case "buffer.close":
if (!b) {
return fail("failed");
}
if (b.version !== b.saved && p.force !== true) {
return fail("unsaved_changes");
}
buffers.delete(id);
emitEditorEvent({ kind: "bufferClosed", id });
return Promise.resolve(null);
case "project.children":
return Promise.resolve({
dir: "",
entries: Object.keys(disk).map((path) => ({
name: path,
path,
kind: "file",
ignored: false,
role: "normal",
})),
truncated: false,
});
default:
return Promise.resolve(null);
}
}
/** Pinia of the current test, installed in every mounted component. */
let pinia: Pinia;
/** Mounted components to unmount after each test. */
let mounted: VueWrapper[] = [];
/** Mounts the editor area. */
async function mountArea(): Promise<VueWrapper> {
const wrapper = mount(EditorArea, {
attachTo: document.body,
slots: { default: "empty" },
global: { plugins: [pinia] },
});
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
/** The CodeMirror view inside a wrapper. */
function viewOf(wrapper: VueWrapper): EditorView {
const el = wrapper.find(".cm-editor").element;
const view = EditorView.findFromDOM(el as HTMLElement);
if (!view) {
throw new Error("no editor view");
}
return view;
}
/**
* Presses a key on the window.
*
* @param init - key event properties.
*/
async function press(init: KeyboardEventInit): Promise<void> {
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
await flushPromises();
}
/** Commands sent to the engine, without project and listing calls. */
function commands(): string[] {
return calls.map((c) => c.command).filter((c) => !c.startsWith("project."));
}
/**
* jsdom has no layout; CodeMirror measures text ranges, so give ranges
* empty rectangles.
*/
function stubRangeGeometry(): void {
const empty = (): DOMRectList => {
const list: DOMRect[] = [];
return Object.assign(list, { item: () => null });
};
Range.prototype.getClientRects = empty;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
}
beforeEach(() => {
stubRangeGeometry();
pinia = createPinia();
setActivePinia(pinia);
buffers = new Map();
disk = { "a.php": "<?php\necho 1;\n", "b.txt": "bee\n" };
nextId = 1;
calls = [];
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([
{ id: "file.save", label: "Save", menuPath: null, defaultShortcut: "Mod+S", params: "", enabled: true },
{ id: "file.saveAll", label: "Save All", menuPath: null, defaultShortcut: "Mod+Alt+S", params: "", enabled: true },
{ id: "buffer.close", label: "Close", menuPath: null, defaultShortcut: "Mod+W", params: "", enabled: true },
]);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.reject(new Error(`unexpected ${cmd}`));
});
});
afterEach(async () => {
await flushPromises();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
});
describe("EditorArea", () => {
it("shows the slot without tabs and opens a file from the project tree", async () => {
const area = await mountArea();
expect(area.text()).toContain("empty");
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(tree);
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
await tree.find("[data-path='a.php']").trigger("dblclick");
await flushPromises();
const tabs = area.findAll("[data-test=editor-tab]");
expect(tabs.map((t) => t.text())).toEqual(["a.php"]);
expect(viewOf(area).state.doc.toString()).toBe("<?php\necho 1;\n");
await tree.find("[data-path='a.php']").trigger("dblclick");
await flushPromises();
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(1);
});
it("sends typing to buffer.edit and marks the tab dirty", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await flushPromises();
const view = viewOf(area);
view.dispatch({ changes: { from: 5, insert: " // hi" } });
view.dispatch({ changes: { from: 0, insert: "#" } });
await flushPromises();
expect(buffers.get(1)?.text).toBe("#<?php // hi\necho 1;\n");
expect(area.find("[data-test=tab-dirty]").exists()).toBe(true);
});
it("applies engine edits made elsewhere to the open editor", async () => {
const area = await mountArea();
await useEditorStore(pinia).openFile("b.txt");
await flushPromises();
const b = buffers.get(1);
if (!b) {
throw new Error("no buffer");
}
b.text = "honey bee\n";
b.version = 2;
emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 });
await flushPromises();
expect(viewOf(area).state.doc.toString()).toBe("honey bee\n");
});
it("switches tabs and closes a clean tab with a middle click", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await editor.openFile("b.txt");
await flushPromises();
expect(editor.activeId).toBe(2);
await area.findAll("[data-test=editor-tab]")[0]?.trigger("click");
expect(viewOf(area).state.doc.toString()).toContain("<?php");
await area.findAll("[data-test=editor-tab]")[1]?.trigger("auxclick", { button: 1 });
await flushPromises();
expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["a.php"]);
expect(commands()).toContain("buffer.close");
});
it("asks before closing a dirty tab: cancel, don't save, save", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
await flushPromises();
await press({ key: "w", code: "KeyW", ctrlKey: true });
expect(area.find("[data-test=close-prompt]").exists()).toBe(true);
await area.find("[data-test=close-cancel]").trigger("click");
await flushPromises();
expect(area.find("[data-test=close-prompt]").exists()).toBe(false);
expect(editor.tabs).toHaveLength(1);
await area.find("[data-test=tab-close]").trigger("click");
await flushPromises();
await area.find("[data-test=close-save]").trigger("click");
await flushPromises();
expect(disk["a.php"]).toBe("x<?php\necho 1;\n");
expect(editor.tabs).toHaveLength(0);
await editor.openFile("b.txt");
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "lost " } });
await flushPromises();
await editor.requestClose();
await flushPromises();
await area.find("[data-test=close-discard]").trigger("click");
await flushPromises();
expect(disk["b.txt"]).toBe("bee\n");
expect(calls.at(-1)).toEqual({ command: "buffer.close", params: { id: 2, force: true } });
expect(editor.tabs).toHaveLength(0);
});
it("saves with the shortcuts the engine defines, after pending edits", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await editor.openFile("b.txt");
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "B" } });
await press({ key: "s", code: "KeyS", ctrlKey: true });
expect(disk["b.txt"]).toBe("Bbee\n");
expect(calls.at(-1)).toEqual({ command: "file.save", params: { id: 2 } });
expect(area.find("[data-test=tab-dirty]").exists()).toBe(false);
await area.findAll("[data-test=editor-tab]")[0]?.trigger("click");
viewOf(area).dispatch({ changes: { from: 0, insert: "A" } });
await press({ key: "ß", code: "KeyS", ctrlKey: true, altKey: true });
expect(disk["a.php"]).toBe("A<?php\necho 1;\n");
expect(calls.at(-1)?.command).toBe("file.saveAll");
calls = [];
await press({ key: "s", code: "KeyS", shiftKey: true });
expect(calls).toEqual([]);
});
it("adds a tab for a buffer opened elsewhere", async () => {
const area = await mountArea();
await execute("file.open", { path: "b.txt" });
emitEditorEvent({ kind: "bufferOpened", id: 1, path: "b.txt" });
await flushPromises();
expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["b.txt"]);
emitEditorEvent({ kind: "bufferClosed", id: 1 });
await flushPromises();
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(0);
});
it("activates the last opened buffer even when its fetch finishes first", async () => {
const area = await mountArea();
await execute("file.open", { path: "a.php" });
await execute("file.open", { path: "b.txt" });
let releaseFirst: () => void = () => undefined;
const fallback = invoke.getMockImplementation();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (args?.command === "buffer.get" && args.params.id === 1) {
return new Promise((resolve) => {
releaseFirst = () => {
resolve(describeBuffer(1));
};
});
}
return fallback?.(cmd, args) as Promise<unknown>;
});
emitEditorEvent({ kind: "bufferOpened", id: 1, path: "a.php" });
emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" });
await flushPromises();
releaseFirst();
await flushPromises();
const editor = useEditorStore(pinia);
expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]);
expect(editor.activeId).toBe(2);
expect(area.find("[aria-selected=true]").text()).toBe("b.txt");
});
it("shows a notice when a dirty file changes on disk, and an open error", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await flushPromises();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false });
await flushPromises();
expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk");
await area.find("[data-test=notice-dismiss]").trigger("click");
expect(area.find("[data-test=editor-notice]").exists()).toBe(false);
await editor.openFile("missing.php");
await flushPromises();
expect(area.find("[data-test=editor-error]").text()).toContain("not_found");
});
it("opens a 1 MB file and records the time", async () => {
const line = "<?php echo 'lutra otter tool use stone';\n";
disk["big.php"] = line.repeat(Math.ceil((1024 * 1024) / line.length));
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("big.php");
await flushPromises();
expect(viewOf(area).state.doc.length).toBe(disk["big.php"].length);
const timing = editor.lastOpen;
expect(timing?.path).toBe("big.php");
expect(timing?.stateMs).toBeLessThan(2000);
});
});

View file

@ -0,0 +1,280 @@
/**
* Tests for the buffer sync: a fake engine with real versioning answers
* `buffer.edit` and `buffer.get` after random delays and makes edits of its
* own (as a reload from disk or the control channel would). Bursts of local
* keystrokes must all reach the engine, and both sides must converge.
*/
import { describe, expect, it } from "vitest";
import {
BufferSync,
type BufferInfo,
type EditParams,
type EditResult,
type SyncTransport,
} from "../../src/components/editor/bufferSync";
import type { RunResult } from "../../src/ipc";
/** Deterministic pseudo-random numbers (mulberry32). */
function rng(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** A fake engine buffer with the engine's edit protocol. */
class FakeEngine implements SyncTransport {
text: string;
version = 1;
readonly lineEnding: string;
/** Answers waiting to be delivered. */
private queue: (() => void)[] = [];
/** Versions to report through `bufferChanged`. */
events: number[] = [];
editCalls = 0;
staleRejections = 0;
constructor(text: string, lineEnding = "lf", private random: () => number = Math.random) {
this.text = text;
this.lineEnding = lineEnding;
}
info(): BufferInfo {
return {
id: 1,
path: "a.txt",
text: this.text,
version: this.version,
dirty: this.version !== 1,
lineEnding: this.lineEnding,
};
}
edit(params: EditParams): Promise<RunResult<EditResult>> {
this.editCalls += 1;
return this.later(() => {
if (params.baseVersion !== this.version) {
this.staleRejections += 1;
return { ok: false, error: { code: "stale_version", message: "stale" } };
}
let out = "";
let pos = 0;
for (const e of params.edits) {
expect(e.from).toBeGreaterThanOrEqual(pos);
expect(e.to).toBeLessThanOrEqual(this.text.length);
out += this.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
this.text = out + this.text.slice(pos);
this.version += 1;
this.events.push(this.version);
return { ok: true, value: { id: 1, version: this.version, dirty: true } };
});
}
get(): Promise<RunResult<BufferInfo>> {
return this.later(() => ({ ok: true, value: this.info() }));
}
/**
* An edit made outside the editor: inserts `text` at a line start.
*
* @param text - inserted text.
* @param line - 0-based line; random when omitted.
*/
external(text: string, line?: number): void {
const starts = [0];
for (let i = 0; i < this.text.length; i += 1) {
if (this.text[i] === "\n") {
starts.push(i + 1);
}
}
const at = starts[line ?? Math.floor(this.random() * starts.length)] ?? 0;
this.text = this.text.slice(0, at) + text + this.text.slice(at);
this.version += 1;
this.events.push(this.version);
}
/** Queues an answer; {@link step} delivers queued answers in random order. */
private later<T>(answer: () => T): Promise<T> {
return new Promise((resolve) => {
this.queue.push(() => {
resolve(answer());
});
});
}
/** Delivers one queued answer, if any. */
step(): boolean {
if (this.queue.length === 0) {
return false;
}
const index = Math.floor(this.random() * this.queue.length);
const [answer] = this.queue.splice(index, 1);
answer?.();
return true;
}
}
/** Lets promise callbacks run. */
async function tick(): Promise<void> {
for (let i = 0; i < 5; i += 1) {
await Promise.resolve();
}
}
/**
* Delivers every pending answer and event until the sync is idle.
*
* @param engine - the fake engine.
* @param sync - the sync under test.
*/
async function drain(engine: FakeEngine, sync: BufferSync): Promise<void> {
for (let i = 0; i < 10_000; i += 1) {
const events = engine.events.splice(0);
for (const v of events) {
sync.notifyVersion(v);
}
const stepped = engine.step();
await tick();
if (!stepped && events.length === 0 && !sync.pending) {
return;
}
}
throw new Error("sync did not settle");
}
/**
* The engine text with CodeMirror's line breaks, for comparison.
*
* @param text - engine text.
*/
function normalised(text: string): string {
return text.replace(/\r\n?/g, "\n");
}
describe("BufferSync", () => {
it("sends local edits with the base version and tracks versions", async () => {
const engine = new FakeEngine("hello\n");
const sync = new BufferSync(engine.info(), [], engine);
sync.dispatch({ changes: { from: 5, insert: " world" } });
expect(sync.pending).toBe(true);
await drain(engine, sync);
expect(engine.text).toBe("hello world\n");
expect(sync.baseVersion).toBe(2);
expect(sync.pending).toBe(false);
});
it("applies a change made in the engine", async () => {
const engine = new FakeEngine("one\ntwo\n");
const sync = new BufferSync(engine.info(), [], engine);
engine.external("zero\n", 0);
await drain(engine, sync);
expect(sync.state.doc.toString()).toBe("zero\none\ntwo\n");
expect(sync.baseVersion).toBe(engine.version);
});
it("keeps the local cursor when a remote change lands before it", async () => {
const engine = new FakeEngine("abc\n");
const sync = new BufferSync(engine.info(), [], engine);
sync.dispatch({ selection: { anchor: 2 } });
engine.external("x\n", 0);
await drain(engine, sync);
expect(sync.state.selection.main.head).toBe(4);
});
it("loses no keystroke in a burst with stale versions and remote edits", async () => {
const random = rng(42);
const engine = new FakeEngine("<?php\n\necho 1;\n", "lf", random);
const sync = new BufferSync(engine.info(), [], engine);
const typed: string[] = [];
for (let i = 0; i < 400; i += 1) {
const token = `[k${String(i)}]`;
typed.push(token);
const doc = sync.state.doc;
const at = doc.line(1 + Math.floor(random() * doc.lines)).to;
sync.dispatch({ changes: { from: at, insert: token } });
if (random() < 0.15) {
engine.external(`/*e${String(i)}*/\n`);
}
if (random() < 0.5) {
engine.step();
}
if (random() < 0.3) {
for (const v of engine.events.splice(0)) {
sync.notifyVersion(v);
}
}
await tick();
}
await drain(engine, sync);
expect(sync.state.doc.toString()).toBe(engine.text);
for (const token of typed) {
expect(engine.text).toContain(token);
}
expect(engine.staleRejections).toBeGreaterThan(0);
expect(engine.editCalls).toBeLessThan(400);
});
it("converges with deletions and line breaks in a CRLF file", async () => {
const random = rng(7);
const engine = new FakeEngine("a\r\nbb\r\nccc\r\n", "crlf", random);
const sync = new BufferSync(engine.info(), [], engine);
for (let i = 0; i < 300; i += 1) {
const len = sync.state.doc.length;
const from = Math.floor(random() * (len + 1));
const to = Math.min(len, from + Math.floor(random() * 3));
const insert = random() < 0.3 ? "\n" : random() < 0.5 ? "é😀" : "";
sync.dispatch({ changes: { from, to, insert } });
if (random() < 0.1) {
engine.external(`r${String(i)}\r\n`);
}
if (random() < 0.6) {
engine.step();
}
if (random() < 0.3) {
for (const v of engine.events.splice(0)) {
sync.notifyVersion(v);
}
}
await tick();
}
await drain(engine, sync);
expect(sync.state.doc.toString()).toBe(normalised(engine.text));
expect(engine.text.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/);
});
it("drops local changes and reports when the engine refuses them", async () => {
const engine = new FakeEngine("keep\n");
const errors: string[] = [];
const refusing: SyncTransport = {
edit: () =>
Promise.resolve({ ok: false, error: { code: "invalid_params", message: "bad" } }),
get: () => engine.get(),
};
const sync = new BufferSync(engine.info(), [], refusing, (e) => errors.push(e.code));
sync.dispatch({ changes: { from: 0, insert: "lost " } });
await drain(engine, sync);
expect(errors).toEqual(["invalid_params"]);
expect(sync.state.doc.toString()).toBe("keep\n");
});
it("idle resolves after the engine confirmed every change", async () => {
const engine = new FakeEngine("");
const sync = new BufferSync(engine.info(), [], engine);
sync.dispatch({ changes: { from: 0, insert: "x" } });
let done = false;
void sync.idle().then(() => {
done = true;
});
await tick();
expect(done).toBe(false);
await drain(engine, sync);
await tick();
expect(done).toBe(true);
});
});

View file

@ -0,0 +1,58 @@
/**
* 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, 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");
});
});