Add workspace links, restore tabs, and update project guides
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import type { Backlink } from "$lib/workspace/noteIndex";
|
||||
|
||||
type Props = {
|
||||
entries: Backlink[];
|
||||
busy?: boolean;
|
||||
error?: string | null;
|
||||
onOpen: (entry: Backlink) => void;
|
||||
onRebuild?: () => void;
|
||||
};
|
||||
let { entries, busy = false, error = null, onOpen, onRebuild }: Props = $props();
|
||||
let expanded = $state(true);
|
||||
const contentId = $props.id();
|
||||
function collapseTooltip(node: HTMLElement) {
|
||||
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="backlinks" aria-label={$t("Backlinks")} aria-busy={busy}>
|
||||
<div class="heading">
|
||||
<button class="toggle" type="button" aria-expanded={expanded} aria-controls={contentId} use:collapseTooltip onclick={() => expanded = !expanded}>
|
||||
<span class:collapsed={!expanded}><Icon icon="chevron-down" /></span>
|
||||
<Icon icon="link" />
|
||||
<span>{$t("Backlinks")}</span>
|
||||
<span class="count">{entries.length}</span>
|
||||
</button>
|
||||
{#if onRebuild}
|
||||
<IconButton icon="refresh" label={$t("Rebuild note index")} disabled={busy} onclick={onRebuild} />
|
||||
{/if}
|
||||
</div>
|
||||
<div id={contentId} class="content" hidden={!expanded}>
|
||||
{#if error}
|
||||
<p class="error" role="status">{error}</p>
|
||||
{/if}
|
||||
{#if busy}
|
||||
<p class="placeholder" role="status">{$t("Reading workspace links…")}</p>
|
||||
{:else if entries.length === 0}
|
||||
<p class="placeholder">{$t("No other notes link to this file.")}</p>
|
||||
{/if}
|
||||
{#if entries.length > 0}
|
||||
<ul>
|
||||
{#each entries as entry (entry.sourcePath + ":" + entry.from)}
|
||||
<li>
|
||||
<button class="source" type="button" aria-label={$t("Open {path}, line {line}", { path: entry.sourcePath, line: entry.line })} onclick={() => onOpen(entry)}>
|
||||
<span class="source-title"><Icon icon="text" /><span>{entry.sourcePath}</span><span class="line">{entry.line}</span></span>
|
||||
<span class="excerpt">{entry.text}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.backlinks { min-height: 0; border-top: 1px solid var(--rs-border); display: flex; flex-direction: column; }
|
||||
.heading { display: flex; align-items: center; gap: 2px; padding: 2px 6px; }
|
||||
.toggle { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; min-height: 28px; padding: 2px 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; font: inherit; }
|
||||
.toggle > span:first-child { display: flex; }
|
||||
.collapsed { transform: rotate(-90deg); }
|
||||
.count { margin-left: auto; font-variant-numeric: tabular-nums; color: var(--rs-text-dim); }
|
||||
.content { min-height: 0; overflow: auto; }
|
||||
.content[hidden] { display: none; }
|
||||
ul { list-style: none; padding: 2px 6px 6px; margin: 0; }
|
||||
.source { width: 100%; display: block; padding: 6px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; font: inherit; }
|
||||
.source-title { display: flex; align-items: center; gap: 6px; color: var(--rs-accent); }
|
||||
.source-title > span:first-of-type { min-width: 0; overflow-wrap: anywhere; }
|
||||
.line { margin-left: auto; color: var(--rs-text-dim); font-variant-numeric: tabular-nums; }
|
||||
.excerpt { display: -webkit-box; line-clamp: 2; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.toggle:hover, .source:hover { background: var(--rs-bg-active); }
|
||||
.toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
|
||||
.placeholder, .error { margin: 8px 12px; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.placeholder { color: var(--rs-text-dim); }
|
||||
.error { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -227,7 +227,7 @@
|
||||
{#if reading && canPreview}
|
||||
{#key buffer.id}
|
||||
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
|
||||
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
|
||||
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {focusLine} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
|
||||
</div>
|
||||
{/key}
|
||||
{/if}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
|
||||
import { imageControls } from "$lib/editor/imageControls";
|
||||
import { readerHeadingFolding } from "$lib/editor/headingFolding";
|
||||
import { documentHeadings } from "$lib/workspace/headingLinks";
|
||||
import "$lib/editor/headingFolding.css";
|
||||
|
||||
import { readingMenu } from "$lib/editor/readingMenu";
|
||||
@@ -16,6 +17,7 @@
|
||||
type Props = {
|
||||
noteRel: string;
|
||||
contents: string;
|
||||
focusLine?: number | null;
|
||||
linkActions?: DocumentLinkActions;
|
||||
onSearch?: (text: string) => void;
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
@@ -24,7 +26,7 @@
|
||||
blockEditor?: Snippet;
|
||||
};
|
||||
|
||||
let { noteRel, contents, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
|
||||
let { noteRel, contents, focusLine = null, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
|
||||
let html = $state("");
|
||||
let menuError = $state("");
|
||||
let sections = $state<MarkdownSection[]>([]);
|
||||
@@ -82,6 +84,8 @@
|
||||
void html;
|
||||
void sections;
|
||||
void editing;
|
||||
const line = focusLine;
|
||||
const headings = documentHeadings(contents);
|
||||
const el = root;
|
||||
let cancelled = false;
|
||||
let releaseImages: (() => void) | undefined;
|
||||
@@ -90,6 +94,16 @@
|
||||
if (cancelled) return;
|
||||
releaseImages = imageControls(el);
|
||||
headingControls = currentHeadings = readerHeadingFolding(el, collapsedHeadings);
|
||||
if (line !== null) requestAnimationFrame(() => {
|
||||
if (cancelled) return;
|
||||
const index = headings.findIndex(heading => heading.line === line);
|
||||
const target = line === 1 && index < 0 ? el.querySelector<HTMLElement>(".document-title") :
|
||||
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
|
||||
if (!target) return;
|
||||
currentHeadings?.reveal(target);
|
||||
target.scrollIntoView({ block: "center" });
|
||||
el.focus({ preventScroll: true });
|
||||
});
|
||||
return renderDiagrams(el, () => cancelled);
|
||||
});
|
||||
return () => { cancelled = true; releaseImages?.(); currentHeadings?.destroy(); };
|
||||
|
||||
@@ -89,6 +89,44 @@
|
||||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||||
}
|
||||
|
||||
function clearTransferTarget() {
|
||||
receiving = false; dropBefore = dropAfter = null;
|
||||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||||
}
|
||||
|
||||
function nearRibbon(event: DragEvent) {
|
||||
if (dragged || !onDropTab || !event.dataTransfer?.types.includes(transferType)) return false;
|
||||
const header = bar?.closest(".header");
|
||||
if (!header || (event.target instanceof Element && event.target.closest(".window-controls"))) return false;
|
||||
const bounds = header.getBoundingClientRect();
|
||||
return event.clientX >= bounds.left && event.clientX <= bounds.right
|
||||
&& event.clientY >= bounds.top && event.clientY <= bounds.bottom + 24;
|
||||
}
|
||||
|
||||
function ribbonDragOver(event: DragEvent) {
|
||||
if (event.defaultPrevented) {
|
||||
if (!(event.target instanceof Node) || !bar.contains(event.target)) clearTransferTarget();
|
||||
return;
|
||||
}
|
||||
if (!nearRibbon(event)) { clearTransferTarget(); return; }
|
||||
event.preventDefault();
|
||||
event.dataTransfer!.dropEffect = "move";
|
||||
clearTransferTarget();
|
||||
receiving = true;
|
||||
// The wider target accepts a transfer at the end. Tabs retain precise ordering.
|
||||
dropAfter = tabs.at(-1)?.relPath ?? null;
|
||||
}
|
||||
|
||||
function ribbonDrop(event: DragEvent) {
|
||||
if (event.defaultPrevented || !nearRibbon(event)) { clearTransferTarget(); return; }
|
||||
const data = event.dataTransfer?.getData(transferType);
|
||||
if (!data) { clearTransferTarget(); return; }
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const index = tabs.length;
|
||||
finishTabTransfer();
|
||||
onDropTab?.(data, index);
|
||||
}
|
||||
|
||||
function dropTab(event: DragEvent) {
|
||||
const data = event.dataTransfer?.getData(transferType);
|
||||
if (!data) return;
|
||||
@@ -101,6 +139,8 @@
|
||||
|
||||
$effect(() => {
|
||||
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
|
||||
// A successful transfer can remove the drag source before dragend arrives.
|
||||
if (dragged && !tabs.some(tab => tab.relPath === dragged)) finishTabTransfer();
|
||||
});
|
||||
|
||||
function tabButton(path: string) {
|
||||
@@ -276,7 +316,10 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
|
||||
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()}
|
||||
ondragover={ribbonDragOver} ondrop={ribbonDrop}
|
||||
ondragleave={(event) => { if (!event.relatedTarget) clearTransferTarget(); }}
|
||||
ondragend={clearTransferTarget} />
|
||||
|
||||
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label={$t("Working tabs")} tabindex="-1"
|
||||
ondragover={dragOver} ondrop={dropTab}
|
||||
@@ -338,7 +381,7 @@
|
||||
box-shadow: inset 0 -1px var(--rs-border);
|
||||
}
|
||||
.tabs:empty { min-width: 80px; }
|
||||
.tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); }
|
||||
.tabs.receiving, .tabs.receiving .tab { box-shadow: inset 0 -2px var(--rs-accent); }
|
||||
|
||||
.tab {
|
||||
position: relative;
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
let input: HTMLInputElement | undefined = $state();
|
||||
$effect(() => {
|
||||
if (dialogs.text && element && input) {
|
||||
element.showModal(); input.focus(); input.select();
|
||||
element.showModal(); input.focus();
|
||||
if (dialogs.text.selection) input.setSelectionRange(...dialogs.text.selection);
|
||||
else input.select();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { DropTarget } from "$lib/workspace/treeDrop";
|
||||
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
|
||||
import { treeFileParts } from "$lib/workspace/chrome";
|
||||
import { renameSelection } from "$lib/workspace/renamePath";
|
||||
import TreeNode from "./TreeNode.svelte";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { pluginDocuments } from "$lib/plugins/external";
|
||||
@@ -64,7 +65,7 @@
|
||||
|
||||
function focusSelect(node: HTMLInputElement) {
|
||||
node.focus();
|
||||
node.select();
|
||||
node.setSelectionRange(...renameSelection(node.value, entry.kind));
|
||||
}
|
||||
|
||||
function edgeWidth(steps: number | null | undefined) {
|
||||
|
||||
+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