From 43106ed9c7eb35ba4969ab00a2b871926bcc70c0 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Tue, 29 Sep 2026 07:48:24 -0700 Subject: [PATCH] Improve workspace navigation, search, and tab actions --- docs/user-guide.md | 3 + package.json | 2 +- scripts/codeBlocks.smoke.mjs | 135 ++++++++++++++++++ scripts/dividers.smoke.mjs | 138 ++++++++++++++++++ scripts/documents.spec.ts | 47 +++++++ scripts/find.smoke.mjs | 167 ++++++++++++++++++++++ scripts/tabActions.spec.ts | 46 ++++++ scripts/tabMenus.smoke.mjs | 139 ++++++++++++++++++ scripts/tabOrder.smoke.mjs | 125 ++++++++++++++++ scripts/treeActions.smoke.mjs | 198 ++++++++++++++++++++++++++ scripts/treeActions.spec.ts | 50 +++++++ src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/lib/editor/FindPanel.svelte | 78 ++++++++++ src/lib/editor/LiveWriter.svelte | 5 + src/lib/editor/liveMarkdown.ts | 34 ++++- src/lib/editor/writerSearch.ts | 23 +++ src/lib/layout/ContextMenu.svelte | 9 +- src/lib/layout/EditorPane.svelte | 4 + src/lib/layout/FileTree.svelte | 152 ++++++++++++-------- src/lib/layout/OutlinePane.svelte | 77 +++++++++- src/lib/layout/TabBar.svelte | 227 ++++++++++++++++++++++++++++-- src/lib/layout/Workbench.svelte | 82 +++++++++-- src/lib/layout/menuTypes.ts | 3 + src/lib/ui/Icon.svelte | 5 +- src/lib/ui/IconButton.svelte | 2 + src/lib/ui/actionIcons.ts | 3 + src/lib/ui/find.css | 59 ++++++++ src/lib/workspace/documents.ts | 21 ++- src/lib/workspace/tabActions.ts | 12 ++ src/lib/workspace/treeActions.ts | 41 ++++++ src/lib/workspace/treeDrop.ts | 4 +- src/lib/workspace/types.ts | 1 + 34 files changed, 1798 insertions(+), 100 deletions(-) create mode 100644 scripts/codeBlocks.smoke.mjs create mode 100644 scripts/dividers.smoke.mjs create mode 100644 scripts/find.smoke.mjs create mode 100644 scripts/tabActions.spec.ts create mode 100644 scripts/tabMenus.smoke.mjs create mode 100644 scripts/tabOrder.smoke.mjs create mode 100644 scripts/treeActions.smoke.mjs create mode 100644 scripts/treeActions.spec.ts create mode 100644 src/lib/editor/FindPanel.svelte create mode 100644 src/lib/editor/writerSearch.ts create mode 100644 src/lib/ui/find.css create mode 100644 src/lib/workspace/tabActions.ts create mode 100644 src/lib/workspace/treeActions.ts diff --git a/docs/user-guide.md b/docs/user-guide.md index bea6521..8fae6e5 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -84,6 +84,9 @@ Current features and limitations as of September 2026. positional: copying, inserting, deleting, sorting, or moving cells does not rewrite addresses. Cross-table references and automatic fill are not supported. - Tabs retain their editor models, undo history, cursor and scroll state while open. +- Drag a tab left or right to change its position. Hold it near either edge to scroll through other tabs. +- Right-click a tab for Move tab left and Move tab right. With a tab focused, use Alt+Shift+Left or Alt+Shift+Right. + Use the arrow keys, Home, or End to select tabs. Press Escape to cancel a drag. - Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file. - Changed notes and scripts autosave every 5 seconds, including background tabs. Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts diff --git a/package.json b/package.json index 5e69d51..0935cbc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.0", + "version": "0.1.2", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { diff --git a/scripts/codeBlocks.smoke.mjs b/scripts/codeBlocks.smoke.mjs new file mode 100644 index 0000000..a7dce0d --- /dev/null +++ b/scripts/codeBlocks.smoke.mjs @@ -0,0 +1,135 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } 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 = []; +await mkdir(".audit", { recursive: true }); +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 }; +}); + +try { + 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" }).first().click(); + await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor(); + await page.evaluate(async () => { + const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); + window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); + }); + const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc()); + const cursor = () => page.evaluate(() => window.__CM__.state.selection.main.head); + async function select(anchor, head = anchor) { + await page.evaluate(({ anchor, head }) => { + window.__CM__.dispatch({ selection: { anchor, head }, scrollIntoView: true }); + window.__CM__.focus(); + }, { anchor, head }); + } + for (const block of ["```js\nconst value = 123;\nsecond line\n```", "~~~text\nconst value = 123;\nsecond line\n~~~", " const value = 123;\n second line"]) { + const original = `Above.\n\n${block}\n\nBelow.\n`; + await page.evaluate(value => { + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }); + }, original); + await page.locator(".writer-preview pre").click(); + await page.locator(".writer-code-source").first().waitFor(); + const position = original.indexOf("123") + 1; + await select(position); + await page.keyboard.press("Backspace"); + assert.equal(await contents(), original.slice(0, position - 1) + original.slice(position)); + await page.keyboard.press("Control+z"); + assert.equal(await contents(), original); + await select(position); + await page.keyboard.press("Delete"); + assert.equal(await contents(), original.slice(0, position) + original.slice(position + 1)); + await page.keyboard.press("Control+z"); + assert.equal(await contents(), original); + await select(position); + await page.keyboard.press("ArrowRight"); + assert.equal(await cursor(), position + 1); + await page.keyboard.press("ArrowLeft"); + assert.equal(await cursor(), position); + await page.keyboard.type("X"); + assert.equal(await contents(), original.slice(0, position) + "X" + original.slice(position)); + await page.keyboard.press("Control+z"); + assert.equal(await contents(), original); + await select(position - 1, position + 2); + await page.keyboard.press("Backspace"); + const edited = original.slice(0, position - 1) + original.slice(position + 2); + assert.equal(await contents(), edited); + await select(0); + assert.ok((await page.locator(".writer-preview pre").textContent()).includes("const value = ;")); + await page.keyboard.press("Control+s"); + await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited); + } + assert.deepEqual(errors, []); + console.log("PASS: Fenced and indented code editing, character deletion, selection deletion, cursor movement, undo, preview and save."); +} catch (error) { + console.error("Browser errors:", errors); + await page.screenshot({ path: ".audit/code-blocks-failure.png" }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/dividers.smoke.mjs b/scripts/dividers.smoke.mjs new file mode 100644 index 0000000..329e94c --- /dev/null +++ b/scripts/dividers.smoke.mjs @@ -0,0 +1,138 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } 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 = []; +await mkdir(".audit", { recursive: true }); +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 }; +}); + +try { + 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" }).first().click(); + const writer = page.getByRole("textbox", { name: "Writing editor", exact: true }); + await writer.waitFor(); + const dividers = "content\n___\ncontent\n***\n\n---\n\n* * *\n\n_ _ _\n\n- - -\n\nHeading\n---\n\n`___`\n\n```text\n___\n```\n\n ***\n\nEnd\n"; + await page.evaluate(async value => { + 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: value }, selection: { anchor: 0 } }); + }, dividers); + await page.waitForFunction(() => document.querySelectorAll(".writer-divider").length === 6); + assert.equal(await page.getByRole("separator").and(page.locator(".writer-divider")).count(), 6); + const dividerStyle = await page.locator(".writer-divider").first().evaluate(node => ({ + width: node.getBoundingClientRect().width, + lineWidth: node.parentElement.getBoundingClientRect().width, + border: getComputedStyle(node, "::after").borderTopWidth, + color: getComputedStyle(node, "::after").borderTopColor, + })); + assert.ok(Math.abs(dividerStyle.width - dividerStyle.lineWidth) < 2); + assert.equal(dividerStyle.border, "1px"); + assert.notEqual(dividerStyle.color, "rgba(0, 0, 0, 0)"); + await page.setViewportSize({ width: 1100, height: 900 }); + await page.screenshot({ path: ".audit/markdown-dividers.png" }); + + await page.locator(".writer-divider").first().click(); + assert.equal(await page.locator(".writer-divider").count(), 5); + assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___"); + await page.keyboard.press("End"); + await page.keyboard.press("Backspace"); + await page.keyboard.press("Control+Home"); + assert.equal(await page.locator(".writer-divider").count(), 5); + assert.ok((await writer.textContent()).includes("__")); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+Home"); + assert.equal(await page.locator(".writer-divider").count(), 6); + await page.keyboard.press("ArrowDown"); + assert.equal(await page.locator(".writer-divider").count(), 5); + assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___"); + await page.keyboard.press("Control+a"); + assert.equal(await page.locator(".writer-divider").count(), 0); + assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), dividers); + await page.keyboard.press("Control+Home"); + assert.equal(await page.locator(".writer-divider").count(), 6); + await page.keyboard.press("Control+s"); + await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, dividers); + + await page.evaluate(() => { + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "Above\n\n ___\n\n> ***\n\nEnd" }, selection: { anchor: 0 } }); + }); + assert.equal(await page.locator(".writer-divider").count(), 2); + for (const divider of await page.locator(".writer-divider").all()) { + assert.ok(await divider.evaluate(node => node.getBoundingClientRect().right <= node.parentElement.getBoundingClientRect().right + 1)); + } + + assert.deepEqual(errors, []); + console.log("PASS: Divider syntax, width, source editing, keyboard navigation, selection, undo and save."); +} catch (error) { + console.error("Browser errors:", errors); + await page.screenshot({ path: ".audit/markdown-dividers-failure.png" }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/documents.spec.ts b/scripts/documents.spec.ts index 2f97706..1e4032a 100644 --- a/scripts/documents.spec.ts +++ b/scripts/documents.spec.ts @@ -24,6 +24,53 @@ function setup() { return { docs, disk, io }; } +test("tab moves preserve selection, dirty buffers, and in-flight saves", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const note = docs.active!; + docs.edit(note.id, "my edits"); + docs.setChrome("Ide"); + await docs.open(entry("script.py")); + docs.newTab(); + const blank = docs.active!; + const gate = deferred(); + const write = io.write; + io.write = async (...args) => { await gate.promise; await write(...args); }; + const pending = docs.save(note.id); + await Promise.resolve(); + docs.move(note.relPath, 2); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", blank.relPath, "note.md"]); + assert.equal(docs.active, blank); + assert.equal(docs.buffers[2], note); + assert.equal(note.contents, "my edits"); + assert.equal(note.saved, "original"); + assert.equal(note.chromeOverride, "Ide"); + docs.move(blank.relPath, 0); + assert.equal(docs.active, blank); + gate.resolve(); + await pending; + assert.equal(disk.get("note.md"), "my edits"); + docs.close(blank.relPath); + assert.equal(docs.activePath, "script.py"); +}); + +test("tab moves ignore stale paths and invalid indices and clamp to the tab strip", async () => { + const { docs } = setup(); + await docs.open(entry("note.md")); + await docs.open(entry("script.py")); + docs.move("missing.md", 0); + docs.move("script.py", NaN); + docs.move("script.py", 0.5); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]); + docs.move("script.py", -1); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", "note.md"]); + docs.move("script.py", 99); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]); + docs.dispose(); + docs.move("script.py", 0); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]); +}); + test("empty tabs are independent, preserve dirty documents, and never access disk", async () => { const { docs, io } = setup(); await docs.open(entry("note.md")); diff --git a/scripts/find.smoke.mjs b/scripts/find.smoke.mjs new file mode 100644 index 0000000..1152e15 --- /dev/null +++ b/scripts/find.smoke.mjs @@ -0,0 +1,167 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } 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 = []; +await mkdir(".audit", { recursive: true }); +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 }; +}); + +try { + 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" }).first().click(); + const editor = page.getByRole("textbox", { name: "Writing editor", exact: true }); + await editor.waitFor(); + 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: "# Alpha\n\nalpha Alpha alphabet\n\n## Beta\n\nBeta text\n" }, selection: { anchor: 0 } }); + window.__CM__.focus(); + }); + await page.keyboard.press("Control+f"); + const find = page.getByRole("textbox", { name: "Find in document", exact: true }); + await find.waitFor(); + assert.equal(await find.evaluate(el => document.activeElement === el), true); + assert.equal(await page.locator(".cm-panels-top .rs-writer-search").count(), 1); + const panelBounds = await page.locator(".rs-writer-search").boundingBox(); + const scrollBounds = await page.locator(".cm-scroller").boundingBox(); + assert.ok(panelBounds.y + panelBounds.height <= scrollBounds.y + 1); + await find.fill("Alpha"); + await page.keyboard.press("Enter"); + const first = await page.evaluate(() => window.__CM__.state.selection.main.from); + await page.keyboard.press("Enter"); + const second = await page.evaluate(() => window.__CM__.state.selection.main.from); + assert.notEqual(first, second); + await page.keyboard.press("Shift+Enter"); + assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.from), first); + await page.getByRole("checkbox", { name: "Match case" }).check(); + await page.getByRole("checkbox", { name: "Whole word" }).check(); + await page.getByRole("textbox", { name: "Replace with" }).fill("Gamma"); + await page.getByRole("button", { name: "Replace all", exact: true }).click(); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /# Gamma\n\nalpha Gamma alphabet/); + await page.getByRole("checkbox", { name: "Regex" }).check(); + await find.fill("["); + assert.equal(await find.getAttribute("aria-invalid"), "true"); + assert.equal(await page.getByRole("button", { name: "Replace all", exact: true }).isDisabled(), true); + await page.getByText("Invalid expression", { exact: true }).waitFor(); + await find.fill("Gamma"); + await page.getByRole("checkbox", { name: "Regex" }).uncheck(); + await page.evaluate(async () => { + const moduleUrl = performance.getEntriesByType("resource").find(entry => entry.name.includes("/@codemirror_search.js"))?.name; + if (!moduleUrl) throw new Error("Search module was not loaded"); + const { SearchQuery, setSearchQuery } = await import(moduleUrl); + window.__CM__.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: "Beta" })) }); + }); + await page.waitForFunction(() => document.querySelector('input[name="search"]').value === "Beta"); + await find.focus(); + await page.keyboard.press("Escape"); + assert.equal(await find.count(), 0); + assert.equal(await editor.evaluate(el => document.activeElement === el), true); + await page.keyboard.press("Control+f"); + await find.waitFor(); + await page.getByRole("button", { name: "Next match (Enter)" }).focus(); + await page.getByRole("tooltip", { name: "Next match (Enter)" }).waitFor({ state: "visible" }); + await find.focus(); + + const outline = page.getByRole("region", { name: "Outline", exact: true }); + if (!await outline.count()) await page.getByRole("button", { name: "Outline", exact: true }).click(); + await outline.focus(); + await page.keyboard.press("Control+f"); + const outlineFind = page.getByRole("textbox", { name: "Find in outline", exact: true }); + await outlineFind.fill("beta"); + assert.equal(await outline.locator("li").count(), 1); + assert.equal(await outline.locator("li button").textContent(), "Beta"); + await outlineFind.fill("missing"); + await outline.getByText("No matching headings or symbols.").waitFor(); + await outlineFind.fill("Gamma"); + await page.screenshot({ path: ".audit/find-bars.png" }); + await page.keyboard.press("Escape"); + assert.equal(await outlineFind.count(), 0); + assert.equal(await outline.locator("li").count(), 2); + assert.equal(await outline.evaluate(el => document.activeElement === el), true); + await page.keyboard.press("Control+f"); + await outlineFind.fill("Beta"); + await page.keyboard.press("Enter"); + await page.waitForFunction(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text === "## Beta"); + assert.equal(await editor.evaluate(el => document.activeElement === el), true); + + await page.setViewportSize({ width: 880, height: 760 }); + await find.focus(); + await page.screenshot({ path: ".audit/find-bars-narrow.png" }); + for (const selector of [".rs-writer-search", ".outline-search"]) { + assert.equal(await page.locator(selector).evaluate(el => el.scrollWidth <= el.clientWidth), true, selector); + } + assert.deepEqual(errors, []); + console.log("PASS: Top search panel, shortcuts, replacement, query sync, invalid regex, focus tooltip, outline filtering, focus return and narrow layout."); +} catch (error) { + console.error("Browser errors:", errors); + await page.screenshot({ path: ".audit/find-failure.png" }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/tabActions.spec.ts b/scripts/tabActions.spec.ts new file mode 100644 index 0000000..706cd38 --- /dev/null +++ b/scripts/tabActions.spec.ts @@ -0,0 +1,46 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { tabsToClose } from "../src/lib/workspace/tabActions.ts"; +import { Documents } from "../src/lib/workspace/documents.ts"; + +function setup() { + return new Documents({ + read: async () => "original", write: async () => {}, image: async () => "data:image/png;base64,", + kind: () => "text", chrome: () => "Writing", + }, () => {}); +} +const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const }); + +test("group closes follow tab order and preserve pins without changing the active tab", async () => { + const docs = setup(); + for (const name of ["a.md", "b.md", "c.md", "d.md"]) await docs.open(entry(name)); + docs.togglePin("b.md"); + docs.move("d.md", 1); + const paths = (scope: "one" | "others" | "after" | "all") => tabsToClose(docs.buffers, "d.md", scope).map(tab => tab.relPath); + assert.deepEqual(paths("one"), ["d.md"]); + assert.deepEqual(paths("others"), ["a.md", "c.md"]); + assert.deepEqual(paths("after"), ["c.md"]); + assert.deepEqual(paths("all"), ["a.md", "d.md", "c.md"]); + assert.equal(docs.activePath, "d.md"); + assert.deepEqual(tabsToClose(docs.buffers, "missing.md", "all"), []); + assert.equal(tabsToClose(docs.buffers, "b.md", "one")[0].pinned, true); +}); + +test("pinning protects current and empty tabs from replacement, and survives rename", async () => { + const docs = setup(); + await docs.open(entry("a.md")); + docs.togglePin("a.md"); + await docs.open(entry("b.md"), "current"); + assert.deepEqual(docs.buffers.map(tab => tab.relPath), ["a.md", "b.md"]); + docs.rename("a.md", "renamed.md"); + assert.equal(docs.buffers[0].pinned, true); + docs.newTab(); + const blank = docs.active!; + docs.togglePin(blank.relPath); + await docs.open(entry("c.md")); + assert.ok(docs.buffers.includes(blank)); + docs.select("renamed.md"); + docs.togglePin("renamed.md"); + await docs.open(entry("d.md"), "current"); + assert.ok(!docs.buffers.some(tab => tab.relPath === "renamed.md")); +}); diff --git a/scripts/tabMenus.smoke.mjs b/scripts/tabMenus.smoke.mjs new file mode 100644 index 0000000..4fd5a20 --- /dev/null +++ b/scripts/tabMenus.smoke.mjs @@ -0,0 +1,139 @@ +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } 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(15000); +const errors = []; +page.on("pageerror", error => errors.push(error.message)); +await mkdir(".audit", { recursive: true }); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\tab-menu-workspace"; + const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n`])); + window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null }; + Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } }); + let sequence = 0; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: () => ++sequence, unregisterCallback: () => {}, + invoke: async (command, args = {}) => { + if (command === "plugin:event|listen") return ++sequence; + if (command === "plugin:event|unlisten") return; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test"); + if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; } + if (command === "workspace_abs_path") return `${root}\\${args.rel}`; + if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; } + if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; } + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; +}); +const tab = name => page.getByRole("tab", { name, exact: true }); +const menu = () => page.getByRole("menu", { name: "Tab actions", exact: true }); +const item = name => page.getByRole("menuitem", { name, exact: true }); +const order = () => page.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)); +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(); + await tab(name).waitFor(); +} +async function show(name) { await tab(name).click({ button: "right" }); await menu().waitFor(); } +try { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("tab-menu-workspace", { exact: true }).waitFor(); + for (const name of ["a.md", "b.md", "c.md", "d.md"]) await open(name); + await page.locator(".cm-content").filter({ hasText: "Original text." }).waitFor(); + await show("b.md"); + assert.equal(await tab("d.md").getAttribute("aria-selected"), "true"); + assert.equal(await item("Rename…").count(), 0); + assert.equal(await item("Reading view").count(), 0); + assert.doesNotMatch(await menu().innerText(), /Alt|Shift|Ctrl/); + await page.screenshot({ path: ".audit/tab-menu-inactive.png" }); + await item("Pin").click(); + assert.equal(await tab("d.md").getAttribute("aria-selected"), "true"); + assert.ok(await tab("b.md").getAttribute("aria-describedby")); + await show("d.md"); + assert.equal(await item("Close tabs after").isDisabled(), true); + await page.screenshot({ path: ".audit/tab-menu-active.png" }); + await page.keyboard.press("Escape"); + assert.equal(await tab("d.md").evaluate(node => node === document.activeElement), true); + await tab("d.md").press("Shift+F10"); + assert.equal(await item("Close").evaluate(node => node === document.activeElement), true); + await page.keyboard.press("End"); + await page.keyboard.press("ArrowRight"); + assert.equal(await item("Move tab left").evaluate(node => node === document.activeElement), true); + await page.keyboard.press("ArrowLeft"); + await page.keyboard.press("Escape"); + await show("d.md"); + await item("Reading view").click(); + await page.locator(".md-page").waitFor(); + await show("d.md"); + await item("Editing view").click(); + await page.locator(".cm-editor").waitFor(); + await show("d.md"); + await item("Source mode").click(); + await page.locator(".monaco-editor").waitFor(); + await show("d.md"); + await item("Writing mode").click(); + await page.locator(".cm-editor").waitFor(); + await show("d.md"); + await item("Copy path").click(); + await item("Workspace path").click(); + assert.equal(await page.evaluate(() => window.tabMenuTest.clipboard), "d.md"); + await show("d.md"); + await item("Show in system explorer").click(); + assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "d.md"); + await show("d.md"); + await item("Rename…").click(); + await page.getByRole("dialog").getByRole("textbox").fill("renamed.md"); + await page.getByRole("dialog").getByRole("button", { name: "Continue", exact: true }).click(); + await tab("renamed.md").waitFor(); + await show("a.md"); + await item("Close tabs after").click(); + await tab("renamed.md").waitFor({ state: "detached" }); + assert.deepEqual(await order(), ["a.md", "b.md"]); + await open("c.md"); + await show("c.md"); + await item("Close others").click(); + await tab("a.md").waitFor({ state: "detached" }); + assert.deepEqual(await order(), ["b.md", "c.md"]); + await page.locator(".cm-content").click(); + await page.keyboard.press("Control+End"); + await page.keyboard.type("Unsaved text"); + await tab("c.md •").waitFor(); + await show("c.md •"); + await item("Close all").click(); + await page.waitForFunction(() => window.tabMenuTest.prompts.length === 1); + assert.deepEqual(await order(), ["b.md", "c.md"]); + await page.evaluate(() => { window.tabMenuTest.answer = "Ok"; }); + await show("c.md •"); + await item("Close all").click(); + await tab("c.md •").waitFor({ state: "detached" }); + assert.deepEqual(await order(), ["b.md"]); + await show("b.md"); + assert.equal(await item("Close all").isDisabled(), true); + await item("Unpin").click(); + await show("b.md"); + await item("Close").click(); + await tab("b.md").waitFor({ state: "detached" }); + await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); + await show("New tab"); + assert.equal(await item("Rename…").count(), 0); + assert.equal(await item("Reading view").count(), 0); + await page.keyboard.press("Escape"); + assert.deepEqual(errors, []); + console.log("PASS: active/inactive menus, keyboard focus, pinning, view modes, file actions, ordered closes, cancelled discard, and empty tabs"); +} catch (error) { + await page.screenshot({ path: ".audit/tab-menu-failure.png" }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/tabOrder.smoke.mjs b/scripts/tabOrder.smoke.mjs new file mode 100644 index 0000000..015d6a0 --- /dev/null +++ b/scripts/tabOrder.smoke.mjs @@ -0,0 +1,125 @@ +// Run against pnpm dev with PLAYWRIGHT_MODULE set if Playwright is shared. +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("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\tab-order-workspace"; + const files = new Map(Array.from({ length: 16 }, (_, i) => [`note-${String(i).padStart(2, "0")}.md`, `# Note ${i}\n\nKeep this text.\n`])); + files.set("note-00.md", Array.from({ length: 200 }, (_, i) => `Paragraph ${i}.\n\n`).join("")); + let sequence = 0; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: () => ++sequence, + unregisterCallback: () => {}, + invoke: async (command, args = {}) => { + if (command === "plugin:event|listen") return ++sequence; + if (command === "plugin:event|unlisten") return; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "tab-order-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") { files.set(args.rel, args.contents); return; } + if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "plugin:dialog|message") return "Cancel"; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; +}); +const tab = name => page.getByRole("tab", { name, exact: true }); +const order = () => page.getByRole("tablist", { name: "Open files" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)); +const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +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(); + await tab(name).waitFor(); +} +async function drag(from, to, side, cancel) { + const source = await tab(from).boundingBox(); + const target = await tab(to).boundingBox(); + await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); + await page.mouse.down(); + await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 }); + if (cancel === "escape") await page.keyboard.press("Escape"); + if (cancel === "outside") await page.mouse.move(target.x, target.y + 100); + await page.mouse.up(); + await settle(); +} +try { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("tab-order-workspace", { exact: true }).waitFor(); + for (const name of ["note-00.md", "note-01.md", "note-02.md"]) await open(name); + await drag("note-00.md", "note-02.md", "after"); + assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]); + assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true"); + await drag("note-00.md", "note-01.md", "before"); + assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]); + for (const cancel of ["escape", "outside"]) { + await drag("note-00.md", "note-02.md", "after", cancel); + assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]); + } + await tab("note-00.md").click(); + assert.equal(await tab("note-00.md").getAttribute("aria-selected"), "true"); + await page.locator(".cm-scroller").evaluate(node => { node.scrollTop = 1200; }); + await settle(); + const scrollTop = await page.locator(".cm-scroller").evaluate(node => node.scrollTop); + assert.ok(scrollTop > 1000); + await tab("note-00.md").press("Alt+Shift+ArrowRight"); + await settle(); + assert.deepEqual(await order(), ["note-01.md", "note-00.md", "note-02.md"]); + assert.ok(Math.abs(await page.locator(".cm-scroller").evaluate(node => node.scrollTop) - scrollTop) < 5); + assert.equal(await tab("note-00.md").evaluate(node => document.activeElement === node), true); + await tab("note-00.md").press("ArrowRight"); + assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true"); + await tab("note-02.md").press("Shift+F10"); + await page.getByRole("menuitem", { name: "Move tab", exact: true }).click(); + assert.equal(await page.getByRole("menuitem", { name: /Move tab right/ }).isDisabled(), true); + await page.getByRole("menuitem", { name: /Move tab left/ }).click(); + assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]); + await tab("note-01.md").click({ button: "right" }); + await page.getByRole("menuitem", { name: "Move tab", exact: true }).click(); + assert.equal(await page.getByRole("menuitem", { name: /Move tab left/ }).isDisabled(), true); + await page.keyboard.press("Escape"); + assert.equal(await page.getByRole("menu", { name: "Tab actions" }).count(), 0); + console.log("PASS: pointer moves, cancellation, keyboard moves, and tab menus"); + + await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); + await tab("New tab").press("Alt+Shift+Home"); + assert.match((await order())[0], /^empty:/); + await page.getByRole("button", { name: "Close New tab", exact: true }).click(); + await tab("note-01.md").click({ button: "middle" }); + assert.deepEqual(await order(), ["note-02.md", "note-00.md"]); + console.log("PASS: empty tabs and middle-click close after reorder"); + + for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`); + const bar = page.getByRole("tablist", { name: "Open files" }); + assert.ok(await bar.evaluate(node => node.scrollLeft > 0)); + await tab("note-15.md").press("Alt+Shift+Home"); + assert.equal((await order())[0], "note-15.md"); + assert.equal(await bar.evaluate(node => node.scrollLeft), 0); + const source = await tab("note-15.md").boundingBox(); + const bounds = await bar.boundingBox(); + await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 }); + await page.waitForFunction(() => { + const bar = document.querySelector('[aria-label="Open files"]'); + return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2; + }); + await page.mouse.up(); + await settle(); + assert.equal((await order()).at(-1), "note-15.md"); + assert.deepEqual(errors, []); + console.log("PASS: automatic scrolling and drag to the end of an overflowing tab bar"); + if (process.env.SCREENSHOT_PATH) await page.screenshot({ path: process.env.SCREENSHOT_PATH }); +} finally { + await browser.close(); +} diff --git a/scripts/treeActions.smoke.mjs b/scripts/treeActions.smoke.mjs new file mode 100644 index 0000000..1f44b42 --- /dev/null +++ b/scripts/treeActions.smoke.mjs @@ -0,0 +1,198 @@ +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("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\tree-actions-test"; + const files = new Map([ + ["notes/a.md", "# A"], ["notes/nested/b.md", "# B"], + ["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"], + ]); + const calls = []; + const state = { files, calls, answer: "Ok", fail: "", clipboard: "" }; + Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } }); + let sequence = 0; + const contains = (parent, path) => path === parent || path.startsWith(parent + "/"); + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: () => ++sequence, + unregisterCallback: () => {}, + invoke: async (command, args = {}) => { + calls.push({ command, args }); + if (command === "plugin:event|listen") return ++sequence; + if (command === "plugin:event|unlisten") return; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "tree-actions-test", 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") { files.set(args.rel, args.contents); 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_delete") { + if (args.rel === state.fail) throw new Error("Access denied"); + for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path); + return; + } + if (command === "workspace_copy") { + const to = args.rel + "-copy"; + for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text); + return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" }; + } + if (command === "workspace_rename") { + if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists"); + for (const [path, text] of [...files]) if (contains(args.from, path)) { + files.delete(path); + files.set(args.to + path.slice(args.from.length), text); + } + return; + } + if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\"); + if (command === "workspace_reveal") return; + if (command === "workspace_search") return []; + if (command === "plugin:dialog|message") return state.answer; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; + window.__TEST__ = state; +}); +const row = rel => page.locator(`[data-tree-rel="${rel}"]`); +const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel)); +const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command); +const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +async function reset() { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await row("notes").waitFor(); +} +async function action(path, name) { + await row(path).click({ button: "right" }); + await page.getByRole("menuitem", { name, exact: true }).click(); + await settle(); +} +async function selectFiles() { + await row("a.md").click(); + await page.getByRole("tab", { name: "a.md", exact: true }).waitFor(); + await settle(); + await row("b.md").click({ modifiers: ["Control"] }); + await settle(); +} +async function drag(sourcePath, targetPath, place = "inside") { + const source = await row(sourcePath).boundingBox(); + const target = await row(targetPath).boundingBox(); + await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); + await page.mouse.down(); + await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 }); + await page.mouse.up(); + await settle(); +} +try { + await reset(); + await selectFiles(); + await row("a.md").click({ button: "right" }); + assert.deepEqual(await selected(), ["a.md", "b.md"]); + assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), true); + await page.keyboard.press("Escape"); + await action("a.md", "Copy workspace paths"); + assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "a.md\nb.md"); + await action("b.md", "Copy system paths"); + assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "C:\\tree-actions-test\\a.md\nC:\\tree-actions-test\\b.md"); + await action("a.md", "Show in Explorer"); + assert.deepEqual((await calls("workspace_reveal")).map(args => args.rel), ["a.md", "b.md"]); + await action("a.md", "Bookmark"); + await action("b.md", "Pin"); + let marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json"))); + assert.deepEqual(marks.bookmarks, ["a.md", "b.md"]); + assert.deepEqual(marks.pins, ["a.md", "b.md"]); + await action("a.md", "Unpin"); + await action("a.md", "Remove bookmarks"); + await action("a.md", "Make copies (2)"); + assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["a.md", "b.md"]); + await row("c.md").click({ button: "right" }); + assert.deepEqual(await selected(), ["c.md"]); + assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), false); + await page.keyboard.press("Escape"); + console.log("PASS: selection, clipboard paths, marks, copies, reveal, and single-item menus"); + + await reset(); + await selectFiles(); + await page.evaluate(() => { window.__TEST__.answer = "Cancel"; }); + await action("a.md", "Delete (2)"); + assert.equal((await calls("workspace_delete")).length, 0); + assert.deepEqual(await selected(), ["a.md", "b.md"]); + await page.evaluate(() => { window.__TEST__.answer = "Ok"; window.__TEST__.fail = "a.md"; }); + await row("c.md").click({ modifiers: ["Control"] }); + await action("a.md", "Delete (3)"); + await row("c.md").waitFor({ state: "detached" }); + assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["a.md", "b.md", "c.md"]); + assert.match(await page.locator(".tree .error").textContent(), /a.md: Access denied/); + assert.deepEqual(await selected(), ["a.md"]); + console.log("PASS: cancellation, one confirmation per batch, partial failure, and selection after deletion"); + + await reset(); + await row("notes").click(); + await row("notes/nested").click(); + await row("notes").click({ modifiers: ["Control"] }); + await row("notes/a.md").click({ modifiers: ["Control"] }); + await row("notes/nested/b.md").click({ modifiers: ["Control"] }); + await row("c.md").click({ modifiers: ["Control"] }); + await action("notes/a.md", "Make copies (5)"); + assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["notes", "c.md"]); + await action("notes/nested/b.md", "Delete (5)"); + await row("notes").waitFor({ state: "detached" }); + assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["notes", "c.md"]); + assert.equal((await calls("plugin:dialog|message")).length, 1); + console.log("PASS: recursive copy and delete process selected folders and children once"); + + await reset(); + await selectFiles(); + await drag("a.md", "target"); + await row("target/b.md").waitFor(); + assert.deepEqual((await calls("workspace_rename")), [{ from: "a.md", to: "target/a 2.md" }, { from: "b.md", to: "target/b.md" }]); + assert.deepEqual(await selected(), ["target/a 2.md", "target/b.md"]); + console.log("PASS: group move into a collapsed folder preserves an existing same-name file"); + + await reset(); + await row("notes").click(); + await row("notes/a.md").click({ modifiers: ["Control"] }); + await row("c.md").click({ modifiers: ["Control"] }); + await drag("notes/a.md", "notes/nested"); + assert.equal((await calls("workspace_rename")).length, 0); + await drag("notes/a.md", "target"); + await row("target/notes").waitFor(); + assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes" }, { from: "c.md", to: "target/c.md" }]); + assert.deepEqual(await selected(), ["target/notes", "target/c.md"]); + await row("target/notes").click(); + await row("target/notes/a.md").waitFor(); + console.log("PASS: mixed folder and file moves skip selected descendants and reject drops into the same folder"); + + await reset(); + await selectFiles(); + await drag("a.md", "c.md", "after"); + marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json"))); + assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]); + await drag("b.md", "c.md", "before"); + marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json"))); + assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]); + assert.deepEqual(errors, []); + if (process.env.SCREENSHOT_PATH) { + await row("a.md").click({ button: "right" }); + await page.screenshot({ path: process.env.SCREENSHOT_PATH }); + } + console.log("PASS: group reorder preserves selected row order in both directions"); +} finally { + await browser.close(); +} diff --git a/scripts/treeActions.spec.ts b/scripts/treeActions.spec.ts new file mode 100644 index 0000000..0d08491 --- /dev/null +++ b/scripts/treeActions.spec.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "../src/lib/workspace/treeActions.ts"; +import { planDrop } from "../src/lib/workspace/treeDrop.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 entries = [entry("notes", "folder"), entry("notes/a.md"), entry("notes/sub", "folder"), entry("notes/sub/b.md"), entry("notes-old/c.md"), entry("z.md")]; +const visible = entries.map(item => item.rel_path); +const find = (path: string) => entries.find(item => item.rel_path === path) ?? null; + +test("context actions use all selected visible rows in display order", () => { + assert.deepEqual(actionEntries(entries[1], new Set(["z.md", "missing", "notes/a.md"]), visible, find), [entries[1], entries[5]]); + assert.deepEqual(actionEntries(entries[0], new Set(["z.md", "notes/a.md"]), visible, find), [entries[0]]); +}); + +test("recursive actions process each selected folder once without including similar names", () => { + assert.deepEqual(selectionRoots([...entries].reverse()), [entries[5], entries[4], entries[0]]); + assert.deepEqual(selectionRoots(entries.slice(1)), [entries[1], entries[2], entries[4], entries[5]]); +}); + +test("mixed marks become uniformly enabled or disabled and preserve other marks", () => { + const current = ["outside.md", "notes/a.md"]; + const selection = [entries[1], entries[5]]; + assert.deepEqual(setSelectedMarks(current, selection, true), ["outside.md", "notes/a.md", "z.md"]); + assert.deepEqual(setSelectedMarks(current, selection, false), ["outside.md"]); + assert.deepEqual(current, ["outside.md", "notes/a.md"]); +}); + +test("a failed action does not skip later items or lose successful results", async () => { + const visited: string[] = []; + const result = await runTreeActions(entries, async item => { + visited.push(item.rel_path); + if (item === entries[1]) throw new Error("Access denied"); + return item.name; + }); + assert.deepEqual(visited, visible); + assert.deepEqual(result.completed.map(item => item.entry), entries.filter(item => item !== entries[1])); + assert.deepEqual(result.failures, ["notes/a.md: Access denied"]); +}); + +test("moving beside an existing same-name file preserves both files in the destination order", () => { + const plan = planDrop("notes/a.md", entry("a.md"), "after", parent => parent === "notes" ? ["a.md"] : ["a.md", "z.md"]); + assert.equal(plan.action, "move"); + if (plan.action === "move") { + assert.equal(plan.to, "a 2.md"); + assert.deepEqual(plan.orderTo, ["a.md", "a 2.md", "z.md"]); + } + assert.deepEqual(planDrop("notes", entries[1], "before", () => []), { action: "noop" }); +}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 796ca7a..d601cbd 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3032,7 +3032,7 @@ dependencies = [ [[package]] name = "runestone" -version = "0.1.0" +version = "0.1.2" dependencies = [ "base64 0.23.1", "dunce", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 0fe36d5..7ed94b5 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runestone" -version = "0.1.0" +version = "0.1.2" description = "Writing workspace plus script editor" authors = ["you"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0a2fabc..adb5f94 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RuneStone", - "version": "0.1.0", + "version": "0.1.2", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/lib/editor/FindPanel.svelte b/src/lib/editor/FindPanel.svelte new file mode 100644 index 0000000..9e16c13 --- /dev/null +++ b/src/lib/editor/FindPanel.svelte @@ -0,0 +1,78 @@ + + + +
+
+
+ + searchText, value => { searchText = value; commit(); }} /> +
+
+ findPrevious(view)} disabled={!query.valid} /> + findNext(view)} disabled={!query.valid} /> + + closeSearchPanel(view)} /> +
+
+
+ + + + {#if searchText && !query.valid}Invalid expression{/if} +
+ {#if !view.state.readOnly} +
+
+ replacement, value => { replacement = value; commit(); }} /> +
+
+ + +
+
+ {/if} +
diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte index dbd83ae..7e8f597 100644 --- a/src/lib/editor/LiveWriter.svelte +++ b/src/lib/editor/LiveWriter.svelte @@ -5,6 +5,7 @@ import { defaultKeymap, history, historyField, historyKeymap, isolateHistory } from "@codemirror/commands"; import { markdown, markdownLanguage } from "@codemirror/lang-markdown"; import { searchKeymap } from "@codemirror/search"; + import { writerSearch } from "./writerSearch"; import type { OpenBuffer } from "$lib/workspace/types"; import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api"; import { linkCandidates } from "$lib/workspace/markdownLinks"; @@ -159,6 +160,7 @@ history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(), EditorView.theme({}, { dark: true }), tableNavigation, + writerSearch, keymap.of([{ key: "Escape", run: view => { if (!view.state.field(imageSource)) return false; view.dispatch({ effects: editImageSource.of(null) }); return true; @@ -335,6 +337,9 @@ .live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); } .live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; } .live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); } + .live-writer :global(.writer-divider-line) { display: flex; align-items: center; } + .live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; } + .live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); } .live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; } /* Keep child margins inside the measured widget; collapsed margins otherwise shift mouse hit-testing to the next line after a table or other preview. */ diff --git a/src/lib/editor/liveMarkdown.ts b/src/lib/editor/liveMarkdown.ts index 8abf6f8..00ffe71 100644 --- a/src/lib/editor/liveMarkdown.ts +++ b/src/lib/editor/liveMarkdown.ts @@ -13,6 +13,23 @@ import { imageSource, editImageSource, imageSourceRanges } from "./imageSource"; export const refreshImages = StateEffect.define(); const imageCleanups = new WeakMap void>(); +class Divider extends WidgetType { + eq(other: Divider) { return other instanceof Divider; } + toDOM(view: EditorView) { + const dom = document.createElement("span"); + dom.className = "writer-divider"; + dom.setAttribute("role", "separator"); + dom.addEventListener("mousedown", event => { + if (event.button !== 0 || event.shiftKey) return; + event.preventDefault(); + view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true }); + view.focus(); + }); + return dom; + } + ignoreEvent() { return false; } +} + class Checkbox extends WidgetType { constructor(readonly checked: boolean) { super(); } eq(other: Checkbox) { return this.checked === other.checked; } @@ -94,7 +111,7 @@ export function liveMarkdown(urls: Map, actions: TableContextAct if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to)); else { hiddenBlocks.push(node); - ranges.push(Decoration.replace({ widget, block }).range(node.from, node.to)); + ranges.push(Decoration.replace({ widget, block, atomic: true }).range(node.from, node.to)); } }); continue; @@ -106,10 +123,10 @@ export function liveMarkdown(urls: Map, actions: TableContextAct continue; } hiddenBlocks.push({ from: section.start, to: end }); - ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions), block: true }).range(section.start, end)); + ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions), block: true, atomic: true }).range(section.start, end)); } const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to); - const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({}).range(from, to)); }; + const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); }; const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); }; const codeRanges: { from: number; to: number }[] = []; syntaxTree(state).iterate({ enter(node) { @@ -124,6 +141,11 @@ export function liveMarkdown(urls: Map, actions: TableContextAct ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from)); } if (selected(node.from, node.to)) return; + if (node.name === "HorizontalRule") { + ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from)); + ranges.push(Decoration.replace({ widget: new Divider(), atomic: true }).range(node.from, node.to)); + return false; + } if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1)); if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong"); if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis"); @@ -148,7 +170,7 @@ export function liveMarkdown(urls: Map, actions: TableContextAct if (node.name === "TaskMarker") { const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text); if (!match) return; - ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x") }).range(line.from + match[1].length, line.from + match[0].length)); + ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(line.from + match[1].length, line.from + match[0].length)); if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed"); } } }); @@ -168,6 +190,8 @@ export function liveMarkdown(urls: Map, actions: TableContextAct update(value, transaction) { return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state) : value; }, - provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field))], + provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({ + filter: (_from, _to, decoration) => decoration.spec.atomic === true, + }))], })]; } diff --git a/src/lib/editor/writerSearch.ts b/src/lib/editor/writerSearch.ts new file mode 100644 index 0000000..e6cc469 --- /dev/null +++ b/src/lib/editor/writerSearch.ts @@ -0,0 +1,23 @@ +import { flushSync, mount, unmount } from "svelte"; +import { getSearchQuery, search, type SearchQuery } from "@codemirror/search"; +import FindPanel from "./FindPanel.svelte"; + +export const writerSearch = search({ + top: true, + createPanel(view) { + const dom = document.createElement("div"); + dom.className = "rs-writer-search"; + let panel: { sync(query: SearchQuery): void } | undefined; + return { + dom, + top: true, + mount() { + panel = mount(FindPanel, { target: dom, props: { view } }); + flushSync(); + dom.querySelector("[main-field]")?.select(); + }, + update() { panel?.sync(getSearchQuery(view.state)); }, + destroy() { if (panel) void unmount(panel); }, + }; + }, +}); diff --git a/src/lib/layout/ContextMenu.svelte b/src/lib/layout/ContextMenu.svelte index a7e11d4..e62566b 100644 --- a/src/lib/layout/ContextMenu.svelte +++ b/src/lib/layout/ContextMenu.svelte @@ -1,5 +1,6 @@ {#if !buffer || buffer.kind === "empty"} diff --git a/src/lib/layout/FileTree.svelte b/src/lib/layout/FileTree.svelte index 04f83b8..bf13b10 100644 --- a/src/lib/layout/FileTree.svelte +++ b/src/lib/layout/FileTree.svelte @@ -12,7 +12,8 @@ workspaceRename, workspaceReveal, } from "$lib/workspace/api"; - import { loadMarks, saveMarks, togglePath, type Marks } from "$lib/workspace/marks"; + import { loadMarks, saveMarks, type Marks } from "$lib/workspace/marks"; + import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions"; import { dropHint, dropPlaceAt, @@ -63,6 +64,7 @@ let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null); let sortMode = $state<"custom" | "name" | "name-desc">("custom"); let dragRel = $state(null); + let dragEntries = $state([]); let dropTarget = $state(null); let dragPoint = $state<{ x: number; y: number } | null>(null); let selection = $state({ paths: new Set(), anchor: null }); @@ -212,7 +214,7 @@ return null; } const rel = hit.dataset.treeRel; - if (!rel || rel === dragRel) { + if (!rel || dragEntries.some(entry => rel === entry.rel_path || rel.startsWith(`${entry.rel_path}/`))) { return null; } const kind = hit.dataset.treeKind === "folder" ? "folder" : "file"; @@ -228,6 +230,7 @@ const startX = event.clientX; const startY = event.clientY; let started = false; + let singleFile = false; cancelDrag?.(); const onMove = (moveEvent: PointerEvent) => { if (!started) { @@ -235,11 +238,13 @@ return; } started = true; - selectOnly(entry.rel_path); + if (!selection.paths.has(entry.rel_path)) selectOnly(entry.rel_path); + dragEntries = selectionRoots(actionEntries(entry, selection.paths, visiblePaths, findEntry)); + singleFile = selection.paths.size === 1 && entry.kind === "file"; dragRel = entry.rel_path; } dragPoint = { x: moveEvent.clientX, y: moveEvent.clientY }; - imageLanding = entry.kind === "file" && highlightImageDrop(entry.rel_path, dragPoint); + imageLanding = singleFile && highlightImageDrop(entry.rel_path, dragPoint); dropTarget = readDropAt(moveEvent.clientX, moveEvent.clientY); }; const clean = () => { @@ -248,7 +253,7 @@ window.removeEventListener("pointercancel", clean); window.removeEventListener("keydown", onKey, true); highlightImageDrop(); - dragRel = null; dropTarget = null; dragPoint = null; imageLanding = false; + dragRel = null; dragEntries = []; dropTarget = null; dragPoint = null; imageLanding = false; cancelDrag = undefined; }; const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } }; @@ -257,12 +262,12 @@ skipClick = true; setTimeout(() => { skipClick = false; }, 0); } - if (started && entry.kind === "file" && dropWorkspaceImage(entry.rel_path, { x: up.clientX, y: up.clientY })) { clean(); return; } + if (started && singleFile && dropWorkspaceImage(entry.rel_path, { x: up.clientX, y: up.clientY })) { clean(); return; } if (started && dragRel && dropTarget) { const target = findEntry(dropTarget.rel); if (target) { skipClick = true; - void handleDrop(target, dragRel, dropTarget.place); + void handleDrop(target, [...dragEntries], dropTarget.place); } } clean(); @@ -436,21 +441,35 @@ } } - async function handleDrop(target: TreeEntry, draggedRel: string, place: DropPlace) { - const plan = planDrop(draggedRel, target, place, namesIn); - if (plan.action === "noop") { + function forgetFolder(rel: string) { + childrenMap = Object.fromEntries(Object.entries(childrenMap).filter(([path]) => path !== rel && !path.startsWith(`${rel}/`))); + expanded = new Set([...expanded].filter(path => path !== rel && !path.startsWith(`${rel}/`))); + } + + async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) { + const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path); + // Load collapsed folders before checking for name conflicts. + try { + childrenMap = { ...childrenMap, [destination]: sortEntries(destination, await workspaceList(destination)) }; + } catch (err) { + error = err instanceof Error ? err.message : String(err); return; } - try { + const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path])); + const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => { + const plan = planDrop(entry.rel_path, target, place, namesIn); + if (plan.action === "noop") return; if (plan.action === "reorder") { const order = { ...marks.order }; order[plan.parent] = plan.names; await persistMarks({ ...marks, order }); await load(plan.parent); - onStatus?.(`Moved ${draggedRel}`); return; } await workspaceRename(plan.from, plan.to); + paths.set(plan.from, plan.to); + forgetFolder(plan.from); + onEntryRenamed?.(plan.from, plan.to); const order = { ...marks.order }; order[plan.fromParent] = plan.orderFrom; order[plan.toParent] = plan.orderTo; @@ -459,9 +478,36 @@ if (plan.toParent !== plan.fromParent) { await load(plan.toParent); } - selectOnly(plan.to); - onEntryRenamed?.(plan.from, plan.to); - onStatus?.(`Moved to ${plan.to}`); + }); + if (place === "inside") expanded = new Set([...expanded, destination]); + selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null }; + error = result.failures.length ? result.failures.join("\n") : null; + onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`); + } + + async function copyEntries(entries: TreeEntry[]) { + const roots = selectionRoots(entries); + const result = await runTreeActions(roots, entry => workspaceCopy(entry.rel_path)); + for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent); + error = result.failures.length ? result.failures.join("\n") : null; + onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`); + } + + async function deleteEntries(entries: TreeEntry[]) { + const roots = selectionRoots(entries); + const message = entries.length === 1 + ? `Permanently delete ${entries[0].name}${entries[0].kind === "folder" ? " and everything inside it" : ""}?` + : `Permanently delete ${entries.length} selected items${entries.some(entry => entry.kind === "folder") ? " and all contents of selected folders" : ""}?\n\n${roots.map(entry => entry.rel_path).join("\n")}`; + try { + if (!await confirm(message, { title: "Delete from disk", kind: "warning" })) return; + const result = await runTreeActions(roots, async entry => { + await workspaceDelete(entry.rel_path); + forgetFolder(entry.rel_path); + onEntryGone?.(entry.rel_path); + }); + for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent); + error = result.failures.length ? result.failures.join("\n") : null; + onStatus?.(`Deleted ${result.completed.length} of ${roots.length} items`); } catch (err) { error = err instanceof Error ? err.message : String(err); } @@ -472,6 +518,7 @@ { kind: "action", label: "Create folder", + icon: "folder-plus", run: () => { void createIn(parent, "folder"); }, @@ -479,6 +526,7 @@ { kind: "action", label: "Create new note", + icon: "file-plus", run: () => { void createIn(parent, "note"); }, @@ -490,55 +538,51 @@ if (!entry) { return paneMenuItems(""); } - const pinned = pins.has(entry.rel_path); - const bookmarked = bookmarks.has(entry.rel_path); + const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry); + const multiple = entries.length > 1; + const pinned = entries.every(item => pins.has(item.rel_path)); + const bookmarked = entries.every(item => bookmarks.has(item.rel_path)); const createItems = - entry.kind === "folder" + !multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []; return [ ...createItems, { kind: "action", - label: "Make a copy", - run: () => { - void (async () => { - try { - const copy = await workspaceCopy(entry.rel_path); - await load(parentRel(entry.rel_path)); - onStatus?.(`Copied to ${copy.rel_path}`); - } catch (err) { - error = err instanceof Error ? err.message : String(err); - } - })(); - }, + label: multiple ? `Make copies (${entries.length})` : "Make a copy", + icon: "files", + run: () => { void copyEntries(entries); }, }, { kind: "action", - label: bookmarked ? "Remove bookmark" : "Bookmark", + label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark", + icon: "bookmark", run: () => { void persistMarks({ ...marks, - bookmarks: togglePath(marks.bookmarks, entry.rel_path), + bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked), }); }, }, { kind: "sep" }, { kind: "action", - label: "Copy workspace path", + label: multiple ? "Copy workspace paths" : "Copy workspace path", + icon: "files", run: () => { - void copyText(entry.rel_path, "workspace path"); + void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path"); }, }, { kind: "action", - label: "Copy system path", + label: multiple ? "Copy system paths" : "Copy system path", + icon: "files", run: () => { void (async () => { try { - const abs = await workspaceAbsPath(entry.rel_path); - await copyText(abs, "system path"); + const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path))); + await copyText(paths.join("\n"), multiple ? "system paths" : "system path"); } catch (err) { error = err instanceof Error ? err.message : String(err); } @@ -548,13 +592,11 @@ { kind: "action", label: "Show in Explorer", + icon: "folder-open", run: () => { void (async () => { - try { - await workspaceReveal(entry.rel_path); - } catch (err) { - error = err instanceof Error ? err.message : String(err); - } + const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path)); + error = result.failures.length ? result.failures.join("\n") : null; })(); }, }, @@ -565,33 +607,24 @@ run: () => { void persistMarks({ ...marks, - pins: togglePath(marks.pins, entry.rel_path), + pins: setSelectedMarks(marks.pins, entries, !pinned), }); }, }, { kind: "action", label: "Rename", + icon: "pen", + disabled: multiple, run: () => { startRename(entry); }, }, { kind: "action", - label: "Delete", - run: () => { - void (async () => { - try { - if (!await confirm(`Permanently delete ${entry.name}${entry.kind === "folder" ? " and everything inside it" : ""}?`, { title: "Delete from disk", kind: "warning" })) return; - await workspaceDelete(entry.rel_path); - await load(parentRel(entry.rel_path)); - onEntryGone?.(entry.rel_path); - onStatus?.(`Deleted ${entry.rel_path}`); - } catch (err) { - error = err instanceof Error ? err.message : String(err); - } - })(); - }, + label: multiple ? `Delete (${entries.length})` : "Delete", + icon: "trash", + run: () => { void deleteEntries(entries); }, }, ]; } @@ -647,8 +680,8 @@ {bookmarks} {onRowClick} onContextMenu={(target, x, y) => { + if (!selection.paths.has(target.rel_path)) selectOnly(target.rel_path); menu = { x, y, entry: target }; - selectOnly(target.rel_path); }} {dropTarget} {dragRel} @@ -670,7 +703,7 @@ {#if dragRel && dragPoint} {@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
- {dragRel.split("/").pop()} + {dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()} {#if imageLanding} Insert image {:else if landing && dropTarget} @@ -715,6 +748,7 @@ padding: 4px 8px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-accent); + border-radius: var(--rs-control-radius); color: var(--rs-text-strong); font-size: 12px; } diff --git a/src/lib/layout/OutlinePane.svelte b/src/lib/layout/OutlinePane.svelte index dc98695..91647b3 100644 --- a/src/lib/layout/OutlinePane.svelte +++ b/src/lib/layout/OutlinePane.svelte @@ -1,5 +1,9 @@ -
-
Outline
+ +
+
+ Outline + void openSearch()} /> +
+ {#if searchOpen} + + {/if} {#if items.length === 0}

No headings or symbols in this file.

+ {:else if visibleItems.length === 0} +

No matching headings or symbols.

{:else}
    - {#each items as item (item.line + item.text)} + {#each visibleItems as item (item.line + item.text)}
  • {/each}
{/if} -
+