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:
parent
0fb7e33fc7
commit
9fa6028335
25 changed files with 2958 additions and 22 deletions
430
ui/tests/editor/EditorArea.test.ts
Normal file
430
ui/tests/editor/EditorArea.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue