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:
+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