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}
|
||||
|
||||
@@ -49,6 +49,11 @@ export function workspaceRead(rel: string): Promise<string> {
|
||||
return invoke("workspace_read", { rel });
|
||||
}
|
||||
|
||||
/** Read at most 64 text files in one request. One failed file does not stop the others. */
|
||||
export function workspaceReadMany(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]> {
|
||||
return invoke("workspace_read_many", { paths });
|
||||
}
|
||||
|
||||
export async function workspaceReadBytes(rel: string): Promise<Uint8Array> {
|
||||
return new Uint8Array(await invoke<ArrayBuffer>("workspace_read_bytes", { rel }));
|
||||
}
|
||||
|
||||
@@ -20,8 +20,11 @@ export function headingSlug(text: string): string {
|
||||
return text.toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\-\s]/gu, "").replace(/\s/g, "-");
|
||||
}
|
||||
|
||||
/** Match rendered heading text and unique Markdown slugs, excluding code and properties. */
|
||||
export function documentHeadings(contents: string): { text: string; slug: string; line: number }[] {
|
||||
/**
|
||||
* The headings of a Markdown document, with rendered text and unique slugs. Code and properties have no headings.
|
||||
* The outline, heading links, and Read use this one parser, so they agree with the rendered document.
|
||||
*/
|
||||
export function documentHeadings(contents: string): { level: number; text: string; slug: string; line: number }[] {
|
||||
const source = contents.replace(/\r\n/g, "\n");
|
||||
const properties = /^\uFEFF?---\n[\s\S]*?\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(source)?.[0] ?? "";
|
||||
const offset = (properties.match(/\n/g) ?? []).length;
|
||||
@@ -34,7 +37,7 @@ export function documentHeadings(contents: string): { text: string; slug: string
|
||||
let slug = base, suffix = 0;
|
||||
while (used.has(slug)) slug = `${base}-${++suffix}`;
|
||||
used.add(slug);
|
||||
return [{ text, slug, line: token.map[0] + offset + 1 }];
|
||||
return [{ level: Number(token.tag.slice(1)), text, slug, line: token.map[0] + offset + 1 }];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -1,6 +1,4 @@
|
||||
import { workspaceRead, workspaceWrite } from "./api";
|
||||
|
||||
const MARKS_PATH = ".runestone/marks.json";
|
||||
export const MARKS_PATH = ".runestone/marks.json";
|
||||
|
||||
export type Marks = {
|
||||
pins: string[];
|
||||
@@ -8,12 +6,14 @@ export type Marks = {
|
||||
order: Record<string, string[]>;
|
||||
};
|
||||
|
||||
const EMPTY: Marks = { pins: [], bookmarks: [], order: {} };
|
||||
export function emptyMarks(): Marks {
|
||||
return { pins: [], bookmarks: [], order: {} };
|
||||
}
|
||||
|
||||
export async function loadMarks(): Promise<Marks> {
|
||||
/** Read the marks file text. Invalid or missing parts become empty. */
|
||||
export function parseMarks(text: string): Marks {
|
||||
try {
|
||||
const raw = await workspaceRead(MARKS_PATH);
|
||||
const parsed = JSON.parse(raw) as Partial<Marks>;
|
||||
const parsed = JSON.parse(text) as Partial<Marks>;
|
||||
return {
|
||||
pins: Array.isArray(parsed.pins) ? parsed.pins : [],
|
||||
bookmarks: Array.isArray(parsed.bookmarks) ? parsed.bookmarks : [],
|
||||
@@ -23,12 +23,12 @@ export async function loadMarks(): Promise<Marks> {
|
||||
: {},
|
||||
};
|
||||
} catch {
|
||||
return { pins: [], bookmarks: [], order: {} };
|
||||
return emptyMarks();
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveMarks(marks: Marks): Promise<void> {
|
||||
await workspaceWrite(MARKS_PATH, `${JSON.stringify(marks, null, 2)}\n`);
|
||||
export function serializeMarks(marks: Marks): string {
|
||||
return `${JSON.stringify(marks, null, 2)}\n`;
|
||||
}
|
||||
|
||||
export function togglePath(list: string[], rel: string): string[] {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { workspaceRead, workspaceWrite } from "./api";
|
||||
import { emptyMarks, MARKS_PATH, parseMarks, serializeMarks, type Marks } from "./marks";
|
||||
|
||||
/**
|
||||
* The only writer of `.runestone/marks.json` in a window.
|
||||
* Changes run in order and each one starts from the latest marks, so no change overwrites another.
|
||||
*/
|
||||
export class MarksStore {
|
||||
current = $state<Marks>(emptyMarks());
|
||||
#root: string | null = null;
|
||||
#text = "";
|
||||
#queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
#run<T>(task: () => Promise<T>): Promise<T> {
|
||||
const result = this.#queue.then(task, task);
|
||||
this.#queue = result.catch(() => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Load the marks of a workspace, or clear them without one. */
|
||||
open(root: string | null): Promise<void> {
|
||||
this.#root = root;
|
||||
this.#text = "";
|
||||
this.current = emptyMarks();
|
||||
return root ? this.reload() : Promise.resolve();
|
||||
}
|
||||
|
||||
/** Read the file again, for example after another window changed it. */
|
||||
reload(): Promise<void> {
|
||||
const root = this.#root;
|
||||
return this.#run(async () => {
|
||||
let text = "";
|
||||
try { text = await workspaceRead(MARKS_PATH); } catch { /* The workspace has no marks yet. */ }
|
||||
if (root !== this.#root || text === this.#text) return;
|
||||
this.#text = text;
|
||||
this.current = parseMarks(text);
|
||||
});
|
||||
}
|
||||
|
||||
/** Change the marks and save them. `change` receives a copy of the latest marks. */
|
||||
update(change: (marks: Marks) => Marks): Promise<void> {
|
||||
const root = this.#root;
|
||||
return this.#run(async () => {
|
||||
if (!root || root !== this.#root) return;
|
||||
const next = change(this.snapshot());
|
||||
const text = serializeMarks(next);
|
||||
this.current = next;
|
||||
if (text === this.#text) return;
|
||||
await workspaceWrite(MARKS_PATH, text);
|
||||
this.#text = text;
|
||||
});
|
||||
}
|
||||
|
||||
snapshot(): Marks {
|
||||
return structuredClone($state.snapshot(this.current)) as Marks;
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,13 @@ export type Backlink = {
|
||||
export type NoteIndexIO = {
|
||||
list: (folder: string) => Promise<{ rel_path: string; kind: "file" | "folder" }[]>;
|
||||
read: (path: string) => Promise<string>;
|
||||
/** Read at most 64 files in one request. Without it, the index reads 8 files at a time. */
|
||||
readMany?: (paths: string[]) => Promise<{ path: string; source?: string; error?: string }[]>;
|
||||
};
|
||||
|
||||
export type NoteIndexIssue = { path: string; operation: "list" | "read"; error: string };
|
||||
type IndexedNote = { contents: string; links: Backlink[] };
|
||||
// The index keeps the links of each note, not its text.
|
||||
type IndexedNote = { links: Backlink[] };
|
||||
type Snapshot = { files: Set<string>; notes: Map<string, IndexedNote> };
|
||||
type Change = (snapshot: Snapshot) => void;
|
||||
|
||||
@@ -129,7 +132,7 @@ export class WorkspaceNoteIndex {
|
||||
update(path: string, contents: string): void {
|
||||
const normalized = normalizePath(path);
|
||||
if (!normalized) return;
|
||||
const note = isIndexedNote(normalized) ? { contents, links: noteLinks(normalized, contents) } : null;
|
||||
const note = isIndexedNote(normalized) ? { links: noteLinks(normalized, contents) } : null;
|
||||
this.#change(snapshot => {
|
||||
snapshot.files.add(normalized);
|
||||
if (note) snapshot.notes.set(normalized, note);
|
||||
@@ -158,20 +161,16 @@ export class WorkspaceNoteIndex {
|
||||
snapshot.files.delete(path);
|
||||
snapshot.notes.delete(path);
|
||||
snapshot.files.add(replacement);
|
||||
if (note && isIndexedNote(replacement)) snapshot.notes.set(replacement, { contents: note.contents, links: noteLinks(replacement, note.contents) });
|
||||
if (note && isIndexedNote(replacement)) snapshot.notes.set(replacement, { links: note.links.map(link => ({ ...link, sourcePath: replacement })) });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async rebuild(io: NoteIndexIO, drafts: ReadonlyMap<string, string> = new Map()): Promise<{ committed: boolean; indexed: number; errors: NoteIndexIssue[] }> {
|
||||
const generation = ++this.#generation;
|
||||
const changes: Change[] = [];
|
||||
this.#changes = changes;
|
||||
const snapshot: Snapshot = { files: new Set(), notes: new Map() };
|
||||
const errors: NoteIndexIssue[] = [];
|
||||
const folders = [""];
|
||||
/** List the files below a folder. A failed folder adds an issue, and the walk continues. */
|
||||
async #walk(io: NoteIndexIO, start: string, files: Set<string>, errors: NoteIndexIssue[], current: () => boolean): Promise<void> {
|
||||
const folders = [start];
|
||||
const visited = new Set<string>();
|
||||
while (folders.length && generation === this.#generation) {
|
||||
while (folders.length && current()) {
|
||||
const folder = folders.pop()!;
|
||||
if (visited.has(folder)) continue;
|
||||
visited.add(folder);
|
||||
@@ -180,25 +179,47 @@ export class WorkspaceNoteIndex {
|
||||
const path = normalizePath(entry.rel_path);
|
||||
if (!path || (folder && !path.startsWith(`${folder}/`))) continue;
|
||||
if (entry.kind === "folder") folders.push(path);
|
||||
else snapshot.files.add(path);
|
||||
else files.add(path);
|
||||
}
|
||||
} catch (error) { errors.push({ path: folder, operation: "list", error: String(error) }); }
|
||||
}
|
||||
const files = [...snapshot.files].filter(isIndexedNote);
|
||||
for (let start = 0; start < files.length && generation === this.#generation; start += 8) {
|
||||
await Promise.all(files.slice(start, start + 8).map(async path => {
|
||||
try {
|
||||
const contents = drafts.get(path) ?? await io.read(path);
|
||||
snapshot.notes.set(path, { contents, links: noteLinks(path, contents) });
|
||||
} catch (error) { errors.push({ path, operation: "read", error: String(error) }); }
|
||||
}));
|
||||
}
|
||||
|
||||
/** Read notes in batches and keep their links. A file that is too large for a batch is read alone. */
|
||||
async #read(io: NoteIndexIO, paths: string[], notes: Map<string, IndexedNote>, errors: NoteIndexIssue[], current: () => boolean): Promise<void> {
|
||||
const keep = (path: string, contents: string) => notes.set(path, { links: noteLinks(path, contents) });
|
||||
const single = async (path: string) => {
|
||||
try { keep(path, await io.read(path)); } catch (error) { errors.push({ path, operation: "read", error: String(error) }); }
|
||||
};
|
||||
const size = io.readMany ? 64 : 8;
|
||||
for (let start = 0; start < paths.length && current(); start += size) {
|
||||
const batch = paths.slice(start, start + size);
|
||||
if (!io.readMany) { await Promise.all(batch.map(single)); continue; }
|
||||
let results: Awaited<ReturnType<NonNullable<NoteIndexIO["readMany"]>>>;
|
||||
try { results = await io.readMany(batch); } catch { await Promise.all(batch.map(single)); continue; }
|
||||
for (const result of results) {
|
||||
if (result.source !== undefined) keep(result.path, result.source);
|
||||
else if (result.error?.includes("MiB")) await single(result.path);
|
||||
else errors.push({ path: result.path, operation: "read", error: result.error ?? "Unknown error" });
|
||||
}
|
||||
}
|
||||
if (generation !== this.#generation) return { committed: false, indexed: snapshot.notes.size, errors };
|
||||
}
|
||||
|
||||
async rebuild(io: NoteIndexIO, drafts: ReadonlyMap<string, string> = new Map()): Promise<{ committed: boolean; indexed: number; errors: NoteIndexIssue[] }> {
|
||||
const generation = ++this.#generation;
|
||||
const current = () => generation === this.#generation;
|
||||
const changes: Change[] = [];
|
||||
this.#changes = changes;
|
||||
const snapshot: Snapshot = { files: new Set(), notes: new Map() };
|
||||
const errors: NoteIndexIssue[] = [];
|
||||
await this.#walk(io, "", snapshot.files, errors, current);
|
||||
await this.#read(io, [...snapshot.files].filter(path => isIndexedNote(path) && !drafts.has(path)), snapshot.notes, errors, current);
|
||||
if (!current()) return { committed: false, indexed: snapshot.notes.size, errors };
|
||||
for (const [path, contents] of drafts) {
|
||||
const normalized = normalizePath(path);
|
||||
if (!normalized || !isIndexedNote(normalized)) continue;
|
||||
snapshot.files.add(normalized);
|
||||
snapshot.notes.set(normalized, { contents, links: noteLinks(normalized, contents) });
|
||||
snapshot.notes.set(normalized, { links: noteLinks(normalized, contents) });
|
||||
}
|
||||
for (const change of changes) change(snapshot);
|
||||
this.#changes = null;
|
||||
@@ -207,6 +228,41 @@ export class WorkspaceNoteIndex {
|
||||
return { committed: true, indexed: snapshot.notes.size, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply paths that changed on disk. The index looks for each path in its parent folder.
|
||||
* A missing path leaves the index, a file is read again, and a folder is listed again with its notes.
|
||||
* Open drafts keep their unsaved links.
|
||||
*/
|
||||
async refresh(io: NoteIndexIO, paths: string[], drafts: ReadonlyMap<string, string> = new Map()): Promise<NoteIndexIssue[]> {
|
||||
const generation = this.#generation;
|
||||
const current = () => generation === this.#generation;
|
||||
const errors: NoteIndexIssue[] = [];
|
||||
const changed = [...new Set(paths.map(normalizePath).filter((path): path is string => !!path))];
|
||||
const parentOf = (path: string) => path.split("/").slice(0, -1).join("/");
|
||||
const listings = new Map<string, Map<string, "file" | "folder">>();
|
||||
for (const parent of new Set(changed.map(parentOf))) {
|
||||
// A parent that cannot be listed is gone, so its changed children are gone too.
|
||||
try { listings.set(parent, new Map((await io.list(parent)).map(entry => [normalizePath(entry.rel_path) ?? "", entry.kind]))); }
|
||||
catch { listings.set(parent, new Map()); }
|
||||
}
|
||||
const kind = (path: string) => listings.get(parentOf(path))!.get(path);
|
||||
const removed = changed.filter(path => !kind(path));
|
||||
const folders = changed.filter(path => kind(path) === "folder");
|
||||
const files = new Set(changed.filter(path => kind(path) === "file"));
|
||||
for (const folder of folders) await this.#walk(io, folder, files, errors, current);
|
||||
const notes = new Map<string, IndexedNote>();
|
||||
await this.#read(io, [...files].filter(path => isIndexedNote(path) && !drafts.has(path)), notes, errors, current);
|
||||
if (!current()) return errors;
|
||||
this.#change(snapshot => {
|
||||
for (const path of [...removed, ...folders]) for (const file of [...snapshot.files]) {
|
||||
if ((file === path || file.startsWith(`${path}/`)) && !drafts.has(file)) { snapshot.files.delete(file); snapshot.notes.delete(file); }
|
||||
}
|
||||
for (const file of files) snapshot.files.add(file);
|
||||
for (const [path, note] of notes) snapshot.notes.set(path, note);
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
resolve(origin: string, target: string, kind: "md" | "wiki"): NoteLinkResolution {
|
||||
let path = target.trim().split("#")[0];
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isMarkdownPath } from "./media";
|
||||
import { isMarkdownPath } from "./media.ts";
|
||||
import { documentHeadings } from "./headingLinks.ts";
|
||||
|
||||
export type OutlineItem = {
|
||||
level: number;
|
||||
@@ -7,21 +8,14 @@ export type OutlineItem = {
|
||||
};
|
||||
|
||||
export function buildOutline(relPath: string, contents: string): OutlineItem[] {
|
||||
// Markdown headings come from the shared parser, so lines in code blocks are not headings.
|
||||
if (isMarkdownPath(relPath)) return documentHeadings(contents).map(({ level, text, line }) => ({ level, text, line }));
|
||||
const lines = contents.split(/\r?\n/);
|
||||
const items: OutlineItem[] = [];
|
||||
const markdown = isMarkdownPath(relPath);
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
if (markdown) {
|
||||
const heading = /^(#{1,6})\s+(.+)\s*$/.exec(line);
|
||||
if (heading) {
|
||||
items.push({ level: heading[1].length, text: heading[2].trim(), line: i + 1 });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const code =
|
||||
/^(?:export\s+)?(?:async\s+)?(?:pub\s+)?(?:def|function|class|fn|struct|impl|interface|enum)\s+([A-Za-z0-9_]+)/.exec(
|
||||
line.trim(),
|
||||
lines[i].trim(),
|
||||
);
|
||||
if (code) {
|
||||
items.push({ level: 1, text: code[1], line: i + 1 });
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { workspaceList, workspaceRead, workspaceReadMany, workspaceRename } from "./api";
|
||||
import { MARKS_PATH, type Marks } from "./marks";
|
||||
import { MarksStore } from "./marksStore.svelte";
|
||||
import { WorkspaceNoteIndex, type NoteIndexIO } from "./noteIndex";
|
||||
import { moveMarks } from "./treeMoveHistory";
|
||||
|
||||
/**
|
||||
* A change to the files of the workspace. Each listener updates only what the paths touch.
|
||||
* - `opened`: the window opened another workspace, or closed it.
|
||||
* - `changed`: files were created, saved, or changed on disk.
|
||||
* - `renamed` and `deleted`: one file or folder, with its contents.
|
||||
* - `internal`: files in `.runestone/` changed, for example in another window.
|
||||
*/
|
||||
export type WorkspaceChange =
|
||||
| { type: "opened"; root: string | null }
|
||||
| { type: "changed"; paths: string[] }
|
||||
| { type: "renamed"; from: string; to: string }
|
||||
| { type: "deleted"; path: string }
|
||||
| { type: "internal"; paths: string[] };
|
||||
|
||||
const indexIO: NoteIndexIO = { list: folder => workspaceList(folder), read: workspaceRead, readMany: workspaceReadMany };
|
||||
const temporary = (path: string) => path.split("/").pop()!.startsWith(".runestone-save-");
|
||||
|
||||
/** The workspace state of one window: marks, the note index, renames, and change events. */
|
||||
export class WorkspaceSession {
|
||||
root = $state<string | null>(null);
|
||||
readonly marks = new MarksStore();
|
||||
readonly index = new WorkspaceNoteIndex();
|
||||
indexRevision = $state(0);
|
||||
indexBusy = $state(false);
|
||||
indexError = $state<string | null>(null);
|
||||
#indexReady: Promise<void> = Promise.resolve();
|
||||
#indexRequest = 0;
|
||||
#drafts: ReadonlyMap<string, string> = new Map();
|
||||
#listeners = new Set<(change: WorkspaceChange) => void>();
|
||||
#watched = new Set<string>();
|
||||
#watchTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
#indexMessage: () => string;
|
||||
|
||||
/** `indexMessage` gives the translated text for an index that could not read all files. */
|
||||
constructor(indexMessage: () => string) { this.#indexMessage = indexMessage; }
|
||||
|
||||
subscribe(listener: (change: WorkspaceChange) => void): () => void {
|
||||
this.#listeners.add(listener);
|
||||
return () => { this.#listeners.delete(listener); };
|
||||
}
|
||||
|
||||
#emit(change: WorkspaceChange) {
|
||||
for (const listener of [...this.#listeners]) listener(change);
|
||||
}
|
||||
|
||||
#indexed() { this.indexRevision = this.index.revision; }
|
||||
|
||||
/** Open a workspace, or close it with `null`. The marks load and the index builds again. */
|
||||
open(root: string | null) {
|
||||
if (root === this.root) return;
|
||||
this.root = root;
|
||||
clearTimeout(this.#watchTimer);
|
||||
this.#watched.clear();
|
||||
this.#drafts = new Map();
|
||||
this.index.clear();
|
||||
this.#indexed();
|
||||
void this.marks.open(root);
|
||||
void this.rebuildIndex();
|
||||
this.#emit({ type: "opened", root });
|
||||
}
|
||||
|
||||
/** A promise that settles when the current index build ends. */
|
||||
get indexReady(): Promise<void> { return this.#indexReady; }
|
||||
|
||||
/** Build the index from all files. The Rebuild command and a new workspace use it. */
|
||||
rebuildIndex(): Promise<void> {
|
||||
const root = this.root, request = ++this.#indexRequest;
|
||||
this.indexBusy = !!root;
|
||||
this.indexError = null;
|
||||
if (!root) return this.#indexReady = Promise.resolve();
|
||||
return this.#indexReady = this.index.rebuild(indexIO, this.#drafts).then(result => {
|
||||
if (request !== this.#indexRequest || this.root !== root) return;
|
||||
this.#indexed();
|
||||
this.indexBusy = false;
|
||||
if (result.errors.length) this.indexError = this.#indexMessage();
|
||||
}).catch(reason => {
|
||||
if (request !== this.#indexRequest) return;
|
||||
this.indexBusy = false;
|
||||
this.indexError = String(reason);
|
||||
});
|
||||
}
|
||||
|
||||
async #refreshIndex(paths: string[]) {
|
||||
const root = this.root;
|
||||
if (!root || !paths.length) return;
|
||||
try {
|
||||
const errors = await this.index.refresh(indexIO, paths, this.#drafts);
|
||||
if (this.root !== root) return;
|
||||
this.#indexed();
|
||||
if (errors.length) this.indexError = this.#indexMessage();
|
||||
} catch (reason) { if (this.root === root) this.indexError = String(reason); }
|
||||
}
|
||||
|
||||
/** Show the unsaved text of open notes in backlinks. A draft that closes is read again from disk. */
|
||||
setDrafts(drafts: ReadonlyMap<string, string>) {
|
||||
const removed = [...this.#drafts.keys()].filter(path => !drafts.has(path));
|
||||
for (const [path, contents] of drafts) if (this.#drafts.get(path) !== contents) this.index.update(path, contents);
|
||||
this.#drafts = drafts;
|
||||
this.#indexed();
|
||||
void this.#refreshIndex(removed);
|
||||
}
|
||||
|
||||
/** Files were created, saved, or changed. */
|
||||
changed(paths: string[]) {
|
||||
if (!this.root || !paths.length) return;
|
||||
void this.#refreshIndex(paths);
|
||||
this.#emit({ type: "changed", paths });
|
||||
}
|
||||
|
||||
/** A file or folder was deleted. */
|
||||
deleted(path: string) {
|
||||
if (!this.root) return;
|
||||
this.index.remove(path);
|
||||
this.#indexed();
|
||||
this.#emit({ type: "deleted", path });
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename or move a file or folder. Open documents, plugin views, the index, and the marks follow it.
|
||||
* `marks` changes the marks after the move. Pass `null` when the caller changes the marks itself.
|
||||
* Returns false when the window opened another workspace during the rename.
|
||||
*/
|
||||
async rename(from: string, to: string, marks: ((current: Marks) => Marks) | null = current => moveMarks(current, from, to)): Promise<boolean> {
|
||||
const root = this.root;
|
||||
if (!root) throw new Error("Open a workspace first.");
|
||||
await workspaceRename(from, to, root);
|
||||
if (this.root !== root) return false;
|
||||
this.index.rename(from, to);
|
||||
this.#indexed();
|
||||
this.#emit({ type: "renamed", from, to });
|
||||
if (marks) await this.marks.update(marks);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Apply paths from the file watcher. Changes collect for 200 ms, so one save causes one update. */
|
||||
watched(paths: string[]) {
|
||||
if (!this.root) return;
|
||||
for (const path of paths) if (!temporary(path)) this.#watched.add(path);
|
||||
if (paths.includes(MARKS_PATH)) void this.marks.reload();
|
||||
clearTimeout(this.#watchTimer);
|
||||
this.#watchTimer = setTimeout(() => {
|
||||
const all = [...this.#watched];
|
||||
this.#watched.clear();
|
||||
const internal = all.filter(path => path === ".runestone" || path.startsWith(".runestone/"));
|
||||
this.changed(all.filter(path => !internal.includes(path)));
|
||||
if (internal.length) this.#emit({ type: "internal", paths: internal });
|
||||
}, 200);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
clearTimeout(this.#watchTimer);
|
||||
this.#listeners.clear();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user