Initial RuneStone project
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { detectChrome, extensionOf, treeFileParts } from "../src/lib/workspace/chrome.ts";
|
||||
import { monacoChrome } from "../src/lib/editor/monacoChrome.ts";
|
||||
|
||||
test("markdown files open in writing chrome", () => {
|
||||
assert.equal(detectChrome("notes/inbox.md"), "Writing");
|
||||
assert.equal(detectChrome("README.markdown"), "Writing");
|
||||
});
|
||||
|
||||
test("scripts open in ide chrome", () => {
|
||||
assert.equal(detectChrome("src/hello.py"), "Ide");
|
||||
assert.equal(detectChrome("tools/setup.sh"), "Ide");
|
||||
assert.equal(detectChrome("Makefile"), "Ide");
|
||||
});
|
||||
|
||||
test("writing chrome wraps and hides line numbers", () => {
|
||||
assert.equal(monacoChrome("Writing").wordWrap, "on");
|
||||
assert.equal(monacoChrome("Writing").lineNumbers, "off");
|
||||
assert.equal(monacoChrome("Writing").minimap.enabled, false);
|
||||
});
|
||||
|
||||
test("ide chrome shows line numbers and no wrap", () => {
|
||||
assert.equal(monacoChrome("Ide").wordWrap, "off");
|
||||
assert.equal(monacoChrome("Ide").lineNumbers, "on");
|
||||
assert.equal(monacoChrome("Ide").minimap.enabled, true);
|
||||
});
|
||||
|
||||
test("extensionOf reads the last suffix", () => {
|
||||
assert.equal(extensionOf("a/b.c.py"), "py");
|
||||
assert.equal(extensionOf(".gitignore"), "");
|
||||
});
|
||||
|
||||
test("treeFileParts splits a display name from its extension", () => {
|
||||
assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" });
|
||||
assert.deepEqual(treeFileParts("chrome_extensions.json"), {
|
||||
label: "chrome_extensions",
|
||||
ext: "json",
|
||||
});
|
||||
assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" });
|
||||
});
|
||||
@@ -0,0 +1,348 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Documents } from "../src/lib/workspace/documents.ts";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => resolve = done);
|
||||
return { promise, resolve };
|
||||
}
|
||||
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
|
||||
function setup() {
|
||||
const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]);
|
||||
const io = {
|
||||
read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; },
|
||||
write: async (path: string, contents: string, expected: string) => {
|
||||
if (disk.get(path) !== expected) throw new Error("conflict");
|
||||
disk.set(path, contents);
|
||||
},
|
||||
image: async () => "data:image/png;base64,",
|
||||
kind: () => "text" as const,
|
||||
chrome: () => "Writing" as const,
|
||||
};
|
||||
const docs = new Documents(io, () => {});
|
||||
return { docs, disk, io };
|
||||
}
|
||||
|
||||
test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "keep my edits");
|
||||
docs.newTab();
|
||||
const first = docs.active!;
|
||||
docs.newTab();
|
||||
const second = docs.active!;
|
||||
assert.equal(first.kind, "empty");
|
||||
assert.equal(second.kind, "empty");
|
||||
assert.notEqual(first.relPath, second.relPath);
|
||||
assert.equal(note.contents, "keep my edits");
|
||||
docs.select(first.relPath);
|
||||
docs.close(first.relPath);
|
||||
assert.equal(docs.active, second);
|
||||
docs.close(note.relPath);
|
||||
io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); };
|
||||
io.write = async () => { assert.fail("empty tabs must not write disk"); };
|
||||
docs.edit(second.id, "ignored");
|
||||
await docs.refresh();
|
||||
await docs.save(second.id);
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
assert.equal(docs.dirty, false);
|
||||
assert.equal(second.diskError, undefined);
|
||||
docs.close(second.relPath);
|
||||
assert.equal(docs.activePath, null);
|
||||
});
|
||||
|
||||
test("opening a file fills the active empty tab in place and failed reads preserve it", async () => {
|
||||
const { docs } = setup();
|
||||
docs.newTab();
|
||||
const first = docs.active!;
|
||||
docs.newTab();
|
||||
const second = docs.active!;
|
||||
docs.select(first.relPath);
|
||||
await assert.rejects(docs.open(entry("missing.md")), /missing/);
|
||||
assert.equal(docs.active, first);
|
||||
await docs.open(entry("note.md"));
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]);
|
||||
docs.select(second.relPath);
|
||||
await docs.open(entry("note.md"));
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
});
|
||||
|
||||
test("a new empty tab stays selected when an earlier file read finishes", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("note.md"));
|
||||
docs.newTab();
|
||||
const blank = docs.active!;
|
||||
gate.resolve("note");
|
||||
await pending;
|
||||
assert.equal(docs.active, blank);
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
});
|
||||
|
||||
test("clean buffers follow agent edits; dirty buffers retain both versions", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
disk.set("note.md", "agent version");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active?.contents, "agent version");
|
||||
docs.edit(docs.active!.id, "my version");
|
||||
disk.set("note.md", "agent version 2");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active?.contents, "my version");
|
||||
assert.equal(docs.active?.diskContents, "agent version 2");
|
||||
await assert.rejects(docs.save(docs.active!.id), /Resolve/);
|
||||
docs.resolve(docs.active!.id, false);
|
||||
await docs.save(docs.active!.id);
|
||||
assert.equal(disk.get("note.md"), "my version");
|
||||
});
|
||||
|
||||
test("typing during a save remains unsaved", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { await gate.promise; return write(...args); };
|
||||
docs.edit(docs.active!.id, "first edit");
|
||||
const pending = docs.save(docs.active!.id);
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "second edit");
|
||||
gate.resolve();
|
||||
await pending;
|
||||
assert.equal(disk.get("note.md"), "first edit");
|
||||
assert.equal(docs.active!.saved, "first edit");
|
||||
assert.equal(docs.active!.contents, "second edit");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("concurrent saves serialize and finish at the latest edit", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { await gate.promise; return write(...args); };
|
||||
docs.edit(docs.active!.id, "first");
|
||||
const first = docs.save(docs.active!.id);
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "latest");
|
||||
const second = docs.save(docs.active!.id);
|
||||
const third = docs.save(docs.active!.id);
|
||||
gate.resolve();
|
||||
await Promise.all([first, second, third]);
|
||||
assert.equal(disk.get("note.md"), "latest");
|
||||
assert.equal(docs.dirty, false);
|
||||
});
|
||||
|
||||
test("latest navigation wins even when earlier reads finish later", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
const read = io.read;
|
||||
io.read = path => path === "note.md" ? gate.promise : read(path);
|
||||
const first = docs.open(entry("note.md"));
|
||||
await docs.open(entry("script.py"));
|
||||
gate.resolve("note");
|
||||
await first;
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("duplicate opens share one document and do not lose edits", async () => {
|
||||
const { docs } = setup();
|
||||
await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]);
|
||||
assert.equal(docs.buffers.length, 1);
|
||||
docs.edit(docs.active!.id, "unsaved");
|
||||
await docs.open(entry("script.py"));
|
||||
await docs.open(entry("note.md"));
|
||||
assert.equal(docs.active!.contents, "unsaved");
|
||||
});
|
||||
|
||||
test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => {
|
||||
const { docs, disk } = setup();
|
||||
disk.set("third.md", "third");
|
||||
await docs.open(entry("note.md"));
|
||||
await docs.open(entry("script.py"), "new");
|
||||
docs.select("note.md");
|
||||
await docs.open(entry("third.md"), "current");
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
|
||||
assert.equal(docs.activePath, "third.md");
|
||||
await docs.open(entry("script.py"), "current");
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("current-tab navigation preserves edits made while the next file is loading", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("script.py"), "current");
|
||||
docs.edit(note.id, "keep these edits");
|
||||
gate.resolve("script");
|
||||
await pending;
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
assert.equal(note.contents, "keep these edits");
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("failed current-tab navigation keeps the active document", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"), "current");
|
||||
await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/);
|
||||
assert.equal(docs.buffers.length, 1);
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
});
|
||||
|
||||
test("a late current-tab read cannot replace a more recently selected tab", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("script.py"), "current");
|
||||
docs.select("note.md");
|
||||
gate.resolve("script");
|
||||
await pending;
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
assert.equal(docs.buffers[0].relPath, "note.md");
|
||||
});
|
||||
|
||||
test("removed files retain text and block accidental recreation", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "precious text");
|
||||
disk.delete("note.md");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active!.contents, "precious text");
|
||||
assert.match(docs.active!.diskError!, /unavailable/);
|
||||
await assert.rejects(docs.save(docs.active!.id));
|
||||
});
|
||||
|
||||
test("disposing a workspace ignores late open results", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("note.md"));
|
||||
docs.dispose(); gate.resolve("late");
|
||||
await pending;
|
||||
assert.equal(docs.buffers.length, 0);
|
||||
});
|
||||
|
||||
test("renaming a folder preserves document identity and dirty state", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const id = docs.active!.id;
|
||||
docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md");
|
||||
assert.equal(docs.activePath, "notes/moved.md");
|
||||
assert.equal(docs.active!.id, id);
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("autosave writes changed background tabs once and skips clean or reverted text", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
const writes: string[] = [];
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { writes.push(args[0]); await write(...args); };
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "background edit");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "temporary edit");
|
||||
docs.edit(docs.active!.id, docs.active!.saved);
|
||||
assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] });
|
||||
assert.equal(disk.get("note.md"), "background edit");
|
||||
await docs.autosave();
|
||||
await docs.save(note.id);
|
||||
assert.deepEqual(writes, ["note.md"]);
|
||||
});
|
||||
|
||||
test("autosave skips in-flight saves and preserves edits for the next pass", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
let writes = 0;
|
||||
io.write = async (...args) => { writes++; await gate.promise; await write(...args); };
|
||||
docs.edit(docs.active!.id, "first");
|
||||
const pending = docs.autosave();
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "still typing");
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
gate.resolve();
|
||||
await pending;
|
||||
assert.equal(writes, 1);
|
||||
assert.equal(disk.get("note.md"), "first");
|
||||
assert.equal(docs.dirty, true);
|
||||
await docs.autosave();
|
||||
assert.equal(writes, 2);
|
||||
assert.equal(disk.get("note.md"), "still typing");
|
||||
});
|
||||
|
||||
test("autosave skips known conflicts and unavailable files", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "my note");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "my script");
|
||||
disk.set("note.md", "external edit");
|
||||
disk.delete("script.py");
|
||||
await docs.refresh();
|
||||
io.write = async () => { assert.fail("blocked files must not be written"); };
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
assert.equal(note.contents, "my note");
|
||||
assert.equal(note.diskContents, "external edit");
|
||||
assert.equal(docs.active!.contents, "my script");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("an autosave failure preserves edits, saves other files, and can be retried", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "my note");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "my script");
|
||||
const write = io.write;
|
||||
io.write = async (...args) => {
|
||||
if (args[0] === "note.md") throw new Error("disk full");
|
||||
await write(...args);
|
||||
};
|
||||
const result = await docs.autosave();
|
||||
assert.deepEqual(result.saved, ["script.py"]);
|
||||
assert.equal(result.failed[0].path, "note.md");
|
||||
assert.match(String(result.failed[0].error), /disk full/);
|
||||
assert.equal(note.saved, "original");
|
||||
assert.equal(note.contents, "my note");
|
||||
assert.equal(disk.get("script.py"), "my script");
|
||||
io.write = write;
|
||||
await docs.autosave();
|
||||
assert.equal(disk.get("note.md"), "my note");
|
||||
assert.equal(docs.dirty, false);
|
||||
});
|
||||
|
||||
test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "my note");
|
||||
disk.set("note.md", "external edit");
|
||||
const result = await docs.autosave();
|
||||
assert.equal(result.failed.length, 1);
|
||||
assert.equal(disk.get("note.md"), "external edit");
|
||||
assert.equal(docs.active!.contents, "my note");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("closed documents and disposed workspaces are not autosaved", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "discarded");
|
||||
docs.close("note.md");
|
||||
io.write = async () => { assert.fail("discarded edits must not be written"); };
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "disposed");
|
||||
docs.dispose();
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { fenceOpenText, headingMarkText } from "../src/lib/editor/headingMarks.ts";
|
||||
|
||||
test("heading marks match the heading level", () => {
|
||||
assert.equal(headingMarkText(1), "#");
|
||||
assert.equal(headingMarkText(3), "###");
|
||||
assert.equal(headingMarkText(6), "######");
|
||||
});
|
||||
|
||||
test("fence open marks include the language", () => {
|
||||
assert.equal(fenceOpenText(""), "```");
|
||||
assert.equal(fenceOpenText("js"), "```js");
|
||||
assert.equal(fenceOpenText(" pp "), "```pp");
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>';
|
||||
files.set("images/picture (#1).svg", btoa(svg));
|
||||
files.set("images/replacement.svg", btoa(svg));
|
||||
files.set("notes/welcome.md", "Above.\n\nBelow.\n");
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_write_bytes") {
|
||||
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
|
||||
if (window.__TEST__.failWrite) throw new Error("Image write failed");
|
||||
files.set(args.rel, args.base64); return;
|
||||
}
|
||||
if (command === "workspace_read_data_url") {
|
||||
if (!files.has(args.rel)) throw new Error("missing image");
|
||||
return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
}
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_reveal") return;
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
|
||||
async function writer() {
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
}
|
||||
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
|
||||
async function dragFromTree(selector = ".cm-content", cancel = false) {
|
||||
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
|
||||
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
|
||||
await page.mouse.move(from.x + 60, from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
|
||||
await page.getByText("Insert image", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator(".image-drop-target").count(), 1);
|
||||
if (cancel) await page.keyboard.press("Escape");
|
||||
await page.mouse.up();
|
||||
}
|
||||
async function imageMenu() {
|
||||
await page.locator(".md-image-frame").first().click({ button: "right" });
|
||||
await page.getByRole("menu", { name: "Image actions" }).waitFor();
|
||||
}
|
||||
try {
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).click();
|
||||
await writer();
|
||||
await page.locator('[data-tree-rel="images"]').click();
|
||||
await dragFromTree();
|
||||
await page.locator(".md-image-frame img").waitFor();
|
||||
const linked = await source();
|
||||
assert.ok(linked.startsWith("\n\nAbove."), linked);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => ["workspace_write_bytes", "workspace_rename"].includes(c.command)).length), 0);
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
// Neither caret movement nor selection exposes an image's Markdown.
|
||||
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: 0, head: 38 } }));
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
await page.locator(".md-image-frame img").click();
|
||||
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await page.getByRole("menu", { name: "Image actions" }).waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
|
||||
await page.screenshot({ path: ".audit/image-context-menu.png" });
|
||||
await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "");
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Copy image", exact: true }).click();
|
||||
await page.waitForFunction(async () => (await navigator.clipboard.read()).some(item => item.types.includes("image/png")));
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Show in Explorer", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "workspace_reveal" && c.args.rel === "images/picture (#1).svg"));
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Remove image", exact: true }).click();
|
||||
assert.ok(!(await source()).includes("picture%20"));
|
||||
assert.ok(await page.evaluate(() => window.__TEST__.files.has("images/picture (#1).svg")));
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await source(), linked);
|
||||
|
||||
await page.locator(".md-image-frame").hover();
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
|
||||
await page.locator(".cm-line").filter({ hasText: "picture%20" }).waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 1);
|
||||
await page.getByRole("button", { name: "Hide image source", exact: true }).click();
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Swap image…", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Image path relative to this note, or https URL" }).fill("../images/replacement.svg");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__CM__.state.doc.toString().includes("replacement.svg"));
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "replacement.svg" }).count(), 0);
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "replacement.svg", exact: true }).waitFor();
|
||||
await page.getByRole("tab", { name: /welcome.md/ }).click();
|
||||
await writer();
|
||||
|
||||
const beforeCancel = await source();
|
||||
await dragFromTree(".cm-content", true);
|
||||
assert.equal(await source(), beforeCancel);
|
||||
assert.equal(await page.locator(".image-drop-target").count(), 0);
|
||||
// Inline images remain independently selectable without hiding adjacent prose.
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "Before  between ![[../images/replacement.svg]] after.\n" }, selection: { anchor: 0 } });
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelectorAll(".md-image-frame").length === 2);
|
||||
assert.ok((await page.locator(".cm-content").innerText()).includes("Before"));
|
||||
assert.ok(!(await page.locator(".cm-content").innerText()).includes("![]"));
|
||||
await page.locator(".md-image-frame img").nth(1).click();
|
||||
await page.keyboard.press("Delete");
|
||||
assert.equal(await source(), "Before  between after.\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.ok((await source()).includes("![[../images/replacement.svg]]"));
|
||||
// Reference-image editing affects only the selected embed, not its definition.
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "![Reference][pic]\n\nBelow.\n\n[pic]: ../images/replacement.svg\n" }, selection: { anchor: 0 } });
|
||||
});
|
||||
await page.locator(".md-image-frame").hover();
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
|
||||
await page.locator(".cm-line").filter({ hasText: "![Reference]" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
|
||||
// The same navigator drag works in the source editor.
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await dragFromTree(".monaco-editor .view-lines");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20"));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/image-navigation-failure.png" });
|
||||
console.error(errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,248 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_write_bytes") {
|
||||
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
|
||||
if (window.__TEST__.failWrite) throw new Error("Image write failed");
|
||||
files.set(args.rel, args.base64); return;
|
||||
}
|
||||
if (command === "workspace_read_data_url") {
|
||||
if (!files.has(args.rel)) throw new Error("missing image");
|
||||
return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
}
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
async function openNote(name = "welcome.md") {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
}
|
||||
async function source() {
|
||||
return page.evaluate(() => window.__CM__.state.doc.toString());
|
||||
}
|
||||
async function save() {
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForTimeout(100);
|
||||
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
|
||||
}
|
||||
async function drop(count = 1, selector = ".cm-content") {
|
||||
await page.locator(selector).evaluate((element, count) => {
|
||||
const data = new DataTransfer();
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
|
||||
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
|
||||
const rect = element.getBoundingClientRect();
|
||||
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
|
||||
}, count);
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await openNote();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } });
|
||||
});
|
||||
const original = await source();
|
||||
const acceptsDrag = await page.locator(".cm-content").evaluate(element => {
|
||||
const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg"));
|
||||
const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data });
|
||||
element.dispatchEvent(event); return event.defaultPrevented;
|
||||
});
|
||||
assert.ok(acceptsDrag);
|
||||
await drop(2);
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2);
|
||||
await page.locator(".md-image-frame img").first().waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
||||
const inserted = await source();
|
||||
assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor");
|
||||
const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]);
|
||||
assert.notEqual(paths[0], paths[1]);
|
||||
assert.ok(paths.every(path => path.startsWith("../attachments/")));
|
||||
assert.equal(await save(), inserted);
|
||||
|
||||
// Selecting and editing Markdown leaves the image visible and updates its alt text.
|
||||
await page.locator(".md-image-frame").first().hover();
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).first().click();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
||||
assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0])));
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2;
|
||||
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
|
||||
});
|
||||
await page.locator('img[alt="Edited alt"]').waitFor();
|
||||
await page.screenshot({ path: ".audit/images-editing.png" });
|
||||
await page.locator(".md-image-frame").first().hover();
|
||||
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
||||
const zoom = page.getByRole("dialog", { name: "Image zoom" });
|
||||
await zoom.waitFor();
|
||||
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
||||
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
|
||||
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
||||
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
|
||||
await page.screenshot({ path: ".audit/images-zoom.png" });
|
||||
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.getByRole("dialog").count(), 0);
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in");
|
||||
|
||||
// Undo the alt edit and the complete drop as separate operations.
|
||||
await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await source(), original);
|
||||
await page.keyboard.press("Control+y");
|
||||
assert.equal(await source(), inserted);
|
||||
|
||||
// Type and move the cursor during a slow import; the drop follows its original position.
|
||||
await page.evaluate(() => { window.__TEST__.delay = true; });
|
||||
await drop();
|
||||
await page.waitForFunction(() => !!window.__TEST__.resume);
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } });
|
||||
window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null;
|
||||
});
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3);
|
||||
assert.ok((await source()).startsWith("Typed while saving.\n\n![]"));
|
||||
|
||||
// Typed local image paths load without changing views, including wiki syntax.
|
||||
await page.evaluate(path => {
|
||||
window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]);
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } });
|
||||
}, "../attachments/typed.svg");
|
||||
await page.locator('img[alt="Wiki image"]').waitFor();
|
||||
await save();
|
||||
await page.getByRole("button", { name: "Read", exact: true }).click();
|
||||
await page.locator(".md-page .md-image-frame").first().hover();
|
||||
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
||||
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// Source mode uses the same drop flow; the batch is one undo step.
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
window.__MONACO__ = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
});
|
||||
const sourceBefore = await page.evaluate(() => window.__MONACO__.getValue());
|
||||
await drop(2, ".monaco-editor .view-lines");
|
||||
await page.waitForFunction(() => (window.__MONACO__.getValue().match(/!\[\]/g) || []).length === 5);
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore);
|
||||
await page.keyboard.press("Control+y");
|
||||
assert.equal((await save()).match(/!\[\]/g).length, 5);
|
||||
// A failed write leaves source unchanged and surfaces an error.
|
||||
const beforeFailure = await page.evaluate(() => window.__MONACO__.getValue());
|
||||
await page.evaluate(() => { window.__TEST__.failWrite = true; });
|
||||
await drop(1, ".monaco-editor .view-lines");
|
||||
await page.getByText("Image write failed", { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure);
|
||||
await page.evaluate(() => { window.__TEST__.failWrite = false; });
|
||||
|
||||
// File drops over a rendered widget are handled by the editor's capture listener.
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
await drop(1, ".md-image-frame img >> nth=0");
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6);
|
||||
|
||||
// Switching tabs while a write is pending cannot insert into the new document.
|
||||
await page.evaluate(() => { window.__TEST__.delay = true; });
|
||||
await drop();
|
||||
await page.waitForFunction(() => !!window.__TEST__.resume);
|
||||
await openNote("second.md");
|
||||
await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); });
|
||||
await page.waitForTimeout(100);
|
||||
assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/"));
|
||||
// Clipboard images are inserted and remain a single undo operation too.
|
||||
await page.locator(".cm-content").evaluate(element => {
|
||||
const data = new DataTransfer();
|
||||
data.items.add(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'], "pasted.svg", { type: "image/svg+xml" }));
|
||||
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/images-failure.png" });
|
||||
console.error(errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../src/lib/workspace/media.ts";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "../src/lib/editor/imageSource.ts";
|
||||
import { imageDrops, trackImageDrop } from "../src/lib/editor/imageDrop.ts";
|
||||
|
||||
test("same-name image imports receive distinct safe attachment paths", () => {
|
||||
const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG")));
|
||||
assert.equal(paths.size, 100);
|
||||
assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path)));
|
||||
});
|
||||
|
||||
test("protected file drags and files without MIME metadata are recognized", () => {
|
||||
assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true);
|
||||
assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false);
|
||||
const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }];
|
||||
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
|
||||
});
|
||||
|
||||
test("image batches form independent Markdown blocks without extra blank lines", () => {
|
||||
assert.equal(imageInsertion("beforeafter", 6, 6, ["", ""]), "\n\n\n\n\n\n");
|
||||
assert.equal(imageInsertion("before\n\nafter", 8, 8, [""]), "\n\n");
|
||||
assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, [""]), "\n\n");
|
||||
});
|
||||
|
||||
test("pending image drops follow intervening edits instead of the current caret", () => {
|
||||
let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] });
|
||||
const id = Symbol();
|
||||
state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state;
|
||||
state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state;
|
||||
assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 });
|
||||
});
|
||||
|
||||
test("navigator image links are relative and encode Markdown and URL punctuation", () => {
|
||||
assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "");
|
||||
assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "");
|
||||
assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "");
|
||||
});
|
||||
|
||||
test("image source is explicitly activated, tracks edits, and hides on leaving", () => {
|
||||
let state = EditorState.create({ doc: "\n\nText", extensions: [imageSource] });
|
||||
state = state.update({ selection: { anchor: 0, head: 10 } }).state;
|
||||
assert.equal(state.field(imageSource), null);
|
||||
state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state;
|
||||
state = state.update({ changes: { from: 2, insert: "Alt" } }).state;
|
||||
assert.deepEqual(state.field(imageSource), { from: 0, to: 13 });
|
||||
state = state.update({ selection: { anchor: state.doc.length } }).state;
|
||||
assert.equal(state.field(imageSource), null);
|
||||
});
|
||||
|
||||
test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => {
|
||||
const source = "``\n\nText  and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n\n```";
|
||||
assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["", "![[a b.png|Photo]]", "![ref][photo]"]);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { languageFor } from "../src/lib/editor/languageFor.ts";
|
||||
|
||||
test("markdown files use the markdown language", () => {
|
||||
assert.equal(languageFor("notes/inbox.md"), "markdown");
|
||||
assert.equal(languageFor("README.markdown"), "markdown");
|
||||
});
|
||||
|
||||
test("python and scripts use their languages", () => {
|
||||
assert.equal(languageFor("src/hello.py"), "python");
|
||||
assert.equal(languageFor("tools/setup.sh"), "shell");
|
||||
});
|
||||
|
||||
test("unknown extensions are plaintext", () => {
|
||||
assert.equal(languageFor("Makefile"), "plaintext");
|
||||
assert.equal(languageFor("notes/data.bin"), "plaintext");
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { markdownBlocks, markdownFences } from "../src/lib/workspace/markdownBlocks.ts";
|
||||
|
||||
test("fenced block with a language is one fence", () => {
|
||||
assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [
|
||||
{ type: "text", line: "hi" },
|
||||
{ type: "fence", lang: "js", body: "const x = 1" },
|
||||
{ type: "text", line: "bye" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("fenced block without a language keeps an empty lang", () => {
|
||||
assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [
|
||||
{ type: "fence", lang: "", body: "HUGE" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("inline backticks stay on a text line", () => {
|
||||
assert.deepEqual(markdownBlocks("say `HUGE` now"), [
|
||||
{ type: "text", line: "say `HUGE` now" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a fence opened and closed on one line is a fence", () => {
|
||||
assert.deepEqual(markdownBlocks("```this was a triumph```"), [
|
||||
{ type: "fence", lang: "", body: "this was a triumph" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("closed fence body is the copy payload", () => {
|
||||
assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [
|
||||
{ lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("one-line fence body excludes ticks", () => {
|
||||
assert.deepEqual(markdownFences("```this was a triumph```"), [
|
||||
{ lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("unclosed fence is not MdFence", () => {
|
||||
assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []);
|
||||
});
|
||||
|
||||
test("markdownBlocks fence body matches markdownFences", () => {
|
||||
const src = "hi\n```js\nconst x = 1\n```\nbye";
|
||||
const block = markdownBlocks(src).find((row) => row.type === "fence");
|
||||
const fence = markdownFences(src)[0];
|
||||
assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1");
|
||||
assert.equal(fence.body, "const x = 1");
|
||||
assert.equal(fence.lang, "js");
|
||||
assert.equal(fence.openLine, 2);
|
||||
assert.equal(fence.closeLine, 4);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../src/lib/editor/markdownCommands.ts";
|
||||
|
||||
const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to);
|
||||
|
||||
test("inline formatting toggles without losing surrounding prose or the selected text", () => {
|
||||
for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) {
|
||||
const source = "before words after", selection = { from: 7, to: 12 };
|
||||
const edit = formatText(source, selection, format), changed = apply(source, edit);
|
||||
assert.equal(changed.slice(edit.anchor, edit.head), "words");
|
||||
assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format);
|
||||
assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format);
|
||||
}
|
||||
assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** ");
|
||||
assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***");
|
||||
const empty = formatText("", { from: 0, to: 0 }, "bold");
|
||||
assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2);
|
||||
});
|
||||
|
||||
test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => {
|
||||
const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code");
|
||||
assert.equal(edit.insert, "``a ` b``");
|
||||
assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source);
|
||||
assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source);
|
||||
const rich = "**bold**\r\n==mark== and \\*literal\\*";
|
||||
assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*");
|
||||
assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold");
|
||||
});
|
||||
|
||||
test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => {
|
||||
const source = "before\r\n - [x] first\r\n 2. second\r\nafter";
|
||||
const selected = { from: source.indexOf("first"), to: source.indexOf("after") };
|
||||
assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter");
|
||||
assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter");
|
||||
assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three");
|
||||
assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] ");
|
||||
assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two");
|
||||
});
|
||||
|
||||
test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => {
|
||||
const source = "left right", selection = { from: 5, to: 10 };
|
||||
for (const kind of ["table", "rule"] as const) {
|
||||
const result = apply(source, insertBlock(source, selection, kind));
|
||||
assert.ok(result.startsWith(source + "\n\n"));
|
||||
}
|
||||
const code = insertBlock("```", { from: 0, to: 3 }, "code");
|
||||
assert.equal(code.insert, "````\n```\n````\n\n");
|
||||
const table = insertBlock("", { from: 0, to: 0 }, "table");
|
||||
assert.equal(table.insert.slice(table.anchor, table.head), "Column 1");
|
||||
assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n");
|
||||
});
|
||||
|
||||
test("footnotes get unique references, retain the document tail, and select the definition", () => {
|
||||
const source = "One[^1] and words.\n\n[^1]: existing\n";
|
||||
const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote");
|
||||
const changed = apply(source, edit);
|
||||
assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n");
|
||||
assert.equal(changed.slice(edit.anchor, edit.head), "words");
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { findMarkdownLinks, wikiCandidates } from "../src/lib/workspace/markdownLinks.ts";
|
||||
|
||||
test("markdown links skip image embeds", () => {
|
||||
const links = findMarkdownLinks("See [alpha](notes/a.md) and ");
|
||||
assert.deepEqual(links, [
|
||||
{ kind: "md", from: 4, to: 23, label: "alpha", target: "notes/a.md" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("wikilinks skip image embeds", () => {
|
||||
const links = findMarkdownLinks("Go [[projects/alpha|Alpha]] and ![[screenshot.png]]");
|
||||
assert.deepEqual(links, [
|
||||
{
|
||||
kind: "wiki",
|
||||
from: 3,
|
||||
to: 27,
|
||||
label: "Alpha",
|
||||
target: "projects/alpha",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("wikiCandidates add .md for a bare name", () => {
|
||||
assert.deepEqual(wikiCandidates("alpha"), ["alpha.md", "notes/alpha.md", "alpha"]);
|
||||
});
|
||||
|
||||
|
||||
import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts";
|
||||
|
||||
test("links resolve relative to notes, including parent paths and encoded spaces", () => {
|
||||
assert.deepEqual(linkCandidates("notes/project/inbox.md", "../other%20note.md", "md"), ["notes/other note.md"]);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "ideas", "wiki"), ["notes/ideas.md", "notes/ideas", "ideas.md", "ideas"]);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "../../secret", "md"), []);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "javascript:alert(1)", "md"), []);
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
async function contents() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
async function waitForText(text) {
|
||||
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
|
||||
}
|
||||
async function focusEditor() {
|
||||
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
|
||||
}
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await quickOpen("welcome.md");
|
||||
const source = "First paragraph.\n\nSecond paragraph.\n";
|
||||
await page.evaluate(async value => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
editor.setValue(value);
|
||||
editor.setSelection(new monaco.Selection(1, 1, 1, 6)); editor.focus();
|
||||
}, source);
|
||||
const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
|
||||
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
|
||||
await page.keyboard.press("Control+z"); await waitForText(source);
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await writer.click(); await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
await page.keyboard.press("Shift+F10"); await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Italic", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Heading 2", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("## First paragraph."));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Table", exact: true }).click();
|
||||
await page.locator(".live-writer table").waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
// Mouse invocation must preserve the selection, too.
|
||||
await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } });
|
||||
await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Highlight", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph."));
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.locator(".writer-highlight").waitFor();
|
||||
assert.equal(await page.locator(".writer-highlight").textContent(), "First");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await page.screenshot({ path: ".audit/markdown-insert-menu.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.setViewportSize({ width: 760, height: 600 });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
await writer.focus();
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list");
|
||||
const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox();
|
||||
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600);
|
||||
await page.screenshot({ path: ".audit/markdown-paragraph-menu.png" });
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "External link URL" }).fill("https://example.com/a(b)");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a%28b%29) paragraph."));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[[/notes/extracted.md|First]] paragraph."));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/extracted.md")), "First\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.evaluate(() => navigator.clipboard.writeText("Pasted"));
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Pasted paragraph."));
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("Pasted paragraph."));
|
||||
await page.evaluate(() => { navigator.clipboard.readText = () => new Promise(resolve => { window.__finishPaste = resolve; }); });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
|
||||
await writer.focus(); await page.keyboard.press("End"); await page.keyboard.type(" kept");
|
||||
await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); });
|
||||
assert.ok(!(await writer.textContent()).includes("STALE"));
|
||||
assert.ok((await writer.textContent()).includes("kept"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
|
||||
await page.screenshot({ path: ".audit/markdown-menu-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts";
|
||||
import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
||||
import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
|
||||
|
||||
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
|
||||
assert.equal(extractedCellMarkdown([
|
||||
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "<br>", marks: [{ type: "code" }] },
|
||||
]), "**Title**\n`<br>`");
|
||||
});
|
||||
|
||||
test("table column insertion retains alignment and existing cell contents", () => {
|
||||
assert.equal(appendTableColumn(table), "| Ticker | Notes | |\n| :--- | ---: | --- |\n| IBKR.US | First<br>Second | |");
|
||||
});
|
||||
|
||||
test("table row insertion keeps existing source byte-for-byte", () => {
|
||||
assert.equal(appendTableRow(table + "\n\n"), table + "\n| | |\n\n");
|
||||
});
|
||||
|
||||
test("table edits preserve CRLF and optional outer pipes", () => {
|
||||
const source = "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n";
|
||||
assert.equal(appendTableRow(source), "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n| | |\r\n");
|
||||
assert.equal(appendTableColumn(source), "| Name | Link | |\r\n| --- | :---: | --- |\r\n| One | [note](note.md) | |\r\n");
|
||||
});
|
||||
|
||||
test("escaped pipes in text, wiki aliases, and inline code stay inside cells", () => {
|
||||
const source = "| One | Two |\n| --- | --- |\n| [[note\\|Alias]] | `a\\|b` and text\\|value |";
|
||||
const parsed = parseMarkdownTable(source)!;
|
||||
assert.equal(parsed.rows[2].cells.length, 2);
|
||||
const changed = appendTableColumn(source);
|
||||
assert.ok(changed.includes("| [[note\\|Alias]] | `a\\|b` and text\\|value | |"));
|
||||
for (const row of parsed.rows) for (const cell of row.cells) assert.equal(source.slice(cell.from, cell.to), cell.text);
|
||||
});
|
||||
|
||||
test("adding columns pads short rows without losing extra source cells", () => {
|
||||
const source = "| A | B |\n| --- | --- |\n| short |\n| a | b | extra |";
|
||||
assert.equal(appendTableColumn(source), "| A | B | |\n| --- | --- | --- |\n| short | | |\n| a | b | | extra |");
|
||||
});
|
||||
|
||||
test("table controls handle header-only and single-column tables", () => {
|
||||
assert.equal(appendTableRow("| Header |\n| --- |"), "| Header |\n| --- |\n| |");
|
||||
assert.equal(parseMarkdownTable(appendTableColumn("| Header |\n| --- |"))?.columns, 2);
|
||||
});
|
||||
|
||||
test("invalid tables are unchanged", () => {
|
||||
for (const source of ["Just text", "| A | B |\n| --- |", "| A |\n| not a delimiter |"] ) {
|
||||
assert.equal(parseMarkdownTable(source), null);
|
||||
assert.equal(appendTableColumn(source), source);
|
||||
assert.equal(appendTableRow(source), source);
|
||||
}
|
||||
});
|
||||
|
||||
test("editing one cell preserves padding, alignment, other cells and CRLF", () => {
|
||||
const source = " | Name | Notes |\r\n | :--- | ---: |\r\n | One | first<br />~~old~~ |\r\n\r\nTail";
|
||||
assert.equal(replaceTableCell(source, 2, 1, "next<br>line\\|pipe"), source.replace("first<br />~~old~~", "next<br>line\\|pipe"));
|
||||
assert.equal(replaceTableCell(source, 0, 0, "Title"), source.replace("Name", "Title"));
|
||||
assert.equal(replaceTableCell(source, 1, 0, "bad"), source);
|
||||
assert.equal(replaceTableCell(source, 2, 1, "break\nrow"), source);
|
||||
});
|
||||
|
||||
test("editing an empty or omitted cell does not overwrite its neighbor", () => {
|
||||
assert.equal(replaceTableCell("| A | B |\n| --- | --- |\n| short |", 2, 1, "new"), "| A | B |\n| --- | --- |\n| short | new |");
|
||||
const source = "| A | B |\n| --- | --- |\n| | value |";
|
||||
assert.equal(replaceTableCell(source, 2, 0, "new"), source.replace("| | value", "| new| value"));
|
||||
});
|
||||
|
||||
test("rich cell serialization retains breaks, formatting, links and literal punctuation", () => {
|
||||
const text = tableCellMarkdown({ type: "doc", content: [{ type: "paragraph", content: [
|
||||
{ type: "text", text: "old", marks: [{ type: "strike" }] },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "bold", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " | *literal* <br> & value" },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "a|`b", marks: [{ type: "code" }] },
|
||||
{ type: "text", text: "note", marks: [{ type: "link", attrs: { href: "note.md", "data-kind": "wiki" } }] },
|
||||
{ type: "text", text: "web", marks: [{ type: "link", attrs: { href: "https://example.com/a(b)" } }] },
|
||||
] }, { type: "paragraph", content: [{ type: "text", text: "Pasted paragraph" }] }] });
|
||||
const source = `| A |\n| --- |\n| ${text} |`;
|
||||
assert.equal(parseMarkdownTable(source)?.rows[2].cells.length, 1);
|
||||
const html = renderMarkdownHtml(source, new Map());
|
||||
assert.ok(html.includes("<s>old</s>"));
|
||||
assert.ok(html.includes("<strong>bold</strong>"));
|
||||
assert.ok(html.includes("| *literal* <br> & value"));
|
||||
assert.ok(html.includes("<code>a|`b</code>"));
|
||||
assert.ok(html.includes('href="note.md" data-kind="wiki"'));
|
||||
assert.ok(html.includes('href="https://example.com/a(b)"'));
|
||||
assert.equal((html.match(/<br>/g) || []).length, 3);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
findMarkdownImages,
|
||||
isImagePath,
|
||||
isRemoteImage,
|
||||
resolveImageRel,
|
||||
} from "../src/lib/workspace/media.ts";
|
||||
|
||||
test("image paths are detected by extension", () => {
|
||||
assert.equal(isImagePath("screenshot.png"), true);
|
||||
assert.equal(isImagePath("notes/photo.JPEG"), true);
|
||||
assert.equal(isImagePath("notes/inbox.md"), false);
|
||||
});
|
||||
|
||||
test("markdown image syntax is parsed", () => {
|
||||
const found = findMarkdownImages("See  and ![[screenshot.png|Hero]]");
|
||||
assert.equal(found.length, 2);
|
||||
assert.equal(found[0].src, "../shot.png");
|
||||
assert.equal(found[0].kind, "md");
|
||||
assert.equal(found[1].src, "screenshot.png");
|
||||
assert.equal(found[1].alt, "Hero");
|
||||
assert.equal(found[1].kind, "wiki");
|
||||
});
|
||||
|
||||
test("image paths resolve from the note folder", () => {
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png");
|
||||
});
|
||||
|
||||
test("remote images stay as URLs", () => {
|
||||
assert.equal(isRemoteImage("https://example.com/a.png"), true);
|
||||
assert.equal(isRemoteImage("screenshot.png"), false);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
|
||||
|
||||
test("headings and inline marks become markdown", () => {
|
||||
const html =
|
||||
"<h1>Heading 1</h1><h2>Heading 2</h2><p>hello <strong>bold</strong> and <code>code</code></p>";
|
||||
assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`");
|
||||
});
|
||||
|
||||
test("fences keep language and body", () => {
|
||||
const html = '<pre class="md-code" data-lang="js"><code class="language-js">const x = 1</code></pre>';
|
||||
assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```");
|
||||
});
|
||||
|
||||
test("wiki and markdown links become markdown", () => {
|
||||
const html =
|
||||
'<p>see <a class="wiki" href="projects/alpha" data-kind="wiki">projects/alpha</a> and <a href="notes/a.md" data-kind="md">label</a></p>';
|
||||
assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)");
|
||||
});
|
||||
|
||||
test("wiki image uses data-md-kind", () => {
|
||||
const html =
|
||||
'<p><img src="data:image/png;base64,xx" alt="screenshot.png" data-md-src="screenshot.png" data-md-kind="wiki" /></p>';
|
||||
assert.equal(htmlToMarkdown(html), "![[screenshot.png]]");
|
||||
});
|
||||
|
||||
test("strike super and sub become markdown", () => {
|
||||
const html = "<p><s>old</s> x<sup>2</sup> a<sub>n</sub></p>";
|
||||
assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~");
|
||||
});
|
||||
|
||||
test("gfm table becomes markdown", () => {
|
||||
const html =
|
||||
"<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>";
|
||||
assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |");
|
||||
});
|
||||
|
||||
test("checked task item becomes a checkbox line", () => {
|
||||
const html =
|
||||
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>done</p></li></ul>';
|
||||
assert.equal(htmlToMarkdown(html), "- [x] done");
|
||||
});
|
||||
|
||||
test("unchecked task item becomes an empty checkbox", () => {
|
||||
const html =
|
||||
'<ul data-type="taskList"><li data-type="taskItem" data-checked="false"><p>todo</p></li></ul>';
|
||||
assert.equal(htmlToMarkdown(html), "- [ ] todo");
|
||||
});
|
||||
|
||||
test("italic highlight math and comment become markdown", () => {
|
||||
const html =
|
||||
'<p><em>hi</em> <mark>glow</mark> <span data-math="1">x^2</span> <span data-comment="1">note</span></p>';
|
||||
assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%");
|
||||
});
|
||||
|
||||
test("blockquote and numbered list become markdown", () => {
|
||||
const html = "<blockquote><p>said</p></blockquote><ol><li>one</li><li>two</li></ol>";
|
||||
assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two");
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const render = (text: string) => renderMarkdownHtml(text, new Map());
|
||||
|
||||
test("writing sections retain exact source ranges and document-wide references", () => {
|
||||
const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n';
|
||||
const sections = renderMarkdownSections(source, new Map());
|
||||
assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source);
|
||||
assert.equal(sections.length, 4);
|
||||
assert.match(sections[2].html, /<ul>[\s\S]*<ul>/);
|
||||
assert.match(sections[3].html, /href="https:\/\/example.com"/);
|
||||
const paragraph = sections[3];
|
||||
const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end);
|
||||
assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start));
|
||||
});
|
||||
|
||||
test("writing exposes empty and reference-only documents for editing", () => {
|
||||
for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) {
|
||||
assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]);
|
||||
}
|
||||
});
|
||||
|
||||
test("Mermaid fences render diagram containers with escaped, copyable source", () => {
|
||||
const html = render('```mermaid\nflowchart LR\n A["<script>bad</script>"] --> B\n```');
|
||||
assert.match(html, /class="md-mermaid"/);
|
||||
assert.match(html, /aria-label="Mermaid diagram"/);
|
||||
assert.match(html, /<summary>Diagram source<\/summary>/);
|
||||
assert.match(html, /<script>bad<\/script>/);
|
||||
assert.doesNotMatch(html, /<script>/);
|
||||
assert.doesNotMatch(render('```js\nconst x = 1;\n```'), /md-mermaid/);
|
||||
});
|
||||
|
||||
test("reader joins soft-wrapped lines and preserves paragraph boundaries", () => {
|
||||
assert.equal(render("First line\ncontinues here.\n\nSecond paragraph."), "<p>First line\ncontinues here.</p>\n<p>Second paragraph.</p>\n");
|
||||
assert.match(render("Hard break \nnext line"), /Hard break<br>\nnext line/);
|
||||
});
|
||||
|
||||
test("reader preserves nested lists, ordered starts and multi-paragraph items", () => {
|
||||
const html = render("7. Parent\n - Nested **item**\n - Other\n8. Next\n\n Another paragraph.\n");
|
||||
assert.match(html, /<ol start="7">/);
|
||||
assert.match(html, /<li>\n<p>Parent<\/p>\n<ul>\n<li>Nested <strong>item<\/strong><\/li>/);
|
||||
assert.match(html, /<p>Next<\/p>\n<p>Another paragraph\.<\/p>/);
|
||||
});
|
||||
|
||||
test("reader renders aligned tables and read-only nested tasks", () => {
|
||||
const html = render("| Left | Right |\n| :--- | ---: |\n| **a** | 2 |\n\n- [x] Done\n - [ ] Nested\n");
|
||||
assert.match(html, /class="md-table-scroll"><table>/);
|
||||
assert.match(html, /<th style="text-align:right">Right<\/th>/);
|
||||
assert.equal((html.match(/type="checkbox" disabled/g) || []).length, 2);
|
||||
assert.equal((html.match(/ checked>/g) || []).length, 1);
|
||||
assert.doesNotMatch(html, /\[x\]|\[ \]/);
|
||||
});
|
||||
|
||||
test("reader keeps code literal and escapes embedded HTML", () => {
|
||||
const html = render('```js\nconst text = "[[note]] **bold** <script>alert(1)</script>";\n```\n\n`[[literal]]`\n\n<img src=x onerror=alert(1)>');
|
||||
assert.match(html, /aria-label="Copy code"/);
|
||||
assert.match(html, /\[\[note\]\] \*\*bold\*\* <script>/);
|
||||
assert.match(html, /<code>\[\[literal\]\]<\/code>/);
|
||||
assert.doesNotMatch(html, /<script>|<img|class="wiki"|<strong>/);
|
||||
});
|
||||
|
||||
test("table cell line breaks render without enabling arbitrary HTML", () => {
|
||||
const html = render('| Notes |\n| --- |\n| First<br>Second<BR />Third<br/>Fourth |');
|
||||
assert.match(html, /First<br>\nSecond<br>\nThird<br>\nFourth/);
|
||||
assert.doesNotMatch(html, /<br/i);
|
||||
assert.match(render('`<br>`'), /<code><br><\/code>/);
|
||||
assert.doesNotMatch(render('<br onclick="alert(1)">'), /<br /);
|
||||
});
|
||||
|
||||
test("frontmatter is collapsed separately from document headings", () => {
|
||||
const html = render("\uFEFF---\r\ntitle: Notes\r\ntags: [work]\r\n---\r\n# Document\n");
|
||||
assert.match(html, /^<details class="md-properties"><summary>Properties<\/summary><pre>title: Notes/);
|
||||
assert.match(html, /<h1>Document<\/h1>/);
|
||||
assert.doesNotMatch(html, /<h2>|<hr>|details[^>]*open/);
|
||||
assert.match(render("---\n\nOrdinary rule"), /^<hr>/);
|
||||
});
|
||||
|
||||
test("wiki links, aliases and reference images retain their targets", () => {
|
||||
const source = 'See [[notes/one|First note]] and [second](second.md).\n\n![A **diagram**][diagram]\n\n![[assets/screenshot.png|Screenshot]]\n\n[diagram]: assets/my%20diagram.png "Diagram"\n';
|
||||
const urls = new Map([['assets/my%20diagram.png', 'data:image/png;base64,AA=='], ['assets/screenshot.png', 'data:image/png;base64,BB==']]);
|
||||
const html = renderMarkdownHtml(source, urls);
|
||||
assert.match(html, /href="notes\/one" data-kind="wiki" class="wiki">First note/);
|
||||
assert.match(html, /href="second.md" data-kind="md"/);
|
||||
assert.match(html, /alt="A diagram"/);
|
||||
assert.match(html, /data-md-kind="wiki"/);
|
||||
assert.deepEqual(markdownImages(source + '\n`![[ignored.png]]`\n\n```\n\n```'), ['assets/my%20diagram.png', 'assets/screenshot.png']);
|
||||
});
|
||||
|
||||
test("reader rejects executable links and image URL injection", () => {
|
||||
const html = render('[bad](javascript:alert%281%29) [[javascript:alert(1)]] ');
|
||||
assert.doesNotMatch(html, /<a |<img /);
|
||||
const image = renderMarkdownHtml('![[safe.png]]', new Map([['safe.png', 'javascript:alert(1)']]));
|
||||
assert.match(image, /Image unavailable/);
|
||||
});
|
||||
|
||||
test("note callouts separate their title from the Markdown body", () => {
|
||||
const html = render('> [!tip] Keep context close\n> Use **notes** beside code.\n>\n> A second paragraph.');
|
||||
assert.match(html, /class="md-callout" data-callout="tip"/);
|
||||
assert.match(html, /class="md-callout-title">Keep context close<\/strong>Use <strong>notes<\/strong>/);
|
||||
assert.match(html, /<p>A second paragraph\.<\/p>/);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { planRename, planTitleRename, planMarkdownTitleRename } from "../src/lib/workspace/renamePath.ts";
|
||||
|
||||
test("rename in a folder keeps the parent", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "b.md"), {
|
||||
action: "rename",
|
||||
to: "notes/b.md",
|
||||
});
|
||||
});
|
||||
|
||||
test("same name is a no-op", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "a.md"), { action: "noop" });
|
||||
});
|
||||
|
||||
test("path separators are rejected", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "foo/bar"), {
|
||||
action: "error",
|
||||
message: "Name cannot contain a path separator",
|
||||
});
|
||||
assert.deepEqual(planRename("notes/a.md", "foo\\bar"), {
|
||||
action: "error",
|
||||
message: "Name cannot contain a path separator",
|
||||
});
|
||||
});
|
||||
|
||||
test("empty name is rejected", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", " "), {
|
||||
action: "error",
|
||||
message: "Name is empty",
|
||||
});
|
||||
});
|
||||
|
||||
test("root file rename stays at the root", () => {
|
||||
assert.deepEqual(planRename("inbox.md", "todo.md"), {
|
||||
action: "rename",
|
||||
to: "todo.md",
|
||||
});
|
||||
});
|
||||
|
||||
test("title rename keeps the existing extension", () => {
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "hello"), {
|
||||
action: "rename",
|
||||
to: "notes/hello.md",
|
||||
});
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
|
||||
});
|
||||
|
||||
test("title rename keeps a typed extension", () => {
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "hello.txt"), {
|
||||
action: "rename",
|
||||
to: "notes/hello.txt",
|
||||
});
|
||||
});
|
||||
|
||||
test("writing titles preserve Markdown extensions and allow dots in names", () => {
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "Release 1.2"), { action: "rename", to: "notes/Release 1.2.md" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.MD", " Renamed.md "), { action: "rename", to: "notes/Renamed.MD" });
|
||||
assert.deepEqual(planMarkdownTitleRename("inbox.markdown", "Renamed"), { action: "rename", to: "Renamed.markdown" });
|
||||
assert.deepEqual(planMarkdownTitleRename("inbox.mdown", "Renamed"), { action: "rename", to: "Renamed.mdown" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md.md", "inbox.md"), { action: "noop" });
|
||||
for (const name of ["", " ", ".md", "../escape", "folder/note", "folder\\note"]) {
|
||||
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_rename") {
|
||||
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
|
||||
if (!files.has(args.from)) throw new Error("File is missing");
|
||||
if (files.has(args.to)) throw new Error("A file with that name already exists");
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function openNote(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.getByRole("button", { name: "Rename note", exact: true }).waitFor();
|
||||
}
|
||||
const title = page.getByRole("button", { name: "Rename note", exact: true });
|
||||
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
async function editTitle(value) { await title.click(); await input.fill(value); }
|
||||
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await openNote("welcome.md");
|
||||
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
|
||||
await writer.click();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Unsaved text");
|
||||
await editTitle("Release 1.2");
|
||||
await input.press("Enter");
|
||||
await renamed("notes/Release 1.2.md");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
|
||||
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
|
||||
await page.locator('.tree').getByText("notes", { exact: true }).click();
|
||||
await page.locator('.tree').getByText("Release 1.2", { exact: true }).waitFor();
|
||||
await writer.click();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
|
||||
|
||||
await editTitle("Cancelled");
|
||||
await input.press("Escape");
|
||||
await renamed("notes/Release 1.2.md");
|
||||
assert.equal(await input.isVisible(), false);
|
||||
// Keyboard activation and filename errors stay outside Markdown editing.
|
||||
await title.focus(); await title.press("Enter");
|
||||
await input.fill(" "); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "Name is empty" }).waitFor();
|
||||
await input.fill("folder/note"); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "path separator" }).waitFor();
|
||||
await input.fill("second"); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
|
||||
assert.equal(await input.inputValue(), "second");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
|
||||
await input.fill("Renamed.md"); await input.press("Tab");
|
||||
await renamed("notes/Renamed.md");
|
||||
await page.mouse.move(10, 10);
|
||||
await page.screenshot({ path: ".audit/rename-title.png" });
|
||||
|
||||
// A pending rename belongs to its original document even if the tab changes.
|
||||
await page.evaluate(() => { window.__TEST__.delayRename = true; });
|
||||
await editTitle("Background"); await input.press("Enter");
|
||||
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
|
||||
await page.locator('.tree').getByText("second", { exact: true }).click();
|
||||
await renamed("notes/second.md");
|
||||
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
|
||||
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
|
||||
await renamed("notes/second.md");
|
||||
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
|
||||
await renamed("notes/Background.md");
|
||||
// Disk reload after rename must not restore the old displayed title.
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
|
||||
assert.ok((await title.innerText()).startsWith("Background"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: inline filename rename, folder/extension preservation, tabs/tree, contents and undo, Enter/blur/Escape, validation/collisions, tab switching during rename, and reload (mocked desktop IPC).");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
|
||||
await page.screenshot({ path: ".audit/rename-title-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,148 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function open(name) {
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
|
||||
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
|
||||
}
|
||||
async function settle() {
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function roundTrip(selector, label) {
|
||||
const scroller = page.locator(selector);
|
||||
const position = async (top) => label === 'IDE'
|
||||
? page.evaluate(async top => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
|
||||
if (top !== undefined) editor.setScrollTop(top, 1);
|
||||
return editor.getScrollTop();
|
||||
}, top)
|
||||
: scroller.evaluate((el, top) => {
|
||||
if (top !== undefined) el.scrollTop = top;
|
||||
return el.scrollTop;
|
||||
}, top);
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(1800);
|
||||
await settle();
|
||||
const first = await position();
|
||||
assert.ok(first > 1000, `${label}: first document is scrollable`);
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(650);
|
||||
await settle();
|
||||
const second = await position();
|
||||
for (let repeat = 0; repeat < 2; repeat++) {
|
||||
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
|
||||
await page.getByRole('tab', { name, exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
const actual = await position();
|
||||
assert.ok(Math.abs(actual - expected) < 5, `${label}: ${name} expected ${expected}, got ${actual}`);
|
||||
}
|
||||
}
|
||||
console.log(`PASS: ${label} retains independent tab scroll positions`);
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(() => {
|
||||
for (const name of ['scroll-a.md', 'scroll-b.md']) {
|
||||
window.__TEST__.files.set(name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join(''));
|
||||
}
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['scroll-a.md', 'scroll-b.md'] });
|
||||
});
|
||||
await open('scroll-b.md');
|
||||
await open('scroll-a.md');
|
||||
if (await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).count()) {
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
}
|
||||
await roundTrip('.cm-scroller', 'Writing');
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Reading');
|
||||
await page.getByRole('button', { name: 'Split', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Split preview');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
await roundTrip('.monaco-scrollable-element', 'IDE');
|
||||
assert.deepEqual(errors, []);
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
console.error((await page.locator('body').innerText()).slice(-2000));
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,234 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
|
||||
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
|
||||
const headers = () => table.locator('th').allTextContents();
|
||||
async function grip(axis, index) {
|
||||
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
|
||||
await handle.scrollIntoViewIfNeeded();
|
||||
const rect = await handle.boundingBox();
|
||||
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
|
||||
await page.mouse.down();
|
||||
}
|
||||
async function target(axis, index, after = false) {
|
||||
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
|
||||
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
|
||||
}
|
||||
async function save() {
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
|
||||
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('drag.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
|
||||
}, source);
|
||||
await quickOpen('drag.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
await table.waitFor();
|
||||
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
|
||||
await page.mouse.move(5, 5);
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
|
||||
const firstGrip = page.locator('.table-drag-row[data-index="1"]');
|
||||
await firstGrip.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '1');
|
||||
assert.equal(await page.locator('.table-drag-row[data-index="2"]').evaluate(el => getComputedStyle(el).opacity), '0');
|
||||
await page.mouse.move(5, 5);
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '0');
|
||||
await grip('row', 1);
|
||||
assert.equal(await page.locator('.table-drag-preview').count(), 0);
|
||||
await target('row', 2, true);
|
||||
const preview = page.locator('.table-drag-preview');
|
||||
await preview.waitFor();
|
||||
assert.match(await preview.innerText(), /Alpha/);
|
||||
assert.equal(await preview.getAttribute('aria-hidden'), 'true');
|
||||
assert.equal(await preview.evaluate(el => getComputedStyle(el).pointerEvents), 'none');
|
||||
const initialPreview = await preview.boundingBox();
|
||||
await target('row', 4, true);
|
||||
assert.ok((await preview.boundingBox()).y > initialPreview.y + 20);
|
||||
assert.equal(await preview.locator('.table-drag-preview-label').innerText(), 'Row 2 → 5');
|
||||
assert.equal(await table.locator('.is-cell-selected').count(), 3);
|
||||
await page.locator('.table-drop-indicator:visible').waitFor();
|
||||
await page.screenshot({ path: '.audit/table-drag-row.png' });
|
||||
await page.mouse.up();
|
||||
assert.equal(await preview.count(), 0);
|
||||
await page.mouse.move(5, 5);
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
|
||||
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
|
||||
await save();
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| Delta | 40 | Four |\n| Alpha'));
|
||||
await page.keyboard.press('Control+z');
|
||||
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
|
||||
await page.keyboard.press('Control+y');
|
||||
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
|
||||
await grip('row', 4); await target('row', 1); await page.mouse.up();
|
||||
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
|
||||
await grip('column', 0); await target('column', 2, true);
|
||||
assert.deepEqual(await preview.locator('tr').allTextContents(), ['Name', 'Alpha', 'Beta', 'Gamma', 'Delta']);
|
||||
await page.locator('.table-drop-indicator:visible').waitFor();
|
||||
await page.screenshot({ path: '.audit/table-drag-column.png' });
|
||||
await page.mouse.up();
|
||||
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
|
||||
await save();
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| ---: | :---: | :--- |'));
|
||||
await grip('column', 2); await target('column', 0); await page.mouse.up();
|
||||
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
|
||||
// Cancel, out-of-table drop, and click without a drag must not change source.
|
||||
await grip('row', 1); await target('row', 4, true); await page.keyboard.press('Escape'); await page.mouse.up();
|
||||
assert.equal(await preview.count(), 0);
|
||||
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
|
||||
await grip('row', 1); await page.mouse.move(5, 5, { steps: 5 }); await page.mouse.up();
|
||||
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
|
||||
await grip('column', 0); await page.mouse.up();
|
||||
assert.equal(await preview.count(), 0);
|
||||
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
|
||||
// The focused grip offers the same operation to keyboard users.
|
||||
// Tab into the handle, rather than leaving mouse focus on it.
|
||||
await page.locator('.table-add-row').focus();
|
||||
await page.keyboard.press('Tab');
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 1');
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-column[data-index="0"]')).opacity === '1');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
assert.deepEqual(await headers(), ['Value', 'Name', 'Notes']);
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 2');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
|
||||
// Editing a cell before dragging must commit its latest contents.
|
||||
await table.locator('tbody tr').first().locator('td').first().click();
|
||||
await page.keyboard.press('Control+End'); await page.keyboard.type(' edited');
|
||||
await grip('row', 1); await target('row', 4, true); await page.mouse.up();
|
||||
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha edited']);
|
||||
await page.keyboard.press('Control+z');
|
||||
assert.deepEqual(await rows(), ['Alpha edited', 'Beta', 'Gamma', 'Delta']);
|
||||
// Keep column handles aligned when a narrow table viewport scrolls.
|
||||
await page.setViewportSize({ width: 760, height: 700 });
|
||||
await table.locator('th').first().scrollIntoViewIfNeeded();
|
||||
await grip('column', 0);
|
||||
const viewport = await page.locator('.writer-table .md-table-scroll').boundingBox();
|
||||
await page.mouse.move(viewport.x + viewport.width - 2, viewport.y + 15, { steps: 8 });
|
||||
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft > 0; });
|
||||
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft + el.clientWidth >= el.scrollWidth - 2; });
|
||||
await target('column', 2, true); await page.mouse.up();
|
||||
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
|
||||
await page.screenshot({ path: '.audit/table-drag-narrow.png' });
|
||||
// Long tables scroll the document while the pointer stays at its lower edge.
|
||||
await page.setViewportSize({ width: 1440, height: 700 });
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set('long.md', '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n');
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
|
||||
});
|
||||
await quickOpen('long.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
await table.waitFor();
|
||||
await grip('row', 1);
|
||||
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
|
||||
const first = await table.locator('tr').nth(1).boundingBox();
|
||||
await page.mouse.move(first.x + 20, scroller.y + scroller.height - 5, { steps: 8 });
|
||||
await page.waitForFunction(() => {
|
||||
const last = document.querySelector('.live-writer table tbody tr:last-child').getBoundingClientRect();
|
||||
const viewport = document.querySelector('.live-writer .cm-scroller').getBoundingClientRect();
|
||||
return last.bottom < viewport.bottom - 20;
|
||||
});
|
||||
await target('row', 30, true);
|
||||
await page.mouse.up();
|
||||
assert.equal((await rows()).at(-1), 'Item 1');
|
||||
assert.equal((await rows())[0], 'Item 2');
|
||||
await page.keyboard.press('Control+z');
|
||||
assert.equal((await rows())[0], 'Item 1');
|
||||
await grip('row', 2); await target('row', 3, true);
|
||||
await page.locator('.table-drag-row[data-index="2"]').dispatchEvent('pointercancel');
|
||||
await page.mouse.up();
|
||||
assert.equal((await rows())[1], 'Item 2');
|
||||
assert.equal(await page.locator('.is-table-dragging').count(), 0);
|
||||
assert.equal(await preview.count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: hover/focus grips, pointer-following previews and cleanup, row/column drag in both directions, indicators, alignment, undo/redo, cancellation, keyboard movement, active edits, horizontal and vertical auto-scroll.');
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
await page.screenshot({ path: '.audit/table-drag-failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,187 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
|
||||
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
const edit = page.locator('.writer-cell-editor');
|
||||
const result = (r, c) => cell(r, c).locator('.md-table-formula');
|
||||
async function save() {
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
|
||||
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('formulas.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
|
||||
}, source);
|
||||
await quickOpen('formulas.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
await table.waitFor();
|
||||
assert.equal(await result(1, 3).innerText(), '9.5');
|
||||
assert.equal(await result(3, 3).innerText(), '17.5');
|
||||
await cell(1, 3).click();
|
||||
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
|
||||
await edit.fill('=AVERAGE(B2+C2)');
|
||||
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 19');
|
||||
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
|
||||
await edit.fill('=AVERAGE(B2,C2)');
|
||||
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
|
||||
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
|
||||
await edit.fill('=AVERAGE(B2:C2)');
|
||||
await page.keyboard.press('Enter');
|
||||
await cell(1, 1).click();
|
||||
await edit.fill('5');
|
||||
assert.equal(await result(1, 3).innerText(), '7.5');
|
||||
assert.equal(await result(3, 3).innerText(), '15.5');
|
||||
await page.keyboard.press('Tab');
|
||||
await cell(1, 3).click();
|
||||
assert.equal(await edit.innerText(), '=AVERAGE(B2:C2)');
|
||||
assert.match(await page.locator('.table-formula-status').innerText(), /D2/);
|
||||
await edit.fill('=B2*C2');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await result(1, 3).innerText(), '50');
|
||||
assert.equal(await result(3, 3).innerText(), '58');
|
||||
assert.match(await save(), /\| =B2\*C2 \|/);
|
||||
await cell(1, 3).click();
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=AVERAGE(B2:C2)');
|
||||
assert.equal(await result(3, 3).innerText(), '15.5');
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=B2*C2');
|
||||
assert.equal(await result(3, 3).innerText(), '58');
|
||||
await cell(2, 3).click();
|
||||
await edit.fill('=D3');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await result(2, 3).innerText(), '#CYCLE!');
|
||||
assert.equal(await result(3, 3).innerText(), '#CYCLE!');
|
||||
await cell(2, 3).click();
|
||||
await edit.fill('=AVERAGE(B3:C3)');
|
||||
await page.keyboard.press('Tab');
|
||||
await cell(3, 1).click();
|
||||
await edit.fill('=SUM(B2:B3)');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await result(3, 1).innerText(), '12');
|
||||
const saved = await save();
|
||||
assert.match(saved, /=SUM\(B2:B3\)/);
|
||||
assert.doesNotMatch(saved, /\\=/);
|
||||
// Footer controls share one normal-flow block aligned to the table at any width.
|
||||
async function checkFooter() {
|
||||
const geometry = await page.evaluate(() => {
|
||||
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
|
||||
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
|
||||
});
|
||||
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
|
||||
assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
|
||||
assert.ok(geometry.footer.y >= geometry.table.bottom);
|
||||
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
|
||||
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
|
||||
assert.ok(geometry.help.right <= geometry.footer.right + 1);
|
||||
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
|
||||
}
|
||||
await cell(3, 1).click();
|
||||
await checkFooter();
|
||||
await page.screenshot({ path: '.audit/table-formula-footer.png' });
|
||||
await page.setViewportSize({ width: 850, height: 1000 });
|
||||
await checkFooter();
|
||||
await page.screenshot({ path: '.audit/table-formula-footer-narrow.png' });
|
||||
await page.locator('.table-formula-help summary').click();
|
||||
assert.equal(await page.locator('.table-formula-help').getAttribute('open'), '');
|
||||
await checkFooter();
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.screenshot({ path: '.audit/table-formulas.png' });
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
assert.equal(await result(3, 1).innerText(), '12');
|
||||
assert.equal(await result(3, 3).innerText(), '58');
|
||||
for (const mode of ['Read', 'Split']) {
|
||||
await page.getByRole('button', { name: mode, exact: true }).click();
|
||||
const preview = page.locator('.md-page table').first();
|
||||
await preview.waitFor();
|
||||
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: live recalculation, raw formula editing, Enter/Tab, undo/redo, cycle recovery, Markdown saves, help, remount, Read, and Split');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,92 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { cellAddress, evaluateTableFormulas } from "../src/lib/editor/tableFormulas.ts";
|
||||
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
||||
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
|
||||
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
|
||||
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
|
||||
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
|
||||
for (const separator of [",", ":"]) {
|
||||
const result = evaluate(`=${name}(B2${separator}C2)`);
|
||||
assert.equal(result.text, separate);
|
||||
}
|
||||
const result = evaluate(`=${name}(B2+C2)`);
|
||||
assert.equal(result.text, combined);
|
||||
}
|
||||
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
|
||||
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
|
||||
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
|
||||
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
|
||||
});
|
||||
|
||||
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
|
||||
for (const [formula, result] of [
|
||||
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
|
||||
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
|
||||
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
|
||||
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
|
||||
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
|
||||
]) assert.equal(calculate(formula), result, formula);
|
||||
});
|
||||
|
||||
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
|
||||
const results = evaluateTableFormulas([
|
||||
["Name", "Appearance", "Cha", "Combined"],
|
||||
["First", "9", "10", "=AVERAGE(B2:C2)"],
|
||||
["Second", "7", "9", "=SUM(B3,C3)/2"],
|
||||
["Total", "", "=B4+1", "=SUM(D2:D3)"],
|
||||
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
|
||||
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
|
||||
]);
|
||||
assert.equal(results[1][3]?.text, "9.5");
|
||||
assert.equal(results[2][3]?.text, "8");
|
||||
assert.equal(results[3][3]?.text, "17.5");
|
||||
assert.equal(results[3][2]?.text, "1");
|
||||
assert.equal(results[4][1]?.text, "5");
|
||||
assert.equal(results[4][2]?.text, "3");
|
||||
assert.equal(results[4][3]?.text, "5.83");
|
||||
assert.equal(results[5][1]?.text, "35");
|
||||
assert.equal(results[5][2]?.text, "8");
|
||||
assert.equal(results[5][3]?.text, "35");
|
||||
assert.equal(results[0][0], null);
|
||||
assert.equal(cellAddress(1, 26), "AA2");
|
||||
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
|
||||
});
|
||||
|
||||
test("errors are visible, propagated, bounded, and never executed", () => {
|
||||
for (const [formula, result] of [
|
||||
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
|
||||
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
|
||||
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
|
||||
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
|
||||
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
|
||||
]) assert.equal(calculate(formula), result, formula);
|
||||
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
|
||||
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
|
||||
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
|
||||
});
|
||||
|
||||
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
|
||||
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
|
||||
const html = renderMarkdownHtml(source, new Map());
|
||||
assert.match(html, /aria-label="=AVERAGE\(A2:B2\) → 9.5">9.5<\/span>/);
|
||||
assert.match(html, /aria-label="=A2\*B2 → 3">3<\/span>/);
|
||||
const sections = renderMarkdownSections(source, new Map());
|
||||
assert.equal(sections.map(s => source.slice(s.start, s.end)).join(""), source);
|
||||
assert.equal(sections.map(s => s.html).join(""), html);
|
||||
const literal = renderMarkdownHtml("=1+2\n\n| A | B | C |\n| --- | --- | --- |\n| `=1+2` | \\=1+2 | ==highlight== |", new Map());
|
||||
assert.doesNotMatch(literal, /md-table-formula/);
|
||||
assert.match(literal, /<mark>highlight<\/mark>/);
|
||||
const hostile = renderMarkdownHtml('| A |\n| --- |\n| ="<img src=x onerror=alert(1)>" |', new Map());
|
||||
assert.doesNotMatch(hostile, /<img/);
|
||||
assert.match(hostile, /#ERROR!/);
|
||||
});
|
||||
|
||||
test("editing keeps formulas readable and code or explicit escapes literal", () => {
|
||||
const doc = (text: string, marks?: { type: string }[]) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text, marks }] }] });
|
||||
assert.equal(tableCellMarkdown(doc("=SUM($B$2:C2)*50%")), "=SUM($B$2:C2)*50%");
|
||||
assert.equal(tableCellMarkdown(doc("\\=1+2")), "\\=1+2");
|
||||
assert.equal(tableCellMarkdown(doc("=1+2", [{ type: "code" }])), "`=1+2`");
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
|
||||
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
const edit = page.locator('.writer-cell-editor');
|
||||
async function expectCell(r, c) {
|
||||
await page.waitForFunction(({ r, c }) => {
|
||||
const active = document.activeElement;
|
||||
const cell = active?.closest('th, td');
|
||||
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
|
||||
}, { r, c });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function at(r, c, edge = 'End') {
|
||||
await cell(r, c).click();
|
||||
// ProseMirror guards native selections at the start for 200ms after focus.
|
||||
await page.waitForTimeout(220);
|
||||
await page.keyboard.press(`Control+${edge}`);
|
||||
await expectCell(r, c);
|
||||
}
|
||||
async function arrow(key, r, c) {
|
||||
await page.keyboard.press(key);
|
||||
await expectCell(r, c);
|
||||
}
|
||||
async function expectProse(after) {
|
||||
await page.waitForFunction(after => {
|
||||
const content = document.querySelector('.live-writer .cm-content');
|
||||
const table = content?.querySelector('table');
|
||||
const caret = document.getSelection()?.focusNode;
|
||||
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
|
||||
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
|
||||
}, after);
|
||||
}
|
||||
async function caret() {
|
||||
return edit.evaluate(el => {
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.setEnd(selection.focusNode, selection.focusOffset);
|
||||
return { offset: range.toString().length, selected: selection.toString() };
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('navigation.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['navigation.md'] });
|
||||
}, source);
|
||||
await quickOpen('navigation.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
await table.waitFor();
|
||||
|
||||
// Reproduce the reported right-arrow escape, including formula destinations.
|
||||
await at(1, 0);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
assert.equal((await caret()).offset, 1);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
await arrow('ArrowRight', 1, 2);
|
||||
assert.equal(await edit.innerText(), '=B2*2');
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await arrow('ArrowLeft', 1, 1);
|
||||
assert.equal((await caret()).offset, 2);
|
||||
await arrow('ArrowLeft', 1, 1);
|
||||
assert.equal((await caret()).offset, 1);
|
||||
|
||||
// Repeated native arrows can arrive before selectionchange is delivered.
|
||||
await at(1, 1, 'Home');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectCell(1, 2);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
|
||||
// Row wrapping, empty cells, and header/body transitions.
|
||||
await at(1, 2);
|
||||
await arrow('ArrowRight', 2, 0);
|
||||
await arrow('ArrowLeft', 1, 2);
|
||||
await at(2, 0);
|
||||
await arrow('ArrowRight', 2, 1);
|
||||
await arrow('ArrowRight', 2, 2);
|
||||
await arrow('ArrowLeft', 2, 1);
|
||||
await arrow('ArrowUp', 1, 1);
|
||||
await arrow('ArrowUp', 0, 1);
|
||||
await arrow('ArrowDown', 1, 1);
|
||||
await arrow('ArrowDown', 2, 1);
|
||||
|
||||
// Exit in all four directions, without adding rows or changing existing prose.
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await expectProse(false);
|
||||
await at(0, 1, 'Home');
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await expectProse(false);
|
||||
await at(3, 2);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(true);
|
||||
await at(3, 1);
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
assert.equal(await table.locator('tr').count(), 4);
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('navigation.md')), source);
|
||||
|
||||
// Reverse each exit using only the keyboard. Horizontal entry starts at the
|
||||
// first/last cell; vertical entry uses the nearest column of the edge row.
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await expectProse(false);
|
||||
await arrow('ArrowRight', 0, 0);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await at(0, 1, 'Home');
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await expectProse(false);
|
||||
await arrow('ArrowDown', 0, 0);
|
||||
await at(3, 2);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(true);
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await arrow('ArrowLeft', 3, 2);
|
||||
assert.equal((await caret()).offset, 3);
|
||||
await at(3, 1);
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await arrow('ArrowUp', 3, 0);
|
||||
|
||||
// Preserve the vertical goal column when crossing an empty prose line.
|
||||
for (const after of [false, true]) {
|
||||
await page.evaluate(async after => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const view = EditorView.findFromDOM(document.querySelector('.live-writer .cm-content'));
|
||||
const EditorSelection = view.state.selection.constructor;
|
||||
const table = view.dom.querySelector('table');
|
||||
const preview = table.closest('.writer-preview');
|
||||
const from = view.posAtDOM(preview);
|
||||
const end = view.state.doc.toString().indexOf('\n\nAfter.');
|
||||
const x = table.rows[0].cells[1].getBoundingClientRect().left + 20;
|
||||
const goal = x - view.contentDOM.getBoundingClientRect().left;
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(after ? end + 1 : from - 1, 0, undefined, goal)]) });
|
||||
view.focus();
|
||||
}, after);
|
||||
await arrow(after ? 'ArrowUp' : 'ArrowDown', after ? 3 : 0, 1);
|
||||
}
|
||||
|
||||
// Ordinary prose cursor movement and extending a selection must stay in the
|
||||
// outer editor, even when the selection crosses the whole table.
|
||||
await page.locator('.cm-line').filter({ hasText: 'Before.' }).click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(false);
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await page.keyboard.press('Shift+ArrowDown');
|
||||
assert.equal(await edit.count(), 0);
|
||||
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
|
||||
|
||||
// Text selection and word navigation remain within the current editor.
|
||||
await at(1, 0);
|
||||
await arrow('Shift+ArrowLeft', 1, 0);
|
||||
assert.equal((await caret()).selected, 'a');
|
||||
await arrow('ArrowRight', 1, 0);
|
||||
assert.equal((await caret()).selected, '');
|
||||
await arrow('Control+ArrowLeft', 1, 0);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
|
||||
// Up/down traverse visual lines before crossing to another row.
|
||||
await at(3, 0, 'Home');
|
||||
await arrow('ArrowDown', 3, 0);
|
||||
assert.ok((await caret()).offset > 0);
|
||||
await arrow('ArrowUp', 3, 0);
|
||||
await arrow('ArrowUp', 2, 0);
|
||||
await at(2, 0);
|
||||
await arrow('ArrowDown', 3, 0);
|
||||
assert.ok((await caret()).offset <= 3, 'Down enters the first line');
|
||||
|
||||
// A wrapped cell also retains ordinary vertical caret movement.
|
||||
await at(3, 1);
|
||||
await edit.fill('A long sentence that wraps onto multiple visual lines in a narrow table cell.');
|
||||
await page.keyboard.press('Control+Home');
|
||||
await arrow('ArrowDown', 3, 1);
|
||||
assert.ok((await caret()).offset > 0 && (await caret()).offset < (await edit.innerText()).length, 'Down moves into the next visual line');
|
||||
await arrow('ArrowUp', 3, 1);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
|
||||
// Edits commit when navigating; formulas update and undo restores the source.
|
||||
await at(1, 1);
|
||||
await edit.fill('15');
|
||||
await arrow('ArrowRight', 1, 2);
|
||||
await arrow('ArrowDown', 2, 2);
|
||||
assert.equal(await cell(1, 2).locator('.md-table-formula').innerText(), '30');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('navigation.md').includes('| Alpha | 15 | =B2*2 |'));
|
||||
await at(1, 1);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '12');
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '15');
|
||||
await page.keyboard.press('Tab');
|
||||
await expectCell(1, 2);
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expectCell(1, 1);
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await edit.count(), 0);
|
||||
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
|
||||
|
||||
// A table at the document boundary still offers somewhere to type outside it.
|
||||
const loneTable = '| Name |\n| --- |\n| Value |';
|
||||
for (const [key, after] of [['ArrowLeft', false], ['ArrowUp', false], ['ArrowRight', true], ['ArrowDown', true]]) {
|
||||
const name = `${key}.md`;
|
||||
await page.evaluate(({ name, text }) => {
|
||||
window.__TEST__.files.set(name, text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
|
||||
}, { name, text: loneTable });
|
||||
await quickOpen(name);
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
await table.waitFor();
|
||||
await at(after ? 1 : 0, 0, after ? 'End' : 'Home');
|
||||
await page.keyboard.press(key);
|
||||
await expectProse(after);
|
||||
const reverse = { ArrowLeft: 'ArrowRight', ArrowUp: 'ArrowDown', ArrowRight: 'ArrowLeft', ArrowDown: 'ArrowUp' }[key];
|
||||
// Exiting added two newlines, so first cross the outer empty line.
|
||||
await page.keyboard.press(reverse);
|
||||
await arrow(reverse, after ? 1 : 0, 0);
|
||||
await page.keyboard.press(`Control+${after ? 'End' : 'Home'}`);
|
||||
await page.keyboard.press(key);
|
||||
await expectProse(after);
|
||||
await page.keyboard.type('Outside.');
|
||||
await page.keyboard.press('Control+s');
|
||||
const expected = after ? `${loneTable}\n\nOutside.` : `\nOutside.\n${loneTable}`;
|
||||
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, save, undo/redo, Tab and Escape');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { alignTableCells, clipboardCells, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts";
|
||||
import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts";
|
||||
import { renderMarkdownHtml, plainInlineMarkdown } from "../src/lib/workspace/noteHtml.ts";
|
||||
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
||||
|
||||
const source = "| A | B | C |\r\n| --- | :---: | ---: |\r\n| one | two | three |\r\n| four | five | six |\r\n\r\nTail";
|
||||
const range = { anchor: { row: 2, column: 1 }, head: { row: 1, column: 0 } };
|
||||
test("reversed rectangular selections only change selected cells and preserve CRLF", () => {
|
||||
const changed = formatTableCells(source, range, "bold");
|
||||
assert.equal(changed, source.replace("one", "**one**").replace("two", "**two**").replace("four", "**four**").replace("five", "**five**"));
|
||||
assert.equal(formatTableCells(changed, range, "bold"), source);
|
||||
assert.equal(formatTableCells(source.replace("one", "**one**"), range, "bold"), changed);
|
||||
assert.equal(copyTableCells(source, range), "one\ttwo\nfour\tfive");
|
||||
assert.equal(alignTableCells(source, range, "left"), source.replace("| --- | :---: | ---: |", "| :--- | :--- | ---: |"));
|
||||
});
|
||||
test("all formats render and clear without interpreting escaped punctuation", () => {
|
||||
const cell = { anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } };
|
||||
for (const [format, html] of [["bold", "<strong>one</strong>"], ["italic", "<em>one</em>"], ["strike", "<s>one</s>"], ["highlight", "<mark>one</mark>"], ["code", "<code>one</code>"], ["math", 'class="md-inline-math">one</span>'], ["comment", 'class="md-inline-comment">one</span>']] as const) {
|
||||
const changed = formatTableCells(source, cell, format);
|
||||
assert.ok(renderMarkdownHtml(changed, new Map()).includes(html), format);
|
||||
assert.equal(formatTableCells(changed, cell, "clear"), source);
|
||||
}
|
||||
assert.equal(plainInlineMarkdown("**bold** ==*highlight*== ~~strike~~ `a|b`<br>\\*literal\\*"), "bold highlight strike a\\|b<br>\\*literal\\*");
|
||||
assert.equal(plainInlineMarkdown("**Photo** "), "Photo ");
|
||||
assert.ok(renderMarkdownHtml("`==not highlighted==` \\==literal\\==", new Map()).includes("<code>==not highlighted==</code>"));
|
||||
for (const type of ["highlight", "math", "comment"]) {
|
||||
const text = tableCellMarkdown({ type: "text", text: "a|b", marks: [{ type }] });
|
||||
assert.equal(parseMarkdownTable(`| H |\n| --- |\n| ${text} |`)?.rows[2].cells.length, 1);
|
||||
}
|
||||
});
|
||||
test("clipboard accepts Markdown and quoted TSV without splitting escaped pipes", () => {
|
||||
assert.deepEqual(clipboardCells('"a\tb"\t"line 1\nline 2"\r\n"say ""hi"""\tx|y\r\n'), [["a\tb", "line 1<br>line 2"], ['say "hi"', "x\\|y"]]);
|
||||
assert.deepEqual(clipboardCells("| A | B |\n| --- | --- |\n| a\\|b | `code` |"), [["A", "B"], ["a\\|b", "`code`"]]);
|
||||
const pasted = pasteTableCells(source, range, "value");
|
||||
assert.equal(copyTableCells(pasted, range), "value\tvalue\nvalue\tvalue");
|
||||
const large = pasteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 2, column: 2 } }, "a\tb\nc\td");
|
||||
assert.equal(parseMarkdownTable(large)?.columns, 4);
|
||||
assert.equal(parseMarkdownTable(large)?.rows.length, 5);
|
||||
assert.ok(large.endsWith("\r\n\r\nTail"));
|
||||
assert.equal(copyTableCells(large, { anchor: { row: 2, column: 2 }, head: { row: 3, column: 3 } }), "a\tb\nc\td");
|
||||
});
|
||||
test("clear preserves structure; delete removes whole rows/columns or shifts partial cells", () => {
|
||||
assert.equal(copyTableCells(mapTableCells(source, range, () => ""), range), "\t\n\t");
|
||||
assert.equal(copyTableCells(deleteTableCells(source, range), range), "three\t\nsix\t");
|
||||
const rows = deleteTableCells(source, { anchor: { row: 1, column: 0 }, head: { row: 1, column: 2 } });
|
||||
assert.equal(parseMarkdownTable(rows)?.rows.length, 3);
|
||||
assert.ok(rows.includes("four")); assert.ok(!rows.includes("one"));
|
||||
const columns = deleteTableCells(source, { anchor: { row: 0, column: 1 }, head: { row: 2, column: 1 } });
|
||||
assert.equal(parseMarkdownTable(columns)?.columns, 2);
|
||||
assert.ok(columns.includes("| one | three |"));
|
||||
const header = deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 0, column: 2 } });
|
||||
assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |"));
|
||||
assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail");
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { changeTableStructure, moveTableAxis, sortTableColumn } from "../src/lib/editor/tableStructure.ts";
|
||||
import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts";
|
||||
|
||||
const source = "| Name | Value |\r\n| :--- | ---: |\r\n| Zebra | `2` |\r\n| **Apple** | 10 |\r\n| apple | 3 |\r\n| | 1 |\r\n\r\nTail";
|
||||
const values = (text: string) => parseMarkdownTable(text)!.rows.map(row => row.cells.map(cell => cell.text));
|
||||
test("dragging rows across multiple positions preserves raw Markdown, header, CRLF and suffix", () => {
|
||||
const moved = moveTableAxis(source, "row", 1, 4);
|
||||
assert.deepEqual(values(moved).slice(2).map(row => row[0]), ["**Apple**", "apple", "", "Zebra"]);
|
||||
assert.ok(moved.includes("| Zebra | `2` |\r\n\r\nTail"));
|
||||
assert.equal(moveTableAxis(moved, "row", 4, 1), source);
|
||||
for (const [from, to] of [[0, 2], [2, 0], [1, 5], [-1, 2], [1, 1], [1.5, 2], [1, NaN]]) {
|
||||
assert.equal(moveTableAxis(source, "row", from, to), source);
|
||||
}
|
||||
});
|
||||
test("dragging columns carries alignment and rich contents across ragged rows", () => {
|
||||
const text = " | A | B | C |\r\n | :--- | :---: | ---: |\r\n | a\\|b | **bold**<br>line | [[note]] | extra |\r\n | short |\r\n\r\nTail";
|
||||
const moved = moveTableAxis(text, "column", 0, 2);
|
||||
assert.deepEqual(values(moved), [["B", "C", "A"], [":---:", "---:", ":---"], ["**bold**<br>line", "[[note]]", "a\\|b", "extra"], ["", "", "short"]]);
|
||||
assert.ok(moved.endsWith("\r\n\r\nTail"));
|
||||
assert.deepEqual(values(moveTableAxis(moved, "column", 2, 0)).slice(0, 3), values(text).slice(0, 3));
|
||||
assert.equal(moveTableAxis(text, "column", 0, 3), text);
|
||||
assert.equal(moveTableAxis("| H |\n| --- |", "column", 0, 0), "| H |\n| --- |");
|
||||
assert.equal(moveTableAxis("invalid", "row", 1, 2), "invalid");
|
||||
});
|
||||
test("row insertion, movement and duplication preserve header, raw cells and CRLF", () => {
|
||||
const inserted = changeTableStructure(source, "row", 1, "before");
|
||||
assert.equal(inserted, source.replace("| Zebra", "| | |\r\n| Zebra"));
|
||||
assert.equal(changeTableStructure(source, "row", 0, "after"), inserted);
|
||||
assert.equal(changeTableStructure(source, "row", 0, "before"), source);
|
||||
const moved = changeTableStructure(source, "row", 2, "previous");
|
||||
assert.equal(moved, source.replace("| Zebra | `2` |\r\n| **Apple** | 10 |", "| **Apple** | 10 |\r\n| Zebra | `2` |"));
|
||||
assert.equal(changeTableStructure(moved, "row", 1, "next"), source);
|
||||
assert.equal(changeTableStructure(source, "row", 1, "previous"), source);
|
||||
assert.equal(changeTableStructure(source, "row", 0, "next"), source);
|
||||
assert.equal(changeTableStructure(source, "row", 4, "next"), source);
|
||||
assert.equal(changeTableStructure(source, "row", 1, "duplicate"), source.replace("| Zebra | `2` |", "| Zebra | `2` |\r\n| Zebra | `2` |"));
|
||||
assert.ok(changeTableStructure(source, "row", 1, "delete").endsWith("\r\n\r\nTail"));
|
||||
});
|
||||
test("column movement and duplication carry header, contents and alignment together", () => {
|
||||
const moved = changeTableStructure(source, "column", 1, "previous");
|
||||
assert.deepEqual(values(moved), values(source).map(row => row.toReversed()));
|
||||
assert.deepEqual(values(changeTableStructure(moved, "column", 0, "next")), values(source));
|
||||
assert.deepEqual(values(changeTableStructure(source, "column", 0, "duplicate")), values(source).map(row => [row[0], ...row]));
|
||||
assert.deepEqual(values(changeTableStructure(source, "column", 1, "before")), values(source).map((row, i) => [row[0], i === 1 ? "---" : "", row[1]]));
|
||||
assert.deepEqual(values(changeTableStructure(source, "column", 1, "delete")), values(source).map(row => [row[0]]));
|
||||
assert.equal(changeTableStructure(source, "column", 0, "previous"), source);
|
||||
assert.equal(changeTableStructure(source, "column", 1, "next"), source);
|
||||
});
|
||||
test("sort uses visible text and natural numbers, is stable, leaves blanks last and header intact", () => {
|
||||
assert.deepEqual(values(sortTableColumn(source, 0)).slice(2).map(row => row[0]), ["**Apple**", "apple", "Zebra", ""]);
|
||||
assert.deepEqual(values(sortTableColumn(source, 0, true)).slice(2).map(row => row[0]), ["Zebra", "**Apple**", "apple", ""]);
|
||||
assert.deepEqual(values(sortTableColumn(source, 1)).slice(2).map(row => row[1]), ["1", "`2`", "3", "10"]);
|
||||
const sorted = sortTableColumn(source, 1, true);
|
||||
assert.ok(sorted.startsWith("| Name | Value |\r\n| :--- | ---: |"));
|
||||
assert.ok(sorted.includes("| Zebra | `2` |"));
|
||||
assert.ok(sorted.endsWith("\r\n\r\nTail"));
|
||||
});
|
||||
test("header-only, ragged and single-column tables remain valid through operations", () => {
|
||||
const header = "| H |\n| --- |";
|
||||
assert.equal(changeTableStructure(header, "row", 0, "duplicate"), header + "\n| H |");
|
||||
assert.equal(changeTableStructure(header, "column", 0, "delete"), "");
|
||||
assert.equal(changeTableStructure(header, "row", 0, "delete"), "");
|
||||
assert.equal(sortTableColumn(header, 0), header);
|
||||
const ragged = "| A | B |\n| --- | --- |\n| short |\n| a\\|b | two | extra |";
|
||||
assert.deepEqual(values(changeTableStructure(ragged, "column", 1, "previous"))[3], ["two", "a\\|b", "extra"]);
|
||||
assert.equal(changeTableStructure("invalid", "row", 0, "after"), "invalid");
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return []; if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }, { id: "git-bash", title: "Git Bash", kind: "bash" }, { id: "node", title: "JavaScript Debug Terminal", kind: "node" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
|
||||
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
|
||||
const click = name => page.getByRole("button", { name, exact: true }).click();
|
||||
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
|
||||
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
|
||||
try {
|
||||
await page.goto("http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await click("Terminal");
|
||||
await waitCount("pty_open", 1);
|
||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
|
||||
const adjacent = await page.getByRole("button", { name: "New terminal", exact: true }).evaluate(button => { const buttons = [...button.closest(".actions").querySelectorAll("button")]; return buttons[buttons.indexOf(button) + 1]?.getAttribute("aria-label"); });
|
||||
assert.equal(adjacent, "Terminal profiles and tasks");
|
||||
await click("Split terminal (Ctrl+Shift+5)");
|
||||
await waitCount("pty_open", 2);
|
||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 1);
|
||||
assert.equal(await page.locator(".pane.shown").count(), 2);
|
||||
const original = await page.locator(".pane.shown").first().boundingBox();
|
||||
await click("Maximize panel");
|
||||
const enlarged = await page.locator(".pane.shown").first().boundingBox();
|
||||
assert.ok(enlarged.height > original.height + 100);
|
||||
assert.equal(await count("pty_close"), 0);
|
||||
await page.screenshot({ path: ".audit/terminal-splits.png" });
|
||||
await click("Restore panel");
|
||||
await click("Hide terminal (sessions keep running)");
|
||||
assert.equal(await count("pty_close"), 0);
|
||||
await page.keyboard.press("Control+j");
|
||||
assert.equal(await count("pty_open"), 2);
|
||||
await click("Terminal profiles and tasks");
|
||||
await page.screenshot({ path: ".audit/terminal-profiles.png" });
|
||||
await menu("Command Prompt");
|
||||
await waitCount("pty_open", 3);
|
||||
assert.equal(await page.locator(".pane.shown").count(), 1);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "cmd");
|
||||
await page.keyboard.press("Control+Shift+5");
|
||||
await waitCount("pty_open", 4);
|
||||
assert.equal(await page.locator(".pane.shown").count(), 2);
|
||||
await click("Kill terminal");
|
||||
await waitCount("pty_close", 1);
|
||||
assert.equal(await page.locator(".pane.shown").count(), 1);
|
||||
// OSC prompt integration reaches the history pickers.
|
||||
await page.evaluate(() => {
|
||||
const id = window.__TEST__.calls.filter(c => c.command === "pty_open")[2].args.id;
|
||||
const data = `\x1b]633;RSCommand;${btoa("echo history-check")}\x07\x1b]633;RSCwd;${btoa("C:\\two words")}\x07\x1b]133;A\x07C:\\two words>\x1b]133;B\x07`;
|
||||
window.__TEST__.emit("pty-data", { id, data: [...new TextEncoder().encode(data)] });
|
||||
});
|
||||
await click("More terminal actions");
|
||||
await page.screenshot({ path: ".audit/terminal-actions.png" });
|
||||
await menu("Run Recent Command… Ctrl+Alt+R");
|
||||
await page.getByRole("dialog").getByRole("button", { name: "echo history-check" }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo history-check")));
|
||||
await page.keyboard.press("Control+g");
|
||||
await page.getByRole("dialog").getByRole("button", { name: "C:\\two words" }).click();
|
||||
assert.ok((await writes()).includes('cd /d "C:\\two words"'));
|
||||
await click("Terminal profiles and tasks");
|
||||
await menu("Configure Terminal Settings");
|
||||
await page.getByLabel("Font size", { exact: true }).fill("16");
|
||||
await page.getByLabel("Default profile", { exact: true }).selectOption("git-bash");
|
||||
await click("Save settings");
|
||||
await click("New terminal");
|
||||
await waitCount("pty_open", 5);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "git-bash");
|
||||
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.terminal")).fontSize), 16);
|
||||
await page.evaluate(() => window.__TEST__.files.set(".runestone/tasks.json", JSON.stringify({ tasks: [{ label: "Smoke task", command: "echo task-ok", profile: "powershell" }] })));
|
||||
await click("Terminal profiles and tasks");
|
||||
await menu("Run Task…");
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Smoke task echo task-ok" }).click();
|
||||
await waitCount("pty_open", 6);
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
|
||||
// Capture selected source while the terminal menu takes focus.
|
||||
await page.getByRole("button", { name: /Find a file/ }).click();
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(e => e.getDomNode()?.isConnected);
|
||||
editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 15 });
|
||||
});
|
||||
await click("More terminal actions");
|
||||
await menu("Run Selected Text");
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("print('hello')")));
|
||||
await click("More terminal actions");
|
||||
await menu("Run Active File");
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("python 'C:\\smoke-workspace\\src\\hello.py'")));
|
||||
await click("Terminal profiles and tasks");
|
||||
await menu("New Terminal Window Ctrl+Shift+Alt+`");
|
||||
await waitCount("pty_new_window", 1);
|
||||
await click("More terminal actions");
|
||||
await menu("Start Dictation");
|
||||
await waitCount("pty_dictation", 1);
|
||||
await click("More terminal actions");
|
||||
await menu("Clear Terminal");
|
||||
assert.equal(await count("pty_close"), 1);
|
||||
await page.setViewportSize({ width: 880, height: 600 });
|
||||
await page.screenshot({ path: ".audit/terminal-narrow.png" });
|
||||
for (let remaining = 5; remaining > 1; remaining--) await click("Kill terminal");
|
||||
await waitCount("pty_close", 5);
|
||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
|
||||
await page.screenshot({ path: ".audit/terminal-single.png" });
|
||||
await click("Kill terminal");
|
||||
await waitCount("pty_close", 6);
|
||||
await click("Start a terminal");
|
||||
await waitCount("pty_open", 7);
|
||||
await page.locator(".pane.shown .xterm-helper-textarea").focus();
|
||||
await page.keyboard.press("Control+Shift+Backquote");
|
||||
await waitCount("pty_open", 8);
|
||||
await page.keyboard.press("Control+Shift+Alt+Backquote");
|
||||
await waitCount("pty_new_window", 2);
|
||||
await page.goto("http://127.0.0.1:1420/?terminalWindow=C%3A%5Csmoke-workspace");
|
||||
await waitCount("pty_open", 1);
|
||||
assert.equal(await count("workspace_open"), 0);
|
||||
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
|
||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
|
||||
await page.screenshot({ path: ".audit/terminal-window.png" });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: split groups, profile selection, maximize/restore/hide, shell history, directory quoting, settings persistence, tasks, editor selection/file execution, window/dictation IPC, and narrow layout.");
|
||||
} catch (error) { console.log("errors", errors, "writes", await writes());
|
||||
await page.screenshot({ path: ".audit/terminal-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../src/lib/terminal/model.ts";
|
||||
|
||||
test("paths are shell-quoted without evaluating metacharacters", () => {
|
||||
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
|
||||
assert.equal(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
|
||||
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
|
||||
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
|
||||
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"));
|
||||
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"));
|
||||
});
|
||||
|
||||
test("run file selects a runner and rejects non-executable documents", () => {
|
||||
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
|
||||
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
|
||||
assert.throws(() => fileCommand("notes.md", "powershell"));
|
||||
assert.throws(() => fileCommand("app.js", "node"));
|
||||
});
|
||||
|
||||
test("task config validates every entry before offering execution", () => {
|
||||
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
|
||||
for (const text of ['{}', '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text));
|
||||
});
|
||||
|
||||
test("history deduplicates most recent entries and is bounded", () => {
|
||||
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
|
||||
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
|
||||
assert.deepEqual(remember(["one"], " "), ["one"]);
|
||||
});
|
||||
|
||||
test("physical key shortcuts distinguish new, split, window, and hide", () => {
|
||||
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
|
||||
assert.equal(terminalShortcut(key), "new");
|
||||
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
|
||||
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
|
||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
|
||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { dropHint, dropPlaceAt, planDrop, uniqueName } from "../src/lib/workspace/treeDrop.ts";
|
||||
|
||||
function kids(map: Record<string, string[]>) {
|
||||
return (parent: string) => map[parent] ?? [];
|
||||
}
|
||||
|
||||
test("same-folder drop before a sibling reorders and keeps the name", () => {
|
||||
const plan = planDrop(
|
||||
"notes/b.md",
|
||||
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
|
||||
"before",
|
||||
kids({ notes: ["a.md", "b.md"] }),
|
||||
);
|
||||
assert.deepEqual(plan, {
|
||||
action: "reorder",
|
||||
parent: "notes",
|
||||
names: ["b.md", "a.md"],
|
||||
});
|
||||
});
|
||||
|
||||
test("same-folder drop after a sibling inserts after that sibling", () => {
|
||||
const plan = planDrop(
|
||||
"notes/a.md",
|
||||
{ name: "b.md", rel_path: "notes/b.md", kind: "file" },
|
||||
"after",
|
||||
kids({ notes: ["a.md", "b.md"] }),
|
||||
);
|
||||
assert.deepEqual(plan, {
|
||||
action: "reorder",
|
||||
parent: "notes",
|
||||
names: ["b.md", "a.md"],
|
||||
});
|
||||
});
|
||||
|
||||
test("drop inside the parent folder is a no-op", () => {
|
||||
const plan = planDrop(
|
||||
"notes/a.md",
|
||||
{ name: "notes", rel_path: "notes", kind: "folder" },
|
||||
"inside",
|
||||
kids({ notes: ["a.md", "b.md"], "": ["notes"] }),
|
||||
);
|
||||
assert.deepEqual(plan, { action: "noop" });
|
||||
});
|
||||
|
||||
test("drop before a sibling folder reorders instead of moving inside", () => {
|
||||
const plan = planDrop(
|
||||
"inbox.md",
|
||||
{ name: "notes", rel_path: "notes", kind: "folder" },
|
||||
"before",
|
||||
kids({ "": ["inbox.md", "notes"] }),
|
||||
);
|
||||
assert.deepEqual(plan, {
|
||||
action: "reorder",
|
||||
parent: "",
|
||||
names: ["inbox.md", "notes"],
|
||||
});
|
||||
});
|
||||
|
||||
test("drop onto self is a no-op", () => {
|
||||
const plan = planDrop(
|
||||
"notes/a.md",
|
||||
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
|
||||
"before",
|
||||
kids({ notes: ["a.md"] }),
|
||||
);
|
||||
assert.deepEqual(plan, { action: "noop" });
|
||||
});
|
||||
|
||||
test("drop inside another folder moves under that folder", () => {
|
||||
const plan = planDrop(
|
||||
"inbox.md",
|
||||
{ name: "notes", rel_path: "notes", kind: "folder" },
|
||||
"inside",
|
||||
kids({ "": ["inbox.md", "notes"], notes: ["a.md"] }),
|
||||
);
|
||||
assert.deepEqual(plan, {
|
||||
action: "move",
|
||||
from: "inbox.md",
|
||||
to: "notes/inbox.md",
|
||||
fromParent: "",
|
||||
toParent: "notes",
|
||||
destName: "inbox.md",
|
||||
orderFrom: ["notes"],
|
||||
orderTo: ["a.md", "inbox.md"],
|
||||
});
|
||||
});
|
||||
|
||||
test("drop into a folder that already has the name picks a unique name", () => {
|
||||
const plan = planDrop(
|
||||
"inbox.md",
|
||||
{ name: "notes", rel_path: "notes", kind: "folder" },
|
||||
"inside",
|
||||
kids({ "": ["inbox.md", "notes"], notes: ["inbox.md"] }),
|
||||
);
|
||||
assert.equal(plan.action, "move");
|
||||
if (plan.action === "move") {
|
||||
assert.equal(plan.to, "notes/inbox 2.md");
|
||||
assert.equal(plan.destName, "inbox 2.md");
|
||||
}
|
||||
});
|
||||
|
||||
test("uniqueName skips taken numbered suffixes", () => {
|
||||
assert.equal(uniqueName(["alpha.md", "alpha 2.md"], "alpha.md"), "alpha 3.md");
|
||||
});
|
||||
|
||||
test("dropPlaceAt splits a file row in half and a folder row into three bands", () => {
|
||||
assert.equal(dropPlaceAt("file", 0.2), "before");
|
||||
assert.equal(dropPlaceAt("file", 0.8), "after");
|
||||
assert.equal(dropPlaceAt("folder", 0.1), "before");
|
||||
assert.equal(dropPlaceAt("folder", 0.5), "inside");
|
||||
assert.equal(dropPlaceAt("folder", 0.9), "after");
|
||||
});
|
||||
|
||||
test("dropHint names the landing", () => {
|
||||
assert.equal(dropHint("notes", "inside"), "Into notes");
|
||||
assert.equal(dropHint("inbox.md", "before"), "Before inbox.md");
|
||||
assert.equal(dropHint("inbox.md", "after"), "After inbox.md");
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
|
||||
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(rows => rows.map(row => row.dataset.treeRel));
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await row('notes').waitFor();
|
||||
await row('notes').click();
|
||||
await row('notes/second.md').waitFor();
|
||||
assert.deepEqual(await selected(), ['notes']);
|
||||
await row('notes/second.md').click({ modifiers: ['Control'] });
|
||||
await row('src').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
|
||||
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(await page.getByRole('tab').count(), 0);
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
|
||||
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
|
||||
await row('notes/second.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md']);
|
||||
await row('src').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md', 'src']);
|
||||
await page.keyboard.press('F2');
|
||||
assert.equal(await page.locator('.tree .rename').count(), 0);
|
||||
await row('notes/welcome.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md']);
|
||||
await row('notes/second.md').click();
|
||||
assert.deepEqual(await selected(), ['notes/second.md']);
|
||||
await page.getByRole('tab', { name: /second/ }).waitFor();
|
||||
await row('notes/second.md').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), []);
|
||||
await row('src').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await page.keyboard.press('F2');
|
||||
assert.equal(await page.locator('.tree .rename').inputValue(), 'src');
|
||||
await page.keyboard.press('Escape');
|
||||
await row('notes/second.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes/second.md', 'notes/welcome.md', 'src']);
|
||||
const colors = await page.locator('.tree .row.selected').evaluateAll(rows => rows.map(row => getComputedStyle(row).backgroundColor));
|
||||
assert.equal(new Set(colors).size, 1);
|
||||
await page.screenshot({ path: '.audit/tree-selection.png' });
|
||||
await page.getByRole('button', { name: 'Collapse all', exact: true }).click();
|
||||
assert.deepEqual(await selected(), ['src']);
|
||||
await row('notes').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'src']);
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Shift', 'Control'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'src']);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Tree selection browser checks passed.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,87 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type TreeSelection } from "../src/lib/workspace/treeSelection.ts";
|
||||
import type { TreeEntry } from "../src/lib/workspace/types.ts";
|
||||
|
||||
const entry = (rel_path: string, kind: "file" | "folder" = "file"): TreeEntry => ({ rel_path, name: rel_path.split("/").pop()!, kind });
|
||||
const children = {
|
||||
"": [entry("notes", "folder"), entry("src", "folder"), entry("z.md")],
|
||||
notes: [entry("notes/b.md"), entry("notes/a.md"), entry("notes/nested", "folder")],
|
||||
"notes/nested": [entry("notes/nested/c.md")],
|
||||
src: [entry("src/main.ts")],
|
||||
};
|
||||
const visible = visibleTreePaths(children, new Set(["notes", "notes/nested"]));
|
||||
const empty = (): TreeSelection => ({ paths: new Set(), anchor: null });
|
||||
|
||||
test("selection outlines omit shared edges and close around gaps and single rows", () => {
|
||||
const rows = ["a.md", "b.md", "c.md", "d.md", "e.md"];
|
||||
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "b.md", "c.md", "e.md"]))], [
|
||||
["a.md", { top: null, bottom: 0 }],
|
||||
["b.md", { top: 0, bottom: 0 }],
|
||||
["c.md", { top: 0, bottom: null }],
|
||||
["e.md", { top: null, bottom: null }],
|
||||
]);
|
||||
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "c.md", "e.md"]))].map(([, edges]) => edges),
|
||||
Array.from({ length: 3 }, () => ({ top: null, bottom: null })));
|
||||
});
|
||||
|
||||
test("nested selection outlines retain only exposed indentation steps in visible order", () => {
|
||||
const edges = treeSelectionEdges(visible, new Set(visible));
|
||||
assert.deepEqual(edges.get("notes"), { top: null, bottom: 1 });
|
||||
assert.deepEqual(edges.get("notes/b.md"), { top: 0, bottom: 0 });
|
||||
assert.deepEqual(edges.get("notes/nested"), { top: 0, bottom: 1 });
|
||||
assert.deepEqual(edges.get("notes/nested/c.md"), { top: 0, bottom: 0 });
|
||||
assert.deepEqual(edges.get("src"), { top: 2, bottom: 0 });
|
||||
assert.deepEqual(edges.get("z.md"), { top: 0, bottom: null });
|
||||
const collapsed = visibleTreePaths(children, new Set());
|
||||
assert.deepEqual([...treeSelectionEdges(collapsed, new Set(visible))], [
|
||||
["notes", { top: null, bottom: 0 }], ["src", { top: 0, bottom: 0 }], ["z.md", { top: 0, bottom: null }],
|
||||
]);
|
||||
});
|
||||
|
||||
test("visible order preserves custom sorting and only visits expanded folders", () => {
|
||||
assert.deepEqual(visible, ["notes", "notes/b.md", "notes/a.md", "notes/nested", "notes/nested/c.md", "src", "z.md"]);
|
||||
assert.deepEqual(visibleTreePaths(children, new Set()), ["notes", "src", "z.md"]);
|
||||
});
|
||||
|
||||
test("Ctrl-click toggles files and folders independently; plain click replaces the selection", () => {
|
||||
const first = selectTreePath(empty(), "notes", visible);
|
||||
const added = selectTreePath(first, "z.md", visible, { ctrlKey: true });
|
||||
assert.deepEqual([...added.paths], ["notes", "z.md"]);
|
||||
assert.deepEqual([...first.paths], ["notes"]);
|
||||
const removed = selectTreePath(added, "notes", visible, { ctrlKey: true });
|
||||
assert.deepEqual([...removed.paths], ["z.md"]);
|
||||
assert.deepEqual([...selectTreePath(removed, "z.md", visible, { ctrlKey: true }).paths], []);
|
||||
assert.deepEqual([...selectTreePath(added, "src", visible).paths], ["src"]);
|
||||
});
|
||||
|
||||
test("Shift-click selects an inclusive range in both directions across files and folders", () => {
|
||||
const first = selectTreePath(empty(), "notes/b.md", visible);
|
||||
const forward = selectTreePath(first, "src", visible, { shiftKey: true });
|
||||
assert.deepEqual([...forward.paths], visible.slice(1, 6));
|
||||
const reverse = selectTreePath(selectTreePath(empty(), "src", visible), "notes/b.md", visible, { shiftKey: true });
|
||||
assert.deepEqual([...reverse.paths], visible.slice(1, 6));
|
||||
});
|
||||
|
||||
test("repeated Shift-click keeps the anchor and shrinks or reverses the range", () => {
|
||||
const first = selectTreePath(empty(), "notes/a.md", visible);
|
||||
const extended = selectTreePath(first, "z.md", visible, { shiftKey: true });
|
||||
const shrunk = selectTreePath(extended, "notes/nested", visible, { shiftKey: true });
|
||||
assert.deepEqual([...shrunk.paths], ["notes/a.md", "notes/nested"]);
|
||||
assert.equal(shrunk.anchor, "notes/a.md");
|
||||
assert.deepEqual([...selectTreePath(shrunk, "notes", visible, { shiftKey: true }).paths], visible.slice(0, 3));
|
||||
});
|
||||
|
||||
test("Ctrl+Shift adds a range and Command-click supports the same toggle behavior", () => {
|
||||
let selection = selectTreePath(empty(), "z.md", visible);
|
||||
selection = selectTreePath(selection, "notes/b.md", visible, { metaKey: true });
|
||||
selection = selectTreePath(selection, "notes/nested", visible, { ctrlKey: true, shiftKey: true });
|
||||
assert.deepEqual([...selection.paths], ["z.md", "notes/b.md", "notes/a.md", "notes/nested"]);
|
||||
assert.deepEqual([...selectTreePath(selection, "z.md", visible, { metaKey: true }).paths], ["notes/b.md", "notes/a.md", "notes/nested"]);
|
||||
});
|
||||
|
||||
test("a missing or hidden anchor makes Shift-click select only the clicked row", () => {
|
||||
assert.deepEqual(selectTreePath(empty(), "src", visible, { shiftKey: true }), { paths: new Set(["src"]), anchor: "src" });
|
||||
const hidden = selectTreePath(empty(), "notes/b.md", visible);
|
||||
assert.deepEqual(selectTreePath(hidden, "z.md", ["notes", "src", "z.md"], { shiftKey: true }), { paths: new Set(["z.md"]), anchor: "z.md" });
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0;
|
||||
const state = { maximized: false, confirm: "Cancel", calls: [] };
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push(command);
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return null;
|
||||
if (command === "plugin:window|is_maximized") return state.maximized;
|
||||
if (command === "plugin:window|toggle_maximize") { state.maximized = !state.maximized; emit("tauri://resize", { width: 1400, height: 900 }); return; }
|
||||
if (command === "plugin:window|minimize" || command === "plugin:window|destroy") return;
|
||||
if (command === "plugin:window|close") { emit("tauri://close-requested"); return; }
|
||||
if (command === "plugin:dialog|message") return state.confirm;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { state, emit };
|
||||
});
|
||||
try {
|
||||
const config = JSON.parse(await readFile(new URL("../src-tauri/tauri.conf.json", import.meta.url), "utf8"));
|
||||
assert.equal(config.app.windows[0].decorations, false);
|
||||
const capability = JSON.parse(await readFile(new URL("../src-tauri/capabilities/default.json", import.meta.url), "utf8"));
|
||||
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
|
||||
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
|
||||
}
|
||||
await page.goto(process.env.SMOKE_URL || "http://localhost:1420");
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
|
||||
// Native maximize/restore (e.g. double-clicking the drag region) updates the button too.
|
||||
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
|
||||
assert.ok(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|minimize")));
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
|
||||
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:dialog|message"));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|destroy")), false);
|
||||
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:window|destroy"));
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
for (const width of [1400, 880]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const layout = await page.evaluate(() => {
|
||||
const header = document.querySelector(".header").getBoundingClientRect();
|
||||
const controls = [...document.querySelectorAll(".header button")].map(el => el.getBoundingClientRect());
|
||||
return { height: header.height, top: header.top, fits: controls.every(rect => rect.x >= 0 && rect.right <= innerWidth && rect.y >= header.y && rect.bottom <= header.bottom), drag: document.querySelector(".window-drag-space").getBoundingClientRect().width };
|
||||
});
|
||||
assert.equal(layout.height, 36);
|
||||
assert.equal(layout.top, 0);
|
||||
assert.ok(layout.fits);
|
||||
assert.ok(layout.drag >= 40);
|
||||
await page.screenshot({ path: `.audit/window-controls-${width}.png` });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,798 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
async function contents() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
async function waitForText(text) {
|
||||
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
|
||||
}
|
||||
async function focusEditor() {
|
||||
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
|
||||
}
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await quickOpen("welcome.md");
|
||||
const original = await contents();
|
||||
assert.ok(original.startsWith("---\ntitle:"));
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Added in source.");
|
||||
await waitForText(original + "Added in source.");
|
||||
await quickOpen("hello.py");
|
||||
await page.getByRole("tab", { name: /welcome\.md/ }).click();
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source.");
|
||||
await page.keyboard.press("Control+y");
|
||||
await waitForText(original + "Added in source.");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
|
||||
|
||||
await page.getByRole("button", { name: "Split", exact: true }).click();
|
||||
await page.locator(".md-page h1").first().waitFor();
|
||||
assert.ok(await page.locator(".monaco-host").isVisible());
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
|
||||
});
|
||||
await waitForText("# Agent update\n");
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Local edit");
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
|
||||
});
|
||||
await page.getByRole("button", { name: "Keep my edits" }).waitFor();
|
||||
assert.equal(await contents(), "# Agent update\nLocal edit");
|
||||
await page.getByRole("button", { name: "Keep my edits" }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit");
|
||||
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
|
||||
await page.screenshot({ path: ".audit/core-rebuild-terminal.png" });
|
||||
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
|
||||
await page.getByRole("button", { name: "New terminal", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
|
||||
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
|
||||
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
|
||||
await page.keyboard.press("Control+n");
|
||||
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
|
||||
await page.screenshot({ path: ".audit/core-rebuild.png" });
|
||||
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("reader-showcase.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
|
||||
}, showcase);
|
||||
await quickOpen("reader-showcase.md");
|
||||
const read = page.getByRole("button", { name: "Read", exact: true });
|
||||
assert.equal(await read.innerText(), "");
|
||||
assert.equal(await read.locator("svg").count(), 1);
|
||||
await read.hover();
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
|
||||
const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox();
|
||||
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
|
||||
await read.click();
|
||||
assert.equal(await read.getAttribute("aria-pressed"), "true");
|
||||
await page.locator(".reading h1:not(.document-title)").waitFor();
|
||||
assert.equal(await page.locator(".monaco-host").isVisible(), false);
|
||||
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
|
||||
assert.equal(await page.locator(".reading ol > li").count(), 3);
|
||||
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
|
||||
assert.equal(await page.locator(".reading input:checked").count(), 2);
|
||||
assert.equal(await page.locator(".md-properties").getAttribute("open"), null);
|
||||
assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes"));
|
||||
const surface = await page.locator(".reading").boundingBox();
|
||||
assert.ok(surface.width <= 741);
|
||||
await page.mouse.move(700, 980);
|
||||
await page.screenshot({ path: ".audit/reader-mode.png" });
|
||||
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
|
||||
await page.getByRole("button", { name: "Copy code", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
|
||||
await page.screenshot({ path: ".audit/reader-details.png" });
|
||||
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
|
||||
await page.screenshot({ path: ".audit/reader-narrow.png" });
|
||||
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
|
||||
await page.getByRole("button", { name: "Split", exact: true }).click();
|
||||
await page.waitForFunction(() => {
|
||||
const host = document.querySelector(".monaco-host");
|
||||
const rendered = host?.querySelector(".monaco-editor");
|
||||
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
|
||||
});
|
||||
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
|
||||
await page.screenshot({ path: ".audit/reader-split.png" });
|
||||
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
|
||||
await page.screenshot({ path: ".audit/reader-split-wide.png" });
|
||||
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
assert.equal(await contents(), showcase);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
|
||||
await page.getByRole("button", { name: "Read", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" });
|
||||
|
||||
// Continuous live Markdown: only active lines reveal source; checkboxes
|
||||
// remain inline and update the original file without HTML serialization.
|
||||
const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("writing.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
|
||||
}, writingSource);
|
||||
await quickOpen("writing.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await writer.waitFor();
|
||||
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
|
||||
assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0);
|
||||
await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 });
|
||||
await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor();
|
||||
const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." });
|
||||
await paragraph.click();
|
||||
await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.type("New ");
|
||||
await page.keyboard.press("Control+s");
|
||||
const editedSource = writingSource.replace("A **formatted**", "New A **formatted**");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource);
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
await waitForText(editedSource);
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await waitForText(writingSource);
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await paragraph.click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("First new paragraph.");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("**Second new paragraph.**");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Third new paragraph.");
|
||||
assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1);
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+ArrowUp");
|
||||
await page.keyboard.press("Shift+ArrowUp");
|
||||
assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph."));
|
||||
await page.keyboard.press("Backspace");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph."));
|
||||
assert.ok(await writer.evaluate(el => el.contains(document.activeElement)));
|
||||
|
||||
// Link syntax becomes editable on a normal click, without opening the link.
|
||||
await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click();
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+End");
|
||||
await page.keyboard.type("[Project link](https://example.com/new)");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor();
|
||||
const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" });
|
||||
const checkbox = task.getByRole("checkbox");
|
||||
assert.ok(await task.evaluate(line => {
|
||||
const box = line.querySelector('input').getBoundingClientRect();
|
||||
const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft'));
|
||||
const range = document.createRange(); range.selectNode(text);
|
||||
const label = range.getBoundingClientRect();
|
||||
return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left;
|
||||
}));
|
||||
await checkbox.click();
|
||||
await task.locator('.writer-completed').waitFor();
|
||||
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
|
||||
await task.locator('.writer-completed').click();
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+End");
|
||||
await page.keyboard.type('- [ ] Revised task');
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
|
||||
await page.locator(".live-writer .md-diagram svg").waitFor();
|
||||
await page.screenshot({ path: ".audit/writing-continuous.png" });
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
|
||||
});
|
||||
await quickOpen("crlf.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.type("Changed ");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n");
|
||||
await page.keyboard.press("Control+n");
|
||||
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await page.keyboard.type("One");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Two");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Three");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
|
||||
await page.getByRole("tab", { name: "crlf.md", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "blank.md", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree");
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
|
||||
await page.keyboard.press("Control+f");
|
||||
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Control+a");
|
||||
await page.keyboard.type("- [ ] First task");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Second task");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task");
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("blank.md", "Fresh disk version\r\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] });
|
||||
});
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.ok((await writer.innerText()).includes("Fresh disk version"));
|
||||
|
||||
const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.<br>Keep listings consistent.<br>Introduce automated investing.<br>Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;<br>- Trading |\n\nAfter the table.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("tables.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["tables.md"] });
|
||||
}, tableSource);
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await quickOpen("tables.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
const table = page.locator('.live-writer table');
|
||||
await table.waitFor();
|
||||
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
|
||||
const tableHeading = page.locator('.live-writer .writer-heading');
|
||||
await tableHeading.click();
|
||||
assert.equal(await tableHeading.innerText(), '# Table layout');
|
||||
await table.locator('tbody tr').first().locator('td').first().click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
|
||||
assert.equal(await table.locator('th').count(), 5);
|
||||
assert.equal(await table.locator('tbody tr').count(), 2);
|
||||
assert.equal(await table.locator('br').count(), 4);
|
||||
assert.ok(!(await table.innerText()).includes('<br>'));
|
||||
assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100)));
|
||||
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
|
||||
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
|
||||
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
|
||||
await addColumn.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
|
||||
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
|
||||
await table.locator('td').first().hover();
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
|
||||
await addColumn.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
|
||||
await page.screenshot({ path: '.audit/writing-table-column.png' });
|
||||
await addColumn.click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
|
||||
await addRow.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
|
||||
await page.screenshot({ path: '.audit/writing-table-row.png' });
|
||||
await addRow.click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |'));
|
||||
assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource);
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.keyboard.press('Control+y');
|
||||
await table.locator('th').last().click();
|
||||
const cellEditor = page.locator('.writer-cell-editor');
|
||||
await cellEditor.waitFor();
|
||||
assert.equal(await table.locator('th').count(), 6);
|
||||
assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0);
|
||||
await page.keyboard.type('New column');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column'));
|
||||
await page.keyboard.press('Tab');
|
||||
assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count());
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count());
|
||||
await table.locator('tbody tr').first().locator('td').nth(4).click();
|
||||
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.keyboard.type('Plain | pipe and *stars*');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
|
||||
assert.equal(await table.locator('th').count(), 6);
|
||||
await page.screenshot({ path: '.audit/writing-table-cell-edit.png' });
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
|
||||
await cellEditor.waitFor();
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain'));
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click();
|
||||
const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md'));
|
||||
await table.locator('tbody tr').first().locator('td').nth(4).click();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit);
|
||||
await table.locator('tbody tr').last().locator('td').last().click();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4);
|
||||
await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
|
||||
assert.equal(await page.locator('.md-page table br').count(), 5);
|
||||
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
|
||||
const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('selection-table.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
|
||||
window.__TEST__.clipboard = '';
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
|
||||
writeText: async text => { window.__TEST__.clipboard = text; },
|
||||
readText: async () => window.__TEST__.clipboard,
|
||||
} });
|
||||
}, selectionTable);
|
||||
await quickOpen('selection-table.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const selectedTable = page.locator('.live-writer table');
|
||||
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
|
||||
await page.mouse.move(fromCell.x + 15, fromCell.y + 15);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
|
||||
await page.screenshot({ path: '.audit/table-cell-selection-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
|
||||
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
|
||||
await page.keyboard.press('Control+i');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0);
|
||||
assert.equal(await selectedTable.locator('strong').count(), 4);
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
|
||||
async function cellAction(name, formatted = false) {
|
||||
await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' });
|
||||
if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name, exact: true }).click();
|
||||
}
|
||||
await cellAction('Clear formatting', true);
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
|
||||
await cellAction('Copy');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive');
|
||||
await cellAction('Cut');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
|
||||
await cellAction('Paste');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await cellAction('Align centre');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
|
||||
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) {
|
||||
await cellAction(name, true);
|
||||
await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector);
|
||||
await cellAction('Clear formatting', true);
|
||||
}
|
||||
// Native clipboard events must operate on the rectangle, including one-step undo.
|
||||
await page.locator('.writer-table').evaluate(el => {
|
||||
const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow');
|
||||
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red');
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
|
||||
await cellAction('Delete cells');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three');
|
||||
assert.equal(await selectedTable.locator('th').count(), 3);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await page.keyboard.press('Control+a');
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9);
|
||||
await cellAction('Delete cells');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0);
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectedTable.waitFor();
|
||||
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) {
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name, exact: true }).click();
|
||||
await selectedCell(1, 0).click();
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Escape');
|
||||
assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`);
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await cellAction('Clear formatting', true);
|
||||
}
|
||||
|
||||
const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('table-actions.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
|
||||
}, actionsSource);
|
||||
await quickOpen('table-actions.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const actionTable = page.locator('.live-writer table');
|
||||
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
async function actionItem(label, group, r = 1, c = 0) {
|
||||
await actionCell(r, c).click({ button: 'right' });
|
||||
if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name: label, exact: true }).click();
|
||||
}
|
||||
async function saveActionSource() {
|
||||
await page.keyboard.press('Control+s');
|
||||
return page.evaluate(() => window.__TEST__.files.get('table-actions.md'));
|
||||
}
|
||||
async function undoAction() {
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource);
|
||||
}
|
||||
for (const [label, group, r, c, rows, columns] of [
|
||||
['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2],
|
||||
['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1],
|
||||
]) {
|
||||
await actionItem(label, group, r, c);
|
||||
assert.equal(await actionTable.locator('tr').count(), rows, label);
|
||||
assert.equal(await actionTable.locator('th').count(), columns, label);
|
||||
await undoAction();
|
||||
}
|
||||
await actionItem('Move row down', 'Row');
|
||||
assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group');
|
||||
await undoAction();
|
||||
await actionItem('Move row up', 'Row', 2);
|
||||
assert.equal(await actionCell(1, 0).innerText(), 'Apple');
|
||||
await undoAction();
|
||||
await actionItem('Move column right', 'Column');
|
||||
assert.equal(await actionCell(0, 0).innerText(), 'Value');
|
||||
assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right');
|
||||
await undoAction();
|
||||
await actionItem('Move column left', 'Column', 1, 1);
|
||||
assert.equal(await actionCell(0, 0).innerText(), 'Value');
|
||||
await undoAction();
|
||||
await actionItem('Sort by column (A to Z)', undefined, 1, 1);
|
||||
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']);
|
||||
await undoAction();
|
||||
await actionItem('Sort by column (Z to A)', undefined, 1, 1);
|
||||
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']);
|
||||
await undoAction();
|
||||
await actionCell(0, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
|
||||
assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled());
|
||||
assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled());
|
||||
await page.keyboard.press('Escape');
|
||||
async function selectBrokers() {
|
||||
await actionCell(1, 0).click();
|
||||
await page.keyboard.press('Control+Home');
|
||||
for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight');
|
||||
for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers');
|
||||
}
|
||||
await selectBrokers();
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
|
||||
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
|
||||
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
|
||||
await page.screenshot({ path: '.audit/table-text-row-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
|
||||
await page.screenshot({ path: '.audit/table-text-column-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column');
|
||||
await page.keyboard.press('Escape');
|
||||
await actionItem('Bold', 'Format');
|
||||
assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers');
|
||||
assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group'));
|
||||
await actionItem('Add external link');
|
||||
await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1');
|
||||
assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Add link');
|
||||
await page.getByRole('dialog').locator('input').fill('notes/second');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Search for “Brokers”');
|
||||
await page.getByPlaceholder('Search files and notes').waitFor();
|
||||
assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers');
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers'));
|
||||
await selectBrokers();
|
||||
await actionItem('Extract current selection…');
|
||||
await page.getByRole('dialog').locator('input').fill('extracted-brokers.md');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await page.evaluate(() => { window.__TEST__.clipboard = '<b>literal</b>\nnext'; });
|
||||
await actionItem('Paste as plain text');
|
||||
assert.ok((await saveActionSource()).includes('Interactive <') || (await saveActionSource()).includes('Interactive \\<b\\>literal\\</b\\><br>next'));
|
||||
assert.equal(await actionCell(1, 0).locator('b').count(), 0);
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await page.evaluate(() => {
|
||||
navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? '<em>Rich paste</em>' : 'Rich paste'], { type }) }];
|
||||
});
|
||||
await actionItem('Paste');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste');
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.evaluate(() => { delete navigator.clipboard.read; });
|
||||
await selectBrokers();
|
||||
await actionItem('Copy');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
|
||||
await actionItem('Cut');
|
||||
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Select all');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group');
|
||||
await page.setViewportSize({ width: 800, height: 600 });
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
|
||||
assert.ok(await page.locator('.table-cell-menu, .table-cell-submenu:not([hidden])').evaluateAll(panels => panels.every(panel => {
|
||||
const rect = panel.getBoundingClientRect(); return rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight;
|
||||
})));
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
|
||||
const richTable = '| Name | Notes |\r\n| :--- | ---: |\r\n| Untouched | ~~Old~~ **bold** [link](https://example.com) <br />Next |\r\n| Short |\r\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('rich-table.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
|
||||
}, richTable);
|
||||
await quickOpen('rich-table.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
|
||||
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
|
||||
await richCell.click();
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited'));
|
||||
const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md'));
|
||||
assert.ok(richSaved.includes('| Untouched |'));
|
||||
assert.ok(richSaved.includes('~~Old~~'));
|
||||
assert.ok(richSaved.includes('**bold**'));
|
||||
assert.ok(richSaved.includes('https://example.com'));
|
||||
assert.ok(richSaved.includes(''));
|
||||
assert.ok(richSaved.includes('<br>Next edited'));
|
||||
assert.ok(!/(?<!\r)\n/.test(richSaved));
|
||||
await page.keyboard.press('Escape');
|
||||
await richCell.click();
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' again');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Next edited again'));
|
||||
const shortCell = page.locator('.live-writer tbody tr').last().locator('td').last();
|
||||
await shortCell.click();
|
||||
await cellEditor.evaluate(el => {
|
||||
const data = new DataTransfer(); data.setData('text/plain', 'Pasted | text\nSecond line');
|
||||
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
});
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Pasted \\| text<br>Second line'));
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Control+b');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('**Pasted \\| text**'));
|
||||
assert.equal(await page.locator('.live-writer th').count(), 2);
|
||||
|
||||
// Physical mouse coordinates below tall block widgets must resolve to the
|
||||
// visible line, including immediately adjacent heading/body lines.
|
||||
const longTable = '| Ticker | Name | Notes |\n| --- | --- | --- |\n' +
|
||||
Array.from({ length: 14 }, (_, index) => `| STOCK${index} | Company ${index} | First note<br>Second note<br>Third note |`).join('\n');
|
||||
const hitTestSource = `# Listed\n\n${longTable}\n\n# Tier 1\nTier one body directly below heading.\n\n${longTable}\n\n## Tier 2\nTier two body directly below heading.\n`;
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('table-hit-testing.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
|
||||
}, hitTestSource);
|
||||
await quickOpen('table-hit-testing.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
async function clickRenderedLine(locator, expected) {
|
||||
await locator.scrollIntoViewIfNeeded();
|
||||
const rect = await locator.boundingBox();
|
||||
assert.ok(rect);
|
||||
await page.mouse.click(rect.x + 45, rect.y + rect.height * .7);
|
||||
const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent);
|
||||
assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`);
|
||||
}
|
||||
async function checkLinesAfterTables() {
|
||||
await page.locator('.cm-scroller').evaluate(async el => {
|
||||
el.scrollTop = 0;
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
});
|
||||
for (const [heading, body] of [
|
||||
['# Tier 1', 'Tier one body directly below heading.'],
|
||||
['## Tier 2', 'Tier two body directly below heading.'],
|
||||
]) {
|
||||
const tables = page.locator('.live-writer .writer-table');
|
||||
await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded();
|
||||
await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading);
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading);
|
||||
await page.keyboard.press('Control+z');
|
||||
await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body);
|
||||
}
|
||||
}
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await checkLinesAfterTables();
|
||||
await page.locator('.cm-scroller').evaluate(async el => {
|
||||
el.scrollTop = 0;
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
});
|
||||
await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click();
|
||||
await page.keyboard.press('Control+End');
|
||||
for (let line = 0; line < 4; line++) {
|
||||
await page.keyboard.press('Enter');
|
||||
await page.keyboard.type('A newly added line changes the table height.');
|
||||
}
|
||||
await checkLinesAfterTables();
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await checkLinesAfterTables();
|
||||
await page.screenshot({ path: '.audit/table-cursor-position.png' });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md")));
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
|
||||
await page.screenshot({ path: ".audit/core-rebuild-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,122 @@
|
||||
// Run against pnpm dev; use PLAYWRIGHT_MODULE for a shared Playwright installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 800 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", err => errors.push(err.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let current = "D:\\Notes";
|
||||
let recent = [current, "D:\\Writing\\Notes", "D:\\Missing"];
|
||||
let picked = null;
|
||||
let contents = "Original note";
|
||||
const calls = [];
|
||||
const windows = [];
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "workspace_last_path") return current;
|
||||
if (command === "workspace_recent") return recent;
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
|
||||
if (command === "workspace_read") { if (args.rel === "note.txt") return contents; throw "File not found"; }
|
||||
if (command === "workspace_write") { contents = args.contents; return; }
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "plugin:dialog|open") return picked;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
if (command === "workspace_new") {
|
||||
if (args.name === "Existing") throw "A file or folder with that name already exists.";
|
||||
const root = args.parent + "\\" + args.name;
|
||||
recent = [root, ...recent]; windows.push(root);
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_open_window") {
|
||||
if (args.path.endsWith("Missing")) throw "folder does not exist";
|
||||
windows.push(args.path);
|
||||
recent = [args.path, ...recent.filter(p => p !== args.path)];
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_open") {
|
||||
if (args.path.endsWith("Missing")) throw "folder does not exist";
|
||||
current = args.path; recent = [current, ...recent.filter(p => p !== current)];
|
||||
return { root: current, name: current.split("\\").pop(), watch_mode: "native" };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [] };
|
||||
});
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco;
|
||||
window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected).setValue("My pending edit");
|
||||
});
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
|
||||
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
|
||||
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
|
||||
await trigger.click();
|
||||
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
|
||||
await page.screenshot({ path: ".audit/workspaces-menu.png" });
|
||||
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
|
||||
await menu.getByRole("button").filter({ hasText: "Current" }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
|
||||
await page.keyboard.press("Control+o");
|
||||
await menu.getByRole("button").filter({ hasText: "Missing" }).click();
|
||||
await menu.getByRole("alert").filter({ hasText: "folder does not exist" }).waitFor();
|
||||
await menu.getByRole("button", { name: "Open another folder…" }).click();
|
||||
assert(await menu.isVisible(), "Cancelling folder picker keeps history available");
|
||||
await menu.getByRole("button").filter({ hasText: "D:\\Writing\\Notes" }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes"]);
|
||||
await trigger.click();
|
||||
await page.evaluate(() => window.__TEST__.pick("D:\\Other"));
|
||||
await menu.getByRole("button", { name: "Open another folder…" }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
await trigger.click();
|
||||
await menu.getByRole("button", { name: "New workspace…" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "New workspace", exact: true });
|
||||
assert(await dialog.getByRole("button", { name: "Create workspace", exact: true }).isDisabled());
|
||||
await dialog.getByLabel("Workspace name").fill("Existing");
|
||||
await page.evaluate(() => window.__TEST__.pick("D:\\Projects"));
|
||||
await dialog.getByRole("button", { name: "Browse…" }).click();
|
||||
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
|
||||
await dialog.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
|
||||
await dialog.getByLabel("Workspace name").fill("Fresh notes");
|
||||
await page.screenshot({ path: ".audit/workspaces-create.png" });
|
||||
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes", "D:\\Other", "D:\\Projects\\Fresh notes"]);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|message").length), 0);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected)?.getValue()), "My pending edit");
|
||||
assert(await page.getByRole("tab", { name: /note\.txt/ }).isVisible());
|
||||
await trigger.click();
|
||||
await page.keyboard.press("End");
|
||||
assert.equal(await page.locator(":focus").textContent(), " Open another folder…");
|
||||
await page.keyboard.press("Escape");
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
await page.evaluate(() => window.__TEST__.clear());
|
||||
await trigger.click();
|
||||
await menu.getByText("No recent workspaces yet.").waitFor();
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Workspace smoke passed: history, opening and creating in new windows, original workspace preserved, cancellation, errors, keyboard and empty state.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,244 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
copySelection,
|
||||
cutSelection,
|
||||
pasteClipboard,
|
||||
writerContextItems,
|
||||
} from "../src/lib/editor/writerMenu.ts";
|
||||
|
||||
type Harness = {
|
||||
selected: string;
|
||||
inTable: boolean;
|
||||
deleted: boolean;
|
||||
focused: boolean;
|
||||
inserted: string | null;
|
||||
dispatched: boolean;
|
||||
};
|
||||
|
||||
function fakeEditor(init?: { selected?: string; inTable?: boolean }) {
|
||||
const harness: Harness = {
|
||||
selected: init?.selected ?? "",
|
||||
inTable: init?.inTable ?? false,
|
||||
deleted: false,
|
||||
focused: false,
|
||||
inserted: null,
|
||||
dispatched: false,
|
||||
};
|
||||
const tr = {
|
||||
insertText(text: string) {
|
||||
harness.inserted = text;
|
||||
return tr;
|
||||
},
|
||||
};
|
||||
const chainApi = {
|
||||
focus() {
|
||||
harness.focused = true;
|
||||
return chainApi;
|
||||
},
|
||||
deleteSelection() {
|
||||
harness.deleted = true;
|
||||
return chainApi;
|
||||
},
|
||||
run() {
|
||||
return true;
|
||||
},
|
||||
};
|
||||
const editor = {
|
||||
isActive(name: string) {
|
||||
return name === "table" && harness.inTable;
|
||||
},
|
||||
chain() {
|
||||
return chainApi;
|
||||
},
|
||||
state: {
|
||||
selection: { from: 0, to: harness.selected.length },
|
||||
doc: {
|
||||
textBetween() {
|
||||
return harness.selected;
|
||||
},
|
||||
},
|
||||
tr,
|
||||
},
|
||||
view: {
|
||||
dispatch() {
|
||||
harness.dispatched = true;
|
||||
},
|
||||
},
|
||||
};
|
||||
return { editor, harness };
|
||||
}
|
||||
|
||||
function withClipboard(
|
||||
impl: { writeText?: (text: string) => Promise<void>; readText?: () => Promise<string> },
|
||||
run: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, "navigator");
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
configurable: true,
|
||||
value: { clipboard: impl },
|
||||
});
|
||||
return run().finally(() => {
|
||||
if (previous) {
|
||||
Object.defineProperty(globalThis, "navigator", previous);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, "navigator");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function actionLabels(items: ReturnType<typeof writerContextItems>): string[] {
|
||||
const labels: string[] = [];
|
||||
for (const item of items) {
|
||||
if (item.kind === "action") {
|
||||
labels.push(item.label);
|
||||
} else if (item.kind === "group") {
|
||||
for (const sub of item.items) {
|
||||
if (sub.kind === "action") {
|
||||
labels.push(sub.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
test("paste inserts clipboard text without parsing tags", async () => {
|
||||
const { editor, harness } = fakeEditor();
|
||||
await withClipboard(
|
||||
{ readText: async () => "<b>bold</b>" },
|
||||
async () => {
|
||||
await pasteClipboard(editor as never);
|
||||
},
|
||||
);
|
||||
assert.equal(harness.focused, true);
|
||||
assert.equal(harness.dispatched, true);
|
||||
assert.equal(harness.inserted, "<b>bold</b>");
|
||||
});
|
||||
|
||||
test("paste swallows clipboard errors", async () => {
|
||||
const { editor, harness } = fakeEditor();
|
||||
await withClipboard(
|
||||
{
|
||||
readText: async () => {
|
||||
throw new Error("denied");
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
await pasteClipboard(editor as never);
|
||||
},
|
||||
);
|
||||
assert.equal(harness.dispatched, false);
|
||||
assert.equal(harness.inserted, null);
|
||||
});
|
||||
|
||||
test("cut keeps the selection when clipboard write fails", async () => {
|
||||
const { editor, harness } = fakeEditor({ selected: "gone" });
|
||||
await withClipboard(
|
||||
{
|
||||
writeText: async () => {
|
||||
throw new Error("denied");
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
await cutSelection(editor as never);
|
||||
},
|
||||
);
|
||||
assert.equal(harness.deleted, false);
|
||||
});
|
||||
|
||||
test("copy swallows clipboard errors", async () => {
|
||||
const { editor } = fakeEditor({ selected: "keep" });
|
||||
let attempted = false;
|
||||
await withClipboard(
|
||||
{
|
||||
writeText: async () => {
|
||||
attempted = true;
|
||||
throw new Error("denied");
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
await copySelection(editor as never);
|
||||
},
|
||||
);
|
||||
assert.equal(attempted, true);
|
||||
});
|
||||
|
||||
test("cut writes selected text then deletes it", async () => {
|
||||
const { editor, harness } = fakeEditor({ selected: "clip" });
|
||||
let written = "";
|
||||
await withClipboard(
|
||||
{
|
||||
writeText: async (text) => {
|
||||
written = text;
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
await cutSelection(editor as never);
|
||||
},
|
||||
);
|
||||
assert.equal(written, "clip");
|
||||
assert.equal(harness.deleted, true);
|
||||
});
|
||||
|
||||
test("table row and column actions disable outside a table", () => {
|
||||
const { editor } = fakeEditor({ inTable: false });
|
||||
const items = writerContextItems(editor as never);
|
||||
const table = items.find((item) => item.kind === "group" && item.label === "Table");
|
||||
assert.equal(table?.kind, "group");
|
||||
if (table?.kind !== "group") {
|
||||
return;
|
||||
}
|
||||
const byLabel = new Map(
|
||||
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
|
||||
);
|
||||
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
|
||||
assert.equal(byLabel.get("Add row above")?.disabled, true);
|
||||
assert.equal(byLabel.get("Delete table")?.disabled, true);
|
||||
});
|
||||
|
||||
test("table row and column actions enable inside a table", () => {
|
||||
const { editor } = fakeEditor({ inTable: true });
|
||||
const items = writerContextItems(editor as never);
|
||||
const table = items.find((item) => item.kind === "group" && item.label === "Table");
|
||||
assert.equal(table?.kind, "group");
|
||||
if (table?.kind !== "group") {
|
||||
return;
|
||||
}
|
||||
const byLabel = new Map(
|
||||
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
|
||||
);
|
||||
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
|
||||
assert.equal(byLabel.get("Add row above")?.disabled, false);
|
||||
assert.equal(byLabel.get("Delete table")?.disabled, false);
|
||||
});
|
||||
|
||||
test("style and format actions cover the requested commands", () => {
|
||||
const { editor } = fakeEditor();
|
||||
const labels = actionLabels(writerContextItems(editor as never));
|
||||
for (const label of [
|
||||
"Cut",
|
||||
"Copy",
|
||||
"Paste",
|
||||
"Heading 1",
|
||||
"Heading 6",
|
||||
"Body",
|
||||
"Quote",
|
||||
"Bullet list",
|
||||
"Numbered list",
|
||||
"Task list",
|
||||
"Bold",
|
||||
"Italic",
|
||||
"Strikethrough",
|
||||
"Highlight",
|
||||
"Code",
|
||||
"Math",
|
||||
"Comment",
|
||||
"Clear formatting",
|
||||
"Insert table",
|
||||
]) {
|
||||
assert.equal(labels.includes(label), true, label);
|
||||
}
|
||||
assert.equal(labels.includes("Superscript"), false);
|
||||
assert.equal(labels.includes("Subscript"), false);
|
||||
});
|
||||
Reference in New Issue
Block a user