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
-1
@@ -83,7 +83,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
|
|||||||
| `layout/` | The app shell (`Workbench.svelte`), the file tree, tabs, panes, Settings, and dialogs |
|
| `layout/` | The app shell (`Workbench.svelte`), the file tree, tabs, panes, Settings, and dialogs |
|
||||||
| `editor/` | The document editor (`DocumentEditor.svelte`) with its Write and Source configurations, Markdown lists, tables, links, images, and editor menus |
|
| `editor/` | The document editor (`DocumentEditor.svelte`) with its Write and Source configurations, Markdown lists, tables, links, images, and editor menus |
|
||||||
| `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) |
|
| `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) |
|
||||||
| `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, templates, and tab transfer (`tabTransfer.ts`) |
|
| `workspace/` | Tauri wrappers, document buffers, the workspace session (`session.svelte.ts`: marks, renames, change events, and the note index), paths, templates, and tab transfer (`tabTransfer.ts`) |
|
||||||
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
|
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
|
||||||
| `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins |
|
| `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins |
|
||||||
| `browser/` | The interface of the built-in browser |
|
| `browser/` | The interface of the built-in browser |
|
||||||
|
|||||||
@@ -374,7 +374,7 @@ All paths are relative to the active workspace of the window. The host rejects p
|
|||||||
| `readBytes(path)` | yes | Read a file of at most 64 MiB as a `Uint8Array`. |
|
| `readBytes(path)` | yes | Read a file of at most 64 MiB as a `Uint8Array`. |
|
||||||
| `create(path, contents)` | yes | Create a text file. Fails when the file exists. |
|
| `create(path, contents)` | yes | Create a text file. Fails when the file exists. |
|
||||||
| `write(path, contents, expected)` | | Save the file only if it still contains `expected`. `expected` is required. |
|
| `write(path, contents, expected)` | | Save the file only if it still contains `expected`. `expected` is required. |
|
||||||
| `subscribe(listener)` | yes | Receive a call when a plugin or the host changes workspace files. Returns a cleanup function. |
|
| `subscribe(listener)` | yes | Receive a call when workspace files change: from a plugin, the host, another program, or another window. Changes in `.runestone/` count too. Returns a cleanup function. |
|
||||||
|
|
||||||
In `readMany`, one failed file does not stop the other reads. More than 64 paths make the whole call fail.
|
In `readMany`, one failed file does not stop the other reads. More than 64 paths make the whole call fail.
|
||||||
`write` and `renameDocument` fail when the file is open in RuneStone with unsaved edits.
|
`write` and `renameDocument` fail when the file is open in RuneStone with unsaved edits.
|
||||||
|
|||||||
@@ -1,23 +1,16 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { t } from "$lib/i18n";
|
import { t } from "$lib/i18n";
|
||||||
import { loadMarks } from "$lib/workspace/marks";
|
|
||||||
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
||||||
|
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||||
import type { TreeEntry } from "$lib/workspace/types";
|
import type { TreeEntry } from "$lib/workspace/types";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
refreshToken: number;
|
session: WorkspaceSession;
|
||||||
onOpen: (entry: TreeEntry) => void;
|
onOpen: (entry: TreeEntry) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
let { refreshToken, onOpen }: Props = $props();
|
let { session, onOpen }: Props = $props();
|
||||||
let bookmarks = $state<string[]>([]);
|
const bookmarks = $derived(session.marks.current.bookmarks);
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
void refreshToken;
|
|
||||||
void loadMarks().then((marks) => {
|
|
||||||
bookmarks = marks.bookmarks;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="pane">
|
<div class="pane">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { t } from "$lib/i18n";
|
import { t } from "$lib/i18n";
|
||||||
import { onMount, tick, untrack } from "svelte";
|
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 { confirm } from "@tauri-apps/plugin-dialog";
|
||||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||||
import type { TreeEntry } from "$lib/workspace/types";
|
import type { TreeEntry } from "$lib/workspace/types";
|
||||||
@@ -11,13 +11,13 @@
|
|||||||
workspaceCreate,
|
workspaceCreate,
|
||||||
workspaceDelete,
|
workspaceDelete,
|
||||||
workspaceList,
|
workspaceList,
|
||||||
workspaceRename,
|
|
||||||
workspaceReveal,
|
workspaceReveal,
|
||||||
workspaceOpenDefault,
|
workspaceOpenDefault,
|
||||||
workspaceOpenTerminal,
|
workspaceOpenTerminal,
|
||||||
} from "$lib/workspace/api";
|
} 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 { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
|
||||||
|
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||||
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
||||||
import {
|
import {
|
||||||
dropPlaceAt,
|
dropPlaceAt,
|
||||||
@@ -42,10 +42,8 @@
|
|||||||
workspaceRoot: string;
|
workspaceRoot: string;
|
||||||
activePath: string | null;
|
activePath: string | null;
|
||||||
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
|
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
|
||||||
refreshToken: number;
|
session: WorkspaceSession;
|
||||||
onStatus?: (message: string) => void;
|
onStatus?: (message: string) => void;
|
||||||
onEntryGone?: (rel: string) => void;
|
|
||||||
onEntryRenamed?: (from: string, to: string) => void;
|
|
||||||
onCreated?: (entry: TreeEntry) => void;
|
onCreated?: (entry: TreeEntry) => void;
|
||||||
keysActive?: boolean;
|
keysActive?: boolean;
|
||||||
showInternal?: boolean;
|
showInternal?: boolean;
|
||||||
@@ -57,10 +55,8 @@
|
|||||||
workspaceRoot,
|
workspaceRoot,
|
||||||
activePath,
|
activePath,
|
||||||
onOpenFile,
|
onOpenFile,
|
||||||
refreshToken,
|
session,
|
||||||
onStatus,
|
onStatus,
|
||||||
onEntryGone,
|
|
||||||
onEntryRenamed,
|
|
||||||
onCreated,
|
onCreated,
|
||||||
keysActive = true,
|
keysActive = true,
|
||||||
showInternal = false,
|
showInternal = false,
|
||||||
@@ -72,7 +68,8 @@
|
|||||||
let childrenMap = $state<Record<string, TreeEntry[]>>({});
|
let childrenMap = $state<Record<string, TreeEntry[]>>({});
|
||||||
let loading = $state(false);
|
let loading = $state(false);
|
||||||
let error = $state<string | null>(null);
|
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 menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null);
|
||||||
let sortMode = $state<"custom" | "name" | "name-desc">("custom");
|
let sortMode = $state<"custom" | "name" | "name-desc">("custom");
|
||||||
let dragRel = $state<string | null>(null);
|
let dragRel = $state<string | null>(null);
|
||||||
@@ -95,7 +92,7 @@
|
|||||||
let moving = $state(false);
|
let moving = $state(false);
|
||||||
let templates = $state<NoteTemplate[]>([]);
|
let templates = $state<NoteTemplate[]>([]);
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
void workspaceRoot; void refreshToken;
|
void workspaceRoot;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void noteTemplates().then(value => { if (!cancelled) templates = value; });
|
void noteTemplates().then(value => { if (!cancelled) templates = value; });
|
||||||
return () => { cancelled = true; };
|
return () => { cancelled = true; };
|
||||||
@@ -162,15 +159,20 @@
|
|||||||
expanded = new Set([""]);
|
expanded = new Set([""]);
|
||||||
selection = { paths: new Set(), anchor: null };
|
selection = { paths: new Set(), anchor: null };
|
||||||
childrenMap = {};
|
childrenMap = {};
|
||||||
marks = { pins: [], bookmarks: [], order: {} };
|
|
||||||
void loadMarks().then((next) => {
|
|
||||||
marks = next;
|
|
||||||
});
|
|
||||||
void load("");
|
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(() => {
|
$effect(() => {
|
||||||
void refreshToken;
|
|
||||||
void showInternal;
|
void showInternal;
|
||||||
void $pluginDocumentTypes;
|
void $pluginDocumentTypes;
|
||||||
const keys = untrack(() => Object.keys(childrenMap));
|
const keys = untrack(() => Object.keys(childrenMap));
|
||||||
@@ -366,10 +368,9 @@
|
|||||||
onStatus?.(`Copied ${label}`);
|
onStatus?.(`Copied ${label}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function persistMarks(next: Marks) {
|
async function persistMarks(change: (current: Marks) => Marks) {
|
||||||
marks = next;
|
|
||||||
try {
|
try {
|
||||||
await saveMarks(next);
|
await session.marks.update(change);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err instanceof Error ? err.message : String(err);
|
error = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
@@ -405,17 +406,13 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const operationRoot = workspaceRoot;
|
const operationRoot = workspaceRoot;
|
||||||
const before = structuredClone($state.snapshot(marks));
|
const before = session.marks.snapshot();
|
||||||
moving = true;
|
moving = true;
|
||||||
try {
|
try {
|
||||||
await workspaceRename(from, plan.to, operationRoot);
|
if (!await session.rename(from, plan.to) || workspaceRoot !== operationRoot) return;
|
||||||
if (workspaceRoot !== operationRoot) return;
|
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: session.marks.snapshot() }];
|
||||||
const after = moveMarks(marks, from, plan.to);
|
|
||||||
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: structuredClone(after) }];
|
|
||||||
redoMoves = [];
|
redoMoves = [];
|
||||||
renameTreePaths(from, plan.to);
|
renameTreePaths(from, plan.to);
|
||||||
onEntryRenamed?.(from, plan.to);
|
|
||||||
await persistMarks(after);
|
|
||||||
await load(parentRel(from));
|
await load(parentRel(from));
|
||||||
selectOnly(plan.to);
|
selectOnly(plan.to);
|
||||||
await focusTreePath(plan.to);
|
await focusTreePath(plan.to);
|
||||||
@@ -507,9 +504,7 @@
|
|||||||
try {
|
try {
|
||||||
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
|
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
|
||||||
if (workspaceRoot !== operationRoot) return;
|
if (workspaceRoot !== operationRoot) return;
|
||||||
const order = { ...marks.order };
|
await persistMarks(current => ({ ...current, order: { ...current.order, [parent]: [...(current.order[parent] ?? []), finalName] } }));
|
||||||
order[parent] = [...(order[parent] ?? []), finalName];
|
|
||||||
await persistMarks({ ...marks, order });
|
|
||||||
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
|
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
|
||||||
const next = new Set(expanded);
|
const next = new Set(expanded);
|
||||||
next.add(parent);
|
next.add(parent);
|
||||||
@@ -546,7 +541,7 @@
|
|||||||
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
|
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
|
||||||
if (moving) return;
|
if (moving) return;
|
||||||
const operationRoot = workspaceRoot;
|
const operationRoot = workspaceRoot;
|
||||||
const before = structuredClone($state.snapshot(marks));
|
const before = session.marks.snapshot();
|
||||||
const moves: MoveBatch["moves"] = [];
|
const moves: MoveBatch["moves"] = [];
|
||||||
const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path);
|
const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path);
|
||||||
// Load collapsed folders before checking for name conflicts.
|
// Load collapsed folders before checking for name conflicts.
|
||||||
@@ -563,23 +558,18 @@
|
|||||||
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
||||||
if (plan.action === "noop") return;
|
if (plan.action === "noop") return;
|
||||||
if (plan.action === "reorder") {
|
if (plan.action === "reorder") {
|
||||||
const order = { ...marks.order };
|
await persistMarks(current => ({ ...current, order: { ...current.order, [plan.parent]: plan.names } }));
|
||||||
order[plan.parent] = plan.names;
|
|
||||||
await persistMarks({ ...marks, order });
|
|
||||||
await load(plan.parent);
|
await load(plan.parent);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await workspaceRename(plan.from, plan.to, operationRoot);
|
forgetFolder(plan.from);
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
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 });
|
moves.push({ from: plan.from, to: plan.to });
|
||||||
paths.set(plan.from, 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);
|
await load(plan.fromParent);
|
||||||
if (plan.toParent !== plan.fromParent) {
|
if (plan.toParent !== plan.fromParent) {
|
||||||
await load(plan.toParent);
|
await load(plan.toParent);
|
||||||
@@ -590,7 +580,7 @@
|
|||||||
error = result.failures.length ? result.failures.join("\n") : null;
|
error = result.failures.length ? result.failures.join("\n") : null;
|
||||||
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
||||||
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
|
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 = [];
|
redoMoves = [];
|
||||||
}
|
}
|
||||||
moving = false;
|
moving = false;
|
||||||
@@ -633,13 +623,12 @@
|
|||||||
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
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;
|
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
|
||||||
await workspaceRename(from, to, operationRoot);
|
// The batch restores the marks after all moves, so each move leaves them alone.
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||||
applied.push({ from, to });
|
applied.push({ from, to });
|
||||||
onEntryRenamed?.(from, to);
|
|
||||||
}
|
}
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
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]; }
|
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
|
||||||
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
|
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
|
||||||
for (const move of applied) renameTreePaths(move.from, move.to);
|
for (const move of applied) renameTreePaths(move.from, move.to);
|
||||||
@@ -652,7 +641,7 @@
|
|||||||
const rollbackErrors: string[] = [];
|
const rollbackErrors: string[] = [];
|
||||||
for (const move of applied.reverse()) {
|
for (const move of applied.reverse()) {
|
||||||
if (workspaceRoot !== operationRoot) { rollbackErrors.push("The original workspace is unavailable."); break; }
|
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)); }
|
catch (failure) { rollbackErrors.push(String(failure)); }
|
||||||
}
|
}
|
||||||
if (rollbackErrors.length) { undoMoves = []; redoMoves = []; }
|
if (rollbackErrors.length) { undoMoves = []; redoMoves = []; }
|
||||||
@@ -664,7 +653,7 @@
|
|||||||
if (!clipboard || clipboard.root !== workspaceRoot || moving) return;
|
if (!clipboard || clipboard.root !== workspaceRoot || moving) return;
|
||||||
const source = clipboard;
|
const source = clipboard;
|
||||||
const operationRoot = workspaceRoot;
|
const operationRoot = workspaceRoot;
|
||||||
const before = structuredClone($state.snapshot(marks));
|
const before = session.marks.snapshot();
|
||||||
const moves: MoveBatch["moves"] = [];
|
const moves: MoveBatch["moves"] = [];
|
||||||
moving = true;
|
moving = true;
|
||||||
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
|
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) {
|
if (source.cut) {
|
||||||
const to = joinRel(parent, entry.name);
|
const to = joinRel(parent, entry.name);
|
||||||
if (to === entry.rel_path) return;
|
if (to === entry.rel_path) return;
|
||||||
await workspaceRename(entry.rel_path, to, operationRoot);
|
if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
|
||||||
moves.push({ from: entry.rel_path, to });
|
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);
|
} 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;
|
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);
|
for (const folder of new Set([parent, ...source.paths.map(parentRel)])) await load(folder);
|
||||||
error = result.failures.length ? result.failures.join("\n") : null;
|
error = result.failures.length ? result.failures.join("\n") : null;
|
||||||
@@ -719,7 +705,7 @@
|
|||||||
const result = await runTreeActions(roots, async entry => {
|
const result = await runTreeActions(roots, async entry => {
|
||||||
await workspaceDelete(entry.rel_path, permanent);
|
await workspaceDelete(entry.rel_path, permanent);
|
||||||
forgetFolder(entry.rel_path);
|
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);
|
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.
|
// 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) {
|
async function createTreeNote(parent: string, template?: NoteTemplate) {
|
||||||
try {
|
try {
|
||||||
const path = await createNote(parent, template);
|
const path = await createNote(parent, template);
|
||||||
|
session.changed([path]);
|
||||||
await load(parent);
|
await load(parent);
|
||||||
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||||
} catch (reason) { error = String(reason); }
|
} catch (reason) { error = String(reason); }
|
||||||
@@ -743,18 +730,19 @@
|
|||||||
|
|
||||||
function paneMenuItems(parent: string): MenuItem[] {
|
function paneMenuItems(parent: string): MenuItem[] {
|
||||||
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
|
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
|
||||||
|
// New note comes first, because notes are the most common new item.
|
||||||
return [
|
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",
|
kind: "action",
|
||||||
label: $t("New file…"),
|
label: $t("New file…"),
|
||||||
icon: "file-plus",
|
icon: "file-plus",
|
||||||
run: () => { void createIn(parent, "file"); },
|
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"); } },
|
{ kind: "action", label: $t("New folder"), icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
|
||||||
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
|
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
|
||||||
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
|
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"),
|
label: bookmarked ? (multiple ? $t("Remove bookmarks") : $t("Remove bookmark")) : $t("Bookmark"),
|
||||||
icon: "bookmark",
|
icon: "bookmark",
|
||||||
run: () => {
|
run: () => {
|
||||||
void persistMarks({
|
void persistMarks(current => ({
|
||||||
...marks,
|
...current,
|
||||||
bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked),
|
bookmarks: setSelectedMarks(current.bookmarks, entries, !bookmarked),
|
||||||
});
|
}));
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ kind: "sep" },
|
{ kind: "sep" },
|
||||||
@@ -885,10 +873,10 @@
|
|||||||
label: pinned ? $t("Unpin") : $t("Pin"),
|
label: pinned ? $t("Unpin") : $t("Pin"),
|
||||||
icon: "pin",
|
icon: "pin",
|
||||||
run: () => {
|
run: () => {
|
||||||
void persistMarks({
|
void persistMarks(current => ({
|
||||||
...marks,
|
...current,
|
||||||
pins: setSelectedMarks(marks.pins, entries, !pinned),
|
pins: setSelectedMarks(current.pins, entries, !pinned),
|
||||||
});
|
}));
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,10 +7,10 @@
|
|||||||
import Icon from "$lib/ui/Icon.svelte";
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||||
import { noteTemplates, saveNoteTemplate, TEMPLATE_FOLDER, type NoteTemplate } from "$lib/workspace/templates";
|
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";
|
import type { TreeEntry } from "$lib/workspace/types";
|
||||||
let { onClose, onEdit, onRenamed, onDeleted }: { onClose: () => void; onEdit: (entry: TreeEntry) => void;
|
let { session, onClose, onEdit }: { session: WorkspaceSession; onClose: () => void; onEdit: (entry: TreeEntry) => void } = $props();
|
||||||
onRenamed: (from: string, to: string) => void; onDeleted: (path: string) => void } = $props();
|
|
||||||
let dialog: HTMLDialogElement;
|
let dialog: HTMLDialogElement;
|
||||||
let templates = $state<NoteTemplate[]>([]);
|
let templates = $state<NoteTemplate[]>([]);
|
||||||
let error = $state("");
|
let error = $state("");
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
const path = `${TEMPLATE_FOLDER}/${title}.md`;
|
const path = `${TEMPLATE_FOLDER}/${title}.md`;
|
||||||
if (path === template.path) return;
|
if (path === template.path) return;
|
||||||
busy = true; error = "";
|
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); }
|
catch (reason) { error = String(reason); }
|
||||||
finally { busy = false; }
|
finally { busy = false; }
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
const accepted = isTauri() ? await confirm(message, { title: $t("Delete template"), kind: "warning" }) : window.confirm(message);
|
const accepted = isTauri() ? await confirm(message, { title: $t("Delete template"), kind: "warning" }) : window.confirm(message);
|
||||||
if (!accepted) return;
|
if (!accepted) return;
|
||||||
busy = true; error = "";
|
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); }
|
catch (reason) { error = String(reason); }
|
||||||
finally { busy = false; }
|
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 { 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 { onMount, onDestroy, tick, untrack } from "svelte";
|
||||||
import type { MenuLink } from "$lib/editor/linkMenu";
|
import type { MenuLink } from "$lib/editor/linkMenu";
|
||||||
import { loadMarks, saveMarks } from "$lib/workspace/marks";
|
import { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||||
import { moveMarks } from "$lib/workspace/treeMoveHistory";
|
|
||||||
import { retainEditorStates } from "$lib/editor/editorStates";
|
import { retainEditorStates } from "$lib/editor/editorStates";
|
||||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
|
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
|
||||||
import { selectedEditorText } from "$lib/editor/selection";
|
import { selectedEditorText } from "$lib/editor/selection";
|
||||||
@@ -42,7 +41,7 @@
|
|||||||
import TabBar from "./TabBar.svelte";
|
import TabBar from "./TabBar.svelte";
|
||||||
import OutlinePane from "./OutlinePane.svelte";
|
import OutlinePane from "./OutlinePane.svelte";
|
||||||
import Backlinks from "./Backlinks.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 IconButton from "$lib/ui/IconButton.svelte";
|
||||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||||
import SearchPane from "./SearchPane.svelte";
|
import SearchPane from "./SearchPane.svelte";
|
||||||
@@ -61,7 +60,6 @@
|
|||||||
workspaceOpenWindow,
|
workspaceOpenWindow,
|
||||||
workspaceRead,
|
workspaceRead,
|
||||||
workspaceReadDataUrl,
|
workspaceReadDataUrl,
|
||||||
workspaceRename,
|
|
||||||
workspaceReveal,
|
workspaceReveal,
|
||||||
workspaceWrite,
|
workspaceWrite,
|
||||||
workspaceWriteBytes,
|
workspaceWriteBytes,
|
||||||
@@ -95,60 +93,39 @@
|
|||||||
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
|
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
|
||||||
let status = $state($t("Open a workspace folder"));
|
let status = $state($t("Open a workspace folder"));
|
||||||
let error = $state<string | null>(null);
|
let error = $state<string | null>(null);
|
||||||
let refreshToken = $state(0);
|
// The session owns the marks, the note index, renames, and the change events of this window.
|
||||||
const noteIndex = new WorkspaceNoteIndex();
|
const session = new WorkspaceSession(() => $t("Could not read all workspace links. Rebuild the index to retry."));
|
||||||
let noteIndexRoot: string | null = null;
|
onDestroy(() => session.dispose());
|
||||||
let noteIndexRevision = $state(0);
|
|
||||||
let noteIndexBusy = $state(false);
|
|
||||||
let noteIndexError = $state<string | null>(null);
|
|
||||||
let noteIndexPending: Promise<void> = Promise.resolve();
|
|
||||||
let noteIndexRequest = 0;
|
|
||||||
const backlinks = $derived.by(() => {
|
const backlinks = $derived.by(() => {
|
||||||
void noteIndexRevision;
|
void session.indexRevision;
|
||||||
return activePath && !editorPluginVisible ? noteIndex.backlinks(activePath) : [];
|
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(() => {
|
$effect(() => {
|
||||||
void workspace?.root; void refreshToken;
|
const root = workspace?.root ?? null;
|
||||||
untrack(() => { void rebuildNoteIndex(); });
|
untrack(() => session.open(root));
|
||||||
});
|
});
|
||||||
|
|
||||||
let indexedDrafts = new Map<string, string>();
|
|
||||||
let draftsRoot: string | null = null;
|
|
||||||
$effect(() => {
|
$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]));
|
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(() => {
|
untrack(() => session.setDrafts(drafts));
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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) {
|
async function openBacklink(entry: Backlink) {
|
||||||
await openFile({ name: entry.sourcePath.split("/").pop()!, rel_path: entry.sourcePath, kind: "file" }, entry.line, "new");
|
await openFile({ name: entry.sourcePath.split("/").pop()!, rel_path: entry.sourcePath, kind: "file" }, entry.line, "new");
|
||||||
}
|
}
|
||||||
@@ -500,7 +477,6 @@
|
|||||||
documents?.dispose();
|
documents?.dispose();
|
||||||
documents = createDocuments();
|
documents = createDocuments();
|
||||||
status = workspace.root;
|
status = workspace.root;
|
||||||
refreshToken += 1;
|
|
||||||
const token = new URLSearchParams(location.search).get("tabTransfer");
|
const token = new URLSearchParams(location.search).get("tabTransfer");
|
||||||
if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true });
|
if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true });
|
||||||
else await restoreDocumentTabs();
|
else await restoreDocumentTabs();
|
||||||
@@ -737,7 +713,7 @@
|
|||||||
if (documents !== current || switching) return null;
|
if (documents !== current || switching) return null;
|
||||||
await workspaceWriteBytes(rel, base64);
|
await workspaceWriteBytes(rel, base64);
|
||||||
if (documents !== current) return null;
|
if (documents !== current) return null;
|
||||||
refreshToken += 1;
|
session.changed([rel]);
|
||||||
return `.length - 1)}${rel})`;
|
return `.length - 1)}${rel})`;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err instanceof Error ? err.message : String(err);
|
error = err instanceof Error ? err.message : String(err);
|
||||||
@@ -766,7 +742,7 @@
|
|||||||
try {
|
try {
|
||||||
await workspaceCreate(rel, "file");
|
await workspaceCreate(rel, "file");
|
||||||
await workspaceWrite(rel, markdown + "\n", "");
|
await workspaceWrite(rel, markdown + "\n", "");
|
||||||
refreshToken++;
|
session.changed([rel]);
|
||||||
status = $t("Extracted selection to {path}", { path: rel });
|
status = $t("Extracted selection to {path}", { path: rel });
|
||||||
return `/${rel}`;
|
return `/${rel}`;
|
||||||
} catch (err) { error = String(err); return null; }
|
} catch (err) { error = String(err); return null; }
|
||||||
@@ -811,7 +787,7 @@
|
|||||||
await workspaceCreate(name, "file");
|
await workspaceCreate(name, "file");
|
||||||
await workspaceWrite(name, tab.contents, "");
|
await workspaceWrite(name, tab.contents, "");
|
||||||
await openFile({ name: name.split("/").pop()!, rel_path: name, kind: "file" });
|
await openFile({ name: name.split("/").pop()!, rel_path: name, kind: "file" });
|
||||||
refreshToken++;
|
session.changed([name]);
|
||||||
} catch (err) { error = String(err); }
|
} catch (err) { error = String(err); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,7 +801,7 @@
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
||||||
refreshToken += 1;
|
session.changed([name.replaceAll("\\", "/")]);
|
||||||
await openCreatedFile({
|
await openCreatedFile({
|
||||||
name: name.split("/").pop() ?? name,
|
name: name.split("/").pop() ?? name,
|
||||||
rel_path: name.replaceAll("\\", "/"),
|
rel_path: name.replaceAll("\\", "/"),
|
||||||
@@ -851,7 +827,7 @@
|
|||||||
const create = async (template?: NoteTemplate) => {
|
const create = async (template?: NoteTemplate) => {
|
||||||
try {
|
try {
|
||||||
const path = await createNote("", template);
|
const path = await createNote("", template);
|
||||||
refreshToken++;
|
session.changed([path]);
|
||||||
await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||||
} catch (reason) { error = String(reason); }
|
} 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) {
|
async function renameNoteTitle(id: string, title: string) {
|
||||||
const current = documents;
|
const current = documents;
|
||||||
const note = current?.buffers.find(tab => tab.id === id);
|
const note = current?.buffers.find(tab => tab.id === id);
|
||||||
@@ -970,10 +939,7 @@
|
|||||||
const plan = planMarkdownTitleRename(from, title);
|
const plan = planMarkdownTitleRename(from, title);
|
||||||
if (plan.action === "error") throw new Error(plan.message);
|
if (plan.action === "error") throw new Error(plan.message);
|
||||||
if (plan.action === "noop") return;
|
if (plan.action === "noop") return;
|
||||||
await workspaceRename(from, plan.to);
|
if (!await session.rename(from, plan.to) || documents !== current) return;
|
||||||
current.rename(from, plan.to);
|
|
||||||
if (documents !== current) return;
|
|
||||||
refreshToken += 1;
|
|
||||||
status = $t("Renamed to {path}", { path: plan.to });
|
status = $t("Renamed to {path}", { path: plan.to });
|
||||||
error = null;
|
error = null;
|
||||||
}
|
}
|
||||||
@@ -998,10 +964,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await workspaceRename(from, plan.to);
|
if (!await session.rename(from, plan.to) || documents !== current) return;
|
||||||
current?.rename(from, plan.to);
|
|
||||||
if (documents !== current) return;
|
|
||||||
refreshToken += 1;
|
|
||||||
status = $t("Renamed to {path}", { path: plan.to });
|
status = $t("Renamed to {path}", { path: plan.to });
|
||||||
error = null;
|
error = null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -1013,8 +976,8 @@
|
|||||||
const current = documents, currentWorkspace = workspace;
|
const current = documents, currentWorkspace = workspace;
|
||||||
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
|
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
|
||||||
const entry = async () => {
|
const entry = async () => {
|
||||||
await noteIndexPending;
|
await session.indexReady;
|
||||||
const resolution = noteIndex.resolve(origin, link.target, link.kind);
|
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(", ") }));
|
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);
|
const paths = resolution.status === "resolved" ? [resolution.path] : link.kind === "wiki" ? [] : linkCandidates(origin, link.target, link.kind);
|
||||||
for (const path of paths) {
|
for (const path of paths) {
|
||||||
@@ -1044,13 +1007,7 @@
|
|||||||
to = plan.to;
|
to = plan.to;
|
||||||
}
|
}
|
||||||
if (to === file.rel_path) return;
|
if (to === file.rel_path) return;
|
||||||
const marks = await loadMarks();
|
if (!await session.rename(file.rel_path, to) || !valid()) return;
|
||||||
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++;
|
|
||||||
status = $t("Moved to {path}", { path: to });
|
status = $t("Moved to {path}", { path: to });
|
||||||
}
|
}
|
||||||
return [
|
return [
|
||||||
@@ -1068,10 +1025,8 @@
|
|||||||
{ label: $t("Rename…"), icon: "rename", run: run(file => rename(file)) },
|
{ 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("Move file to…"), icon: "folder", run: run(file => rename(file, true)) },
|
||||||
{ label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
|
{ label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
|
||||||
const marks = await loadMarks();
|
await session.marks.update(marks => marks.bookmarks.includes(file.rel_path) ? marks : { ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
||||||
if (!valid()) return;
|
if (valid()) status = $t("Bookmarked {name}", { name: file.name });
|
||||||
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
|
||||||
refreshToken++; status = $t("Bookmarked {name}", { name: file.name });
|
|
||||||
}) },
|
}) },
|
||||||
{ label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
|
{ 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)) },
|
{ label: $t("Show in system explorer"), icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
|
||||||
@@ -1088,9 +1043,9 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const current = documents, root = workspace?.root;
|
const current = documents, root = workspace?.root;
|
||||||
await noteIndexPending;
|
await session.indexReady;
|
||||||
if (documents !== current || workspace?.root !== root) return;
|
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") {
|
if (resolution.status === "ambiguous") {
|
||||||
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: resolution.candidates.join(", ") });
|
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: resolution.candidates.join(", ") });
|
||||||
return;
|
return;
|
||||||
@@ -1193,27 +1148,16 @@
|
|||||||
const plan = planDocumentTitleRename(from, name);
|
const plan = planDocumentTitleRename(from, name);
|
||||||
if (plan.action === "error") throw new Error(plan.message);
|
if (plan.action === "error") throw new Error(plan.message);
|
||||||
if (plan.action === "noop") return from;
|
if (plan.action === "noop") return from;
|
||||||
await workspaceRename(from, plan.to);
|
if (!await session.rename(from, plan.to) || documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
||||||
if (documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
|
||||||
applyPathRename(from, plan.to);
|
|
||||||
refreshToken++;
|
|
||||||
return plan.to;
|
return plan.to;
|
||||||
}));
|
}));
|
||||||
unlisteners.push(guardPluginWrites(path => {
|
unlisteners.push(guardPluginWrites(path => {
|
||||||
const open = documents?.buffers.find(tab => tab.relPath === 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.");
|
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); };
|
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
||||||
void onWorkspaceEvent((event) => {
|
void onWorkspaceEvent((event) => {
|
||||||
if (event.root !== workspace?.root) return;
|
if (event.root === workspace?.root) session.watched(event.paths);
|
||||||
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);
|
|
||||||
}).then(register).catch(err => error = String(err));
|
}).then(register).catch(err => error = String(err));
|
||||||
let closing = false;
|
let closing = false;
|
||||||
void getCurrentWindow().onCloseRequested(async event => {
|
void getCurrentWindow().onCloseRequested(async event => {
|
||||||
@@ -1229,12 +1173,12 @@
|
|||||||
}
|
}
|
||||||
} finally { closing = false; }
|
} finally { closing = false; }
|
||||||
}).then(register).catch(err => error = String(err));
|
}).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);
|
window.addEventListener("focus", focus);
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
documents?.dispose();
|
documents?.dispose();
|
||||||
clearTimeout(refreshTimer);
|
|
||||||
unlisteners.forEach(off => off());
|
unlisteners.forEach(off => off());
|
||||||
window.removeEventListener("focus", focus);
|
window.removeEventListener("focus", focus);
|
||||||
};
|
};
|
||||||
@@ -1247,10 +1191,8 @@
|
|||||||
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
<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 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 quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
||||||
{#if templateManager && workspace}<TemplateManager onClose={() => templateManager = false}
|
{#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false}
|
||||||
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }}
|
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if}
|
||||||
onRenamed={(from, to) => { applyPathRename(from, to); refreshToken++; }}
|
|
||||||
onDeleted={(path) => { removePluginDocuments(path); void documents?.refresh(); refreshToken++; }} />{/if}
|
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="shell"
|
class="shell"
|
||||||
@@ -1357,7 +1299,7 @@
|
|||||||
onManageTemplates={() => templateManager = true}
|
onManageTemplates={() => templateManager = true}
|
||||||
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
||||||
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
||||||
{refreshToken}
|
{session}
|
||||||
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
||||||
onCreated={(entry) => {
|
onCreated={(entry) => {
|
||||||
void openCreatedFile(entry);
|
void openCreatedFile(entry);
|
||||||
@@ -1366,14 +1308,12 @@
|
|||||||
status = message;
|
status = message;
|
||||||
error = null;
|
error = null;
|
||||||
}}
|
}}
|
||||||
onEntryGone={(path) => { removePluginDocuments(path); noteIndex.remove(path); noteIndexRevision = noteIndex.revision; void documents?.refresh(); refreshToken++; }}
|
|
||||||
onEntryRenamed={applyPathRename}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{#if leftView === "search"}
|
{#if leftView === "search"}
|
||||||
<SearchPane {searchRequest} onOpen={(entry, line) => void openFile(entry, line)} />
|
<SearchPane {searchRequest} onOpen={(entry, line) => void openFile(entry, line)} />
|
||||||
{:else if leftView === "bookmarks"}
|
{:else if leftView === "bookmarks"}
|
||||||
<BookmarksPane {refreshToken} onOpen={(entry) => void openFile(entry)} />
|
<BookmarksPane {session} onOpen={(entry) => void openFile(entry)} />
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -1515,7 +1455,7 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{#if buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
|
{#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}
|
{/if}
|
||||||
</aside>
|
</aside>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -49,6 +49,11 @@ export function workspaceRead(rel: string): Promise<string> {
|
|||||||
return invoke("workspace_read", { rel });
|
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> {
|
export async function workspaceReadBytes(rel: string): Promise<Uint8Array> {
|
||||||
return new Uint8Array(await invoke<ArrayBuffer>("workspace_read_bytes", { rel }));
|
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, "-");
|
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 source = contents.replace(/\r\n/g, "\n");
|
||||||
const properties = /^\uFEFF?---\n[\s\S]*?\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(source)?.[0] ?? "";
|
const properties = /^\uFEFF?---\n[\s\S]*?\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(source)?.[0] ?? "";
|
||||||
const offset = (properties.match(/\n/g) ?? []).length;
|
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;
|
let slug = base, suffix = 0;
|
||||||
while (used.has(slug)) slug = `${base}-${++suffix}`;
|
while (used.has(slug)) slug = `${base}-${++suffix}`;
|
||||||
used.add(slug);
|
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";
|
export const MARKS_PATH = ".runestone/marks.json";
|
||||||
|
|
||||||
const MARKS_PATH = ".runestone/marks.json";
|
|
||||||
|
|
||||||
export type Marks = {
|
export type Marks = {
|
||||||
pins: string[];
|
pins: string[];
|
||||||
@@ -8,12 +6,14 @@ export type Marks = {
|
|||||||
order: Record<string, string[]>;
|
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 {
|
try {
|
||||||
const raw = await workspaceRead(MARKS_PATH);
|
const parsed = JSON.parse(text) as Partial<Marks>;
|
||||||
const parsed = JSON.parse(raw) as Partial<Marks>;
|
|
||||||
return {
|
return {
|
||||||
pins: Array.isArray(parsed.pins) ? parsed.pins : [],
|
pins: Array.isArray(parsed.pins) ? parsed.pins : [],
|
||||||
bookmarks: Array.isArray(parsed.bookmarks) ? parsed.bookmarks : [],
|
bookmarks: Array.isArray(parsed.bookmarks) ? parsed.bookmarks : [],
|
||||||
@@ -23,12 +23,12 @@ export async function loadMarks(): Promise<Marks> {
|
|||||||
: {},
|
: {},
|
||||||
};
|
};
|
||||||
} catch {
|
} catch {
|
||||||
return { pins: [], bookmarks: [], order: {} };
|
return emptyMarks();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveMarks(marks: Marks): Promise<void> {
|
export function serializeMarks(marks: Marks): string {
|
||||||
await workspaceWrite(MARKS_PATH, `${JSON.stringify(marks, null, 2)}\n`);
|
return `${JSON.stringify(marks, null, 2)}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function togglePath(list: string[], rel: string): string[] {
|
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 = {
|
export type NoteIndexIO = {
|
||||||
list: (folder: string) => Promise<{ rel_path: string; kind: "file" | "folder" }[]>;
|
list: (folder: string) => Promise<{ rel_path: string; kind: "file" | "folder" }[]>;
|
||||||
read: (path: string) => Promise<string>;
|
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 };
|
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 Snapshot = { files: Set<string>; notes: Map<string, IndexedNote> };
|
||||||
type Change = (snapshot: Snapshot) => void;
|
type Change = (snapshot: Snapshot) => void;
|
||||||
|
|
||||||
@@ -129,7 +132,7 @@ export class WorkspaceNoteIndex {
|
|||||||
update(path: string, contents: string): void {
|
update(path: string, contents: string): void {
|
||||||
const normalized = normalizePath(path);
|
const normalized = normalizePath(path);
|
||||||
if (!normalized) return;
|
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 => {
|
this.#change(snapshot => {
|
||||||
snapshot.files.add(normalized);
|
snapshot.files.add(normalized);
|
||||||
if (note) snapshot.notes.set(normalized, note);
|
if (note) snapshot.notes.set(normalized, note);
|
||||||
@@ -158,20 +161,16 @@ export class WorkspaceNoteIndex {
|
|||||||
snapshot.files.delete(path);
|
snapshot.files.delete(path);
|
||||||
snapshot.notes.delete(path);
|
snapshot.notes.delete(path);
|
||||||
snapshot.files.add(replacement);
|
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[] }> {
|
/** List the files below a folder. A failed folder adds an issue, and the walk continues. */
|
||||||
const generation = ++this.#generation;
|
async #walk(io: NoteIndexIO, start: string, files: Set<string>, errors: NoteIndexIssue[], current: () => boolean): Promise<void> {
|
||||||
const changes: Change[] = [];
|
const folders = [start];
|
||||||
this.#changes = changes;
|
|
||||||
const snapshot: Snapshot = { files: new Set(), notes: new Map() };
|
|
||||||
const errors: NoteIndexIssue[] = [];
|
|
||||||
const folders = [""];
|
|
||||||
const visited = new Set<string>();
|
const visited = new Set<string>();
|
||||||
while (folders.length && generation === this.#generation) {
|
while (folders.length && current()) {
|
||||||
const folder = folders.pop()!;
|
const folder = folders.pop()!;
|
||||||
if (visited.has(folder)) continue;
|
if (visited.has(folder)) continue;
|
||||||
visited.add(folder);
|
visited.add(folder);
|
||||||
@@ -180,25 +179,47 @@ export class WorkspaceNoteIndex {
|
|||||||
const path = normalizePath(entry.rel_path);
|
const path = normalizePath(entry.rel_path);
|
||||||
if (!path || (folder && !path.startsWith(`${folder}/`))) continue;
|
if (!path || (folder && !path.startsWith(`${folder}/`))) continue;
|
||||||
if (entry.kind === "folder") folders.push(path);
|
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) }); }
|
} 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 => {
|
/** Read notes in batches and keep their links. A file that is too large for a batch is read alone. */
|
||||||
try {
|
async #read(io: NoteIndexIO, paths: string[], notes: Map<string, IndexedNote>, errors: NoteIndexIssue[], current: () => boolean): Promise<void> {
|
||||||
const contents = drafts.get(path) ?? await io.read(path);
|
const keep = (path: string, contents: string) => notes.set(path, { links: noteLinks(path, contents) });
|
||||||
snapshot.notes.set(path, { contents, links: noteLinks(path, contents) });
|
const single = async (path: string) => {
|
||||||
} catch (error) { errors.push({ path, operation: "read", error: String(error) }); }
|
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) {
|
for (const [path, contents] of drafts) {
|
||||||
const normalized = normalizePath(path);
|
const normalized = normalizePath(path);
|
||||||
if (!normalized || !isIndexedNote(normalized)) continue;
|
if (!normalized || !isIndexedNote(normalized)) continue;
|
||||||
snapshot.files.add(normalized);
|
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);
|
for (const change of changes) change(snapshot);
|
||||||
this.#changes = null;
|
this.#changes = null;
|
||||||
@@ -207,6 +228,41 @@ export class WorkspaceNoteIndex {
|
|||||||
return { committed: true, indexed: snapshot.notes.size, errors };
|
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 {
|
resolve(origin: string, target: string, kind: "md" | "wiki"): NoteLinkResolution {
|
||||||
let path = target.trim().split("#")[0];
|
let path = target.trim().split("#")[0];
|
||||||
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
|
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 = {
|
export type OutlineItem = {
|
||||||
level: number;
|
level: number;
|
||||||
@@ -7,21 +8,14 @@ export type OutlineItem = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function buildOutline(relPath: string, contents: string): 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 lines = contents.split(/\r?\n/);
|
||||||
const items: OutlineItem[] = [];
|
const items: OutlineItem[] = [];
|
||||||
const markdown = isMarkdownPath(relPath);
|
|
||||||
for (let i = 0; i < lines.length; i += 1) {
|
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 =
|
const code =
|
||||||
/^(?:export\s+)?(?:async\s+)?(?:pub\s+)?(?:def|function|class|fn|struct|impl|interface|enum)\s+([A-Za-z0-9_]+)/.exec(
|
/^(?: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) {
|
if (code) {
|
||||||
items.push({ level: 1, text: code[1], line: i + 1 });
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Workspace session: a title rename moves pins and bookmarks, marks from another window reach the panes, watcher paths update the tree and backlinks, and focus does not rescan the workspace.
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||||
|
|
||||||
|
await runSmoke("workspace/session", async ({ page }) => {
|
||||||
|
await mockTauri(page, {
|
||||||
|
commands: test => {
|
||||||
|
const ws = test.workspace({
|
||||||
|
root: "C:\\smoke-workspace",
|
||||||
|
files: {
|
||||||
|
"notes/welcome.md": "# Welcome\n",
|
||||||
|
"notes/other.md": "# Other\n",
|
||||||
|
".runestone/marks.json": JSON.stringify({ pins: ["notes/welcome.md"], bookmarks: ["notes/welcome.md"], order: {} }, null, 2) + "\n",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const files = ws.files;
|
||||||
|
Object.assign(test, { files, root: ws.root });
|
||||||
|
return {
|
||||||
|
...ws,
|
||||||
|
workspace_rename: ({ from, to }) => {
|
||||||
|
if (!files.has(from)) throw new Error("File is missing");
|
||||||
|
files.set(to, files.get(from));
|
||||||
|
files.delete(from);
|
||||||
|
},
|
||||||
|
spelling_menu_install: () => null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const marks = () => page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
|
||||||
|
const emit = (kind, paths) => page.evaluate(([kind, paths]) => window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind, paths }), [kind, paths]);
|
||||||
|
const tree = page.locator(".tree");
|
||||||
|
const backlinks = page.getByRole("region", { name: "Backlinks" });
|
||||||
|
|
||||||
|
await page.goto(smokeUrl);
|
||||||
|
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||||
|
await tree.getByText("notes", { exact: true }).click();
|
||||||
|
await tree.getByText("welcome", { exact: true }).dblclick();
|
||||||
|
const title = page.getByRole("button", { name: "Rename note", exact: true });
|
||||||
|
await title.click();
|
||||||
|
await page.getByRole("textbox", { name: "Note filename", exact: true }).fill("renamed");
|
||||||
|
await page.keyboard.press("Enter");
|
||||||
|
await page.waitForFunction(() => document.querySelector(".breadcrumb")?.textContent === "notes/renamed.md");
|
||||||
|
await page.waitForFunction(() => window.__TEST__.files.get(".runestone/marks.json").includes("notes/renamed.md"));
|
||||||
|
assert.deepEqual(await marks(), { pins: ["notes/renamed.md"], bookmarks: ["notes/renamed.md"], order: {} }, "A title rename moves the pin and the bookmark");
|
||||||
|
await tree.getByText("renamed", { exact: true }).waitFor();
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
|
||||||
|
const bookmarks = page.locator(".pane").filter({ hasText: "Bookmarks" });
|
||||||
|
await bookmarks.getByText("notes/renamed.md").waitFor();
|
||||||
|
// Another window bookmarks a second note. The watcher reports the marks file.
|
||||||
|
await page.evaluate(() => window.__TEST__.files.set(".runestone/marks.json", JSON.stringify({ pins: ["notes/renamed.md"], bookmarks: ["notes/renamed.md", "notes/other.md"], order: {} })));
|
||||||
|
await emit("modify", [".runestone/marks.json"]);
|
||||||
|
await bookmarks.getByText("notes/other.md").waitFor();
|
||||||
|
await page.getByRole("button", { name: "Files", exact: true }).click();
|
||||||
|
|
||||||
|
// A note that another program creates appears in the tree and in the backlinks, without a rescan.
|
||||||
|
const listCalls = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_list").length);
|
||||||
|
const before = await listCalls();
|
||||||
|
await page.evaluate(() => window.__TEST__.files.set("notes/linker.md", "See [[renamed]] for details.\n"));
|
||||||
|
await emit("create", ["notes/linker.md"]);
|
||||||
|
await tree.getByText("linker", { exact: true }).waitFor();
|
||||||
|
await backlinks.getByText("notes/linker.md").waitFor();
|
||||||
|
assert.ok(await listCalls() - before <= 3, "One change lists only the folders that it touches");
|
||||||
|
|
||||||
|
const afterChange = await listCalls();
|
||||||
|
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||||
|
await page.waitForTimeout(400);
|
||||||
|
assert.equal(await listCalls(), afterChange, "Window focus does not rescan the workspace");
|
||||||
|
|
||||||
|
// A deleted note leaves the tree and the backlinks.
|
||||||
|
await page.evaluate(() => window.__TEST__.files.delete("notes/linker.md"));
|
||||||
|
await emit("remove", ["notes/linker.md"]);
|
||||||
|
await backlinks.getByText("No other notes link to this file.").waitFor();
|
||||||
|
assert.equal(await tree.getByText("linker", { exact: true }).count(), 0);
|
||||||
|
console.log("PASS: title rename moves marks, marks from another window, watcher paths update the tree and backlinks, no rescan on focus.");
|
||||||
|
});
|
||||||
@@ -21,8 +21,8 @@ test("headings use rendered text, Unicode, and unique slugs", () => {
|
|||||||
test("section lines exclude properties and code, and include Setext headings", () => {
|
test("section lines exclude properties and code, and include Setext headings", () => {
|
||||||
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
|
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
|
||||||
assert.deepEqual(documentHeadings(source), [
|
assert.deepEqual(documentHeadings(source), [
|
||||||
{ text: "Install", slug: "install", line: 9 },
|
{ level: 1, text: "Install", slug: "install", line: 9 },
|
||||||
{ text: "Real", slug: "real", line: 12 },
|
{ level: 2, text: "Real", slug: "real", line: 12 },
|
||||||
]);
|
]);
|
||||||
assert.equal(headingLinkLine(source, "fake"), null);
|
assert.equal(headingLinkLine(source, "fake"), null);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -162,3 +162,48 @@ test("read and list failures report incomplete coverage and remain rebuildable",
|
|||||||
await index.rebuild(io);
|
await index.rebuild(io);
|
||||||
assert.equal(index.backlinks("Target.md").length, 1);
|
assert.equal(index.backlinks("Target.md").length, 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("watcher paths update, add, and remove notes without a full rebuild", async () => {
|
||||||
|
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["old/note.md", "[[Target]]"]]);
|
||||||
|
const index = new WorkspaceNoteIndex();
|
||||||
|
await index.rebuild(workspace(files));
|
||||||
|
assert.equal(index.backlinks("Target.md").length, 2);
|
||||||
|
let lists = 0;
|
||||||
|
const io = workspace(files), counted: NoteIndexIO = { ...io, list: folder => { lists++; return io.list(folder); } };
|
||||||
|
files.set("source.md", "No link now");
|
||||||
|
files.delete("old/note.md");
|
||||||
|
files.set("new/deeper/linker.md", "[[Target]]");
|
||||||
|
await index.refresh(counted, ["source.md", "old/note.md", "old", "new"]);
|
||||||
|
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["new/deeper/linker.md"]);
|
||||||
|
assert.equal(lists, 4, "The root, the deleted folder, the new folder, and its subfolder");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("refresh keeps the unsaved links of an open draft", async () => {
|
||||||
|
const files = new Map([["Target.md", ""], ["draft.md", ""]]);
|
||||||
|
const index = new WorkspaceNoteIndex();
|
||||||
|
await index.rebuild(workspace(files));
|
||||||
|
index.update("draft.md", "[[Target]]");
|
||||||
|
await index.refresh(workspace(files), ["draft.md"], new Map([["draft.md", "[[Target]]"]]));
|
||||||
|
assert.equal(index.backlinks("Target.md").length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a rename keeps the links of the moved note", async () => {
|
||||||
|
const index = new WorkspaceNoteIndex();
|
||||||
|
await index.rebuild(workspace(new Map([["Target.md", ""], ["notes/source.md", "[Up](../Target.md)"]])));
|
||||||
|
index.rename("notes", "archive");
|
||||||
|
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["archive/source.md"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bulk reads use batches of 64 and read a file that is too large for a batch alone", async () => {
|
||||||
|
const files = new Map([["Target.md", ""], ...Array.from({ length: 70 }, (_, i) => [`n${i}.md`, "[[Target]]"] as [string, string])]);
|
||||||
|
const io = workspace(files), batches: number[] = [], singles: string[] = [];
|
||||||
|
const index = new WorkspaceNoteIndex();
|
||||||
|
await index.rebuild({
|
||||||
|
...io,
|
||||||
|
read: async path => { singles.push(path); return io.read(path); },
|
||||||
|
readMany: async paths => { batches.push(paths.length); return paths.map(path => path === "n5.md" ? { path, error: "The batch exceeds the 16 MiB limit." } : { path, source: files.get(path)! }); },
|
||||||
|
});
|
||||||
|
assert.deepEqual(batches, [64, 7]);
|
||||||
|
assert.deepEqual(singles, ["n5.md"]);
|
||||||
|
assert.equal(index.backlinks("Target.md").length, 70);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { buildOutline } from "../../../src/lib/workspace/outline.ts";
|
||||||
|
|
||||||
|
test("the Markdown outline skips code blocks and properties and shows rendered text", () => {
|
||||||
|
const source = "---\ntitle: Note\n---\n# **Bold** title\n\n```sh\n# not a heading\n```\n\nSetext\n------\n";
|
||||||
|
assert.deepEqual(buildOutline("note.md", source), [{ level: 1, text: "Bold title", line: 4 }, { level: 2, text: "Setext", line: 10 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("code files list their definitions", () => {
|
||||||
|
assert.deepEqual(buildOutline("tool.py", "import os\ndef run():\n pass\n"), [{ level: 1, text: "run", line: 2 }]);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user