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,23 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { loadMarks } from "$lib/workspace/marks";
|
||||
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
||||
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||
import type { TreeEntry } from "$lib/workspace/types";
|
||||
|
||||
type Props = {
|
||||
refreshToken: number;
|
||||
session: WorkspaceSession;
|
||||
onOpen: (entry: TreeEntry) => void;
|
||||
};
|
||||
|
||||
let { refreshToken, onOpen }: Props = $props();
|
||||
let bookmarks = $state<string[]>([]);
|
||||
|
||||
$effect(() => {
|
||||
void refreshToken;
|
||||
void loadMarks().then((marks) => {
|
||||
bookmarks = marks.bookmarks;
|
||||
});
|
||||
});
|
||||
let { session, onOpen }: Props = $props();
|
||||
const bookmarks = $derived(session.marks.current.bookmarks);
|
||||
</script>
|
||||
|
||||
<div class="pane">
|
||||
|
||||
@@ -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),
|
||||
}));
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import { noteTemplates, saveNoteTemplate, TEMPLATE_FOLDER, type NoteTemplate } from "$lib/workspace/templates";
|
||||
import { workspaceDelete, workspaceRename } from "$lib/workspace/api";
|
||||
import { workspaceDelete } from "$lib/workspace/api";
|
||||
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||
import type { TreeEntry } from "$lib/workspace/types";
|
||||
let { onClose, onEdit, onRenamed, onDeleted }: { onClose: () => void; onEdit: (entry: TreeEntry) => void;
|
||||
onRenamed: (from: string, to: string) => void; onDeleted: (path: string) => void } = $props();
|
||||
let { session, onClose, onEdit }: { session: WorkspaceSession; onClose: () => void; onEdit: (entry: TreeEntry) => void } = $props();
|
||||
let dialog: HTMLDialogElement;
|
||||
let templates = $state<NoteTemplate[]>([]);
|
||||
let error = $state("");
|
||||
@@ -34,7 +34,7 @@
|
||||
const path = `${TEMPLATE_FOLDER}/${title}.md`;
|
||||
if (path === template.path) return;
|
||||
busy = true; error = "";
|
||||
try { await workspaceRename(template.path, path); onRenamed(template.path, path); await refresh(); }
|
||||
try { await session.rename(template.path, path); await refresh(); }
|
||||
catch (reason) { error = String(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
@@ -43,7 +43,7 @@
|
||||
const accepted = isTauri() ? await confirm(message, { title: $t("Delete template"), kind: "warning" }) : window.confirm(message);
|
||||
if (!accepted) return;
|
||||
busy = true; error = "";
|
||||
try { await workspaceDelete(template.path); onDeleted(template.path); await refresh(); }
|
||||
try { await workspaceDelete(template.path); session.deleted(template.path); await refresh(); }
|
||||
catch (reason) { error = String(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
|
||||
+48
-108
@@ -9,8 +9,7 @@
|
||||
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { onMount, onDestroy, tick, untrack } from "svelte";
|
||||
import type { MenuLink } from "$lib/editor/linkMenu";
|
||||
import { loadMarks, saveMarks } from "$lib/workspace/marks";
|
||||
import { moveMarks } from "$lib/workspace/treeMoveHistory";
|
||||
import { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||
import { retainEditorStates } from "$lib/editor/editorStates";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
|
||||
import { selectedEditorText } from "$lib/editor/selection";
|
||||
@@ -42,7 +41,7 @@
|
||||
import TabBar from "./TabBar.svelte";
|
||||
import OutlinePane from "./OutlinePane.svelte";
|
||||
import Backlinks from "./Backlinks.svelte";
|
||||
import { WorkspaceNoteIndex, type Backlink } from "$lib/workspace/noteIndex";
|
||||
import type { Backlink } from "$lib/workspace/noteIndex";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||
import SearchPane from "./SearchPane.svelte";
|
||||
@@ -61,7 +60,6 @@
|
||||
workspaceOpenWindow,
|
||||
workspaceRead,
|
||||
workspaceReadDataUrl,
|
||||
workspaceRename,
|
||||
workspaceReveal,
|
||||
workspaceWrite,
|
||||
workspaceWriteBytes,
|
||||
@@ -95,60 +93,39 @@
|
||||
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
|
||||
let status = $state($t("Open a workspace folder"));
|
||||
let error = $state<string | null>(null);
|
||||
let refreshToken = $state(0);
|
||||
const noteIndex = new WorkspaceNoteIndex();
|
||||
let noteIndexRoot: string | null = null;
|
||||
let noteIndexRevision = $state(0);
|
||||
let noteIndexBusy = $state(false);
|
||||
let noteIndexError = $state<string | null>(null);
|
||||
let noteIndexPending: Promise<void> = Promise.resolve();
|
||||
let noteIndexRequest = 0;
|
||||
// The session owns the marks, the note index, renames, and the change events of this window.
|
||||
const session = new WorkspaceSession(() => $t("Could not read all workspace links. Rebuild the index to retry."));
|
||||
onDestroy(() => session.dispose());
|
||||
const backlinks = $derived.by(() => {
|
||||
void noteIndexRevision;
|
||||
return activePath && !editorPluginVisible ? noteIndex.backlinks(activePath) : [];
|
||||
void session.indexRevision;
|
||||
return activePath && !editorPluginVisible ? session.index.backlinks(activePath) : [];
|
||||
});
|
||||
|
||||
function rebuildNoteIndex() {
|
||||
const root = workspace?.root ?? null;
|
||||
if (root !== noteIndexRoot) {
|
||||
noteIndex.clear(); noteIndexRoot = root; noteIndexRevision = noteIndex.revision;
|
||||
}
|
||||
const request = ++noteIndexRequest;
|
||||
noteIndexBusy = !!root;
|
||||
noteIndexError = null;
|
||||
if (!root) return noteIndexPending = Promise.resolve();
|
||||
const drafts = new Map((documents?.buffers ?? []).filter(tab => tab.kind === "text" && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
|
||||
return noteIndexPending = noteIndex.rebuild({ list: workspaceList, read: workspaceRead }, drafts).then(result => {
|
||||
if (request !== noteIndexRequest || workspace?.root !== root) return;
|
||||
noteIndexRevision = noteIndex.revision;
|
||||
noteIndexBusy = false;
|
||||
if (result.errors.length) noteIndexError = $t("Could not read all workspace links. Rebuild the index to retry.");
|
||||
}).catch(reason => {
|
||||
if (request !== noteIndexRequest) return;
|
||||
noteIndexBusy = false; noteIndexError = String(reason);
|
||||
});
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void workspace?.root; void refreshToken;
|
||||
untrack(() => { void rebuildNoteIndex(); });
|
||||
const root = workspace?.root ?? null;
|
||||
untrack(() => session.open(root));
|
||||
});
|
||||
|
||||
let indexedDrafts = new Map<string, string>();
|
||||
let draftsRoot: string | null = null;
|
||||
$effect(() => {
|
||||
const root = workspace?.root ?? null;
|
||||
const drafts = new Map(tabs.filter(tab => tab.kind === "text" && isMarkdownPath(tab.relPath) && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
|
||||
untrack(() => {
|
||||
if (draftsRoot !== root) { indexedDrafts = new Map(); draftsRoot = root; }
|
||||
const removed = [...indexedDrafts.keys()].some(path => !drafts.has(path));
|
||||
for (const [path, contents] of drafts) if (indexedDrafts.get(path) !== contents) noteIndex.update(path, contents);
|
||||
indexedDrafts = drafts;
|
||||
noteIndexRevision = noteIndex.revision;
|
||||
if (removed) void rebuildNoteIndex();
|
||||
});
|
||||
untrack(() => session.setDrafts(drafts));
|
||||
});
|
||||
|
||||
// Open documents and plugin views follow the files that the session reports.
|
||||
$effect(() => session.subscribe(change => {
|
||||
if (change.type === "renamed") {
|
||||
documents?.rename(change.from, change.to);
|
||||
renamePluginDocuments(change.from, change.to);
|
||||
} else if (change.type === "deleted") {
|
||||
removePluginDocuments(change.path);
|
||||
void documents?.refresh();
|
||||
notifyPluginWorkspace();
|
||||
} else if (change.type === "changed") {
|
||||
void documents?.refresh();
|
||||
notifyPluginWorkspace();
|
||||
} else if (change.type === "internal") notifyPluginWorkspace();
|
||||
}));
|
||||
|
||||
async function openBacklink(entry: Backlink) {
|
||||
await openFile({ name: entry.sourcePath.split("/").pop()!, rel_path: entry.sourcePath, kind: "file" }, entry.line, "new");
|
||||
}
|
||||
@@ -500,7 +477,6 @@
|
||||
documents?.dispose();
|
||||
documents = createDocuments();
|
||||
status = workspace.root;
|
||||
refreshToken += 1;
|
||||
const token = new URLSearchParams(location.search).get("tabTransfer");
|
||||
if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true });
|
||||
else await restoreDocumentTabs();
|
||||
@@ -737,7 +713,7 @@
|
||||
if (documents !== current || switching) return null;
|
||||
await workspaceWriteBytes(rel, base64);
|
||||
if (documents !== current) return null;
|
||||
refreshToken += 1;
|
||||
session.changed([rel]);
|
||||
return `.length - 1)}${rel})`;
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
@@ -766,7 +742,7 @@
|
||||
try {
|
||||
await workspaceCreate(rel, "file");
|
||||
await workspaceWrite(rel, markdown + "\n", "");
|
||||
refreshToken++;
|
||||
session.changed([rel]);
|
||||
status = $t("Extracted selection to {path}", { path: rel });
|
||||
return `/${rel}`;
|
||||
} catch (err) { error = String(err); return null; }
|
||||
@@ -811,7 +787,7 @@
|
||||
await workspaceCreate(name, "file");
|
||||
await workspaceWrite(name, tab.contents, "");
|
||||
await openFile({ name: name.split("/").pop()!, rel_path: name, kind: "file" });
|
||||
refreshToken++;
|
||||
session.changed([name]);
|
||||
} catch (err) { error = String(err); }
|
||||
}
|
||||
|
||||
@@ -825,7 +801,7 @@
|
||||
}
|
||||
try {
|
||||
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
||||
refreshToken += 1;
|
||||
session.changed([name.replaceAll("\\", "/")]);
|
||||
await openCreatedFile({
|
||||
name: name.split("/").pop() ?? name,
|
||||
rel_path: name.replaceAll("\\", "/"),
|
||||
@@ -851,7 +827,7 @@
|
||||
const create = async (template?: NoteTemplate) => {
|
||||
try {
|
||||
const path = await createNote("", template);
|
||||
refreshToken++;
|
||||
session.changed([path]);
|
||||
await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||
} catch (reason) { error = String(reason); }
|
||||
};
|
||||
@@ -955,13 +931,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function applyPathRename(from: string, to: string) {
|
||||
documents?.rename(from, to);
|
||||
renamePluginDocuments(from, to);
|
||||
noteIndex.rename(from, to);
|
||||
noteIndexRevision = noteIndex.revision;
|
||||
}
|
||||
|
||||
async function renameNoteTitle(id: string, title: string) {
|
||||
const current = documents;
|
||||
const note = current?.buffers.find(tab => tab.id === id);
|
||||
@@ -970,10 +939,7 @@
|
||||
const plan = planMarkdownTitleRename(from, title);
|
||||
if (plan.action === "error") throw new Error(plan.message);
|
||||
if (plan.action === "noop") return;
|
||||
await workspaceRename(from, plan.to);
|
||||
current.rename(from, plan.to);
|
||||
if (documents !== current) return;
|
||||
refreshToken += 1;
|
||||
if (!await session.rename(from, plan.to) || documents !== current) return;
|
||||
status = $t("Renamed to {path}", { path: plan.to });
|
||||
error = null;
|
||||
}
|
||||
@@ -998,10 +964,7 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await workspaceRename(from, plan.to);
|
||||
current?.rename(from, plan.to);
|
||||
if (documents !== current) return;
|
||||
refreshToken += 1;
|
||||
if (!await session.rename(from, plan.to) || documents !== current) return;
|
||||
status = $t("Renamed to {path}", { path: plan.to });
|
||||
error = null;
|
||||
} catch (err) {
|
||||
@@ -1013,8 +976,8 @@
|
||||
const current = documents, currentWorkspace = workspace;
|
||||
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
|
||||
const entry = async () => {
|
||||
await noteIndexPending;
|
||||
const resolution = noteIndex.resolve(origin, link.target, link.kind);
|
||||
await session.indexReady;
|
||||
const resolution = session.index.resolve(origin, link.target, link.kind);
|
||||
if (resolution.status === "ambiguous") throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: resolution.candidates.join(", ") }));
|
||||
const paths = resolution.status === "resolved" ? [resolution.path] : link.kind === "wiki" ? [] : linkCandidates(origin, link.target, link.kind);
|
||||
for (const path of paths) {
|
||||
@@ -1044,13 +1007,7 @@
|
||||
to = plan.to;
|
||||
}
|
||||
if (to === file.rel_path) return;
|
||||
const marks = await loadMarks();
|
||||
if (!valid()) return;
|
||||
await workspaceRename(file.rel_path, to, currentWorkspace!.root);
|
||||
if (!valid()) return;
|
||||
applyPathRename(file.rel_path, to);
|
||||
await saveMarks(moveMarks(marks, file.rel_path, to));
|
||||
refreshToken++;
|
||||
if (!await session.rename(file.rel_path, to) || !valid()) return;
|
||||
status = $t("Moved to {path}", { path: to });
|
||||
}
|
||||
return [
|
||||
@@ -1068,10 +1025,8 @@
|
||||
{ label: $t("Rename…"), icon: "rename", run: run(file => rename(file)) },
|
||||
{ label: $t("Move file to…"), icon: "folder", run: run(file => rename(file, true)) },
|
||||
{ label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
|
||||
const marks = await loadMarks();
|
||||
if (!valid()) return;
|
||||
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
||||
refreshToken++; status = $t("Bookmarked {name}", { name: file.name });
|
||||
await session.marks.update(marks => marks.bookmarks.includes(file.rel_path) ? marks : { ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
||||
if (valid()) status = $t("Bookmarked {name}", { name: file.name });
|
||||
}) },
|
||||
{ label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
|
||||
{ label: $t("Show in system explorer"), icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
|
||||
@@ -1088,9 +1043,9 @@
|
||||
return;
|
||||
}
|
||||
const current = documents, root = workspace?.root;
|
||||
await noteIndexPending;
|
||||
await session.indexReady;
|
||||
if (documents !== current || workspace?.root !== root) return;
|
||||
const resolution = noteIndex.resolve(origin, target, kind);
|
||||
const resolution = session.index.resolve(origin, target, kind);
|
||||
if (resolution.status === "ambiguous") {
|
||||
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: resolution.candidates.join(", ") });
|
||||
return;
|
||||
@@ -1193,27 +1148,16 @@
|
||||
const plan = planDocumentTitleRename(from, name);
|
||||
if (plan.action === "error") throw new Error(plan.message);
|
||||
if (plan.action === "noop") return from;
|
||||
await workspaceRename(from, plan.to);
|
||||
if (documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
||||
applyPathRename(from, plan.to);
|
||||
refreshToken++;
|
||||
if (!await session.rename(from, plan.to) || documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
||||
return plan.to;
|
||||
}));
|
||||
unlisteners.push(guardPluginWrites(path => {
|
||||
const open = documents?.buffers.find(tab => tab.relPath === path);
|
||||
if (open && open.contents !== open.saved) throw new Error("Save or discard the open note's edits before changing it from a plugin.");
|
||||
}));
|
||||
let refreshTimer: ReturnType<typeof setTimeout>;
|
||||
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
||||
void onWorkspaceEvent((event) => {
|
||||
if (event.root !== workspace?.root) return;
|
||||
if (event.paths.every(path => path.startsWith(".runestone/") || path.split("/").pop()?.startsWith(".runestone-save-"))) return;
|
||||
clearTimeout(refreshTimer);
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshToken++;
|
||||
void documents?.refresh();
|
||||
notifyPluginWorkspace();
|
||||
}, 200);
|
||||
if (event.root === workspace?.root) session.watched(event.paths);
|
||||
}).then(register).catch(err => error = String(err));
|
||||
let closing = false;
|
||||
void getCurrentWindow().onCloseRequested(async event => {
|
||||
@@ -1229,12 +1173,12 @@
|
||||
}
|
||||
} finally { closing = false; }
|
||||
}).then(register).catch(err => error = String(err));
|
||||
const focus = () => { void documents?.refresh(); refreshToken++; };
|
||||
// Focus checks only the open documents. The file watcher reports the other changes.
|
||||
const focus = () => { void documents?.refresh(); };
|
||||
window.addEventListener("focus", focus);
|
||||
return () => {
|
||||
disposed = true;
|
||||
documents?.dispose();
|
||||
clearTimeout(refreshTimer);
|
||||
unlisteners.forEach(off => off());
|
||||
window.removeEventListener("focus", focus);
|
||||
};
|
||||
@@ -1247,10 +1191,8 @@
|
||||
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
||||
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
|
||||
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
||||
{#if templateManager && workspace}<TemplateManager onClose={() => templateManager = false}
|
||||
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }}
|
||||
onRenamed={(from, to) => { applyPathRename(from, to); refreshToken++; }}
|
||||
onDeleted={(path) => { removePluginDocuments(path); void documents?.refresh(); refreshToken++; }} />{/if}
|
||||
{#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false}
|
||||
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if}
|
||||
|
||||
<div
|
||||
class="shell"
|
||||
@@ -1357,7 +1299,7 @@
|
||||
onManageTemplates={() => templateManager = true}
|
||||
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
||||
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
||||
{refreshToken}
|
||||
{session}
|
||||
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
||||
onCreated={(entry) => {
|
||||
void openCreatedFile(entry);
|
||||
@@ -1366,14 +1308,12 @@
|
||||
status = message;
|
||||
error = null;
|
||||
}}
|
||||
onEntryGone={(path) => { removePluginDocuments(path); noteIndex.remove(path); noteIndexRevision = noteIndex.revision; void documents?.refresh(); refreshToken++; }}
|
||||
onEntryRenamed={applyPathRename}
|
||||
/>
|
||||
</div>
|
||||
{#if leftView === "search"}
|
||||
<SearchPane {searchRequest} onOpen={(entry, line) => void openFile(entry, line)} />
|
||||
{:else if leftView === "bookmarks"}
|
||||
<BookmarksPane {refreshToken} onOpen={(entry) => void openFile(entry)} />
|
||||
<BookmarksPane {session} onOpen={(entry) => void openFile(entry)} />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1515,7 +1455,7 @@
|
||||
/>
|
||||
</div>
|
||||
{#if buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
|
||||
<Backlinks entries={backlinks} busy={noteIndexBusy} error={noteIndexError} onOpen={entry => void openBacklink(entry)} onRebuild={() => void rebuildNoteIndex()} />
|
||||
<Backlinks entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={entry => void openBacklink(entry)} onRebuild={() => void session.rebuildIndex()} />
|
||||
{/if}
|
||||
</aside>
|
||||
{/if}
|
||||
|
||||
Reference in New Issue
Block a user