Add workspace links, restore tabs, and update project guides
This commit is contained in:
+170
-19
@@ -4,7 +4,7 @@
|
||||
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab } from "$lib/plugins/external";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup } from "$lib/plugins/external";
|
||||
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
|
||||
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";
|
||||
@@ -21,6 +21,7 @@
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { Documents } from "$lib/workspace/documents";
|
||||
import { documentSessionKey, parseDocumentSession, restoreDocumentSession, type DocumentSession } from "$lib/workspace/documentSession";
|
||||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||||
import { orderWorkbenchTabs, type WorkbenchTab } from "$lib/workspace/workbenchTabs";
|
||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
@@ -38,6 +39,8 @@
|
||||
import EditorPane from "./EditorPane.svelte";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
import OutlinePane from "./OutlinePane.svelte";
|
||||
import Backlinks from "./Backlinks.svelte";
|
||||
import { WorkspaceNoteIndex, type Backlink } from "$lib/workspace/noteIndex";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||
import SearchPane from "./SearchPane.svelte";
|
||||
@@ -62,9 +65,10 @@
|
||||
workspaceWriteBytes,
|
||||
} from "$lib/workspace/api";
|
||||
import { detectChrome } from "$lib/workspace/chrome";
|
||||
import { planRename, planMarkdownTitleRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
|
||||
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
|
||||
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
|
||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
|
||||
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
|
||||
|
||||
let workspace = $state<WorkspaceInfo | null>(null);
|
||||
@@ -90,6 +94,62 @@
|
||||
let status = $state($t("Open a workspace folder"));
|
||||
let error = $state<string | null>(null);
|
||||
let refreshToken = $state(0);
|
||||
const noteIndex = new WorkspaceNoteIndex();
|
||||
let noteIndexRoot: string | null = null;
|
||||
let noteIndexRevision = $state(0);
|
||||
let noteIndexBusy = $state(false);
|
||||
let noteIndexError = $state<string | null>(null);
|
||||
let noteIndexPending: Promise<void> = Promise.resolve();
|
||||
let noteIndexRequest = 0;
|
||||
const backlinks = $derived.by(() => {
|
||||
void noteIndexRevision;
|
||||
return activePath && !editorPluginVisible ? noteIndex.backlinks(activePath) : [];
|
||||
});
|
||||
|
||||
function rebuildNoteIndex() {
|
||||
const root = workspace?.root ?? null;
|
||||
if (root !== noteIndexRoot) {
|
||||
noteIndex.clear(); noteIndexRoot = root; noteIndexRevision = noteIndex.revision;
|
||||
}
|
||||
const request = ++noteIndexRequest;
|
||||
noteIndexBusy = !!root;
|
||||
noteIndexError = null;
|
||||
if (!root) return noteIndexPending = Promise.resolve();
|
||||
const drafts = new Map((documents?.buffers ?? []).filter(tab => tab.kind === "text" && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
|
||||
return noteIndexPending = noteIndex.rebuild({ list: workspaceList, read: workspaceRead }, drafts).then(result => {
|
||||
if (request !== noteIndexRequest || workspace?.root !== root) return;
|
||||
noteIndexRevision = noteIndex.revision;
|
||||
noteIndexBusy = false;
|
||||
if (result.errors.length) noteIndexError = $t("Could not read all workspace links. Rebuild the index to retry.");
|
||||
}).catch(reason => {
|
||||
if (request !== noteIndexRequest) return;
|
||||
noteIndexBusy = false; noteIndexError = String(reason);
|
||||
});
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void workspace?.root; void refreshToken;
|
||||
untrack(() => { void rebuildNoteIndex(); });
|
||||
});
|
||||
|
||||
let indexedDrafts = new Map<string, string>();
|
||||
let draftsRoot: string | null = null;
|
||||
$effect(() => {
|
||||
const root = workspace?.root ?? null;
|
||||
const drafts = new Map(tabs.filter(tab => tab.kind === "text" && isMarkdownPath(tab.relPath) && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
|
||||
untrack(() => {
|
||||
if (draftsRoot !== root) { indexedDrafts = new Map(); draftsRoot = root; }
|
||||
const removed = [...indexedDrafts.keys()].some(path => !drafts.has(path));
|
||||
for (const [path, contents] of drafts) if (indexedDrafts.get(path) !== contents) noteIndex.update(path, contents);
|
||||
indexedDrafts = drafts;
|
||||
noteIndexRevision = noteIndex.revision;
|
||||
if (removed) void rebuildNoteIndex();
|
||||
});
|
||||
});
|
||||
|
||||
async function openBacklink(entry: Backlink) {
|
||||
await openFile({ name: entry.sourcePath.split("/").pop()!, rel_path: entry.sourcePath, kind: "file" }, entry.line, "new");
|
||||
}
|
||||
let view = $state<Chrome>("Writing");
|
||||
let layoutReady = $state(false);
|
||||
let leftWidth = $state(DEFAULT_WORKBENCH_LAYOUT.leftWidth);
|
||||
@@ -237,10 +297,9 @@
|
||||
});
|
||||
function workingTabDragData(tab: WorkbenchTab) {
|
||||
const view = $pluginEditors.find(view => view.key === tab.id);
|
||||
if (view) return pluginTabDragData(view);
|
||||
const item = workingTabs.find(item => item.id === tab.id);
|
||||
if (!item || !workspace || !desktop) return;
|
||||
try { return JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
|
||||
try { return (view && pluginTabDragData(view)) || JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
|
||||
catch (reason) { error = String(reason); return; }
|
||||
}
|
||||
async function receiveTab(data: string, index: number) {
|
||||
@@ -253,14 +312,21 @@
|
||||
if (!raw) throw new Error("This tab transfer expired. Drag the tab again.");
|
||||
const transfer = JSON.parse(raw);
|
||||
if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace.");
|
||||
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000
|
||||
|| !transfer.buffer || typeof transfer.buffer.relPath !== "string" || typeof transfer.buffer.contents !== "string"
|
||||
|| typeof transfer.buffer.saved !== "string") throw new Error("Invalid tab transfer.");
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
||||
selectTab(transfer.buffer.relPath);
|
||||
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000) throw new Error("Invalid tab transfer.");
|
||||
let path: string;
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string"
|
||||
&& typeof transfer.buffer.saved === "string") {
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
||||
path = transfer.buffer.relPath;
|
||||
selectTab(path);
|
||||
} else if (transfer.plugin) {
|
||||
if (!await restorePluginTab(transfer.plugin)) throw new Error("Enable this tab's plugin before moving it to this window.");
|
||||
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
|
||||
path = `plugin:${$pluginView.key}`;
|
||||
} else throw new Error("Invalid tab transfer.");
|
||||
setReading(transfer.reading === true);
|
||||
await tick();
|
||||
moveWorkingTab(transfer.buffer.relPath, index);
|
||||
moveWorkingTab(path, index);
|
||||
localStorage.setItem(key + ".accepted", "true");
|
||||
localStorage.removeItem(key);
|
||||
error = null;
|
||||
@@ -358,6 +424,51 @@
|
||||
await workspacePicker.show();
|
||||
}
|
||||
|
||||
function saveDocumentTabs() {
|
||||
if (!workspace || !workbenchReady || transferredWindow) return;
|
||||
const documents = workingTabs.flatMap(tab => "buffer" in tab && tab.buffer.kind !== "empty"
|
||||
? [{ path: tab.buffer.relPath, pinned: !!tab.pinned }]
|
||||
: "plugin" in tab && tab.plugin.document ? [{ path: tab.plugin.document.path, pinned: !!tab.pinned, plugin: true }] : []);
|
||||
const active = workingTabs.find(tab => tab.relPath === activeTabPath);
|
||||
const activeDocument = active && ("buffer" in active ? active.buffer.relPath : active.plugin.document?.path);
|
||||
const session: DocumentSession = { version: 1, documents, activePath: activeDocument ?? activePath };
|
||||
try { localStorage.setItem(documentSessionKey(workspace.root), JSON.stringify(session)); }
|
||||
catch (reason) { console.warn("Could not save document tabs.", reason); }
|
||||
}
|
||||
|
||||
async function restoreDocumentTabs() {
|
||||
const current = documents;
|
||||
if (!current || !workspace) return;
|
||||
const session = parseDocumentSession(localStorage.getItem(documentSessionKey(workspace.root)));
|
||||
if (!session) return;
|
||||
if (session.documents.some(tab => tab.plugin)) await waitForPluginStartup();
|
||||
const order: string[] = [];
|
||||
const paths = new Map<string, string>();
|
||||
const active = await restoreDocumentSession(session, async tab => {
|
||||
if (tab.plugin) {
|
||||
const entries = await workspaceList(tab.path.split("/").slice(0, -1).join("/"));
|
||||
if (!entries.some(entry => entry.kind === "file" && entry.rel_path === tab.path)) throw new Error("Missing document.");
|
||||
}
|
||||
if (tab.plugin && await openPluginDocument(tab.path)) {
|
||||
await tick();
|
||||
const opened = $pluginEditors.find(view => view.document?.path === tab.path);
|
||||
if (!opened) throw new Error("The plugin did not open this document.");
|
||||
if (tab.pinned !== !!opened.pinned) pinPluginEditor(opened.key);
|
||||
order.push(opened.key);
|
||||
paths.set(tab.path, `plugin:${opened.key}`);
|
||||
} else {
|
||||
await current.open({ name: tab.path.split("/").pop()!, rel_path: tab.path, kind: "file" }, "background");
|
||||
if (tab.pinned) current.togglePin(tab.path);
|
||||
const opened = current.buffers.find(buffer => buffer.relPath === tab.path)!;
|
||||
order.push(opened.tabId ?? opened.id);
|
||||
paths.set(tab.path, tab.path);
|
||||
}
|
||||
});
|
||||
await tick();
|
||||
tabOrder = order;
|
||||
if (active) selectWorkingTab(paths.get(active)!);
|
||||
}
|
||||
|
||||
async function restoreLast() {
|
||||
switching = true;
|
||||
try {
|
||||
@@ -391,7 +502,7 @@
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else await restoreDocumentTabs();
|
||||
}
|
||||
} catch (err) { error = String(err); }
|
||||
finally { switching = false; workbenchReady = true; }
|
||||
@@ -835,6 +946,8 @@
|
||||
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) {
|
||||
@@ -859,7 +972,8 @@
|
||||
}
|
||||
const current = documents;
|
||||
const from = activePath;
|
||||
const typed = await requestText($t("Rename to"), from.split("/").pop() ?? from);
|
||||
const name = from.split("/").pop() ?? from;
|
||||
const typed = await requestText($t("Rename to"), name, { selection: renameSelection(name) });
|
||||
if (typed == null || documents !== current || switching) {
|
||||
return;
|
||||
}
|
||||
@@ -887,7 +1001,11 @@
|
||||
const current = documents, currentWorkspace = workspace;
|
||||
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
|
||||
const entry = async () => {
|
||||
for (const path of linkCandidates(origin, link.target, link.kind)) {
|
||||
await noteIndexPending;
|
||||
const resolution = noteIndex.resolve(origin, link.target, link.kind);
|
||||
if (resolution.status === "ambiguous") throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: resolution.candidates.join(", ") }));
|
||||
const paths = resolution.status === "resolved" ? [resolution.path] : link.kind === "wiki" ? [] : linkCandidates(origin, link.target, link.kind);
|
||||
for (const path of paths) {
|
||||
if (!valid()) throw new Error("The workspace changed. Open the link menu again.");
|
||||
const parent = path.split("/").slice(0, -1).join("/");
|
||||
let files: TreeEntry[];
|
||||
@@ -901,7 +1019,8 @@
|
||||
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
|
||||
};
|
||||
async function rename(file: TreeEntry, move = false) {
|
||||
const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name);
|
||||
const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name,
|
||||
move ? undefined : { selection: renameSelection(file.name) });
|
||||
if (!typed || !valid()) return;
|
||||
let to = typed.trim().replaceAll("\\", "/");
|
||||
if (move) {
|
||||
@@ -956,12 +1075,33 @@
|
||||
} catch (err) { error = String(err); }
|
||||
return;
|
||||
}
|
||||
const rels = linkCandidates(origin, target, kind);
|
||||
const current = documents, root = workspace?.root;
|
||||
await noteIndexPending;
|
||||
if (documents !== current || workspace?.root !== root) return;
|
||||
const resolution = noteIndex.resolve(origin, target, kind);
|
||||
if (resolution.status === "ambiguous") {
|
||||
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: resolution.candidates.join(", ") });
|
||||
return;
|
||||
}
|
||||
const rels = resolution.status === "resolved" ? [resolution.path] : kind === "wiki" ? [] : linkCandidates(origin, target, kind);
|
||||
const fragment = linkFragment(target);
|
||||
focusDocumentPane(paneId);
|
||||
for (const rel of rels) {
|
||||
try {
|
||||
await documents?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" });
|
||||
await current?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" }, "new");
|
||||
if (documents !== current || workspace?.root !== root) return;
|
||||
pluginEditorActive.set(false);
|
||||
error = null;
|
||||
focusLine = null;
|
||||
if (fragment !== null) {
|
||||
const opened = current?.buffers.find(buffer => buffer.relPath === rel);
|
||||
const line = opened?.kind === "text" ? headingLinkLine(opened.contents, fragment) : null;
|
||||
if (line === null) error = $t("Could not open {path}", { path: target });
|
||||
else {
|
||||
await tick();
|
||||
if (documents === current && workspace?.root === root && documentPanes.active === paneId) focusLine = line;
|
||||
}
|
||||
}
|
||||
return;
|
||||
} catch { /* Try the workspace-root candidate after the note-relative path. */ }
|
||||
}
|
||||
@@ -1065,13 +1205,16 @@
|
||||
}).then(register).catch(err => error = String(err));
|
||||
let closing = false;
|
||||
void getCurrentWindow().onCloseRequested(async event => {
|
||||
if (!hasDirty && !terminalStarted) return;
|
||||
if (!hasDirty && !terminalStarted) { saveDocumentTabs(); return; }
|
||||
event.preventDefault();
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
try {
|
||||
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n");
|
||||
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) await getCurrentWindow().destroy();
|
||||
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) {
|
||||
saveDocumentTabs();
|
||||
await getCurrentWindow().destroy();
|
||||
}
|
||||
} finally { closing = false; }
|
||||
}).then(register).catch(err => error = String(err));
|
||||
const focus = () => { void documents?.refresh(); refreshToken++; };
|
||||
@@ -1211,7 +1354,7 @@
|
||||
status = message;
|
||||
error = null;
|
||||
}}
|
||||
onEntryGone={(path) => { removePluginDocuments(path); void documents?.refresh(); }}
|
||||
onEntryGone={(path) => { removePluginDocuments(path); noteIndex.remove(path); noteIndexRevision = noteIndex.revision; void documents?.refresh(); refreshToken++; }}
|
||||
onEntryRenamed={applyPathRename}
|
||||
/>
|
||||
</div>
|
||||
@@ -1346,6 +1489,7 @@
|
||||
onpointerdown={() => (dragging = "right")}
|
||||
></div>
|
||||
<aside class="right">
|
||||
<div class="outline-area">
|
||||
<OutlinePane
|
||||
items={outlineItems}
|
||||
onJump={(line) => {
|
||||
@@ -1357,6 +1501,10 @@
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{#if buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
|
||||
<Backlinks entries={backlinks} busy={noteIndexBusy} error={noteIndexError} onOpen={entry => void openBacklink(entry)} onRebuild={() => void rebuildNoteIndex()} />
|
||||
{/if}
|
||||
</aside>
|
||||
{/if}
|
||||
|
||||
@@ -1370,6 +1518,9 @@
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.right { display: flex; flex-direction: column; }
|
||||
.outline-area { flex: 1; min-height: 80px; overflow: hidden; }
|
||||
.right > :global(.backlinks) { flex: 0 1 auto; max-height: 50%; }
|
||||
.terminal-hidden { display: none !important; }
|
||||
.terminal-maximized > .center, .terminal-maximized > .gutter-h { display: none; }
|
||||
.terminal-maximized > .bottom { flex: 1; height: auto; }
|
||||
|
||||
Reference in New Issue
Block a user