Add workspace links, restore tabs, and update project guides
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
|
||||
import { writerHistory, historyKeymap } from "./writerHistory";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { foldedRanges, unfoldEffect } from "@codemirror/language";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
|
||||
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
||||
@@ -409,7 +410,9 @@
|
||||
if (!view || line == null) return;
|
||||
untrack(() => {
|
||||
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
|
||||
view.dispatch({ selection: { anchor }, effects: EditorView.scrollIntoView(anchor, { y: "center" }) });
|
||||
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
|
||||
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
|
||||
view.dispatch({ selection: { anchor }, effects });
|
||||
view.focus();
|
||||
});
|
||||
});
|
||||
@@ -461,7 +464,7 @@
|
||||
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
|
||||
/* Keep child margins inside the measured widget; collapsed margins otherwise
|
||||
shift mouse hit-testing to the next line after a table or other preview. */
|
||||
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; }
|
||||
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
|
||||
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
|
||||
.live-writer :global(.writer-preview img) { max-width: 100%; }
|
||||
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
|
||||
|
||||
@@ -121,6 +121,19 @@ class Preview extends WidgetType {
|
||||
previewFormulas.set(dom, this.formulas);
|
||||
dom.className = "reading writer-preview";
|
||||
dom.innerHTML = this.html;
|
||||
// Widgets handle their own events, so CodeMirror's link handler cannot run.
|
||||
dom.addEventListener("mousedown", event => {
|
||||
if (event.button !== 0 || (!event.ctrlKey && !event.metaKey)) return;
|
||||
const link = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-href], a[href]") : null;
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void this.actions.linkActions?.().open?.({ kind: link.dataset.kind === "wiki" ? "wiki" : "md", target: link.dataset.href ?? link.getAttribute("href") ?? "" });
|
||||
}, { capture: true });
|
||||
// Cancel native anchor navigation even when an ordinary click reveals source.
|
||||
dom.addEventListener("click", event => {
|
||||
if (event.target instanceof Element && event.target.closest("a[href], [data-href]")) event.preventDefault();
|
||||
}, { capture: true });
|
||||
tableControls(dom, view, this.source, this.actions);
|
||||
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
|
||||
this.measure(dom, view);
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
export type Locale = 'en' | 'fr' | 'ja' | 'zh-CN';
|
||||
export const messageRows: [string, string, string, string][] = [
|
||||
["Backlinks", "Liens entrants", "バックリンク", "反向链接"],
|
||||
["Rebuild note index", "Reconstruire l’index des notes", "ノート索引を再構築", "重建笔记索引"],
|
||||
["Reading workspace links…", "Lecture des liens de l’espace de travail…", "ワークスペースのリンクを読み込み中…", "正在读取工作区链接…"],
|
||||
["No other notes link to this file.", "Aucune autre note ne pointe vers ce fichier.", "このファイルへのリンクがある他のノートはありません。", "没有其他笔记链接到此文件。"],
|
||||
["Open {path}, line {line}", "Ouvrir {path}, ligne {line}", "{path} の {line} 行目を開く", "打开 {path},第 {line} 行"],
|
||||
["Could not read all workspace links. Rebuild the index to retry.", "Impossible de lire tous les liens. Reconstruisez l’index pour réessayer.", "一部のリンクを読み込めませんでした。索引を再構築して再試行してください。", "无法读取所有工作区链接。请重建索引以重试。"],
|
||||
["More than one note matches {path}. Use its workspace path: {candidates}", "Plusieurs notes correspondent à {path}. Utilisez le chemin dans l’espace de travail : {candidates}", "{path} に一致するノートが複数あります。ワークスペース内のパスを指定してください: {candidates}", "多个笔记与 {path} 匹配。请使用其工作区路径:{candidates}"],
|
||||
["{name}: package applied.", "{name} : paquet appliqué.", "{name}: パッケージを適用しました。", "{name}:已应用软件包。"],
|
||||
["To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.", "Pour mettre à jour un plug-in, sélectionnez son nouveau ZIP ou lien de version. Ses paramètres et son état restent identiques.", "プラグインを更新するには、新しいZIPまたはリリースリンクを選択してください。設定と有効状態は保持されます。", "要更新插件,请选择新的 ZIP 或发行链接。设置和启用状态保持不变。"],
|
||||
["Update {current} → {next}. Settings and enabled state stay the same.", "Mise à jour {current} → {next}. Les paramètres et l’état restent identiques.", "{current} → {next} に更新します。設定と有効状態は保持されます。", "更新 {current} → {next}。设置和启用状态保持不变。"],
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -28,8 +28,16 @@ export function pluginTabState(view: OpenPluginView) {
|
||||
state: sessions.get(view.owner)?.session.views.get(view.id)?.saveTabState?.() };
|
||||
}
|
||||
export async function restorePluginTab(transfer: ReturnType<typeof pluginTabState>): Promise<boolean> {
|
||||
if (!transfer || typeof transfer.owner !== "string" || typeof transfer.id !== "string"
|
||||
|| (transfer.document && (typeof transfer.document.path !== "string" || typeof transfer.document.id !== "string"))) {
|
||||
throw new Error("Invalid tab transfer.");
|
||||
}
|
||||
const session = sessions.get(transfer.owner)?.session;
|
||||
if (!session) return false;
|
||||
if (get(pluginEditors).some(view => view.owner === transfer.owner && view.id === transfer.id
|
||||
&& (transfer.document ? view.document?.path === transfer.document.path : !view.document))) {
|
||||
throw new Error("This tab is already open in this window. The source tab remains open.");
|
||||
}
|
||||
if (transfer.document) {
|
||||
if (!await openPluginDocument(transfer.document.path)) return false;
|
||||
} else {
|
||||
@@ -73,6 +81,7 @@ const failures = new Map<string, string>();
|
||||
const errors: Record<string, string> = {};
|
||||
const restarted = new Set<string>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
export function waitForPluginStartup() { return queue; }
|
||||
let started = false;
|
||||
let allowedPlugins: string[] | undefined;
|
||||
let generation = 0;
|
||||
@@ -158,7 +167,7 @@ export async function openPluginDocument(path: string, current: () => boolean =
|
||||
const { owner, type, document } = match;
|
||||
const existing = get(pluginEditors).find(view => view.owner === owner && view.id === type.id && view.document?.path === path && view.document.id === document.id);
|
||||
if (existing) { selectPluginEditor(existing); return true; }
|
||||
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon };
|
||||
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon, draggable: true };
|
||||
pluginEditors.update(views => [...views, view]); selectPluginEditor(view);
|
||||
return true;
|
||||
}
|
||||
@@ -206,7 +215,7 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||
}
|
||||
if (placement === "editor") {
|
||||
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
|
||||
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
|
||||
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: true, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
|
||||
if (!existing && options) {
|
||||
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
|
||||
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
type TextRequest = { title: string; value: string; resolve: (value: string | null) => void };
|
||||
type TextRequest = { title: string; value: string; selection?: [number, number]; resolve: (value: string | null) => void };
|
||||
export const dialogs = $state<{ text: TextRequest | null }>({ text: null });
|
||||
|
||||
export function requestText(title: string, value = ""): Promise<string | null> {
|
||||
export function requestText(title: string, value = "", options: { selection?: [number, number] } = {}): Promise<string | null> {
|
||||
dialogs.text?.resolve(null);
|
||||
return new Promise(resolve => { dialogs.text = { title, value, resolve }; });
|
||||
return new Promise(resolve => { dialogs.text = { title, value, ...options, resolve }; });
|
||||
}
|
||||
|
||||
export function finishText(value: string | null) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
export type SessionDocument = { path: string; pinned: boolean; plugin?: boolean };
|
||||
export type DocumentSession = { version: 1; documents: SessionDocument[]; activePath: string | null };
|
||||
|
||||
export const documentSessionKey = (root: string) => `runestone.document-session.${encodeURIComponent(root)}`;
|
||||
const validPath = (path: unknown): path is string => typeof path === "string" && path.length > 0
|
||||
&& !/[\\:\u0000-\u001f]/.test(path) && !path.startsWith("/")
|
||||
&& path.split("/").every(part => !!part && part !== "." && part !== "..");
|
||||
|
||||
export function parseDocumentSession(raw: string | null): DocumentSession | null {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
if (value?.version !== 1 || !Array.isArray(value.documents)) return null;
|
||||
const seen = new Set<string>();
|
||||
const documents = value.documents.flatMap((item: unknown) => {
|
||||
if (!item || typeof item !== "object" || !("path" in item) || !validPath(item.path) || seen.has(item.path)) return [];
|
||||
seen.add(item.path);
|
||||
return [{ path: item.path, pinned: "pinned" in item && item.pinned === true,
|
||||
...("plugin" in item && item.plugin === true ? { plugin: true } : {}) }];
|
||||
});
|
||||
return { version: 1, documents, activePath: seen.has(value.activePath) ? value.activePath : null };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** Reopen disk files independently so a missing file does not stop the session. */
|
||||
export async function restoreDocumentSession(session: DocumentSession, open: (document: SessionDocument) => Promise<void>) {
|
||||
const opened: string[] = [];
|
||||
for (const document of session.documents) {
|
||||
try { await open(document); opened.push(document.path); }
|
||||
catch { /* Missing, renamed, or unreadable files do not block later tabs. */ }
|
||||
}
|
||||
return session.activePath && opened.includes(session.activePath) ? session.activePath : opened[0] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
|
||||
const markdown = new MarkdownIt({ html: false });
|
||||
|
||||
export function linkFragment(target: string): string | null {
|
||||
const index = target.indexOf("#");
|
||||
if (index < 0) return null;
|
||||
const fragment = target.slice(index + 1);
|
||||
try { return decodeURIComponent(fragment); } catch { return fragment; }
|
||||
}
|
||||
|
||||
function headingText(tokens: Token[]): string {
|
||||
return tokens.map(token => token.children ? headingText(token.children) :
|
||||
["text", "code_inline"].includes(token.type) ? token.content :
|
||||
["softbreak", "hardbreak"].includes(token.type) ? " " : "").join("");
|
||||
}
|
||||
|
||||
export function headingSlug(text: string): string {
|
||||
return text.toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\-\s]/gu, "").replace(/\s/g, "-");
|
||||
}
|
||||
|
||||
/** Match rendered heading text and unique Markdown slugs, excluding code and properties. */
|
||||
export function documentHeadings(contents: string): { text: string; slug: string; line: number }[] {
|
||||
const source = contents.replace(/\r\n/g, "\n");
|
||||
const properties = /^\uFEFF?---\n[\s\S]*?\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(source)?.[0] ?? "";
|
||||
const offset = (properties.match(/\n/g) ?? []).length;
|
||||
const tokens = markdown.parse(source.slice(properties.length), {});
|
||||
const used = new Set<string>();
|
||||
return tokens.flatMap((token, index) => {
|
||||
if (token.type !== "heading_open" || !token.map) return [];
|
||||
const text = headingText(tokens[index + 1]?.children ?? []);
|
||||
const base = headingSlug(text);
|
||||
let slug = base, suffix = 0;
|
||||
while (used.has(slug)) slug = `${base}-${++suffix}`;
|
||||
used.add(slug);
|
||||
return [{ text, slug, line: token.map[0] + offset + 1 }];
|
||||
});
|
||||
}
|
||||
|
||||
export function headingLinkLine(contents: string, fragment: string): number | null {
|
||||
if (!fragment) return 1;
|
||||
const headings = documentHeadings(contents);
|
||||
return (headings.find(heading => heading.slug === fragment) ??
|
||||
headings.find(heading => heading.text.toLowerCase() === fragment.toLowerCase()))?.line ?? null;
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { documentLinks, type DocumentLink } from "../editor/documentLinks.ts";
|
||||
|
||||
export type NoteLinkResolution =
|
||||
| { status: "resolved"; path: string }
|
||||
| { status: "ambiguous"; candidates: string[] }
|
||||
| { status: "missing" | "external" };
|
||||
|
||||
export type Backlink = {
|
||||
sourcePath: string;
|
||||
line: number;
|
||||
from: number;
|
||||
to: number;
|
||||
text: string;
|
||||
target: string;
|
||||
kind: "md" | "wiki";
|
||||
};
|
||||
|
||||
export type NoteIndexIO = {
|
||||
list: (folder: string) => Promise<{ rel_path: string; kind: "file" | "folder" }[]>;
|
||||
read: (path: string) => Promise<string>;
|
||||
};
|
||||
|
||||
export type NoteIndexIssue = { path: string; operation: "list" | "read"; error: string };
|
||||
type IndexedNote = { contents: string; links: Backlink[] };
|
||||
type Snapshot = { files: Set<string>; notes: Map<string, IndexedNote> };
|
||||
type Change = (snapshot: Snapshot) => void;
|
||||
|
||||
export function isIndexedNote(path: string): boolean {
|
||||
return /\.(?:md|markdown|mdown)$/i.test(path);
|
||||
}
|
||||
|
||||
function normalizePath(value: string): string | null {
|
||||
const parts: string[] = [];
|
||||
for (const part of value.replaceAll("\\", "/").split("/")) {
|
||||
if (!part || part === ".") continue;
|
||||
if (part === "..") {
|
||||
if (!parts.length) return null;
|
||||
parts.pop();
|
||||
} else parts.push(part);
|
||||
}
|
||||
return parts.join("/");
|
||||
}
|
||||
|
||||
function referenceLabel(label: string): string {
|
||||
return label.replace(/^\[|\]$/g, "").trim().replace(/\s+/g, " ").toLowerCase();
|
||||
}
|
||||
|
||||
/** Read link ranges without changing the Markdown file or requiring a sidecar. */
|
||||
function noteLinks(sourcePath: string, contents: string): Backlink[] {
|
||||
const definitions = new Map<string, string>();
|
||||
const references: { from: number; to: number; label: string }[] = [];
|
||||
const comments: { from: number; to: number }[] = [];
|
||||
markdownLanguage.parser.parse(contents).iterate({ enter(node) {
|
||||
if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) return false;
|
||||
if (["CommentBlock", "HTMLBlock", "HTMLTag"].includes(node.name)) {
|
||||
comments.push({ from: node.from, to: node.to });
|
||||
return false;
|
||||
}
|
||||
if (node.name === "LinkReference") {
|
||||
const label = node.node.getChild("LinkLabel"), url = node.node.getChild("URL");
|
||||
if (label && url) {
|
||||
const key = referenceLabel(contents.slice(label.from, label.to));
|
||||
if (!definitions.has(key)) definitions.set(key, contents.slice(url.from, url.to).replace(/^<|>$/g, ""));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (node.name !== "Link" || node.node.getChild("URL")) return;
|
||||
const label = node.node.getChild("LinkLabel");
|
||||
const raw = contents.slice(node.from, node.to);
|
||||
const explicit = label ? contents.slice(label.from, label.to) : "";
|
||||
references.push({ from: node.from, to: node.to, label: referenceLabel(explicit && explicit !== "[]" ? explicit : raw.match(/^\[([^\]]+)\]/)?.[0] ?? "") });
|
||||
return false;
|
||||
} });
|
||||
const links: DocumentLink[] = documentLinks(contents);
|
||||
for (const reference of references) {
|
||||
const target = definitions.get(reference.label);
|
||||
if (target) links.push({ ...reference, target, kind: "md", targetFrom: reference.from, targetTo: reference.to });
|
||||
}
|
||||
const lineStarts = [0];
|
||||
for (let offset = 0; offset < contents.length; offset++) if (contents[offset] === "\n") lineStarts.push(offset + 1);
|
||||
return links.filter(link => {
|
||||
if (comments.some(comment => link.from < comment.to && link.to > comment.from)) return false;
|
||||
if (link.kind !== "wiki") return true;
|
||||
let escapes = 0;
|
||||
for (let offset = link.from - 1; offset >= 0 && contents[offset] === "\\"; offset--) escapes++;
|
||||
return escapes % 2 === 0;
|
||||
}).sort((a, b) => a.from - b.from).map(link => {
|
||||
let low = 0, high = lineStarts.length;
|
||||
while (low + 1 < high) {
|
||||
const middle = (low + high) >>> 1;
|
||||
if (lineStarts[middle] <= link.from) low = middle;
|
||||
else high = middle;
|
||||
}
|
||||
const end = contents.indexOf("\n", link.from);
|
||||
return { sourcePath, line: low + 1, from: link.from, to: link.to, target: link.target, kind: link.kind,
|
||||
text: contents.slice(lineStarts[low], end < 0 ? contents.length : end).trim() };
|
||||
});
|
||||
}
|
||||
|
||||
/** An in-memory index. The workspace files remain the source of truth. */
|
||||
export class WorkspaceNoteIndex {
|
||||
#snapshot: Snapshot = { files: new Set(), notes: new Map() };
|
||||
#revision = 0;
|
||||
#generation = 0;
|
||||
#changes: Change[] | null = null;
|
||||
#backlinksRevision = -1;
|
||||
#backlinks = new Map<string, Backlink[]>();
|
||||
#pathsRevision = -1;
|
||||
#paths = new Map<string, string[]>();
|
||||
#names = new Map<string, string[]>();
|
||||
|
||||
get revision(): number { return this.#revision; }
|
||||
get size(): number { return this.#snapshot.notes.size; }
|
||||
|
||||
clear(): void {
|
||||
this.#generation++;
|
||||
this.#changes = null;
|
||||
this.#snapshot = { files: new Set(), notes: new Map() };
|
||||
this.#revision++;
|
||||
}
|
||||
|
||||
#change(change: Change): void {
|
||||
change(this.#snapshot);
|
||||
this.#changes?.push(change);
|
||||
this.#revision++;
|
||||
}
|
||||
|
||||
update(path: string, contents: string): void {
|
||||
const normalized = normalizePath(path);
|
||||
if (!normalized) return;
|
||||
const note = isIndexedNote(normalized) ? { contents, links: noteLinks(normalized, contents) } : null;
|
||||
this.#change(snapshot => {
|
||||
snapshot.files.add(normalized);
|
||||
if (note) snapshot.notes.set(normalized, note);
|
||||
});
|
||||
}
|
||||
|
||||
remove(path: string): void {
|
||||
const normalized = normalizePath(path);
|
||||
if (!normalized) return;
|
||||
this.#change(snapshot => {
|
||||
for (const file of snapshot.files) if (file === normalized || file.startsWith(`${normalized}/`)) {
|
||||
snapshot.files.delete(file);
|
||||
snapshot.notes.delete(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
rename(from: string, to: string): void {
|
||||
const oldPath = normalizePath(from), newPath = normalizePath(to);
|
||||
if (!oldPath || !newPath || oldPath === newPath) return;
|
||||
this.#change(snapshot => {
|
||||
const moved = [...snapshot.files].filter(path => path === oldPath || path.startsWith(`${oldPath}/`));
|
||||
for (const path of moved) {
|
||||
const replacement = newPath + path.slice(oldPath.length);
|
||||
const note = snapshot.notes.get(path);
|
||||
snapshot.files.delete(path);
|
||||
snapshot.notes.delete(path);
|
||||
snapshot.files.add(replacement);
|
||||
if (note && isIndexedNote(replacement)) snapshot.notes.set(replacement, { contents: note.contents, links: noteLinks(replacement, note.contents) });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async rebuild(io: NoteIndexIO, drafts: ReadonlyMap<string, string> = new Map()): Promise<{ committed: boolean; indexed: number; errors: NoteIndexIssue[] }> {
|
||||
const generation = ++this.#generation;
|
||||
const changes: Change[] = [];
|
||||
this.#changes = changes;
|
||||
const snapshot: Snapshot = { files: new Set(), notes: new Map() };
|
||||
const errors: NoteIndexIssue[] = [];
|
||||
const folders = [""];
|
||||
const visited = new Set<string>();
|
||||
while (folders.length && generation === this.#generation) {
|
||||
const folder = folders.pop()!;
|
||||
if (visited.has(folder)) continue;
|
||||
visited.add(folder);
|
||||
try {
|
||||
for (const entry of await io.list(folder)) {
|
||||
const path = normalizePath(entry.rel_path);
|
||||
if (!path || (folder && !path.startsWith(`${folder}/`))) continue;
|
||||
if (entry.kind === "folder") folders.push(path);
|
||||
else snapshot.files.add(path);
|
||||
}
|
||||
} catch (error) { errors.push({ path: folder, operation: "list", error: String(error) }); }
|
||||
}
|
||||
const files = [...snapshot.files].filter(isIndexedNote);
|
||||
for (let start = 0; start < files.length && generation === this.#generation; start += 8) {
|
||||
await Promise.all(files.slice(start, start + 8).map(async path => {
|
||||
try {
|
||||
const contents = drafts.get(path) ?? await io.read(path);
|
||||
snapshot.notes.set(path, { contents, links: noteLinks(path, contents) });
|
||||
} catch (error) { errors.push({ path, operation: "read", error: String(error) }); }
|
||||
}));
|
||||
}
|
||||
if (generation !== this.#generation) return { committed: false, indexed: snapshot.notes.size, errors };
|
||||
for (const [path, contents] of drafts) {
|
||||
const normalized = normalizePath(path);
|
||||
if (!normalized || !isIndexedNote(normalized)) continue;
|
||||
snapshot.files.add(normalized);
|
||||
snapshot.notes.set(normalized, { contents, links: noteLinks(normalized, contents) });
|
||||
}
|
||||
for (const change of changes) change(snapshot);
|
||||
this.#changes = null;
|
||||
this.#snapshot = snapshot;
|
||||
this.#revision++;
|
||||
return { committed: true, indexed: snapshot.notes.size, errors };
|
||||
}
|
||||
|
||||
resolve(origin: string, target: string, kind: "md" | "wiki"): NoteLinkResolution {
|
||||
let path = target.trim().split("#")[0];
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
|
||||
try { path = decodeURIComponent(path); } catch { /* A literal percent can occur in a file name. */ }
|
||||
path = path.replaceAll("\\", "/");
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
|
||||
const source = normalizePath(origin);
|
||||
if (!path) return source && this.#snapshot.files.has(source) ? { status: "resolved", path: source } : { status: "missing" };
|
||||
const folder = source?.split("/").slice(0, -1).join("/") ?? "";
|
||||
const bareWiki = kind === "wiki" && !path.includes("/") && path !== "." && path !== "..";
|
||||
if (this.#pathsRevision !== this.#revision) {
|
||||
this.#paths = new Map();
|
||||
this.#names = new Map();
|
||||
for (const file of this.#snapshot.files) {
|
||||
const key = file.toLowerCase(), matches = this.#paths.get(key) ?? [];
|
||||
matches.push(file);
|
||||
this.#paths.set(key, matches);
|
||||
if (isIndexedNote(file)) {
|
||||
const name = file.split("/").pop()!.toLowerCase(), names = this.#names.get(name) ?? [];
|
||||
names.push(file);
|
||||
this.#names.set(name, names);
|
||||
}
|
||||
}
|
||||
this.#pathsRevision = this.#revision;
|
||||
}
|
||||
const withExtension = (value: string) => kind === "wiki" && !isIndexedNote(value) ? [value, `${value}.md`, `${value}.markdown`, `${value}.mdown`] : [value];
|
||||
let candidates: string[];
|
||||
if (bareWiki) {
|
||||
const names = new Set(withExtension(path).map(name => name.toLowerCase()));
|
||||
candidates = [...names].flatMap(name => this.#names.get(name) ?? []);
|
||||
} else {
|
||||
const relative = path.startsWith("/") ? path.slice(1) : `${folder}/${path}`;
|
||||
const bases = [relative];
|
||||
// A wiki folder path can name a workspace folder. Dot paths are always relative.
|
||||
if (kind === "wiki" && !path.startsWith("/") && !/^\.{1,2}\//.test(path)) bases.push(path);
|
||||
const paths = new Set(bases.flatMap(base => {
|
||||
const normalized = normalizePath(base);
|
||||
return normalized ? withExtension(normalized) : [];
|
||||
}).map(value => value.toLowerCase()));
|
||||
candidates = [...paths].flatMap(path => this.#paths.get(path) ?? []);
|
||||
}
|
||||
candidates.sort((a, b) => a.localeCompare(b));
|
||||
if (candidates.length > 1) return { status: "ambiguous", candidates };
|
||||
return candidates.length ? { status: "resolved", path: candidates[0] } : { status: "missing" };
|
||||
}
|
||||
|
||||
backlinks(path: string): Backlink[] {
|
||||
if (this.#backlinksRevision !== this.#revision) {
|
||||
this.#backlinks = new Map();
|
||||
for (const note of this.#snapshot.notes.values()) for (const link of note.links) {
|
||||
const resolution = this.resolve(link.sourcePath, link.target, link.kind);
|
||||
if (resolution.status !== "resolved" || resolution.path === link.sourcePath) continue;
|
||||
const links = this.#backlinks.get(resolution.path) ?? [];
|
||||
links.push(link);
|
||||
this.#backlinks.set(resolution.path, links);
|
||||
}
|
||||
for (const links of this.#backlinks.values()) links.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath) || a.from - b.from);
|
||||
this.#backlinksRevision = this.#revision;
|
||||
}
|
||||
return [...(this.#backlinks.get(normalizePath(path) ?? "") ?? [])];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,11 @@ export type RenamePlan =
|
||||
| { action: "error"; message: string }
|
||||
| { action: "rename"; to: string };
|
||||
|
||||
export function renameSelection(name: string, kind: "file" | "folder" = "file"): [number, number] {
|
||||
const dot = name.lastIndexOf(".");
|
||||
return [0, kind === "file" && dot > 0 ? dot : name.length];
|
||||
}
|
||||
|
||||
function parentOf(rel: string): string {
|
||||
const idx = rel.lastIndexOf("/");
|
||||
if (idx <= 0) {
|
||||
|
||||
Reference in New Issue
Block a user