Add a workspace session for marks, renames, the index, and events
Phase 4d. session.svelte.ts holds the workspace state of each window: the marks, the note index, renames, and typed change events. It replaces refreshToken. - One rename path: session.rename serves the tree, the note title, the rename command, the link menu, plugins, and the template manager. Open documents, plugin views, the index, and the marks follow it. A title rename, the rename command, and a plugin rename now also move pins and bookmarks. - marksStore.svelte.ts is the only writer of .runestone/marks.json. Changes run in order from the latest marks. A change from another window reloads the marks. - The note index updates only the paths that change, does not rescan on window focus, reads in batches of 64, and keeps links, not text. - Plugins also hear about .runestone/ changes from other windows. - The outline uses the heading parser of heading links and Read, so lines in code blocks are no longer headings. - New note is above New file in the tree menu (card a6032af5). - New workspace/session smoke test and new unit tests for the index and the outline. pnpm check, pnpm test (347 of 347), and the full smoke suite pass, except workspace/manageTemplates, which failed one time under load and passed on retry and 4 of 4 times alone.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { createNote, noteTemplates, type NoteTemplate } from "$lib/workspace/templates";
|
||||
import { createNote, noteTemplates, TEMPLATE_FOLDER, type NoteTemplate } from "$lib/workspace/templates";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import type { TreeEntry } from "$lib/workspace/types";
|
||||
@@ -11,13 +11,13 @@
|
||||
workspaceCreate,
|
||||
workspaceDelete,
|
||||
workspaceList,
|
||||
workspaceRename,
|
||||
workspaceReveal,
|
||||
workspaceOpenDefault,
|
||||
workspaceOpenTerminal,
|
||||
} from "$lib/workspace/api";
|
||||
import { loadMarks, saveMarks, type Marks } from "$lib/workspace/marks";
|
||||
import type { Marks } from "$lib/workspace/marks";
|
||||
import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
|
||||
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
||||
import {
|
||||
dropPlaceAt,
|
||||
@@ -42,10 +42,8 @@
|
||||
workspaceRoot: string;
|
||||
activePath: string | null;
|
||||
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
|
||||
refreshToken: number;
|
||||
session: WorkspaceSession;
|
||||
onStatus?: (message: string) => void;
|
||||
onEntryGone?: (rel: string) => void;
|
||||
onEntryRenamed?: (from: string, to: string) => void;
|
||||
onCreated?: (entry: TreeEntry) => void;
|
||||
keysActive?: boolean;
|
||||
showInternal?: boolean;
|
||||
@@ -57,10 +55,8 @@
|
||||
workspaceRoot,
|
||||
activePath,
|
||||
onOpenFile,
|
||||
refreshToken,
|
||||
session,
|
||||
onStatus,
|
||||
onEntryGone,
|
||||
onEntryRenamed,
|
||||
onCreated,
|
||||
keysActive = true,
|
||||
showInternal = false,
|
||||
@@ -72,7 +68,8 @@
|
||||
let childrenMap = $state<Record<string, TreeEntry[]>>({});
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let marks = $state<Marks>({ pins: [], bookmarks: [], order: {} });
|
||||
// The session store is the only writer of the marks.
|
||||
const marks = $derived(session.marks.current);
|
||||
let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null);
|
||||
let sortMode = $state<"custom" | "name" | "name-desc">("custom");
|
||||
let dragRel = $state<string | null>(null);
|
||||
@@ -95,7 +92,7 @@
|
||||
let moving = $state(false);
|
||||
let templates = $state<NoteTemplate[]>([]);
|
||||
$effect(() => {
|
||||
void workspaceRoot; void refreshToken;
|
||||
void workspaceRoot;
|
||||
let cancelled = false;
|
||||
void noteTemplates().then(value => { if (!cancelled) templates = value; });
|
||||
return () => { cancelled = true; };
|
||||
@@ -162,15 +159,20 @@
|
||||
expanded = new Set([""]);
|
||||
selection = { paths: new Set(), anchor: null };
|
||||
childrenMap = {};
|
||||
marks = { pins: [], bookmarks: [], order: {} };
|
||||
void loadMarks().then((next) => {
|
||||
marks = next;
|
||||
});
|
||||
void load("");
|
||||
});
|
||||
|
||||
// Reload the loaded folders that a change touches. Expanded folders keep their state after a rename.
|
||||
$effect(() => session.subscribe(change => {
|
||||
const parents = new Set<string>();
|
||||
if (change.type === "changed") change.paths.forEach(path => parents.add(parentRel(path)));
|
||||
else if (change.type === "deleted") { forgetFolder(change.path); parents.add(parentRel(change.path)); }
|
||||
else if (change.type === "renamed") { renameTreePaths(change.from, change.to); parents.add(parentRel(change.from)); parents.add(parentRel(change.to)); }
|
||||
else if (change.type === "internal" && change.paths.some(path => path.startsWith(TEMPLATE_FOLDER))) void noteTemplates().then(value => templates = value);
|
||||
for (const parent of parents) if (parent in untrack(() => childrenMap)) void load(parent);
|
||||
}));
|
||||
|
||||
$effect(() => {
|
||||
void refreshToken;
|
||||
void showInternal;
|
||||
void $pluginDocumentTypes;
|
||||
const keys = untrack(() => Object.keys(childrenMap));
|
||||
@@ -366,10 +368,9 @@
|
||||
onStatus?.(`Copied ${label}`);
|
||||
}
|
||||
|
||||
async function persistMarks(next: Marks) {
|
||||
marks = next;
|
||||
async function persistMarks(change: (current: Marks) => Marks) {
|
||||
try {
|
||||
await saveMarks(next);
|
||||
await session.marks.update(change);
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -405,17 +406,13 @@
|
||||
return;
|
||||
}
|
||||
const operationRoot = workspaceRoot;
|
||||
const before = structuredClone($state.snapshot(marks));
|
||||
const before = session.marks.snapshot();
|
||||
moving = true;
|
||||
try {
|
||||
await workspaceRename(from, plan.to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) return;
|
||||
const after = moveMarks(marks, from, plan.to);
|
||||
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: structuredClone(after) }];
|
||||
if (!await session.rename(from, plan.to) || workspaceRoot !== operationRoot) return;
|
||||
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: session.marks.snapshot() }];
|
||||
redoMoves = [];
|
||||
renameTreePaths(from, plan.to);
|
||||
onEntryRenamed?.(from, plan.to);
|
||||
await persistMarks(after);
|
||||
await load(parentRel(from));
|
||||
selectOnly(plan.to);
|
||||
await focusTreePath(plan.to);
|
||||
@@ -507,9 +504,7 @@
|
||||
try {
|
||||
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
|
||||
if (workspaceRoot !== operationRoot) return;
|
||||
const order = { ...marks.order };
|
||||
order[parent] = [...(order[parent] ?? []), finalName];
|
||||
await persistMarks({ ...marks, order });
|
||||
await persistMarks(current => ({ ...current, order: { ...current.order, [parent]: [...(current.order[parent] ?? []), finalName] } }));
|
||||
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
|
||||
const next = new Set(expanded);
|
||||
next.add(parent);
|
||||
@@ -546,7 +541,7 @@
|
||||
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
|
||||
if (moving) return;
|
||||
const operationRoot = workspaceRoot;
|
||||
const before = structuredClone($state.snapshot(marks));
|
||||
const before = session.marks.snapshot();
|
||||
const moves: MoveBatch["moves"] = [];
|
||||
const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path);
|
||||
// Load collapsed folders before checking for name conflicts.
|
||||
@@ -563,23 +558,18 @@
|
||||
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
||||
if (plan.action === "noop") return;
|
||||
if (plan.action === "reorder") {
|
||||
const order = { ...marks.order };
|
||||
order[plan.parent] = plan.names;
|
||||
await persistMarks({ ...marks, order });
|
||||
await persistMarks(current => ({ ...current, order: { ...current.order, [plan.parent]: plan.names } }));
|
||||
await load(plan.parent);
|
||||
return;
|
||||
}
|
||||
await workspaceRename(plan.from, plan.to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
forgetFolder(plan.from);
|
||||
const moved = await session.rename(plan.from, plan.to, current => {
|
||||
const next = moveMarks(current, plan.from, plan.to);
|
||||
return { ...next, order: { ...next.order, [plan.fromParent]: plan.orderFrom, [plan.toParent]: plan.orderTo } };
|
||||
});
|
||||
if (!moved || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
moves.push({ from: plan.from, to: plan.to });
|
||||
paths.set(plan.from, plan.to);
|
||||
forgetFolder(plan.from);
|
||||
onEntryRenamed?.(plan.from, plan.to);
|
||||
const next = moveMarks(marks, plan.from, plan.to);
|
||||
const order = { ...next.order };
|
||||
order[plan.fromParent] = plan.orderFrom;
|
||||
order[plan.toParent] = plan.orderTo;
|
||||
await persistMarks({ ...next, order });
|
||||
await load(plan.fromParent);
|
||||
if (plan.toParent !== plan.fromParent) {
|
||||
await load(plan.toParent);
|
||||
@@ -590,7 +580,7 @@
|
||||
error = result.failures.length ? result.failures.join("\n") : null;
|
||||
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
||||
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
|
||||
undoMoves = [...undoMoves, { moves, before, after: structuredClone($state.snapshot(marks)) }];
|
||||
undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }];
|
||||
redoMoves = [];
|
||||
}
|
||||
moving = false;
|
||||
@@ -633,13 +623,12 @@
|
||||
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
|
||||
await workspaceRename(from, to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
// The batch restores the marks after all moves, so each move leaves them alone.
|
||||
if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
applied.push({ from, to });
|
||||
onEntryRenamed?.(from, to);
|
||||
}
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
await persistMarks(replayMoveMarks(marks, batch.before, batch.after, batch.moves, redo));
|
||||
await persistMarks(current => replayMoveMarks(current, batch.before, batch.after, batch.moves, redo));
|
||||
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
|
||||
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
|
||||
for (const move of applied) renameTreePaths(move.from, move.to);
|
||||
@@ -652,7 +641,7 @@
|
||||
const rollbackErrors: string[] = [];
|
||||
for (const move of applied.reverse()) {
|
||||
if (workspaceRoot !== operationRoot) { rollbackErrors.push("The original workspace is unavailable."); break; }
|
||||
try { await workspaceRename(move.to, move.from, operationRoot); onEntryRenamed?.(move.to, move.from); }
|
||||
try { await session.rename(move.to, move.from, null); }
|
||||
catch (failure) { rollbackErrors.push(String(failure)); }
|
||||
}
|
||||
if (rollbackErrors.length) { undoMoves = []; redoMoves = []; }
|
||||
@@ -664,7 +653,7 @@
|
||||
if (!clipboard || clipboard.root !== workspaceRoot || moving) return;
|
||||
const source = clipboard;
|
||||
const operationRoot = workspaceRoot;
|
||||
const before = structuredClone($state.snapshot(marks));
|
||||
const before = session.marks.snapshot();
|
||||
const moves: MoveBatch["moves"] = [];
|
||||
moving = true;
|
||||
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
|
||||
@@ -672,14 +661,11 @@
|
||||
if (source.cut) {
|
||||
const to = joinRel(parent, entry.name);
|
||||
if (to === entry.rel_path) return;
|
||||
await workspaceRename(entry.rel_path, to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
||||
if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
||||
moves.push({ from: entry.rel_path, to });
|
||||
onEntryRenamed?.(entry.rel_path, to);
|
||||
await persistMarks(moveMarks(marks, entry.rel_path, to));
|
||||
} else await workspaceCopy(entry.rel_path, parent, operationRoot);
|
||||
});
|
||||
if (moves.length) { undoMoves = [...undoMoves, { moves, before, after: structuredClone($state.snapshot(marks)) }]; redoMoves = []; }
|
||||
if (moves.length) { undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }]; redoMoves = []; }
|
||||
if (source.cut) clipboard = result.failures.length ? { ...source, paths: source.paths.filter(path => !moves.some(move => move.from === path)) } : null;
|
||||
for (const folder of new Set([parent, ...source.paths.map(parentRel)])) await load(folder);
|
||||
error = result.failures.length ? result.failures.join("\n") : null;
|
||||
@@ -719,7 +705,7 @@
|
||||
const result = await runTreeActions(roots, async entry => {
|
||||
await workspaceDelete(entry.rel_path, permanent);
|
||||
forgetFolder(entry.rel_path);
|
||||
onEntryGone?.(entry.rel_path);
|
||||
session.deleted(entry.rel_path);
|
||||
});
|
||||
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
|
||||
// The trash can be unavailable, for example on a network drive. A permanent delete stays an explicit choice.
|
||||
@@ -736,6 +722,7 @@
|
||||
async function createTreeNote(parent: string, template?: NoteTemplate) {
|
||||
try {
|
||||
const path = await createNote(parent, template);
|
||||
session.changed([path]);
|
||||
await load(parent);
|
||||
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||
} catch (reason) { error = String(reason); }
|
||||
@@ -743,18 +730,19 @@
|
||||
|
||||
function paneMenuItems(parent: string): MenuItem[] {
|
||||
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
|
||||
// New note comes first, because notes are the most common new item.
|
||||
return [
|
||||
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
|
||||
{ kind: "action" as const, label: $t("Blank note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } },
|
||||
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
|
||||
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: $t("Manage templates…"), icon: "copy" as const, run: onManageTemplates }] : []),
|
||||
] }] : [{ kind: "action" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
|
||||
{
|
||||
kind: "action",
|
||||
label: $t("New file…"),
|
||||
icon: "file-plus",
|
||||
run: () => { void createIn(parent, "file"); },
|
||||
},
|
||||
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
|
||||
{ kind: "action" as const, label: $t("Blank note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } },
|
||||
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
|
||||
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: $t("Manage templates…"), icon: "copy" as const, run: onManageTemplates }] : []),
|
||||
] }] : [{ kind: "action" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
|
||||
{ kind: "action", label: $t("New folder"), icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
|
||||
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
|
||||
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
|
||||
@@ -838,10 +826,10 @@
|
||||
label: bookmarked ? (multiple ? $t("Remove bookmarks") : $t("Remove bookmark")) : $t("Bookmark"),
|
||||
icon: "bookmark",
|
||||
run: () => {
|
||||
void persistMarks({
|
||||
...marks,
|
||||
bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked),
|
||||
});
|
||||
void persistMarks(current => ({
|
||||
...current,
|
||||
bookmarks: setSelectedMarks(current.bookmarks, entries, !bookmarked),
|
||||
}));
|
||||
},
|
||||
},
|
||||
{ kind: "sep" },
|
||||
@@ -885,10 +873,10 @@
|
||||
label: pinned ? $t("Unpin") : $t("Pin"),
|
||||
icon: "pin",
|
||||
run: () => {
|
||||
void persistMarks({
|
||||
...marks,
|
||||
pins: setSelectedMarks(marks.pins, entries, !pinned),
|
||||
});
|
||||
void persistMarks(current => ({
|
||||
...current,
|
||||
pins: setSelectedMarks(current.pins, entries, !pinned),
|
||||
}));
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user