Improve workspace navigation, search, and tab actions

This commit is contained in:
Knotty Wyvern
2026-09-29 07:48:24 -07:00
parent bdc15e952d
commit 43106ed9c7
34 changed files with 1798 additions and 100 deletions
+3
View File
@@ -84,6 +84,9 @@ Current features and limitations as of September 2026.
positional: copying, inserting, deleting, sorting, or moving cells does not positional: copying, inserting, deleting, sorting, or moving cells does not
rewrite addresses. Cross-table references and automatic fill are not supported. rewrite addresses. Cross-table references and automatic fill are not supported.
- Tabs retain their editor models, undo history, cursor and scroll state while open. - 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. - 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. - Changed notes and scripts autosave every 5 seconds, including background tabs.
Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone", "name": "runestone",
"version": "0.1.0", "version": "0.1.2",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
+135
View File
@@ -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(); }
+138
View File
@@ -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(); }
+47
View File
@@ -24,6 +24,53 @@ function setup() {
return { docs, disk, io }; 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<void>();
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 () => { test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
const { docs, io } = setup(); const { docs, io } = setup();
await docs.open(entry("note.md")); await docs.open(entry("note.md"));
+167
View File
@@ -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(); }
+46
View File
@@ -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"));
});
+139
View File
@@ -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(); }
+125
View File
@@ -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();
}
+198
View File
@@ -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();
}
+50
View File
@@ -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" });
});
+1 -1
View File
@@ -3032,7 +3032,7 @@ dependencies = [
[[package]] [[package]]
name = "runestone" name = "runestone"
version = "0.1.0" version = "0.1.2"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "runestone" name = "runestone"
version = "0.1.0" version = "0.1.2"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["you"] authors = ["you"]
edition = "2021" edition = "2021"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "0.1.0", "version": "0.1.2",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+78
View File
@@ -0,0 +1,78 @@
<script lang="ts">
import { untrack } from "svelte";
import { runScopeHandlers, type EditorView } from "@codemirror/view";
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import "$lib/ui/find.css";
let { view }: { view: EditorView } = $props();
const initialQuery = untrack(() => getSearchQuery(view.state));
let query = $state.raw(initialQuery);
let searchText = $state(initialQuery.search);
let replacement = $state(initialQuery.replace);
let caseSensitive = $state(initialQuery.caseSensitive);
let regexp = $state(initialQuery.regexp);
let wholeWord = $state(initialQuery.wholeWord);
export function sync(next: SearchQuery) {
if (next.eq(query)) return;
query = next;
searchText = next.search;
replacement = next.replace;
caseSensitive = next.caseSensitive;
regexp = next.regexp;
wholeWord = next.wholeWord;
}
function commit() {
query = new SearchQuery({ search: searchText, replace: replacement, caseSensitive, regexp, wholeWord });
view.dispatch({ effects: setSearchQuery.of(query) });
}
function keydown(event: KeyboardEvent) {
if (runScopeHandlers(view, event, "search-panel")) {
event.preventDefault();
event.stopPropagation();
} else if (event.key === "Enter" && event.target instanceof HTMLInputElement && event.target.type === "text") {
event.preventDefault();
commit();
if (event.target.name === "replace") replaceNext(view);
else (event.shiftKey ? findPrevious : findNext)(view);
}
}
</script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Handle shortcuts from the search controls.) -->
<section class="rs-find-bar" aria-label="Find and replace" onkeydown={keydown}>
<div class="rs-find-row">
<div class="rs-find-field">
<Icon icon="search" />
<input type="text" name="search" {...{ "main-field": "true" }} aria-label="Find in document" placeholder="Find in document"
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
</div>
<div class="rs-find-actions">
<IconButton icon="up" label="Previous match (Shift+Enter)" onclick={() => findPrevious(view)} disabled={!query.valid} />
<IconButton icon="down" label="Next match (Enter)" onclick={() => findNext(view)} disabled={!query.valid} />
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>Select all</button>
<IconButton icon="close" label="Close find (Escape)" onclick={() => closeSearchPanel(view)} />
</div>
</div>
<div class="rs-find-options">
<label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />Match case</label>
<label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />Whole word</label>
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />Regex</label>
{#if searchText && !query.valid}<span class="rs-find-error" role="status">Invalid expression</span>{/if}
</div>
{#if !view.state.readOnly}
<div class="rs-find-row">
<div class="rs-find-field">
<input type="text" name="replace" aria-label="Replace with" placeholder="Replace with" bind:value={() => replacement, value => { replacement = value; commit(); }} />
</div>
<div class="rs-find-actions">
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>Replace</button>
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>Replace all</button>
</div>
</div>
{/if}
</section>
+5
View File
@@ -5,6 +5,7 @@
import { defaultKeymap, history, historyField, historyKeymap, isolateHistory } from "@codemirror/commands"; import { defaultKeymap, history, historyField, historyKeymap, isolateHistory } from "@codemirror/commands";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown"; import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { searchKeymap } from "@codemirror/search"; import { searchKeymap } from "@codemirror/search";
import { writerSearch } from "./writerSearch";
import type { OpenBuffer } from "$lib/workspace/types"; import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api"; import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks"; import { linkCandidates } from "$lib/workspace/markdownLinks";
@@ -159,6 +160,7 @@
history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(), history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(),
EditorView.theme({}, { dark: true }), EditorView.theme({}, { dark: true }),
tableNavigation, tableNavigation,
writerSearch,
keymap.of([{ key: "Escape", run: view => { keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false; if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true; 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-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-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-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; } .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 /* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */ shift mouse hit-testing to the next line after a table or other preview. */
+29 -5
View File
@@ -13,6 +13,23 @@ import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
export const refreshImages = StateEffect.define<void>(); export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>(); const imageCleanups = new WeakMap<HTMLElement, () => 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 { class Checkbox extends WidgetType {
constructor(readonly checked: boolean) { super(); } constructor(readonly checked: boolean) { super(); }
eq(other: Checkbox) { return this.checked === other.checked; } eq(other: Checkbox) { return this.checked === other.checked; }
@@ -94,7 +111,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to)); if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to));
else { else {
hiddenBlocks.push(node); 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; continue;
@@ -106,10 +123,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
continue; continue;
} }
hiddenBlocks.push({ from: section.start, to: end }); 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 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 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 }[] = []; const codeRanges: { from: number; to: number }[] = [];
syntaxTree(state).iterate({ enter(node) { syntaxTree(state).iterate({ enter(node) {
@@ -124,6 +141,11 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from)); ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
} }
if (selected(node.from, node.to)) return; 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 === "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 === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis"); if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
@@ -148,7 +170,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (node.name === "TaskMarker") { if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text); const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return; 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"); if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
} }
} }); } });
@@ -168,6 +190,8 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
update(value, transaction) { update(value, transaction) {
return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state) : value; 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,
}))],
})]; })];
} }
+23
View File
@@ -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<HTMLInputElement>("[main-field]")?.select();
},
update() { panel?.sync(getSearchQuery(view.state)); },
destroy() { if (panel) void unmount(panel); },
};
},
});
+8 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import type { MenuAction, MenuItem } from "./menuTypes"; import type { MenuAction, MenuItem } from "./menuTypes";
import Icon from "$lib/ui/Icon.svelte";
type Props = { type Props = {
x: number; x: number;
@@ -75,6 +76,7 @@
disabled={sub.disabled} disabled={sub.disabled}
onclick={() => runAction(sub)} onclick={() => runAction(sub)}
> >
{#if sub.icon}<Icon icon={sub.icon} />{/if}
{sub.label} {sub.label}
</button> </button>
{/if} {/if}
@@ -88,6 +90,7 @@
disabled={item.disabled} disabled={item.disabled}
onclick={() => runAction(item)} onclick={() => runAction(item)}
> >
{#if item.icon}<Icon icon={item.icon} />{/if}
{item.label} {item.label}
</button> </button>
{/if} {/if}
@@ -101,6 +104,7 @@
padding: 4px 0; padding: 4px 0;
background: var(--rs-bg-elevated); background: var(--rs-bg-elevated);
border: 1px solid var(--rs-border); border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
} }
@@ -139,13 +143,16 @@
} }
button { button {
display: block; display: flex;
align-items: center;
gap: 8px;
width: 100%; width: 100%;
border: 0; border: 0;
background: transparent; background: transparent;
color: var(--rs-text-strong); color: var(--rs-text-strong);
text-align: left; text-align: left;
padding: 6px 12px; padding: 6px 12px;
border-radius: var(--rs-control-radius);
} }
button:hover, button:hover,
+4
View File
@@ -76,6 +76,10 @@
if (mode !== "edit") previewMode = mode === "read" ? "preview" : "split"; if (mode !== "edit") previewMode = mode === "read" ? "preview" : "split";
if (reading !== (mode !== "edit")) onToggleReading?.(); if (reading !== (mode !== "edit")) onToggleReading?.();
} }
export function toggleReadingView() {
setDocumentMode(reading ? "edit" : "read");
}
</script> </script>
{#if !buffer || buffer.kind === "empty"} {#if !buffer || buffer.kind === "empty"}
+93 -59
View File
@@ -12,7 +12,8 @@
workspaceRename, workspaceRename,
workspaceReveal, workspaceReveal,
} from "$lib/workspace/api"; } 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 { import {
dropHint, dropHint,
dropPlaceAt, dropPlaceAt,
@@ -63,6 +64,7 @@
let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null); let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null);
let sortMode = $state<"custom" | "name" | "name-desc">("custom"); let sortMode = $state<"custom" | "name" | "name-desc">("custom");
let dragRel = $state<string | null>(null); let dragRel = $state<string | null>(null);
let dragEntries = $state<TreeEntry[]>([]);
let dropTarget = $state<DropTarget | null>(null); let dropTarget = $state<DropTarget | null>(null);
let dragPoint = $state<{ x: number; y: number } | null>(null); let dragPoint = $state<{ x: number; y: number } | null>(null);
let selection = $state<TreeSelection>({ paths: new Set(), anchor: null }); let selection = $state<TreeSelection>({ paths: new Set(), anchor: null });
@@ -212,7 +214,7 @@
return null; return null;
} }
const rel = hit.dataset.treeRel; 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; return null;
} }
const kind = hit.dataset.treeKind === "folder" ? "folder" : "file"; const kind = hit.dataset.treeKind === "folder" ? "folder" : "file";
@@ -228,6 +230,7 @@
const startX = event.clientX; const startX = event.clientX;
const startY = event.clientY; const startY = event.clientY;
let started = false; let started = false;
let singleFile = false;
cancelDrag?.(); cancelDrag?.();
const onMove = (moveEvent: PointerEvent) => { const onMove = (moveEvent: PointerEvent) => {
if (!started) { if (!started) {
@@ -235,11 +238,13 @@
return; return;
} }
started = true; 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; dragRel = entry.rel_path;
} }
dragPoint = { x: moveEvent.clientX, y: moveEvent.clientY }; 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); dropTarget = readDropAt(moveEvent.clientX, moveEvent.clientY);
}; };
const clean = () => { const clean = () => {
@@ -248,7 +253,7 @@
window.removeEventListener("pointercancel", clean); window.removeEventListener("pointercancel", clean);
window.removeEventListener("keydown", onKey, true); window.removeEventListener("keydown", onKey, true);
highlightImageDrop(); highlightImageDrop();
dragRel = null; dropTarget = null; dragPoint = null; imageLanding = false; dragRel = null; dragEntries = []; dropTarget = null; dragPoint = null; imageLanding = false;
cancelDrag = undefined; cancelDrag = undefined;
}; };
const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } }; const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } };
@@ -257,12 +262,12 @@
skipClick = true; skipClick = true;
setTimeout(() => { skipClick = false; }, 0); 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) { if (started && dragRel && dropTarget) {
const target = findEntry(dropTarget.rel); const target = findEntry(dropTarget.rel);
if (target) { if (target) {
skipClick = true; skipClick = true;
void handleDrop(target, dragRel, dropTarget.place); void handleDrop(target, [...dragEntries], dropTarget.place);
} }
} }
clean(); clean();
@@ -436,21 +441,35 @@
} }
} }
async function handleDrop(target: TreeEntry, draggedRel: string, place: DropPlace) { function forgetFolder(rel: string) {
const plan = planDrop(draggedRel, target, place, namesIn); childrenMap = Object.fromEntries(Object.entries(childrenMap).filter(([path]) => path !== rel && !path.startsWith(`${rel}/`)));
if (plan.action === "noop") { 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; 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") { if (plan.action === "reorder") {
const order = { ...marks.order }; const order = { ...marks.order };
order[plan.parent] = plan.names; order[plan.parent] = plan.names;
await persistMarks({ ...marks, order }); await persistMarks({ ...marks, order });
await load(plan.parent); await load(plan.parent);
onStatus?.(`Moved ${draggedRel}`);
return; return;
} }
await workspaceRename(plan.from, plan.to); await workspaceRename(plan.from, plan.to);
paths.set(plan.from, plan.to);
forgetFolder(plan.from);
onEntryRenamed?.(plan.from, plan.to);
const order = { ...marks.order }; const order = { ...marks.order };
order[plan.fromParent] = plan.orderFrom; order[plan.fromParent] = plan.orderFrom;
order[plan.toParent] = plan.orderTo; order[plan.toParent] = plan.orderTo;
@@ -459,9 +478,36 @@
if (plan.toParent !== plan.fromParent) { if (plan.toParent !== plan.fromParent) {
await load(plan.toParent); await load(plan.toParent);
} }
selectOnly(plan.to); });
onEntryRenamed?.(plan.from, plan.to); if (place === "inside") expanded = new Set([...expanded, destination]);
onStatus?.(`Moved to ${plan.to}`); 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) { } catch (err) {
error = err instanceof Error ? err.message : String(err); error = err instanceof Error ? err.message : String(err);
} }
@@ -472,6 +518,7 @@
{ {
kind: "action", kind: "action",
label: "Create folder", label: "Create folder",
icon: "folder-plus",
run: () => { run: () => {
void createIn(parent, "folder"); void createIn(parent, "folder");
}, },
@@ -479,6 +526,7 @@
{ {
kind: "action", kind: "action",
label: "Create new note", label: "Create new note",
icon: "file-plus",
run: () => { run: () => {
void createIn(parent, "note"); void createIn(parent, "note");
}, },
@@ -490,55 +538,51 @@
if (!entry) { if (!entry) {
return paneMenuItems(""); return paneMenuItems("");
} }
const pinned = pins.has(entry.rel_path); const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry);
const bookmarked = bookmarks.has(entry.rel_path); 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 = const createItems =
entry.kind === "folder" !multiple && entry.kind === "folder"
? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }]
: []; : [];
return [ return [
...createItems, ...createItems,
{ {
kind: "action", kind: "action",
label: "Make a copy", label: multiple ? `Make copies (${entries.length})` : "Make a copy",
run: () => { icon: "files",
void (async () => { run: () => { void copyEntries(entries); },
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);
}
})();
},
}, },
{ {
kind: "action", kind: "action",
label: bookmarked ? "Remove bookmark" : "Bookmark", label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark",
icon: "bookmark",
run: () => { run: () => {
void persistMarks({ void persistMarks({
...marks, ...marks,
bookmarks: togglePath(marks.bookmarks, entry.rel_path), bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked),
}); });
}, },
}, },
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: "Copy workspace path", label: multiple ? "Copy workspace paths" : "Copy workspace path",
icon: "files",
run: () => { 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", kind: "action",
label: "Copy system path", label: multiple ? "Copy system paths" : "Copy system path",
icon: "files",
run: () => { run: () => {
void (async () => { void (async () => {
try { try {
const abs = await workspaceAbsPath(entry.rel_path); const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path)));
await copyText(abs, "system path"); await copyText(paths.join("\n"), multiple ? "system paths" : "system path");
} catch (err) { } catch (err) {
error = err instanceof Error ? err.message : String(err); error = err instanceof Error ? err.message : String(err);
} }
@@ -548,13 +592,11 @@
{ {
kind: "action", kind: "action",
label: "Show in Explorer", label: "Show in Explorer",
icon: "folder-open",
run: () => { run: () => {
void (async () => { void (async () => {
try { const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
await workspaceReveal(entry.rel_path); error = result.failures.length ? result.failures.join("\n") : null;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})(); })();
}, },
}, },
@@ -565,33 +607,24 @@
run: () => { run: () => {
void persistMarks({ void persistMarks({
...marks, ...marks,
pins: togglePath(marks.pins, entry.rel_path), pins: setSelectedMarks(marks.pins, entries, !pinned),
}); });
}, },
}, },
{ {
kind: "action", kind: "action",
label: "Rename", label: "Rename",
icon: "pen",
disabled: multiple,
run: () => { run: () => {
startRename(entry); startRename(entry);
}, },
}, },
{ {
kind: "action", kind: "action",
label: "Delete", label: multiple ? `Delete (${entries.length})` : "Delete",
run: () => { icon: "trash",
void (async () => { run: () => { void deleteEntries(entries); },
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);
}
})();
},
}, },
]; ];
} }
@@ -647,8 +680,8 @@
{bookmarks} {bookmarks}
{onRowClick} {onRowClick}
onContextMenu={(target, x, y) => { onContextMenu={(target, x, y) => {
if (!selection.paths.has(target.rel_path)) selectOnly(target.rel_path);
menu = { x, y, entry: target }; menu = { x, y, entry: target };
selectOnly(target.rel_path);
}} }}
{dropTarget} {dropTarget}
{dragRel} {dragRel}
@@ -670,7 +703,7 @@
{#if dragRel && dragPoint} {#if dragRel && dragPoint}
{@const landing = dropTarget ? findEntry(dropTarget.rel) : null} {@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px"> <div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
<span>{dragRel.split("/").pop()}</span> <span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span>
{#if imageLanding} {#if imageLanding}
<span class="hint">Insert image</span> <span class="hint">Insert image</span>
{:else if landing && dropTarget} {:else if landing && dropTarget}
@@ -715,6 +748,7 @@
padding: 4px 8px; padding: 4px 8px;
background: var(--rs-bg-elevated); background: var(--rs-bg-elevated);
border: 1px solid var(--rs-accent); border: 1px solid var(--rs-accent);
border-radius: var(--rs-control-radius);
color: var(--rs-text-strong); color: var(--rs-text-strong);
font-size: 12px; font-size: 12px;
} }
+70 -7
View File
@@ -1,5 +1,9 @@
<script lang="ts"> <script lang="ts">
import { tick } from "svelte";
import type { OutlineItem } from "$lib/workspace/outline"; import type { OutlineItem } from "$lib/workspace/outline";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import "$lib/ui/find.css";
type Props = { type Props = {
items: OutlineItem[]; items: OutlineItem[];
@@ -7,22 +11,73 @@
}; };
let { items, onJump }: Props = $props(); let { items, onJump }: Props = $props();
let searchOpen = $state(false);
let query = $state("");
let pane: HTMLElement;
let searchInput = $state<HTMLInputElement>();
const visibleItems = $derived(items.filter(item => item.text.toLocaleLowerCase().includes(query.toLocaleLowerCase())));
async function openSearch() {
searchOpen = true;
await tick();
searchInput?.focus();
searchInput?.select();
}
function closeSearch() {
searchOpen = false;
query = "";
pane.focus();
}
function keydown(event: KeyboardEvent) {
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
event.preventDefault();
event.stopPropagation();
void openSearch();
} else if (event.key === "Escape" && searchOpen) {
event.preventDefault();
event.stopPropagation();
closeSearch();
} else if (event.key === "Enter" && event.target === searchInput && visibleItems[0]) {
event.preventDefault();
onJump(visibleItems[0].line);
}
}
</script> </script>
<div class="outline"> <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (The outline accepts focus for pane-local search shortcuts.) -->
<div class="pane-label">Outline</div> <section class="outline" aria-label="Outline" tabindex="0" bind:this={pane} onkeydown={keydown}>
<div class="pane-label">
<span>Outline</span>
<IconButton icon="search" label="Find in outline (Ctrl+F)" active={searchOpen} onclick={() => void openSearch()} />
</div>
{#if searchOpen}
<div class="rs-find-bar outline-search">
<div class="rs-find-row">
<div class="rs-find-field">
<Icon icon="search" />
<input bind:this={searchInput} bind:value={query} aria-label="Find in outline" placeholder="Find in outline" />
</div>
<IconButton icon="close" label="Close outline find (Escape)" onclick={closeSearch} />
</div>
<span class="match-count" role="status">{visibleItems.length} of {items.length} headings or symbols</span>
</div>
{/if}
{#if items.length === 0} {#if items.length === 0}
<p class="placeholder">No headings or symbols in this file.</p> <p class="placeholder">No headings or symbols in this file.</p>
{:else if visibleItems.length === 0}
<p class="placeholder">No matching headings or symbols.</p>
{:else} {:else}
<ul> <ul>
{#each items as item (item.line + item.text)} {#each visibleItems as item (item.line + item.text)}
<li style:padding-left="{8 + (item.level - 1) * 12}px"> <li style:padding-left="{8 + (item.level - 1) * 12}px">
<button type="button" onclick={() => onJump(item.line)}>{item.text}</button> <button type="button" onclick={() => onJump(item.line)}>{item.text}</button>
</li> </li>
{/each} {/each}
</ul> </ul>
{/if} {/if}
</div> </section>
<style> <style>
.outline { .outline {
@@ -33,7 +88,10 @@
} }
.pane-label { .pane-label {
padding: 6px 10px; display: flex;
align-items: center;
justify-content: space-between;
padding: 2px 8px 2px 10px;
font-size: 11px; font-size: 11px;
letter-spacing: 0.06em; letter-spacing: 0.06em;
text-transform: uppercase; text-transform: uppercase;
@@ -42,6 +100,11 @@
text-align: center; text-align: center;
} }
.outline-search { border-bottom: 1px solid var(--rs-border); }
.outline-search :global(.rs-find-row) { flex-wrap: nowrap; }
.outline-search :global(.rs-find-field) { flex-basis: 0; }
.match-count { color: var(--rs-text-dim); font-size: 11px; }
.placeholder { .placeholder {
margin: 12px; margin: 12px;
color: var(--rs-text-dim); color: var(--rs-text-dim);
@@ -54,7 +117,7 @@
overflow: auto; overflow: auto;
} }
button { li button {
width: 100%; width: 100%;
border-radius: var(--rs-control-radius); border-radius: var(--rs-control-radius);
border: 0; border: 0;
@@ -67,7 +130,7 @@
white-space: nowrap; white-space: nowrap;
} }
button:hover { li button:hover {
background: var(--rs-bg-active); background: var(--rs-bg-active);
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
+219 -8
View File
@@ -1,4 +1,8 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, tick } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { OpenBuffer } from "$lib/workspace/types"; import type { OpenBuffer } from "$lib/workspace/types";
type Props = { type Props = {
@@ -6,9 +10,175 @@
activePath: string | null; activePath: string | null;
onSelect: (relPath: string) => void; onSelect: (relPath: string) => void;
onClose: (relPath: string) => void; onClose: (relPath: string) => void;
onMove: (relPath: string, index: number) => void;
onCloseTabs: (relPath: string, scope: TabCloseScope) => void;
onPin: (relPath: string) => void;
fileActions: (tab: OpenBuffer) => ActionMenuItem[];
}; };
let { tabs, activePath, onSelect, onClose }: Props = $props(); let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions }: Props = $props();
let bar: HTMLDivElement;
let dragged = $state<string | null>(null);
let dropBefore = $state<string | null>(null);
let dropAfter = $state<string | null>(null);
let announcement = $state("");
let cancelDrag = () => {};
let suppressClick = false;
let menu: HTMLElement | undefined;
let menuAnchor: HTMLButtonElement | undefined;
let menuPath = $state<string | null>(null);
$effect(() => {
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
});
function tabButton(path: string) {
return [...bar.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find(button => button.dataset.path === path);
}
$effect(() => {
const path = activePath;
if (path) void tick().then(() => tabButton(path)?.scrollIntoView({ block: "nearest", inline: "nearest" }));
});
async function move(path: string, index: number) {
onMove(path, index);
await tick();
tabButton(path)?.focus();
const position = tabs.findIndex(tab => tab.relPath === path);
if (position >= 0) announcement = `${tabs[position].name}, position ${position + 1} of ${tabs.length}`;
}
function closeMenu(restoreFocus = false) {
menu?.remove();
menu = undefined;
menuPath = null;
if (restoreFocus) menuAnchor?.focus();
}
function showMenu(button: HTMLButtonElement, path: string, x: number, y: number) {
cancelDrag();
closeMenu();
menuAnchor = button;
const index = tabs.findIndex(tab => tab.relPath === path);
if (index < 0) return;
menuPath = path;
const run = (action: () => void) => () => { closeMenu(true); action(); };
const closing = (label: string, scope: TabCloseScope): ActionMenuItem => ({
label, icon: "close", disabled: !tabsToClose(tabs, path, scope).length,
run: run(() => onCloseTabs(path, scope)),
});
const wrapActions = (items: ActionMenuItem[]): ActionMenuItem[] => items.map(item => {
if ("separator" in item) return item;
return { ...item, run: item.run ? run(item.run) : undefined,
children: item.children ? wrapActions(item.children) : undefined };
});
menu = actionMenu(x, y, [
closing("Close", "one"),
closing("Close others", "others"),
closing("Close tabs after", "after"),
closing("Close all", "all"),
{ separator: true },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin", run: run(() => onPin(path)) },
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
{ separator: true },
{ label: "Move tab", icon: "swap", children: [
{ label: "Move tab left", icon: "move-left", disabled: index <= 0,
run: run(() => { void move(path, index - 1); }) },
{ label: "Move tab right", icon: "move-right", disabled: index === tabs.length - 1,
run: run(() => { void move(path, index + 1); }) },
] },
], () => closeMenu(true), "Tab actions");
menu.classList.add("tab-menu");
}
function onKey(event: KeyboardEvent, path: string) {
if (event.key === "Enter" || event.key === " ") suppressClick = false;
const index = tabs.findIndex(tab => tab.relPath === path);
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
event.preventDefault();
event.stopPropagation();
const button = event.currentTarget as HTMLButtonElement, bounds = button.getBoundingClientRect();
showMenu(button, path, bounds.left, bounds.bottom);
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key) && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
event.stopPropagation();
const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
: Math.max(0, Math.min(tabs.length - 1, index + (event.key === "ArrowLeft" ? -1 : 1)));
if (event.altKey && event.shiftKey) void move(path, next);
else if (!event.altKey && !event.shiftKey) {
onSelect(tabs[next].relPath);
tabButton(tabs[next].relPath)?.focus();
}
}
}
function startDrag(event: PointerEvent, path: string) {
if (event.button !== 0 || !event.isPrimary) return;
cancelDrag();
closeMenu();
suppressClick = false;
const startX = event.clientX, startY = event.clientY, pointerId = event.pointerId;
let x = startX, y = startY, started = false, destination: number | null = null, frame = 0;
const update = () => {
dropBefore = dropAfter = null;
destination = null;
const bounds = bar.getBoundingClientRect();
if (y < bounds.top || y > bounds.bottom) return;
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== path);
const before = others.findIndex(row => { const rect = row.getBoundingClientRect(); return x < rect.left + rect.width / 2; });
destination = before < 0 ? others.length : before;
if (destination === tabs.findIndex(tab => tab.relPath === path)) return;
if (before >= 0) dropBefore = others[before].dataset.path!;
else dropAfter = others.at(-1)?.dataset.path ?? null;
};
const scroll = () => {
if (!started) return;
const bounds = bar.getBoundingClientRect();
if (y >= bounds.top && y <= bounds.bottom) {
const speed = x < bounds.left + 28 ? -10 : x > bounds.right - 28 ? 10 : 0;
if (speed) { bar.scrollLeft += speed; update(); }
}
frame = requestAnimationFrame(scroll);
};
const clean = () => {
cancelAnimationFrame(frame);
dragged = dropBefore = dropAfter = null;
window.removeEventListener("pointermove", onMovePointer);
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", clean);
window.removeEventListener("blur", clean);
window.removeEventListener("keydown", onEscape, true);
cancelDrag = () => {};
};
const onMovePointer = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY;
if (!started && Math.hypot(x - startX, y - startY) < 5) return;
e.preventDefault();
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
update();
};
const onUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY;
if (started) update();
const target = destination;
clean();
if (started && target !== null) void move(path, target);
};
const onEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); clean(); }
};
cancelDrag = clean;
window.addEventListener("pointermove", onMovePointer, { passive: false });
window.addEventListener("pointerup", onUp);
window.addEventListener("pointercancel", clean);
window.addEventListener("blur", clean);
window.addEventListener("keydown", onEscape, true);
}
onDestroy(() => { cancelDrag(); closeMenu(); });
function onMiddleDown(event: MouseEvent) { function onMiddleDown(event: MouseEvent) {
if (event.button === 1) { if (event.button === 1) {
@@ -25,20 +195,33 @@
} }
</script> </script>
<div class="tabs" role="tablist" aria-label="Open files"> <svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<div bind:this={bar} class="tabs" role="tablist" aria-label="Open files">
{#each tabs as tab (tab.relPath)} {#each tabs as tab (tab.relPath)}
<div class="tab" class:active={tab.relPath === activePath}> <div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath}
class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}>
<button <button
type="button" type="button"
role="tab" role="tab"
data-path={tab.relPath}
tabindex={tab.relPath === activePath ? 0 : -1}
aria-selected={tab.relPath === activePath} aria-selected={tab.relPath === activePath}
title={tab.kind === "empty" ? tab.name : tab.relPath} aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
onclick={() => onSelect(tab.relPath)} aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.kind === "empty" ? tab.name : tab.relPath}\nDrag to reorder. Right-click for tab actions.`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => startDrag(event, tab.relPath)}
ondragstart={(event) => event.preventDefault()}
onkeydown={(event) => onKey(event, tab.relPath)}
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
onmousedown={onMiddleDown} onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)} onmouseup={(event) => onMiddleUp(event, tab.relPath)}
> >
{#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if}
{tab.name}{tab.contents !== tab.saved ? " •" : ""} {tab.name}{tab.contents !== tab.saved ? " •" : ""}
</button> </button>
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if}
<button <button
class="close" class="close"
type="button" type="button"
@@ -53,6 +236,7 @@
</div> </div>
{/each} {/each}
</div> </div>
<span class="sr-only" role="status">{announcement}</span>
<style> <style>
.tabs { .tabs {
@@ -64,21 +248,43 @@
} }
.tab { .tab {
position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
max-width: 220px; max-width: 220px;
flex-shrink: 0; flex-shrink: 0;
border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0; border-radius: var(--rs-item-selection-radius);
border-right: 1px solid var(--rs-border); border-right: 1px solid var(--rs-border);
background: var(--rs-bg); background: var(--rs-bg);
} }
.tab.active { .tab.active {
background: var(--rs-bg-active); background: var(--rs-item-selection-bg);
box-shadow: inset 0 2px var(--rs-accent); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border);
} }
.tab:hover { background: var(--rs-bg-active); }
.tab.dragging { opacity: 0.5; }
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
.tab.drop-before::before, .tab.drop-after::after {
content: "";
position: absolute;
top: 3px;
bottom: 3px;
width: 3px;
border-radius: var(--rs-control-radius);
background: var(--rs-accent);
pointer-events: none;
}
.tab.drop-before::before { left: 0; }
.tab.drop-after::after { right: 0; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.tab > button:first-child { .tab > button:first-child {
border-radius: var(--rs-control-radius);
touch-action: none;
user-select: none;
cursor: grab;
flex: 1; flex: 1;
min-width: 0; min-width: 0;
border: 0; border: 0;
@@ -96,6 +302,11 @@
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
:global(.tab-menu) { width: 244px; border-radius: var(--rs-control-radius); }
:global(.tab-menu button) { border-radius: var(--rs-control-radius); min-height: 30px; }
:global(.tab-menu .table-cell-submenu) { border-radius: var(--rs-control-radius); }
.close { .close {
border: 0; border: 0;
border-radius: var(--rs-control-radius); border-radius: var(--rs-control-radius);
+70 -12
View File
@@ -7,6 +7,8 @@
import { confirm } from "@tauri-apps/plugin-dialog"; import { confirm } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener"; import { openUrl } from "@tauri-apps/plugin-opener";
import { Documents } from "$lib/workspace/documents"; import { Documents } from "$lib/workspace/documents";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { ActionMenuItem } from "$lib/ui/actionMenu";
import { requestText } from "$lib/workspace/dialogs.svelte"; import { requestText } from "$lib/workspace/dialogs.svelte";
import TextDialog from "./TextDialog.svelte"; import TextDialog from "./TextDialog.svelte";
import QuickOpen from "./QuickOpen.svelte"; import QuickOpen from "./QuickOpen.svelte";
@@ -32,6 +34,7 @@
workspaceRead, workspaceRead,
workspaceReadDataUrl, workspaceReadDataUrl,
workspaceRename, workspaceRename,
workspaceReveal,
workspaceWrite, workspaceWrite,
workspaceWriteBytes, workspaceWriteBytes,
} from "$lib/workspace/api"; } from "$lib/workspace/api";
@@ -68,6 +71,8 @@
let saving = $state(false); let saving = $state(false);
let switching = false; let switching = false;
let documents: Documents | null = null; let documents: Documents | null = null;
let editorPane: EditorPane | undefined = $state();
let closingTabs = false;
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved)); const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
function createDocuments() { function createDocuments() {
@@ -194,10 +199,58 @@
} }
async function closeTab(relPath: string) { async function closeTab(relPath: string) {
const tab = tabs.find(item => item.relPath === relPath); await closeTabs(relPath, "one");
if (!tab) return; }
if (tab.contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) return;
documents?.close(relPath); async function closeTabs(path: string, scope: TabCloseScope) {
const current = documents;
if (!current || closingTabs || switching) return;
closingTabs = true;
try {
const targets = tabsToClose(current.buffers, path, scope);
for (const target of targets) {
if (documents !== current || switching) break;
const tab = current.buffers.find(item => item.id === target.id);
if (!tab || (scope !== "one" && tab.pinned)) continue;
const contents = tab.contents;
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break;
if (documents !== current || switching || tab.contents !== contents) break;
if (scope !== "one" && tab.pinned) continue;
current.close(tab.relPath);
}
} catch (err) { error = String(err); }
finally { closingTabs = false; }
}
async function copyTabPath(path: string, system: boolean) {
try {
const text = system ? await workspaceAbsPath(path) : path;
await navigator.clipboard.writeText(text);
status = system ? "Copied system path" : "Copied workspace path";
} catch (err) { error = String(err); }
}
function tabFileActions(tab: OpenBuffer): ActionMenuItem[] {
if (tab.kind === "empty") return [];
const items: ActionMenuItem[] = [];
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push(
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
);
}
items.push({ separator: true },
{ label: "Rename…", icon: "rename", run: () => { void renameActive(); } },
);
if (tab.kind === "text") items.push({ label: "Save a copy…", icon: "copy", run: () => { void saveCopy(); } });
items.push({ separator: true },
{ label: "Copy path", icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
{ label: "System path", icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
] },
{ label: "Show in system explorer", icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
);
return items;
} }
async function openFile(entry: TreeEntry, line?: number, target: "current" | "new" = "new") { async function openFile(entry: TreeEntry, line?: number, target: "current" | "new" = "new") {
@@ -427,12 +480,13 @@
if (!activePath || buffer?.kind === "empty") { if (!activePath || buffer?.kind === "empty") {
return; return;
} }
const current = activePath.split("/").pop() ?? activePath; const current = documents;
const typed = await requestText("Rename to", current); const from = activePath;
if (typed == null) { const typed = await requestText("Rename to", from.split("/").pop() ?? from);
if (typed == null || documents !== current || switching) {
return; return;
} }
const plan = planRename(activePath, typed); const plan = planRename(from, typed);
if (plan.action === "error") { if (plan.action === "error") {
error = plan.message; error = plan.message;
return; return;
@@ -441,8 +495,9 @@
return; return;
} }
try { try {
await workspaceRename(activePath, plan.to); await workspaceRename(from, plan.to);
applyPathRename(activePath, plan.to); current?.rename(from, plan.to);
if (documents !== current) return;
refreshToken += 1; refreshToken += 1;
status = `Renamed to ${plan.to}`; status = `Renamed to ${plan.to}`;
error = null; error = null;
@@ -569,7 +624,9 @@
</div> </div>
<div class="header-center" data-tauri-drag-region> <div class="header-center" data-tauri-drag-region>
{#if tabs.length > 0} {#if tabs.length > 0}
<TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab} /> <TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab}
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)}
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} />
{/if} {/if}
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} /> <IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if} {#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
@@ -650,6 +707,7 @@
<details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details> <details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details>
{/if} {/if}
<EditorPane <EditorPane
bind:this={editorPane}
{tabs} {tabs}
hasWorkspace={!!workspace} hasWorkspace={!!workspace}
onOpenWorkspace={() => void chooseWorkspace()} onOpenWorkspace={() => void chooseWorkspace()}
@@ -811,7 +869,7 @@
} }
.header-center :global(.tab.active) { .header-center :global(.tab.active) {
background: var(--rs-bg-active); background: var(--rs-item-selection-bg);
} }
.ws { .ws {
+3
View File
@@ -1,8 +1,11 @@
import type { IconName } from "$lib/ui/IconButton.svelte";
export type MenuAction = { export type MenuAction = {
kind: "action"; kind: "action";
label: string; label: string;
run: () => void; run: () => void;
disabled?: boolean; disabled?: boolean;
icon?: IconName;
}; };
export type MenuSep = { kind: "sep" }; export type MenuSep = { kind: "sep" };
+4 -1
View File
@@ -1,9 +1,12 @@
<script lang="ts"> <script lang="ts">
import type { IconName } from "./IconButton.svelte"; import type { IconName } from "./IconButton.svelte";
import { actionIcons } from "./actionIcons";
let { icon }: { icon: IconName } = $props(); let { icon }: { icon: IconName } = $props();
</script> </script>
<svg viewBox="0 0 24 24" aria-hidden="true"> <svg viewBox="0 0 24 24" aria-hidden="true">
{#if icon === "more"} {#if icon === "up" || icon === "down"}
{@html actionIcons[icon]}
{:else if icon === "more"}
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" /> <circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
{:else if icon === "chevron-down"} {:else if icon === "chevron-down"}
<path d="m6 9 6 6 6-6" /> <path d="m6 9 6 6 6-6" />
+2
View File
@@ -5,6 +5,8 @@
| "split" | "split"
| "more" | "more"
| "chevron-down" | "chevron-down"
| "up"
| "down"
| "maximize" | "maximize"
| "minimize" | "minimize"
| "window-maximize" | "window-maximize"
+3
View File
@@ -1,5 +1,8 @@
// Stroke icons share the same 24px grid and weight as IconButton. // Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = { export const actionIcons = {
pin: '<path d="m16 3 5 5-4 1-3 3 1 4-2 2-7-7 2-2 4 1 3-3ZM8 16l-5 5"/>',
book: '<path d="M12 6v15M3 3h5a4 4 0 0 1 4 3 4 4 0 0 1 4-3h5v15h-5a4 4 0 0 0-4 3 4 4 0 0 0-4-3H3Z"/>',
folder: '<path d="M3 7V4h6l3 3h9v13H3Z"/>',
rename: '<path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>', rename: '<path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
'zoom-in': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6M10 7v6"/>', 'zoom-in': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6M10 7v6"/>',
'zoom-out': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6"/>', 'zoom-out': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6"/>',
+59
View File
@@ -0,0 +1,59 @@
.rs-find-bar {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 10px;
background: var(--rs-bg-elevated);
color: var(--rs-text);
font: 13px/1.4 var(--rs-font-ui);
}
.rs-find-row, .rs-find-actions, .rs-find-field, .rs-find-options {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.rs-find-row, .rs-find-options { flex-wrap: wrap; }
.rs-find-actions { flex: 0 0 auto; }
.rs-find-field {
flex: 1 1 180px;
min-height: 30px;
padding: 0 8px;
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: var(--rs-bg);
color: var(--rs-text-dim);
}
.rs-find-field:focus-within { border-color: var(--rs-accent); }
.rs-find-field:has([aria-invalid="true"]) { border-color: var(--rs-error); }
.rs-find-field input {
width: 100%;
min-width: 0;
padding: 5px 0;
border: 0;
outline: none;
background: transparent;
color: var(--rs-text);
font: inherit;
}
.rs-find-field input::placeholder { color: var(--rs-text-dim); }
.rs-find-button {
min-height: 28px;
padding: 3px 9px;
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text);
font: inherit;
white-space: nowrap;
}
.rs-find-button:hover:not(:disabled) { background: var(--rs-bg-active); color: var(--rs-accent); }
.rs-find-options { gap: 4px 14px; color: var(--rs-text-dim); font-size: 12px; }
.rs-find-options label { display: inline-flex; align-items: center; gap: 5px; min-height: 24px; cursor: pointer; }
.rs-find-options input { margin: 0; accent-color: var(--rs-accent); }
.rs-find-error { color: var(--rs-error); }
.live-writer .cm-panels.cm-panels-top { border-bottom: 1px solid var(--rs-border); }
.live-writer .cm-searchMatch { background: var(--rs-item-selection-bg); }
.live-writer .cm-searchMatch-selected { background: var(--rs-selection); outline: 1px solid var(--rs-accent); }
+20 -1
View File
@@ -71,7 +71,7 @@ export class Documents {
} }
if (!this.disposed && request === this.selection) { if (!this.disposed && request === this.selection) {
// Replace only after a successful read, and never discard edits or disk conflicts. // Replace only after a successful read, and never discard edits or disk conflicts.
if (!alreadyOpen && previous && previous.contents === previous.saved if (!alreadyOpen && previous && !previous.pinned && previous.contents === previous.saved
&& previous.diskContents === undefined && !previous.diskError) { && previous.diskContents === undefined && !previous.diskError) {
const index = this.buffers.indexOf(previous); const index = this.buffers.indexOf(previous);
const opened = this.buffers.find(b => b.relPath === entry.rel_path); const opened = this.buffers.find(b => b.relPath === entry.rel_path);
@@ -102,6 +102,25 @@ export class Documents {
this.emit(); this.emit();
} }
togglePin(path: string) {
if (this.disposed) return;
const buffer = this.buffers.find(b => b.relPath === path);
if (!buffer) return;
buffer.pinned = !buffer.pinned;
this.emit();
}
move(path: string, to: number) {
if (this.disposed || !Number.isInteger(to)) return;
const from = this.buffers.findIndex(b => b.relPath === path);
if (from < 0) return;
const index = Math.max(0, Math.min(to, this.buffers.length - 1));
if (from === index) return;
const [buffer] = this.buffers.splice(from, 1);
this.buffers.splice(index, 0, buffer);
this.emit();
}
rename(from: string, to: string) { rename(from: string, to: string) {
for (const b of this.buffers) { for (const b of this.buffers) {
if (b.kind === "empty") continue; if (b.kind === "empty") continue;
+12
View File
@@ -0,0 +1,12 @@
import type { OpenBuffer } from "./types";
export type TabCloseScope = "one" | "others" | "after" | "all";
export function tabsToClose(tabs: OpenBuffer[], path: string, scope: TabCloseScope): OpenBuffer[] {
const index = tabs.findIndex(tab => tab.relPath === path);
if (index < 0) return [];
if (scope === "one") return [tabs[index]];
return tabs.filter((tab, position) => !tab.pinned && (
scope === "all" || (scope === "others" ? position !== index : position > index)
));
}
+41
View File
@@ -0,0 +1,41 @@
import type { TreeEntry } from "./types";
export function actionEntries(entry: TreeEntry, selected: ReadonlySet<string>, visible: readonly string[], find: (path: string) => TreeEntry | null): TreeEntry[] {
if (!selected.has(entry.rel_path)) return [entry];
return visible.filter(path => selected.has(path)).map(find).filter((item): item is TreeEntry => item !== null);
}
export function selectionRoots(entries: readonly TreeEntry[]): TreeEntry[] {
const folders = new Set(entries.filter(entry => entry.kind === "folder").map(entry => entry.rel_path));
return entries.filter(entry => {
const parts = entry.rel_path.split("/");
parts.pop();
while (parts.length) {
if (folders.has(parts.join("/"))) return false;
parts.pop();
}
return true;
});
}
export function setSelectedMarks(current: readonly string[], entries: readonly TreeEntry[], enabled: boolean): string[] {
const next = new Set(current);
for (const entry of entries) {
if (enabled) next.add(entry.rel_path);
else next.delete(entry.rel_path);
}
return [...next];
}
export async function runTreeActions<T>(entries: readonly TreeEntry[], action: (entry: TreeEntry) => Promise<T>) {
const completed: { entry: TreeEntry; result: T }[] = [];
const failures: string[] = [];
for (const entry of entries) {
try {
completed.push({ entry, result: await action(entry) });
} catch (error) {
failures.push(`${entry.rel_path}: ${error instanceof Error ? error.message : String(error)}`);
}
}
return { completed, failures };
}
+2 -2
View File
@@ -122,7 +122,7 @@ export function planDrop(
}; };
} }
if (target.kind === "folder" && isInside(draggedRel, target.rel_path)) { if (isInside(draggedRel, target.rel_path)) {
return { action: "noop" }; return { action: "noop" };
} }
@@ -137,7 +137,7 @@ export function planDrop(
} }
const destName = uniqueName(childrenOf(toParent), draggedName); const destName = uniqueName(childrenOf(toParent), draggedName);
const names = childrenOf(toParent).filter((name) => name !== draggedName); const names = childrenOf(toParent);
return { return {
action: "move", action: "move",
from: draggedRel, from: draggedRel,
+1
View File
@@ -30,6 +30,7 @@ export type OpenBuffer = {
chromeOverride: Chrome | null; chromeOverride: Chrome | null;
kind: "text" | "image" | "empty"; kind: "text" | "image" | "empty";
imageUrl: string | null; imageUrl: string | null;
pinned?: boolean;
diskContents?: string | null; diskContents?: string | null;
diskError?: string | null; diskError?: string | null;
}; };