Keep the user preferences in settings.json in the app config folder. WebView storage can be lost, and the host cannot read it. The file has a schema number, a revision number, and one value for each section: general, appearance, customThemes, customThemesLegacy, and language. - settings_read gives all sections, the revision, and a one-time notice. - settings_write replaces one section, writes the file atomically, and sends settings-changed to all windows. The limit is 8 MiB. - settings_migrate writes the first file only when no file exists. - The host moves a damaged file to settings.corrupt-<seconds>.json, starts from the defaults, and reports this one time. Each window loads the sections before its first render. One store in src/lib/settings/store.ts replaces the storage listeners. When no file exists, the window normalizes the old localStorage values and migrates them. The old keys stay in place for one release. The window layout and the open tabs stay in localStorage on purpose. The browser preview keeps all preferences in localStorage. Keep tab transfer offers in host memory, not in localStorage, because an offer can hold unsaved text. A window takes an offer once. The host checks the workspace root and a 120 second expiry. When the receiver accepts the tab, the host sends tab-transfer-accepted to the source window only. A refused offer stays open, and the source tab stays open. A new window and a drop on the tab ribbon use one check. The smoke harness serves the new commands from one shared state for each browser context. Tests read saved values from the mock settings file. Rust, unit, and smoke tests cover the changes.
1905 lines
82 KiB
Svelte
1905 lines
82 KiB
Svelte
<script lang="ts">
|
|
import { t } from "$lib/i18n";
|
|
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
|
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, 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";
|
|
import type { MenuLink } from "$lib/editor/linkMenu";
|
|
import { loadMarks, saveMarks } from "$lib/workspace/marks";
|
|
import { moveMarks } from "$lib/workspace/treeMoveHistory";
|
|
import { retainEditorSessions } from "$lib/editor/sessions";
|
|
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
|
|
import { selectedEditorText } from "$lib/editor/selection";
|
|
import { pluginHost } from "$lib/plugins/registry";
|
|
import type { Contributions } from "$lib/plugins/contracts";
|
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
|
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";
|
|
import { createNote, noteTemplates, saveNoteTemplate, type NoteTemplate } from "$lib/workspace/templates";
|
|
import { requestText } from "$lib/workspace/dialogs.svelte";
|
|
import TextDialog from "./TextDialog.svelte";
|
|
import QuickOpen from "./QuickOpen.svelte";
|
|
import TemplateManager from "./TemplateManager.svelte";
|
|
import WorkspacePicker from "./WorkspacePicker.svelte";
|
|
import SettingsDialog from "./SettingsDialog.svelte";
|
|
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
|
import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
|
import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store";
|
|
import { TAB_TRANSFER_ID, cancelTabTransfer, finishTabTransfer, offerTabTransfer, onTabTransferAccepted, parseTabTransfer, takeTabTransfer } from "$lib/workspace/tabTransfer";
|
|
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout";
|
|
import FileTree from "./FileTree.svelte";
|
|
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";
|
|
import BookmarksPane from "./BookmarksPane.svelte";
|
|
|
|
import { buildOutline } from "$lib/workspace/outline";
|
|
import {
|
|
onWorkspaceEvent,
|
|
workspaceNew,
|
|
workspaceList,
|
|
workspaceOpenDefault,
|
|
workspaceCreate,
|
|
workspaceAbsPath,
|
|
workspaceLastPath,
|
|
workspaceOpen,
|
|
workspaceOpenWindow,
|
|
workspaceRead,
|
|
workspaceReadDataUrl,
|
|
workspaceRename,
|
|
workspaceReveal,
|
|
workspaceWrite,
|
|
workspaceWriteBytes,
|
|
} from "$lib/workspace/api";
|
|
import { detectChrome } from "$lib/workspace/chrome";
|
|
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);
|
|
let workspacePicker: WorkspacePicker;
|
|
let preferences = $state<"settings" | "help" | null>(null);
|
|
let openingSettings = false;
|
|
async function openSettings() {
|
|
if (!desktop) { preferences = "settings"; return; }
|
|
if (openingSettings) return;
|
|
openingSettings = true;
|
|
try { await invoke("settings_open_window"); }
|
|
catch (reason) { error = $t("Could not open settings: {error}", { error: String(reason) }); }
|
|
finally { openingSettings = false; }
|
|
}
|
|
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
|
let settingsReady = $state(false);
|
|
let workspaceAnchor: HTMLDivElement | undefined = $state();
|
|
const desktop = isTauri();
|
|
const transferredWindow = /^[0-9a-f-]{36}$/i.test(new URLSearchParams(location.search).get("tabTransfer") ?? "");
|
|
let tabs = $state<OpenBuffer[]>([]);
|
|
let activePath = $state<string | null>(null);
|
|
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
|
|
let status = $state($t("Open a workspace folder"));
|
|
let error = $state<string | null>(null);
|
|
let refreshToken = $state(0);
|
|
const noteIndex = new WorkspaceNoteIndex();
|
|
let noteIndexRoot: string | null = null;
|
|
let noteIndexRevision = $state(0);
|
|
let noteIndexBusy = $state(false);
|
|
let noteIndexError = $state<string | null>(null);
|
|
let noteIndexPending: Promise<void> = Promise.resolve();
|
|
let noteIndexRequest = 0;
|
|
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);
|
|
let rightWidth = $state(DEFAULT_WORKBENCH_LAYOUT.rightWidth);
|
|
let bottomHeight = $state(180);
|
|
let leftView = $state<WorkbenchLayout["leftView"]>(DEFAULT_WORKBENCH_LAYOUT.leftView);
|
|
let searchRequest = $state<{ text: string; id: number } | null>(null);
|
|
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
|
|
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
|
|
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
|
|
let terminalOpen = $state(false);
|
|
let documentPanes = $state(initialDocumentPanes());
|
|
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false);
|
|
let quickOpen = $state(false);
|
|
let templateManager = $state(false);
|
|
let terminalStarted = $state(false);
|
|
let terminalMaximized = $state(false);
|
|
let terminalDock: TerminalSlot | undefined = $state();
|
|
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
|
const terminalEnabled = $derived(!!terminalContribution);
|
|
const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar"));
|
|
const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar));
|
|
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
|
|
let browserOpening = $state(false);
|
|
async function openBrowser() {
|
|
if (browserOpening || !browserContribution?.newTab) return;
|
|
browserOpening = true;
|
|
const current = documents;
|
|
const empty = !editorPluginVisible && buffer?.kind === "empty" ? buffer : null;
|
|
const existing = new Set($pluginEditors.map(view => view.key));
|
|
try {
|
|
await browserContribution.newTab();
|
|
const opened = $pluginView;
|
|
if (empty && documents === current && current?.buffers.some(tab => tab.id === empty.id && tab.kind === "empty")
|
|
&& opened?.placement === "editor" && !existing.has(opened.key)) {
|
|
tabOrder = workingTabs.map(tab => tab.id === (empty.tabId ?? empty.id) ? opened.key : tab.id).filter((id, index, order) => order.indexOf(id) === index);
|
|
if (empty.pinned && !opened.pinned) pinPluginEditor(opened.key);
|
|
current.close(empty.relPath);
|
|
}
|
|
error = null;
|
|
}
|
|
catch (reason) { error = String(reason); }
|
|
finally { browserOpening = false; }
|
|
}
|
|
|
|
$effect(() => {
|
|
if (!terminalEnabled) {
|
|
terminalOpen = false; terminalStarted = false; terminalMaximized = false;
|
|
}
|
|
});
|
|
|
|
let saving = $state(false);
|
|
let switching = false;
|
|
let workbenchReady = $state(false);
|
|
let documents: Documents | null = null;
|
|
let paneComponents = $state<Record<string, EditorPane | undefined>>({});
|
|
let pluginPaneComponents = $state<Record<string, PluginEditor | undefined>>({});
|
|
function activeEditor() { return paneComponents[documentPanes.active]; }
|
|
let fileTree: FileTree | undefined = $state();
|
|
let closingTabs = false;
|
|
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
|
|
|
|
function createDocuments() {
|
|
documentPanes = initialDocumentPanes();
|
|
const next = new Documents({
|
|
read: workspaceRead, write: workspaceWrite, image: workspaceReadDataUrl,
|
|
kind: path => isImagePath(path) ? "image" : "text", chrome: detectChrome,
|
|
}, () => {
|
|
if (documents !== next) return;
|
|
tabs = next.buffers.map(tab => ({ ...tab }));
|
|
activePath = next.activePath;
|
|
const selected = next.active;
|
|
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
|
|
if (selected) view = selected.chromeOverride ?? selected.chrome;
|
|
});
|
|
return next;
|
|
}
|
|
$effect(() => retainEditorSessions(tabs.map(tab => tab.id)));
|
|
onDestroy(() => retainEditorSessions([]));
|
|
const documentViews = $derived.by(() => {
|
|
const bounds = paneBounds(documentPanes.layout);
|
|
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
|
|
.sort((a, b) => a.bounds.left - b.bounds.left);
|
|
});
|
|
function setReading(next: boolean, paneId = documentPanes.active) {
|
|
documentPanes = readDocumentPane(documentPanes, paneId, next);
|
|
}
|
|
function focusDocumentPane(paneId: string, focusEditor = false) {
|
|
const pane = documentPanes.panes.find(pane => pane.id === paneId);
|
|
if (!pane) return;
|
|
const tab = tabs.find(tab => tab.id === pane.documentId);
|
|
documentPanes = selectPane(documentPanes, paneId);
|
|
pluginEditorActive.set(false);
|
|
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
|
|
if (focusEditor) void tick().then(() => {
|
|
if (documentPanes.active !== paneId) return;
|
|
paneComponents[paneId]?.focusEditor();
|
|
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
});
|
|
}
|
|
function closeSplit(paneId: string) {
|
|
documentPanes = closeDocumentPane(documentPanes, paneId);
|
|
focusDocumentPane(documentPanes.active, true);
|
|
}
|
|
async function openToRight(file: TreeEntry, sourcePane: string) {
|
|
const current = documents;
|
|
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
|
|
if (!current || switching || !source) return;
|
|
await current.open(file, "background");
|
|
if (documents !== current || switching || documentPanes.active !== sourcePane
|
|
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
|
|
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
|
|
if (!target) return;
|
|
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
|
|
focusDocumentPane(documentPanes.active, true);
|
|
}
|
|
let focusLine = $state<number | null>(null);
|
|
let dragging = $state<"left" | "right" | "bottom" | null>(null);
|
|
let centerStack: HTMLElement | undefined = $state();
|
|
|
|
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
|
|
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
|
|
let tabOrder = $state<string[]>([]);
|
|
const availableTabs = $derived<EditorTab[]>([
|
|
...tabs.map(tab => ({
|
|
id: tab.tabId ?? tab.id, relPath: tab.relPath, name: tab.name,
|
|
title: tab.kind === "empty" ? tab.name : tab.relPath,
|
|
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, draggable: desktop, buffer: tab,
|
|
})),
|
|
...$pluginEditors.map(plugin => ({
|
|
id: plugin.key, relPath: `plugin:${plugin.key}`, name: plugin.title,
|
|
title: plugin.document?.path ?? plugin.title,
|
|
icon: plugin.icon === "file" ? "files" as const : plugin.icon ?? "puzzle" as const,
|
|
iconImage: plugin.iconImage,
|
|
panelId: `plugin-editor-${plugin.key}`, pinned: !!plugin.pinned, draggable: plugin.draggable, plugin,
|
|
})),
|
|
]);
|
|
const workingTabs = $derived(orderWorkbenchTabs(availableTabs, tabOrder));
|
|
$effect(() => {
|
|
if (workbenchReady && !availableTabs.length) untrack(() => {
|
|
const previousError = error;
|
|
newTab();
|
|
error = previousError;
|
|
});
|
|
});
|
|
function workingTabDragData(tab: WorkbenchTab) {
|
|
const view = $pluginEditors.find(view => view.key === tab.id);
|
|
const item = workingTabs.find(item => item.id === tab.id);
|
|
if (!item || !workspace || !desktop) return;
|
|
try { return (view && pluginTabDragData(view)) || JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
|
|
catch (reason) { error = String(reason); return; }
|
|
}
|
|
/**
|
|
* Take a tab from another window of this workspace. Both entry points use this one check:
|
|
* a new window opened with `?tabTransfer=<id>` (`startup`), and a drop on the tab ribbon (`index`).
|
|
* The source tab closes only after this window accepts the tab.
|
|
*/
|
|
async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) {
|
|
if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer.");
|
|
const current = documents;
|
|
if (!workspace || !current || (switching && !startup)) throw new Error("Move tabs only between windows of the same workspace.");
|
|
const payload = await takeTabTransfer(id, workspace.root);
|
|
let accepted = false;
|
|
try {
|
|
const transfer = parseTabTransfer(payload);
|
|
let path = "";
|
|
if ("buffer" in transfer) {
|
|
if (!current.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
|
path = transfer.buffer.relPath;
|
|
if (!startup) selectTab(path);
|
|
} else {
|
|
// A new window starts its plugins after the workspace opens. Wait for them there.
|
|
const deadline = Date.now() + (startup ? 15000 : 0);
|
|
while (!await restorePluginTab(transfer.plugin as Parameters<typeof restorePluginTab>[0])) {
|
|
if (Date.now() >= deadline) throw new Error("Enable this tab's plugin before moving it to this window.");
|
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
}
|
|
if (index !== undefined) {
|
|
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
|
|
path = `plugin:${$pluginView.key}`;
|
|
}
|
|
}
|
|
setReading(transfer.reading);
|
|
accepted = true;
|
|
if (index !== undefined) {
|
|
await tick();
|
|
moveWorkingTab(path, index);
|
|
}
|
|
} finally {
|
|
// Without this acknowledgement, the source tab stays open.
|
|
await finishTabTransfer(id, accepted).catch(reason => console.warn("Could not finish the tab transfer.", reason));
|
|
}
|
|
}
|
|
async function receiveTab(data: string, index: number) {
|
|
try {
|
|
const payload = JSON.parse(data);
|
|
if (typeof payload?.tabTransfer === "string") {
|
|
await acceptTabTransfer(payload.tabTransfer, { index });
|
|
error = null;
|
|
return;
|
|
}
|
|
await dropPluginTab(data);
|
|
if ($pluginView?.placement === "editor") moveWorkingTab(`plugin:${$pluginView.key}`, index);
|
|
error = null;
|
|
} catch (reason) { error = String(reason); }
|
|
}
|
|
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
|
|
const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key)));
|
|
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
|
|
$effect(() => {
|
|
const order = workingTabs.map(tab => tab.id);
|
|
if (order.length !== tabOrder.length || order.some((id, index) => id !== tabOrder[index])) tabOrder = order;
|
|
});
|
|
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
|
|
const isIde = $derived(view === "Ide");
|
|
const outlineItems = $derived(
|
|
buffer && buffer.kind === "text" ? buildOutline(buffer.relPath, buffer.contents) : [],
|
|
);
|
|
|
|
function applyChrome(next: Chrome) {
|
|
view = next;
|
|
}
|
|
|
|
function toggleChrome() {
|
|
const next = view === "Writing" ? "Ide" : "Writing";
|
|
setReading(false);
|
|
applyChrome(next);
|
|
documents?.setChrome(next);
|
|
}
|
|
|
|
function toggleTerminal() {
|
|
if (!terminalEnabled) return;
|
|
terminalOpen = !terminalOpen;
|
|
if (terminalOpen) { terminalStarted = true; }
|
|
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
|
}
|
|
|
|
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
|
|
if (!terminalEnabled) return;
|
|
if (!workspace) { error = $t("Open a workspace to start a terminal."); return; }
|
|
const started = terminalStarted;
|
|
terminalStarted = true; terminalOpen = true;
|
|
if (bottomHeight < 220) bottomHeight = 260;
|
|
await tick();
|
|
if (terminalEnabled && (action !== "new" || started)) await terminalDock?.command(action);
|
|
}
|
|
|
|
async function terminalFile(): Promise<string | null> {
|
|
const current = documents, tab = buffer;
|
|
if (!current || !tab || tab.kind !== "text" || saving || switching) return null;
|
|
saving = true;
|
|
try {
|
|
await current.save(tab.id);
|
|
return await workspaceAbsPath(tab.relPath);
|
|
} finally { saving = false; }
|
|
}
|
|
|
|
async function configureTasks() {
|
|
if (!workspace) return;
|
|
const path = ".runestone/tasks.json";
|
|
try { await workspaceRead(path); }
|
|
catch {
|
|
// Creation is exclusive, so an existing config can never be overwritten.
|
|
await workspaceCreate(path, "file");
|
|
await workspaceWrite(path, JSON.stringify({ tasks: [{ label: "Example task", command: "echo Hello from RuneStone" }] }, null, 2) + "\n", "");
|
|
}
|
|
terminalMaximized = false;
|
|
await openFile({ name: "tasks.json", rel_path: path, kind: "file" });
|
|
}
|
|
|
|
function selectLeft(next: "files" | "search" | "bookmarks") {
|
|
if (transferredWindow) return;
|
|
const hadSidebar = !!$pluginSidebar;
|
|
closePluginSidebar();
|
|
if (!hadSidebar && leftOpen && leftView === next) {
|
|
leftOpen = false;
|
|
return;
|
|
}
|
|
leftView = next;
|
|
leftOpen = true;
|
|
}
|
|
|
|
async function openPath(path: string, name?: string): Promise<boolean> {
|
|
if (!name && path === workspace?.root) return true;
|
|
if (name) await workspaceNew(path, name);
|
|
else await workspaceOpenWindow(path);
|
|
return true;
|
|
}
|
|
|
|
async function chooseWorkspace() {
|
|
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 };
|
|
// The open tabs stay in localStorage on purpose: per-machine view state that is harmless to lose.
|
|
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 {
|
|
const last = await workspaceLastPath();
|
|
if (last) {
|
|
workspace = await workspaceOpen(last);
|
|
documents?.dispose();
|
|
documents = createDocuments();
|
|
status = workspace.root;
|
|
refreshToken += 1;
|
|
const token = new URLSearchParams(location.search).get("tabTransfer");
|
|
if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true });
|
|
else await restoreDocumentTabs();
|
|
}
|
|
} catch (err) { error = String(err); }
|
|
finally { switching = false; workbenchReady = true; }
|
|
}
|
|
|
|
function selectTab(relPath: string) {
|
|
cancelPluginDocumentOpen();
|
|
pluginEditorActive.set(false);
|
|
focusLine = null;
|
|
documents?.select(relPath);
|
|
focusDocumentPane(documentPanes.active, true);
|
|
status = documents?.active?.kind === "empty" ? $t("New tab") : relPath;
|
|
}
|
|
|
|
function selectWorkingTab(path: string) {
|
|
const tab = workingTabs.find(tab => tab.relPath === path);
|
|
if (!tab) return;
|
|
if ("plugin" in tab) selectPluginEditor(tab.plugin);
|
|
else selectTab(path);
|
|
}
|
|
|
|
function moveWorkingTab(path: string, index: number) {
|
|
const from = workingTabs.findIndex(tab => tab.relPath === path);
|
|
if (from < 0 || !Number.isInteger(index)) return;
|
|
const ordered = [...workingTabs];
|
|
const [tab] = ordered.splice(from, 1);
|
|
const destination = Math.max(0, Math.min(index, ordered.length));
|
|
ordered.splice(destination, 0, tab);
|
|
tabOrder = ordered.map(tab => tab.id);
|
|
if ("buffer" in tab) documents?.move(path, ordered.slice(0, destination).filter(tab => "buffer" in tab).length);
|
|
}
|
|
|
|
function workingTabFileActions(item: WorkbenchTab): ActionMenuItem[] {
|
|
const tab = workingTabs.find(tab => tab.id === item.id);
|
|
return tab && "buffer" in tab ? tabFileActions(tab.buffer) : [];
|
|
}
|
|
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
|
|
const tab = workingTabs.find(tab => tab.id === item.id);
|
|
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
|
|
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
|
|
return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
|
|
}
|
|
async function detachTab(item: WorkbenchTab, keepSource = false) {
|
|
const tab = workingTabs.find(tab => tab.id === item.id);
|
|
if (!tab || !workspace || !desktop) return;
|
|
if ("plugin" in tab) {
|
|
const action = pluginTabActions(tab.plugin).find(action => "label" in action && /(?:move|open).*new window/i.test(action.label));
|
|
if (action && "run" in action && !action.disabled) { action.run?.(); return; }
|
|
}
|
|
let transfer: ReturnType<typeof prepareTabTransfer> | undefined;
|
|
try {
|
|
transfer = prepareTabTransfer(tab, keepSource, true);
|
|
await transfer.offered;
|
|
await workspaceOpenWindow(workspace.root, transfer.token);
|
|
} catch (reason) { transfer?.finish(); error = String(reason); }
|
|
}
|
|
// The offers of this window that wait for another window, by offer ID.
|
|
const pendingTransfers = new Map<string, () => void>();
|
|
onMount(() => {
|
|
if (!desktop) return;
|
|
const stop = onTabTransferAccepted(id => pendingTransfers.get(id)?.());
|
|
return () => { void stop.then(unlisten => unlisten()); };
|
|
});
|
|
function prepareTabTransfer(tab: EditorTab, keepSource = false, reportTimeout = false) {
|
|
const current = documents;
|
|
const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined);
|
|
const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin));
|
|
const token = crypto.randomUUID();
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
let done = false;
|
|
const finish = (withdraw = true) => {
|
|
if (done) return;
|
|
done = true;
|
|
pendingTransfers.delete(token);
|
|
clearTimeout(timer);
|
|
if (withdraw) void cancelTabTransfer(token).catch(() => {});
|
|
};
|
|
// Close the source tab only if it did not change during the transfer.
|
|
pendingTransfers.set(token, () => {
|
|
if (!keepSource && "buffer" in tab) {
|
|
if (documents === current && bufferSnapshot(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
|
|
} else if (!keepSource && "plugin" in tab && JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
|
|
finish(false);
|
|
});
|
|
try {
|
|
const offered = offerTabTransfer(token, workspace!.root, { ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading });
|
|
// A drag cannot wait for the offer. Report a failed drag offer here. `detachTab` reports its own.
|
|
offered.catch(reason => { finish(false); if (!reportTimeout) error = String(reason); });
|
|
timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
|
return { token, finish, offered };
|
|
} catch (reason) { finish(); throw reason; }
|
|
}
|
|
function pinWorkingTab(path: string) {
|
|
const tab = workingTabs.find(tab => tab.relPath === path);
|
|
if (tab && "plugin" in tab) pinPluginEditor(tab.plugin.key);
|
|
else documents?.togglePin(path);
|
|
}
|
|
|
|
function newTab() {
|
|
cancelPluginDocumentOpen();
|
|
if (switching) return;
|
|
pluginEditorActive.set(false);
|
|
documents ??= createDocuments();
|
|
focusLine = null;
|
|
documents.newTab();
|
|
terminalMaximized = false;
|
|
status = $t("New tab");
|
|
error = null;
|
|
}
|
|
|
|
async function closeTab(relPath: string) {
|
|
await closeTabs(relPath, "one");
|
|
}
|
|
|
|
async function closeTabs(path: string, scope: TabCloseScope) {
|
|
const current = documents;
|
|
if (closingTabs || switching) return;
|
|
closingTabs = true;
|
|
try {
|
|
const targets = tabsToClose(workingTabs, path, scope);
|
|
for (const target of targets) {
|
|
if (documents !== current || switching) break;
|
|
const tab = "buffer" in target ? current?.buffers.find(item => item.id === target.buffer.id) : undefined;
|
|
if ("buffer" in target && (!tab || (scope !== "one" && tab.pinned))) continue;
|
|
if (desktop && getCurrentWindow().label.startsWith("workspace-") && workingTabs.length === 1) {
|
|
await getCurrentWindow().close();
|
|
break;
|
|
}
|
|
if ("buffer" in target) {
|
|
if (!tab) continue;
|
|
const contents = tab.contents;
|
|
if (contents !== tab.saved && !await confirm($t("Discard unsaved edits in {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning" })) break;
|
|
if (documents !== current || switching || tab.contents !== contents) break;
|
|
if (scope !== "one" && tab.pinned) continue;
|
|
}
|
|
const index = workingTabs.findIndex(item => item.id === target.id);
|
|
if (index < 0) continue;
|
|
const selected = workingTabs[index].relPath === activeTabPath
|
|
? (workingTabs[index + 1] ?? workingTabs[index - 1])?.relPath : activeTabPath;
|
|
if ("plugin" in target) closePluginEditor(target.plugin.key);
|
|
else if (tab) current?.close(tab.relPath);
|
|
if (selected && selected !== activeTabPath) selectWorkingTab(selected);
|
|
}
|
|
} catch (err) { error = String(err); }
|
|
finally { closingTabs = false; }
|
|
}
|
|
|
|
async function copyTabPath(path: string, system: boolean) {
|
|
try {
|
|
const text = system ? await workspaceAbsPath(path) : path;
|
|
await navigator.clipboard.writeText(text);
|
|
status = system ? $t("Copied system path") : $t("Copied workspace path");
|
|
} catch (err) { error = String(err); }
|
|
}
|
|
|
|
function tabFileActions(tab: OpenBuffer): ActionMenuItem[] {
|
|
if (tab.kind === "empty") return [];
|
|
const items: ActionMenuItem[] = [];
|
|
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
|
|
items.push(
|
|
{ label: $t("Save as template"), icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
|
|
{ label: reading ? $t("Editing view") : $t("Reading view"), icon: "book", run: () => activeEditor()?.toggleReadingView() },
|
|
{ label: isIde ? $t("Writing mode") : $t("Source mode"), icon: "code", run: toggleChrome },
|
|
);
|
|
}
|
|
items.push({ separator: true },
|
|
{ label: $t("Rename…"), icon: "rename", run: () => { void renameActive(); } },
|
|
);
|
|
if (tab.kind === "text") items.push({ label: $t("Save a copy…"), icon: "copy", run: () => { void saveCopy(); } });
|
|
items.push({ separator: true },
|
|
{ label: $t("Copy path"), icon: "copy", children: [
|
|
{ label: $t("Workspace path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
|
|
{ label: $t("System path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
|
|
] },
|
|
{ label: $t("Show in system explorer"), icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
|
|
);
|
|
return items;
|
|
}
|
|
|
|
async function openFile(entry: TreeEntry, line?: number, target: "current" | "new" = "new") {
|
|
const current = documents;
|
|
if (!current || switching) return;
|
|
try {
|
|
const open = current.buffers.find(tab => tab.relPath === entry.rel_path);
|
|
if (!line && !(open && open.contents !== open.saved) && await openPluginDocument(entry.rel_path, () => documents === current && !switching)) {
|
|
status = entry.rel_path; error = null; return;
|
|
}
|
|
await current.open(entry, target);
|
|
if (documents !== current) return;
|
|
pluginEditorActive.set(false);
|
|
status = entry.rel_path;
|
|
error = null;
|
|
focusLine = null;
|
|
if (line) {
|
|
setReading(false);
|
|
queueMicrotask(() => { focusLine = line; });
|
|
}
|
|
} catch (err) { if (documents === current) error = String(err); }
|
|
}
|
|
|
|
async function openCreatedFile(entry: TreeEntry) {
|
|
const current = documents;
|
|
await openFile(entry);
|
|
if (documents !== current || current?.active?.relPath !== entry.rel_path || !isMarkdownPath(entry.rel_path)) return;
|
|
setReading(false);
|
|
activeEditor()?.focusTitle(current.active.id);
|
|
}
|
|
|
|
function readFileDataUrl(file: File): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(String(reader.result));
|
|
reader.onerror = () => reject(reader.error);
|
|
reader.readAsDataURL(file);
|
|
});
|
|
}
|
|
|
|
async function insertImage(file: File, note = buffer): Promise<string | null> {
|
|
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
|
|
return null;
|
|
}
|
|
const noteRel = note.relPath;
|
|
const current = documents;
|
|
try {
|
|
const rel = attachmentRel(file.name);
|
|
const dataUrl = await readFileDataUrl(file);
|
|
const base64 = dataUrl.split(",")[1];
|
|
if (!base64) {
|
|
return null;
|
|
}
|
|
if (documents !== current || switching) return null;
|
|
await workspaceWriteBytes(rel, base64);
|
|
if (documents !== current) return null;
|
|
refreshToken += 1;
|
|
return `.length - 1)}${rel})`;
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function onChange(value: string, id: string) {
|
|
documents?.edit(id, value);
|
|
}
|
|
|
|
function searchSelection(text: string) {
|
|
leftOpen = true; leftView = "search";
|
|
searchRequest = { text, id: (searchRequest?.id || 0) + 1 };
|
|
}
|
|
|
|
async function extractSelection(markdown: string, label: string, valid: () => boolean, note = buffer): Promise<string | null> {
|
|
const current = documents;
|
|
if (!workspace || !current || !note) return null;
|
|
const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1);
|
|
const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection";
|
|
const name = await requestText($t("Extract selection to a new note (workspace relative path)"), `${folder}${suggested}.md`);
|
|
if (!name || documents !== current || !valid() || saving || switching) return null;
|
|
const rel = name.replaceAll("\\", "/").replace(/\.md$/i, "") + ".md";
|
|
saving = true;
|
|
try {
|
|
await workspaceCreate(rel, "file");
|
|
await workspaceWrite(rel, markdown + "\n", "");
|
|
refreshToken++;
|
|
status = $t("Extracted selection to {path}", { path: rel });
|
|
return `/${rel}`;
|
|
} catch (err) { error = String(err); return null; }
|
|
finally { saving = false; }
|
|
}
|
|
|
|
async function save() {
|
|
const current = documents;
|
|
const tab = buffer;
|
|
if (!current || !tab || tab.kind !== "text" || saving || switching) return;
|
|
saving = true;
|
|
try {
|
|
await current.save(tab.id);
|
|
status = $t("Saved {path}", { path: tab.relPath });
|
|
error = null;
|
|
} catch (err) {
|
|
error = String(err);
|
|
await current.refresh();
|
|
} finally { saving = false; }
|
|
}
|
|
|
|
async function autosave() {
|
|
const current = documents;
|
|
if (!current || !current.dirty || saving || switching) return;
|
|
saving = true;
|
|
try {
|
|
const result = await current.autosave();
|
|
if (documents !== current) return;
|
|
if (result.saved.length) status = result.saved.length === 1 ? $t("Autosaved 1 file") : $t("Autosaved {count} files", { count: result.saved.length });
|
|
if (result.failed.length) {
|
|
error = result.failed.map(({ path, error }) => $t("Could not autosave {path}: {error}", { path, error: String(error) })).join("\n");
|
|
await current.refresh();
|
|
}
|
|
} finally { saving = false; }
|
|
}
|
|
|
|
async function saveCopy(tab = buffer) {
|
|
if (!tab || tab.kind !== "text") return;
|
|
const name = await requestText($t("Save a copy as (workspace relative path)"), tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
|
|
if (!name) return;
|
|
try {
|
|
await workspaceCreate(name, "file");
|
|
await workspaceWrite(name, tab.contents, "");
|
|
await openFile({ name: name.split("/").pop()!, rel_path: name, kind: "file" });
|
|
refreshToken++;
|
|
} catch (err) { error = String(err); }
|
|
}
|
|
|
|
async function newFile() {
|
|
if (!workspace) {
|
|
return;
|
|
}
|
|
const name = await requestText($t("New file path relative to the workspace"), "Untitled.md");
|
|
if (!name) {
|
|
return;
|
|
}
|
|
try {
|
|
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
|
refreshToken += 1;
|
|
await openCreatedFile({
|
|
name: name.split("/").pop() ?? name,
|
|
rel_path: name.replaceAll("\\", "/"),
|
|
kind: "file",
|
|
});
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
async function saveTemplate(entry: TreeEntry) {
|
|
const name = await requestText($t("Template name"), entry.name.replace(/\.md$/i, ""));
|
|
if (!name) return;
|
|
try {
|
|
const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path);
|
|
await saveNoteTemplate(name, contents);
|
|
status = $t("Saved template: {name}", { name });
|
|
} catch (reason) { error = String(reason); }
|
|
}
|
|
|
|
async function newNote(event?: MouseEvent) {
|
|
if (!workspace) return;
|
|
const create = async (template?: NoteTemplate) => {
|
|
try {
|
|
const path = await createNote("", template);
|
|
refreshToken++;
|
|
await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
|
} catch (reason) { error = String(reason); }
|
|
};
|
|
const templates = await noteTemplates();
|
|
if (!templates.length || !event) { await create(); return; }
|
|
const anchor = event.currentTarget instanceof HTMLElement ? event.currentTarget : document.activeElement as HTMLElement;
|
|
const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); };
|
|
const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); };
|
|
const menu = actionMenu(event.clientX, event.clientY, [
|
|
{ label: $t("Blank note"), icon: "file-plus", run: () => { close(); void create(); } },
|
|
...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })),
|
|
], close, $t("New note"));
|
|
window.addEventListener("pointerdown", outside);
|
|
}
|
|
|
|
function onPreferencesKeydown(event: KeyboardEvent) {
|
|
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
|
if (event.ctrlKey && !event.altKey && !event.metaKey && event.key === "Tab" && workingTabs.length) {
|
|
event.preventDefault(); event.stopPropagation();
|
|
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
|
|
const next = (index + (event.shiftKey ? -1 : 1) + workingTabs.length) % workingTabs.length;
|
|
selectWorkingTab(workingTabs[next].relPath);
|
|
return;
|
|
}
|
|
|
|
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") {
|
|
event.preventDefault(); event.stopPropagation(); void openSettings();
|
|
}
|
|
if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
|
event.preventDefault(); event.stopPropagation(); preferences = "help";
|
|
}
|
|
}
|
|
|
|
function onKeydown(event: KeyboardEvent) {
|
|
if (event.defaultPrevented) return;
|
|
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
|
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f" && editorPluginVisible && $pluginView) {
|
|
event.preventDefault();
|
|
void pluginPaneComponents[$pluginView.key]?.openFind();
|
|
return;
|
|
}
|
|
const action = pluginHost.get("terminal")?.shortcut(event);
|
|
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
|
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
|
|
event.preventDefault();
|
|
if (action === "toggle") toggleTerminal(); else void terminalAction(action);
|
|
return;
|
|
}
|
|
// Let shells and terminal applications own their control keys.
|
|
if (event.target instanceof Element && event.target.closest(".xterm") && event.key !== "`") return;
|
|
if (event.target instanceof Element && event.target.closest("dialog")) return;
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "p") {
|
|
event.preventDefault(); if (workspace) quickOpen = true; return;
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "t") {
|
|
event.preventDefault(); newTab(); return;
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "f") {
|
|
event.preventDefault(); if (!transferredWindow) { leftOpen = true; leftView = "search"; } return;
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
|
event.preventDefault();
|
|
if (!editorPluginVisible) void save();
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
|
|
event.preventDefault();
|
|
void chooseWorkspace();
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "n") {
|
|
event.preventDefault();
|
|
void newFile();
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "e") {
|
|
event.preventDefault();
|
|
if (!editorPluginVisible) toggleChrome();
|
|
}
|
|
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
|
|
event.preventDefault();
|
|
toggleTerminal();
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
|
|
event.preventDefault();
|
|
if (editorPluginVisible) {
|
|
if (activeTabPath) void closeTab(activeTabPath);
|
|
} else if (activePath) {
|
|
closeTab(activePath);
|
|
}
|
|
}
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "b") {
|
|
event.preventDefault();
|
|
if (!transferredWindow) leftOpen = !leftOpen;
|
|
}
|
|
if (event.key === "F2" && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
|
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
if (!editorPluginVisible && !(leftOpen && leftView === "files")) {
|
|
void renameActive();
|
|
}
|
|
}
|
|
}
|
|
|
|
function applyPathRename(from: string, to: string) {
|
|
documents?.rename(from, to);
|
|
renamePluginDocuments(from, to);
|
|
noteIndex.rename(from, to);
|
|
noteIndexRevision = noteIndex.revision;
|
|
}
|
|
|
|
async function renameNoteTitle(id: string, title: string) {
|
|
const current = documents;
|
|
const note = current?.buffers.find(tab => tab.id === id);
|
|
if (!current || !note || switching) throw new Error("This note is no longer available.");
|
|
const from = note.relPath;
|
|
const plan = planMarkdownTitleRename(from, title);
|
|
if (plan.action === "error") throw new Error(plan.message);
|
|
if (plan.action === "noop") return;
|
|
await workspaceRename(from, plan.to);
|
|
current.rename(from, plan.to);
|
|
if (documents !== current) return;
|
|
refreshToken += 1;
|
|
status = $t("Renamed to {path}", { path: plan.to });
|
|
error = null;
|
|
}
|
|
|
|
async function renameActive() {
|
|
if (!activePath || buffer?.kind === "empty") {
|
|
return;
|
|
}
|
|
const current = documents;
|
|
const from = activePath;
|
|
const name = from.split("/").pop() ?? from;
|
|
const typed = await requestText($t("Rename to"), name, { selection: renameSelection(name) });
|
|
if (typed == null || documents !== current || switching) {
|
|
return;
|
|
}
|
|
const plan = planRename(from, typed);
|
|
if (plan.action === "error") {
|
|
error = plan.message;
|
|
return;
|
|
}
|
|
if (plan.action === "noop") {
|
|
return;
|
|
}
|
|
try {
|
|
await workspaceRename(from, plan.to);
|
|
current?.rename(from, plan.to);
|
|
if (documents !== current) return;
|
|
refreshToken += 1;
|
|
status = $t("Renamed to {path}", { path: plan.to });
|
|
error = null;
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
function workspaceLinkItems(link: MenuLink, origin = activePath ?? "", sourcePane = documentPanes.active): ActionMenuItem[] {
|
|
const current = documents, currentWorkspace = workspace;
|
|
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
|
|
const entry = async () => {
|
|
await noteIndexPending;
|
|
const resolution = noteIndex.resolve(origin, link.target, link.kind);
|
|
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[];
|
|
try { files = await workspaceList(parent); } catch { continue; }
|
|
const found = files.find(file => file.rel_path === path && file.kind === "file");
|
|
if (found) return found;
|
|
}
|
|
throw new Error($t("Could not find {path} in the workspace.", { path: link.target }));
|
|
};
|
|
const run = (action: (file: TreeEntry) => void | Promise<void>) => () => {
|
|
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,
|
|
move ? undefined : { selection: renameSelection(file.name) });
|
|
if (!typed || !valid()) return;
|
|
let to = typed.trim().replaceAll("\\", "/");
|
|
if (move) {
|
|
if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error("Enter a relative workspace path without reserved characters.");
|
|
} else {
|
|
const plan = planRename(file.rel_path, to);
|
|
if (plan.action === "noop") return;
|
|
if (plan.action === "error") throw new Error(plan.message);
|
|
to = plan.to;
|
|
}
|
|
if (to === file.rel_path) return;
|
|
const marks = await loadMarks();
|
|
if (!valid()) return;
|
|
await workspaceRename(file.rel_path, to, currentWorkspace!.root);
|
|
if (!valid()) return;
|
|
applyPathRename(file.rel_path, to);
|
|
await saveMarks(moveMarks(marks, file.rel_path, to));
|
|
refreshToken++;
|
|
status = $t("Moved to {path}", { path: to });
|
|
}
|
|
return [
|
|
{ label: $t("Open to the right"), icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
|
|
{ label: $t("Open in new window"), icon: "external", disabled: !desktop, run: run(async file => {
|
|
await openFile(file, undefined, "new");
|
|
if (!valid()) return;
|
|
const tab = workingTabs.find(tab => tab.relPath === file.rel_path);
|
|
if (tab) await detachTab(tab, true);
|
|
}) },
|
|
{ label: $t("Copy path"), icon: "copy", children: [
|
|
{ label: $t("Workspace path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
|
|
{ label: $t("System path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
|
|
] },
|
|
{ label: $t("Rename…"), icon: "rename", run: run(file => rename(file)) },
|
|
{ label: $t("Move file to…"), icon: "folder", run: run(file => rename(file, true)) },
|
|
{ label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
|
|
const marks = await loadMarks();
|
|
if (!valid()) return;
|
|
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
|
refreshToken++; status = $t("Bookmarked {name}", { name: file.name });
|
|
}) },
|
|
{ label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
|
|
{ label: $t("Show in system explorer"), icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
|
|
{ label: $t("Reveal file in navigation"), icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
|
|
];
|
|
}
|
|
|
|
async function openLink(kind: "md" | "wiki", target: string, origin = activePath ?? "", paneId = documentPanes.active) {
|
|
if (/^(https?:\/\/|mailto:)/i.test(target)) {
|
|
try {
|
|
if (/^https?:\/\//i.test(target) && await pluginHost.get("browser")?.open(target)) return;
|
|
await openUrl(target);
|
|
} catch (err) { error = String(err); }
|
|
return;
|
|
}
|
|
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 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. */ }
|
|
}
|
|
error = $t("Could not open {path}", { path: target });
|
|
}
|
|
|
|
function onPointerMove(event: PointerEvent) {
|
|
if (!dragging) {
|
|
return;
|
|
}
|
|
const shell = event.currentTarget as HTMLElement;
|
|
const rect = shell.getBoundingClientRect();
|
|
if (dragging === "left") {
|
|
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - (ribbonNavigation.length ? 44 : 0)));
|
|
}
|
|
if (dragging === "right") {
|
|
rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX));
|
|
}
|
|
if (dragging === "bottom" && centerStack) {
|
|
const stack = centerStack.getBoundingClientRect();
|
|
bottomHeight = Math.min(stack.height - 80, Math.max(80, stack.bottom - event.clientY));
|
|
}
|
|
}
|
|
|
|
function updateSettings(next: AppSettings) {
|
|
const saved = saveSettings(next);
|
|
settings = { ...next };
|
|
return saved;
|
|
}
|
|
|
|
onMount(() => {
|
|
try {
|
|
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
|
|
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
|
|
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
|
if (transferredWindow) { leftOpen = false; rightOpen = false; }
|
|
layoutReady = true;
|
|
} catch { error = "Could not read your layout. Default layout applies for this window."; }
|
|
});
|
|
|
|
$effect(() => {
|
|
if (!layoutReady || transferredWindow) return;
|
|
try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); }
|
|
catch { error = "Could not save your layout. Layout changes apply for this window only."; }
|
|
});
|
|
|
|
onMount(() => {
|
|
try { settings = readSettings(); }
|
|
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
|
error = takeSettingsNotice() ?? error;
|
|
settingsReady = true;
|
|
const stopSettings = onSettingsChange("general", () => { settings = readSettings(); });
|
|
window.addEventListener("keydown", onPreferencesKeydown, true);
|
|
return () => {
|
|
stopSettings();
|
|
window.removeEventListener("keydown", onPreferencesKeydown, true);
|
|
};
|
|
});
|
|
|
|
$effect(() => {
|
|
if (!desktop || !settingsReady || !settings.autosaveEnabled) return;
|
|
const timer = setInterval(() => { void autosave(); }, settings.autosaveSeconds * 1000);
|
|
return () => clearInterval(timer);
|
|
});
|
|
|
|
onMount(() => {
|
|
if (!isTauri()) { status = "Desktop features require pnpm tauri dev"; return; }
|
|
void restoreLast();
|
|
let disposed = false;
|
|
const unlisteners: (() => void)[] = [];
|
|
unlisteners.push(handlePluginFileOpen(async path => {
|
|
await openFile({ name: path.split("/").pop() ?? path, rel_path: path, kind: "file" });
|
|
}));
|
|
unlisteners.push(handlePluginDocumentRename(async (from, name) => {
|
|
const current = documents;
|
|
if (!current || switching) throw new Error("Open a workspace before renaming a document.");
|
|
const plan = planDocumentTitleRename(from, name);
|
|
if (plan.action === "error") throw new Error(plan.message);
|
|
if (plan.action === "noop") return from;
|
|
await workspaceRename(from, plan.to);
|
|
if (documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
|
applyPathRename(from, plan.to);
|
|
refreshToken++;
|
|
return plan.to;
|
|
}));
|
|
unlisteners.push(guardPluginWrites(path => {
|
|
const open = documents?.buffers.find(tab => tab.relPath === path);
|
|
if (open && open.contents !== open.saved) throw new Error("Save or discard the open note's edits before changing it from a plugin.");
|
|
}));
|
|
let refreshTimer: ReturnType<typeof setTimeout>;
|
|
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
|
void onWorkspaceEvent((event) => {
|
|
if (event.root !== workspace?.root || event.kind === "access") return;
|
|
if (event.paths.every(path => path.startsWith(".runestone/") || path.split("/").pop()?.startsWith(".runestone-save-"))) return;
|
|
clearTimeout(refreshTimer);
|
|
refreshTimer = setTimeout(() => {
|
|
refreshToken++;
|
|
void documents?.refresh();
|
|
notifyPluginWorkspace();
|
|
}, 200);
|
|
}).then(register).catch(err => error = String(err));
|
|
let closing = false;
|
|
void getCurrentWindow().onCloseRequested(async event => {
|
|
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" })) {
|
|
saveDocumentTabs();
|
|
await getCurrentWindow().destroy();
|
|
}
|
|
} finally { closing = false; }
|
|
}).then(register).catch(err => error = String(err));
|
|
const focus = () => { void documents?.refresh(); refreshToken++; };
|
|
window.addEventListener("focus", focus);
|
|
return () => {
|
|
disposed = true;
|
|
documents?.dispose();
|
|
clearTimeout(refreshTimer);
|
|
unlisteners.forEach(off => off());
|
|
window.removeEventListener("focus", focus);
|
|
};
|
|
});
|
|
|
|
</script>
|
|
|
|
<svelte:window onkeydown={onKeydown} onbeforeunload={(event) => { if (hasDirty) { event.preventDefault(); event.returnValue = ""; } }} />
|
|
<TextDialog />
|
|
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
|
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
|
|
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
|
{#if templateManager && workspace}<TemplateManager onClose={() => templateManager = false}
|
|
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }}
|
|
onRenamed={(from, to) => { applyPathRename(from, to); refreshToken++; }}
|
|
onDeleted={(path) => { removePluginDocuments(path); void documents?.refresh(); refreshToken++; }} />{/if}
|
|
|
|
<div
|
|
class="shell"
|
|
class:detached={transferredWindow}
|
|
class:has-ribbon={!transferredWindow && ribbonNavigation.length > 0}
|
|
class:left-open={!transferredWindow && leftOpen}
|
|
class:right-open={!transferredWindow && rightOpen}
|
|
role="application"
|
|
aria-label={$t("RuneStone workbench")}
|
|
style:--left="{leftWidth}px"
|
|
style:--right="{rightWidth}px"
|
|
style:--bottom="{bottomHeight}px"
|
|
onpointermove={onPointerMove}
|
|
onpointerup={() => (dragging = null)}
|
|
onpointerleave={() => (dragging = null)}
|
|
>
|
|
<div class="workarea-background" aria-hidden="true"></div>
|
|
<header class="header" data-tauri-drag-region>
|
|
<div class="header-left" data-tauri-drag-region>
|
|
{#if !transferredWindow}
|
|
<IconButton
|
|
icon="files"
|
|
label={$t("Files")}
|
|
active={leftOpen && !$pluginSidebar && leftView === "files"}
|
|
onclick={() => selectLeft("files")}
|
|
/>
|
|
<IconButton
|
|
icon="search"
|
|
label={$t("Search")}
|
|
active={leftOpen && !$pluginSidebar && leftView === "search"}
|
|
onclick={() => selectLeft("search")}
|
|
/>
|
|
<IconButton
|
|
icon="bookmark"
|
|
label={$t("Bookmarks")}
|
|
active={leftOpen && !$pluginSidebar && leftView === "bookmarks"}
|
|
onclick={() => selectLeft("bookmarks")}
|
|
/>
|
|
{#each sidebarNavigation as item (`${item.owner}:${item.id}`)}
|
|
<IconButton
|
|
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
|
|
label={item.title}
|
|
active={leftOpen && $pluginSidebar?.owner === item.owner && $pluginSidebar?.id === item.id}
|
|
onclick={() => openPluginView(item.owner, item.id)}
|
|
/>
|
|
{/each}
|
|
{/if}
|
|
</div>
|
|
<div class="header-center" data-tauri-drag-region>
|
|
<TabBar tabs={workingTabs} activePath={activeTabPath} onSelect={selectWorkingTab} onClose={closeTab}
|
|
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={pinWorkingTab}
|
|
fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
|
|
onDetach={(tab) => { void detachTab(tab); }}
|
|
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
|
|
<IconButton icon="plus" label={$t("New tab (Ctrl T)")} onclick={newTab} />
|
|
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
|
</div>
|
|
<div class="header-right" data-tauri-drag-region>
|
|
{#if browserContribution?.newTab}<IconButton icon="globe" label={$t("New browser tab")} disabled={browserOpening} onclick={() => void openBrowser()} />{/if}
|
|
<PluginAccessMenu surface="open" compact />
|
|
<PluginTools />
|
|
<PluginAccessMenu surface="commands" compact />
|
|
<IconButton icon="save" label={$t("Save")} disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
|
|
{#if terminalEnabled}<IconButton icon="terminal" label={$t("Terminal")} active={terminalOpen} onclick={toggleTerminal} />{/if}
|
|
{#if !transferredWindow}<IconButton
|
|
icon="panel-right"
|
|
label={rightOpen ? $t("Hide outline") : $t("Show outline")}
|
|
active={rightOpen}
|
|
onclick={() => (rightOpen = !rightOpen)}
|
|
/>{/if}
|
|
{#if desktop}<WindowControls onError={(message) => error = message} />{/if}
|
|
</div>
|
|
</header>
|
|
|
|
{#if !transferredWindow}<nav class="plugin-ribbon" aria-label={$t("Plugin shortcuts")} hidden={ribbonNavigation.length === 0}>
|
|
{#each ribbonNavigation as item (`${item.owner}:${item.id}`)}
|
|
<IconButton
|
|
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
|
|
label={item.title}
|
|
side="right"
|
|
active={($pluginSidebar?.owner === item.owner && $pluginSidebar?.id === item.id) || $pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
|
|
onclick={() => openPluginView(item.owner, item.id)}
|
|
/>
|
|
{/each}
|
|
</nav>{/if}
|
|
|
|
{#if leftOpen && !transferredWindow}
|
|
<aside class="left">
|
|
<div class="left-body">
|
|
{#if $pluginSidebar}
|
|
{#key $pluginSidebar.key}<PluginEditor view={$pluginSidebar} />{/key}
|
|
{/if}
|
|
<div class="native-left" class:sidebar-covered={!!$pluginSidebar}>
|
|
{#if !workspace}
|
|
{#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">{$t("No folder is open.")}</p>{/if}
|
|
{:else}
|
|
<div class="left-stack">
|
|
<div class="left-layer" class:shown={leftView === "files"}>
|
|
<FileTree
|
|
bind:this={fileTree}
|
|
workspaceRoot={workspace.root}
|
|
showInternal={settings.showInternalFolder}
|
|
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
|
|
onManageTemplates={() => templateManager = true}
|
|
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
|
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
|
{refreshToken}
|
|
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
|
onCreated={(entry) => {
|
|
void openCreatedFile(entry);
|
|
}}
|
|
onStatus={(message) => {
|
|
status = message;
|
|
error = null;
|
|
}}
|
|
onEntryGone={(path) => { removePluginDocuments(path); noteIndex.remove(path); noteIndexRevision = noteIndex.revision; void documents?.refresh(); refreshToken++; }}
|
|
onEntryRenamed={applyPathRename}
|
|
/>
|
|
</div>
|
|
{#if leftView === "search"}
|
|
<SearchPane {searchRequest} onOpen={(entry, line) => void openFile(entry, line)} />
|
|
{:else if leftView === "bookmarks"}
|
|
<BookmarksPane {refreshToken} onOpen={(entry) => void openFile(entry)} />
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
<div class="left-footer">
|
|
<div class="footer-start" bind:this={workspaceAnchor}>
|
|
<IconButton icon="folder-open" label={$t("Open folder")} onclick={chooseWorkspace} />
|
|
<span class="ws">{workspace ? workspace.name : $t("No workspace")}</span>
|
|
</div>
|
|
<div class="footer-actions">
|
|
<IconButton icon="help" label={$t("Help and about (F1)")} onclick={() => preferences = "help"} />
|
|
<IconButton icon="settings" label={$t("Settings (Ctrl+,)")} onclick={() => void openSettings()} />
|
|
</div>
|
|
</div>
|
|
</aside>
|
|
|
|
<div
|
|
class="gutter gutter-v"
|
|
role="separator"
|
|
onpointerdown={() => (dragging = "left")}
|
|
></div>
|
|
{/if}
|
|
|
|
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
|
|
<main class="center">
|
|
<div class="plugin-panes" class:inactive={!editorPluginVisible}>
|
|
{#each $pluginEditors as pane (pane.key)}
|
|
{@const bounds = pluginBounds[pane.key]}
|
|
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
|
|
<div class="plugin-pane" class:inactive={!bounds} class:split={!!activeSplit} class:focused={$pluginView?.key === pane.key}
|
|
style:left={`${bounds?.left ?? 0}%`} style:top={`${bounds?.top ?? 0}%`}
|
|
style:width={`${bounds?.width ?? 100}%`} style:height={`${bounds?.height ?? 100}%`}
|
|
onfocusin={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}
|
|
onpointerdown={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}>
|
|
{#if activeSplit && bounds}
|
|
<TabBar tabs={workingTabs.filter(tab => tab.id === pane.key)} activePath={activeTabPath}
|
|
onSelect={selectWorkingTab} onClose={closeTab} onMove={moveWorkingTab} onPin={pinWorkingTab}
|
|
onCloseTabs={(path, scope) => void closeTabs(path, scope)} fileActions={workingTabFileActions} tabActions={workingTabActions}
|
|
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
|
|
{/if}
|
|
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
|
|
</div>
|
|
{/each}
|
|
</div>
|
|
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
|
|
<div class="document-panes" class:split={documentViews.length > 1}>
|
|
{#each documentViews as pane (pane.id)}
|
|
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
|
|
<div class="document-pane" class:focused={documentPanes.active === pane.id}
|
|
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
|
|
style:--pane-weight={pane.bounds.width}
|
|
onpointerdowncapture={() => focusDocumentPane(pane.id)}
|
|
onfocusin={() => focusDocumentPane(pane.id)}>
|
|
{#if pane.buffer?.diskError}
|
|
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button><button onclick={() => void documents?.refresh()}>{$t("Retry")}</button></div>
|
|
{:else if pane.buffer?.diskContents != null}
|
|
<div class="conflict" role="alert">
|
|
<span>{$t("This file changed on disk. Your edits are preserved. Review both versions before saving.")}</span>
|
|
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>{$t("Use disk version")}</button>
|
|
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>{$t("Keep my edits")}</button>
|
|
<button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button>
|
|
</div>
|
|
<details class="disk-review"><summary>{$t("View disk version")}</summary><pre>{pane.buffer.diskContents}</pre></details>
|
|
{/if}
|
|
<EditorPane
|
|
bind:this={paneComponents[pane.id]}
|
|
{tabs}
|
|
active={documentPanes.active === pane.id}
|
|
onCloseSplit={documentViews.length > 1 ? () => closeSplit(pane.id) : undefined}
|
|
hasWorkspace={!!workspace}
|
|
onOpenWorkspace={() => void chooseWorkspace()}
|
|
onNewFile={() => void newFile()}
|
|
onNewNote={(event) => { void newNote(event); }}
|
|
onQuickOpen={() => quickOpen = true}
|
|
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
|
|
{browserOpening}
|
|
buffer={pane.buffer}
|
|
chrome={pane.buffer?.chromeOverride ?? pane.buffer?.chrome ?? "Writing"}
|
|
reading={pane.reading}
|
|
focusLine={documentPanes.active === pane.id ? focusLine : null}
|
|
{onChange}
|
|
onInsertImage={file => insertImage(file, pane.buffer)}
|
|
onRenameTitle={renameNoteTitle}
|
|
tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }}
|
|
linkActions={{
|
|
browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error("Could not open the app browser."); } : undefined,
|
|
defaultBrowser: target => openUrl(target),
|
|
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
|
|
}}
|
|
onToggleReading={() => setReading(!pane.reading, pane.id)}
|
|
onToggleChrome={() => { focusDocumentPane(pane.id); toggleChrome(); }}
|
|
onOpenLink={(kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
|
|
/>
|
|
</div>
|
|
{/each}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
{#if terminalContribution && terminalStarted}
|
|
<div
|
|
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
|
role="separator"
|
|
onpointerdown={() => (dragging = "bottom")}
|
|
></div>
|
|
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
|
{#if workspace}
|
|
{#key workspace.root}
|
|
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
|
|
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
|
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
|
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
|
{/key}
|
|
{:else}
|
|
<p class="placeholder">{$t("Open a workspace to start the terminal.")}</p>
|
|
{/if}
|
|
</section>
|
|
{/if}
|
|
</div>
|
|
|
|
{#if rightOpen && !transferredWindow}
|
|
<div
|
|
class="gutter gutter-v"
|
|
role="separator"
|
|
onpointerdown={() => (dragging = "right")}
|
|
></div>
|
|
<aside class="right">
|
|
<div class="outline-area">
|
|
<OutlinePane
|
|
items={outlineItems}
|
|
onJump={(line) => {
|
|
pluginEditorActive.set(false);
|
|
setReading(false);
|
|
focusLine = null;
|
|
queueMicrotask(() => {
|
|
focusLine = line;
|
|
});
|
|
}}
|
|
/>
|
|
</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}
|
|
|
|
<footer class="status">
|
|
<span>{error ?? status}</span>
|
|
{#if workspace}
|
|
<span>{workspace.watch_mode} watch</span>
|
|
{/if}
|
|
<span>{isIde ? $t("IDE") : $t("Writer")}</span>
|
|
</footer>
|
|
</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; }
|
|
.conflict { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px; background: var(--rs-bg-active); border-bottom: 1px solid var(--rs-warning, #ebcb8b); }
|
|
.conflict span { flex: 1 1 300px; }
|
|
.conflict button { border: 1px solid var(--rs-border); background: var(--rs-bg); padding: 4px 8px; }
|
|
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
|
|
.disk-review pre { white-space: pre-wrap; user-select: text; }
|
|
.shell {
|
|
position: relative;
|
|
isolation: isolate;
|
|
height: 100vh;
|
|
display: grid;
|
|
--ribbon-width: 0px;
|
|
grid-template-columns: var(--ribbon-width) minmax(0, 1fr);
|
|
grid-template-rows: var(--rs-titlebar-height) minmax(0, 1fr) 22px;
|
|
background: var(--rs-bg);
|
|
}
|
|
|
|
.workarea-background {
|
|
position: absolute;
|
|
inset: var(--rs-titlebar-height) 0 22px;
|
|
z-index: -1;
|
|
pointer-events: none;
|
|
background-color: var(--rs-new-tab-bg, var(--rs-bg));
|
|
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
|
|
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
|
|
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
|
|
background-repeat: no-repeat;
|
|
}
|
|
|
|
.workarea-background::before,
|
|
.workarea-background::after {
|
|
content: '';
|
|
position: absolute;
|
|
inset: 0;
|
|
pointer-events: none;
|
|
background-repeat: no-repeat;
|
|
}
|
|
|
|
.workarea-background::before {
|
|
background-image: var(--rs-background-previous-image, none);
|
|
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
|
|
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
|
|
}
|
|
|
|
.workarea-background::after {
|
|
background-image: var(--rs-background-transition-image, none);
|
|
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
|
|
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
|
|
}
|
|
|
|
.shell.left-open {
|
|
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr);
|
|
}
|
|
|
|
.shell.right-open {
|
|
grid-template-columns: var(--ribbon-width) minmax(0, 1fr) 1px var(--right);
|
|
}
|
|
|
|
.shell.left-open.right-open {
|
|
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr) 1px var(--right);
|
|
}
|
|
|
|
.shell.has-ribbon { --ribbon-width: 44px; }
|
|
.shell.detached { grid-template-columns: minmax(0, 1fr); }
|
|
|
|
.plugin-ribbon {
|
|
grid-column: 1;
|
|
grid-row: 2;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
gap: 4px;
|
|
min-height: 0;
|
|
padding: 6px 5px;
|
|
overflow-y: auto;
|
|
background: var(--rs-workarea-sidebar-bg);
|
|
border-right: 1px solid var(--rs-border);
|
|
}
|
|
|
|
.plugin-ribbon[hidden] { display: block; visibility: hidden; padding: 0; border: 0; }
|
|
.plugin-ribbon :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
|
|
|
.header {
|
|
grid-column: 1 / -1;
|
|
display: grid;
|
|
grid-template-columns: auto minmax(0, 1fr) auto;
|
|
align-items: center;
|
|
gap: 0;
|
|
padding: 0;
|
|
background: var(--rs-bg-elevated);
|
|
box-shadow: inset 0 -1px var(--rs-border);
|
|
user-select: none;
|
|
}
|
|
|
|
.header-left,
|
|
.header-right {
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
gap: 2px;
|
|
min-width: 0;
|
|
padding: 0 4px;
|
|
}
|
|
|
|
.header-center {
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: flex-start;
|
|
gap: 6px;
|
|
min-width: 0;
|
|
padding: 0;
|
|
border-left: 1px solid var(--rs-border);
|
|
border-right: 1px solid var(--rs-border);
|
|
}
|
|
|
|
.header-left, .header-center, .header-right { height: 100%; }
|
|
.shell.left-open .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); padding-left: calc(var(--ribbon-width) + 4px); }
|
|
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
|
|
.header-right { justify-content: flex-end; }
|
|
.window-drag-space { flex: 0 0 40px; align-self: stretch; }
|
|
|
|
.header-center :global(.tabs) {
|
|
flex: 0 1 auto;
|
|
align-self: stretch;
|
|
min-width: 0;
|
|
min-height: 28px;
|
|
background: transparent;
|
|
border-bottom: 0;
|
|
}
|
|
.header-center :global(.tab) {
|
|
flex: 0 1 180px;
|
|
width: 180px;
|
|
min-width: 96px;
|
|
max-width: 180px;
|
|
background: transparent;
|
|
}
|
|
|
|
.header-center :global(.tab.active) {
|
|
background: var(--rs-bg);
|
|
}
|
|
|
|
.ws {
|
|
color: var(--rs-text-dim);
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
min-width: 0;
|
|
flex: 1;
|
|
}
|
|
|
|
.left,
|
|
.center,
|
|
.right,
|
|
.bottom,
|
|
.center-stack {
|
|
min-width: 0;
|
|
min-height: 0;
|
|
overflow: hidden;
|
|
background: transparent;
|
|
}
|
|
|
|
.center-stack {
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.center {
|
|
flex: 1;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.editor-host {
|
|
flex: 1;
|
|
min-height: 0;
|
|
display: flex;
|
|
flex-direction: column;
|
|
position: relative;
|
|
}
|
|
|
|
.editor-host { container-type: inline-size; }
|
|
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
|
|
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
|
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
|
|
.document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); }
|
|
@container (max-width: 640px) {
|
|
.document-panes.split { flex-direction: column; overflow-y: auto; }
|
|
.document-panes.split .document-pane { flex: 1 0 320px; }
|
|
.document-pane + .document-pane { border-left: 0; border-top: 1px solid var(--rs-border); }
|
|
}
|
|
.editor-host.plugin-covered { display: none; }
|
|
.center { position: relative; }
|
|
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
|
|
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; }
|
|
.plugin-pane.split { border: 1px solid var(--rs-border); }
|
|
.plugin-pane.split.focused { border-color: var(--rs-accent); }
|
|
.plugin-panes.inactive, .plugin-pane.inactive { display: none; }
|
|
|
|
.left,
|
|
.right {
|
|
background: var(--rs-workarea-sidebar-bg);
|
|
}
|
|
|
|
.left {
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.left-body {
|
|
flex: 1;
|
|
min-height: 0;
|
|
overflow: hidden;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.left-body > :global(*) {
|
|
flex: 1;
|
|
min-height: 0;
|
|
}
|
|
|
|
.native-left { display: flex; flex-direction: column; min-height: 0; }
|
|
.native-left.sidebar-covered { display: none; }
|
|
|
|
.left-stack {
|
|
flex: 1;
|
|
min-height: 0;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.left-layer {
|
|
display: none;
|
|
flex: 1;
|
|
min-height: 0;
|
|
}
|
|
|
|
.left-layer.shown {
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.left-layer.shown > :global(*) {
|
|
flex: 1;
|
|
min-height: 0;
|
|
}
|
|
|
|
.left-stack > :global(.pane) {
|
|
flex: 1;
|
|
min-height: 0;
|
|
}
|
|
|
|
.left-footer {
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
gap: 8px;
|
|
padding: 4px 6px;
|
|
border-top: 1px solid var(--rs-border);
|
|
flex: 0 0 auto;
|
|
}
|
|
|
|
.footer-start {
|
|
flex: 1;
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 2px;
|
|
min-width: 0;
|
|
}
|
|
|
|
.footer-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
|
|
.footer-actions :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
|
|
|
.placeholder {
|
|
margin: 12px;
|
|
color: var(--rs-text-dim);
|
|
}
|
|
|
|
.gutter {
|
|
position: relative;
|
|
z-index: 2;
|
|
background: var(--rs-border);
|
|
touch-action: none;
|
|
}
|
|
|
|
/* Keep the resize target easy to grab without reserving space between panes. */
|
|
.gutter::before {
|
|
content: "";
|
|
position: absolute;
|
|
}
|
|
|
|
.gutter::after {
|
|
content: "";
|
|
position: absolute;
|
|
pointer-events: none;
|
|
background: var(--rs-accent-deep);
|
|
opacity: 0;
|
|
transition: opacity 150ms ease;
|
|
}
|
|
|
|
.gutter-v {
|
|
cursor: col-resize;
|
|
}
|
|
|
|
.gutter-v::before {
|
|
inset: 0 -4px;
|
|
}
|
|
|
|
.gutter-v::after {
|
|
inset: 0 -1.5px;
|
|
}
|
|
|
|
.gutter-h {
|
|
flex: 0 0 1px;
|
|
cursor: row-resize;
|
|
}
|
|
|
|
.gutter-h::before {
|
|
inset: -4px 0;
|
|
}
|
|
|
|
.gutter-h::after {
|
|
inset: -1.5px 0;
|
|
}
|
|
|
|
.gutter:hover::after,
|
|
.gutter:active::after {
|
|
opacity: 1;
|
|
}
|
|
|
|
@media (prefers-reduced-motion: reduce) {
|
|
.gutter::after { transition: none; }
|
|
}
|
|
|
|
.bottom {
|
|
flex: 0 0 var(--bottom);
|
|
height: var(--bottom);
|
|
display: flex;
|
|
flex-direction: column;
|
|
min-height: 0;
|
|
background: transparent;
|
|
}
|
|
|
|
.bottom > :global(*) {
|
|
flex: 1;
|
|
min-height: 0;
|
|
}
|
|
|
|
.status {
|
|
grid-column: 1 / -1;
|
|
display: flex;
|
|
justify-content: space-between;
|
|
gap: 12px;
|
|
padding: 0 10px;
|
|
background: var(--rs-bg-elevated);
|
|
border-top: 1px solid var(--rs-border);
|
|
color: var(--rs-text-dim);
|
|
font-size: 12px;
|
|
}
|
|
|
|
.status :first-child {
|
|
color: var(--rs-text);
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
}
|
|
</style>
|