- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them. - Move the DOM interface onto the host menus, the shared tooltip, and the host icons. - A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns. - Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes. - A save, move, or delete reads only that card again. Watcher paths reach the feature. - Add Settings → Project Management and the projectManagement section. View states move to localStorage. - Background reads the boards from workspace.json. Remove api.backgrounds and the boards service. - Add yaml 2.9.1. Use the host markdown-it. - Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
1584 lines
72 KiB
Svelte
1584 lines
72 KiB
Svelte
<script lang="ts">
|
|
import { t } from "$lib/i18n";
|
|
import TerminalHost from "$lib/features/TerminalHost.svelte";
|
|
import { featureSwitches } from "$lib/features/state";
|
|
import { terminalShortcut, type TerminalAction } from "$lib/features/terminalKeys";
|
|
import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
|
import { featureOfOwner } from "$lib/features/catalog";
|
|
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } 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 { WorkspaceSession } from "$lib/workspace/session.svelte";
|
|
import { retainEditorStates } from "$lib/editor/editorStates";
|
|
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "$lib/workspace/documentPanes";
|
|
import type { ViewMode } from "./ViewModes.svelte";
|
|
import { selectedEditorText } from "$lib/editor/selection";
|
|
import { pluginHost } from "$lib/plugins/registry";
|
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
|
import { confirm, message as dialogMessage } from "@tauri-apps/plugin-dialog";
|
|
import { openUrl } from "@tauri-apps/plugin-opener";
|
|
import { Documents } from "$lib/workspace/documents.svelte";
|
|
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 { revealLabel } from "$lib/ui/menuItems";
|
|
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 CommandPalette, { type PaletteCommand } from "./CommandPalette.svelte";
|
|
import TemplateManager from "./TemplateManager.svelte";
|
|
import WorkspacePicker from "./WorkspacePicker.svelte";
|
|
import SettingsDialog from "./SettingsDialog.svelte";
|
|
import { THEME_EDITOR_EVENT } from "$lib/theme/themeEditorRequest";
|
|
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 type FileTree from "./FileTree.svelte";
|
|
import { COMMAND_LABELS, commandShortcut, preferenceKeys, workbenchCommand, type WorkbenchCommand } from "./workbenchKeys";
|
|
import type EditorPane from "./EditorPane.svelte";
|
|
import WorkbenchHeader from "./WorkbenchHeader.svelte";
|
|
import PluginRibbon from "./PluginRibbon.svelte";
|
|
import LeftPane from "./LeftPane.svelte";
|
|
import DocumentArea from "./DocumentArea.svelte";
|
|
import RightPane from "./RightPane.svelte";
|
|
import StatusBar from "./StatusBar.svelte";
|
|
import type { Backlink } from "$lib/workspace/noteIndex";
|
|
import { buildOutline } from "$lib/workspace/outline";
|
|
import {
|
|
onWorkspaceEvent,
|
|
workspaceNew,
|
|
workspaceList,
|
|
workspaceOpenDefault,
|
|
workspaceCreate,
|
|
workspaceAbsPath,
|
|
workspaceLastPath,
|
|
workspaceOpen,
|
|
workspaceOpenWindow,
|
|
workspaceRead,
|
|
workspaceReadDataUrl,
|
|
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 { 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);
|
|
// The theme editor opens as a tab. Close the in-window Settings dialog, so the tab shows.
|
|
$effect(() => {
|
|
const close = () => { preferences = null; };
|
|
window.addEventListener(THEME_EDITOR_EVENT, close);
|
|
return () => window.removeEventListener(THEME_EDITOR_EVENT, close);
|
|
});
|
|
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: HTMLElement | undefined = $state();
|
|
const desktop = isTauri();
|
|
const transferredWindow = /^[0-9a-f-]{36}$/i.test(new URLSearchParams(location.search).get("tabTransfer") ?? "");
|
|
// The documents of the open workspace. Their buffers are reactive, so the tabs read them directly.
|
|
let documents = $state.raw<Documents | null>(null);
|
|
const tabs = $derived<OpenBuffer[]>(documents?.buffers ?? []);
|
|
const activePath = $derived(documents?.activePath ?? 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);
|
|
// The session owns the marks, the note index, renames, and the change events of this window.
|
|
const session = new WorkspaceSession(() => $t("Could not read all workspace links. Rebuild the index to retry."));
|
|
onDestroy(() => session.dispose());
|
|
const backlinks = $derived.by(() => {
|
|
void session.indexRevision;
|
|
return activePath && !editorPluginVisible ? session.index.backlinks(activePath) : [];
|
|
});
|
|
|
|
$effect(() => {
|
|
const root = workspace?.root ?? null;
|
|
untrack(() => session.open(root));
|
|
});
|
|
|
|
$effect(() => {
|
|
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(() => session.setDrafts(drafts));
|
|
});
|
|
|
|
// Open documents and plugin views follow the files that the session reports.
|
|
$effect(() => session.subscribe(change => {
|
|
if (change.type === "renamed") {
|
|
documents?.rename(change.from, change.to);
|
|
renamePluginDocuments(change.from, change.to);
|
|
} else if (change.type === "deleted") {
|
|
removePluginDocuments(change.path);
|
|
void documents?.refresh();
|
|
notifyPluginWorkspace([change.path]);
|
|
} else if (change.type === "changed") {
|
|
void documents?.refresh();
|
|
notifyPluginWorkspace(change.paths);
|
|
} else if (change.type === "internal") notifyPluginWorkspace(change.paths);
|
|
}));
|
|
|
|
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 activeDocumentPane = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active));
|
|
const reading = $derived(activeDocumentPane?.reading ?? false);
|
|
let quickOpen = $state(false);
|
|
let palette = $state(false);
|
|
/** The name of a native feature, or of an installed plugin. */
|
|
function ownerName(owner: string) {
|
|
const feature = featureOfOwner(owner);
|
|
return feature ? $t(feature.name) : $installedPlugins.plugins.find(row => row.manifest.id === owner)?.manifest.name ?? owner;
|
|
}
|
|
/** The commands of the palette: the app commands that apply here, then the feature and plugin commands. */
|
|
function paletteCommands(): PaletteCommand[] {
|
|
const hidden = new Set<WorkbenchCommand>(["command-palette", ...(terminalEnabled ? [] : ["toggle-terminal" as const]), ...(workspace ? [] : ["quick-open" as const])]);
|
|
const app = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).filter(command => !hidden.has(command)).map(command => ({
|
|
id: command, label: $t(COMMAND_LABELS[command]), shortcut: commandShortcut(command) || undefined, run: () => { runCommand(command); },
|
|
}));
|
|
const plugins = $pluginTools.filter(tool => tool.kind === "command" && tool.surface === "commands").map(tool => ({
|
|
id: `plugin:${tool.owner}:${tool.id}`, label: tool.title, detail: ownerName(tool.owner),
|
|
run: () => { void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); },
|
|
}));
|
|
return [...app, ...plugins];
|
|
}
|
|
let templateManager = $state(false);
|
|
let terminalStarted = $state(false);
|
|
let terminalMaximized = $state(false);
|
|
let terminalDock: TerminalHost | undefined = $state();
|
|
// The Terminal buttons, shortcuts, and command work from the switch alone. The first use loads the feature.
|
|
const terminalEnabled = $derived($featureSwitches.terminal);
|
|
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 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;
|
|
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(() => retainEditorStates(tabs.map(tab => tab.id)));
|
|
onDestroy(() => retainEditorStates([]));
|
|
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($t("Invalid tab transfer."));
|
|
const current = documents;
|
|
if (!workspace || !current || (switching && !startup)) throw new Error($t("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($t("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($t("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($t("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) : {});
|
|
// The working tabs, for the header and for the tab bar of each plugin pane in a split.
|
|
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
|
|
onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions,
|
|
tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) });
|
|
$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 isSource = $derived(view === "Source");
|
|
const readable = $derived(buffer?.kind === "text" && isMarkdownPath(buffer.relPath));
|
|
// The status bar names the view of the active pane. Split shows the editor view.
|
|
const viewMode: ViewMode = $derived(reading && readable ? "read" : isSource ? "source" : "write");
|
|
// The outline and the status bar follow the active tab. A plugin or browser tab has no document facts.
|
|
const documentActive = $derived(!editorPluginVisible && buffer?.kind === "text");
|
|
const outlineItems = $derived(
|
|
documentActive && buffer ? buildOutline(buffer.relPath, buffer.contents) : [],
|
|
);
|
|
let cursor = $state({ line: 1, column: 1 });
|
|
$effect(() => { void buffer?.id; cursor = { line: 1, column: 1 }; });
|
|
const documentFacts = $derived(documentActive && buffer ? {
|
|
saved: buffer.contents === buffer.saved,
|
|
line: cursor.line,
|
|
column: cursor.column,
|
|
words: countWords(buffer.contents),
|
|
endings: buffer.saved.includes("\r\n") ? "CRLF" as const : "LF" as const,
|
|
} : null);
|
|
|
|
/** Words separated by space, and each Han, Hiragana, or Katakana character as one word. */
|
|
function countWords(text: string) {
|
|
const ideographs = text.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu)?.length ?? 0;
|
|
const rest = text.replace(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu, " ").trim();
|
|
return ideographs + (rest ? rest.split(/\s+/).length : 0);
|
|
}
|
|
|
|
function applyChrome(next: Chrome) {
|
|
view = next;
|
|
}
|
|
|
|
function toggleChrome() {
|
|
const next = view === "Writing" ? "Source" : "Writing";
|
|
setReading(false);
|
|
applyChrome(next);
|
|
documents?.setChrome(next);
|
|
}
|
|
|
|
/** Show Write, Source, or Read in a pane. Write and Source keep a Split view. */
|
|
function setDocumentView(paneId: string, next: ViewMode) {
|
|
focusDocumentPane(paneId);
|
|
if (next === "read") { setReading(true, paneId); return; }
|
|
setReading(false, paneId);
|
|
const chrome = next === "source" ? "Source" : "Writing";
|
|
if (chrome !== view) { applyChrome(chrome); documents?.setChrome(chrome); }
|
|
}
|
|
|
|
function setSplitView(paneId: string, split: boolean) {
|
|
focusDocumentPane(paneId);
|
|
documentPanes = splitDocumentView(documentPanes, paneId, split);
|
|
}
|
|
|
|
function toggleTerminal() {
|
|
if (!terminalEnabled) return;
|
|
terminalOpen = !terminalOpen;
|
|
if (terminalOpen) { terminalStarted = true; }
|
|
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
|
}
|
|
|
|
async function terminalAction(action: Exclude<TerminalAction, "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($t("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;
|
|
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") : "";
|
|
}
|
|
|
|
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 = $t("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) {
|
|
// The platform choices for a changed document: Save, Don't save, or Cancel.
|
|
const labels = { yes: $t("Save"), no: $t("Don't save"), cancel: $t("Cancel") };
|
|
const choice = await dialogMessage($t("Save the changes to {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning", buttons: labels });
|
|
if (choice !== labels.yes && choice !== "Yes" && choice !== labels.no && choice !== "No") break;
|
|
if (documents !== current || switching || tab.contents !== contents) break;
|
|
if (choice === labels.yes || choice === "Yes") {
|
|
try { await current!.save(tab.id); } catch (reason) { error = String(reason); break; }
|
|
}
|
|
}
|
|
if (documents !== current || switching) 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: "template", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
|
|
{ label: $t("View"), icon: "book", children: [
|
|
{ label: $t("Write"), icon: "paragraph", radio: true, checked: viewMode === "write", run: () => setDocumentView(documentPanes.active, "write") },
|
|
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
|
|
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
|
|
{ separator: true },
|
|
{ label: $t("Split"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
|
|
] },
|
|
);
|
|
}
|
|
items.push({ separator: true },
|
|
{ label: $t("Rename…"), icon: "rename", run: () => { void renameActive(); } },
|
|
);
|
|
if (tab.kind === "text") items.push({ label: $t("Save a copy…"), icon: "duplicate", 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(revealLabel()), 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 = ""; error = null; return;
|
|
}
|
|
await current.open(entry, target);
|
|
if (documents !== current) return;
|
|
pluginEditorActive.set(false);
|
|
status = "";
|
|
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;
|
|
session.changed([rel]);
|
|
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", "");
|
|
session.changed([rel]);
|
|
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" });
|
|
session.changed([name]);
|
|
} 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");
|
|
session.changed([name.replaceAll("\\", "/")]);
|
|
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);
|
|
session.changed([path]);
|
|
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);
|
|
}
|
|
|
|
/** Run a shortcut command. Returns false when the command does not apply now, so the key keeps its default. */
|
|
function runCommand(command: WorkbenchCommand): boolean {
|
|
switch (command) {
|
|
case "next-tab": case "previous-tab": {
|
|
if (!workingTabs.length) return false;
|
|
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
|
|
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
|
|
selectWorkingTab(workingTabs[next].relPath);
|
|
return true;
|
|
}
|
|
case "command-palette": palette = true; return true;
|
|
case "settings": void openSettings(); return true;
|
|
case "help": preferences = "help"; return true;
|
|
case "quick-open": if (workspace) quickOpen = true; return true;
|
|
case "new-tab": newTab(); return true;
|
|
case "search-workspace": if (!transferredWindow) { leftOpen = true; leftView = "search"; } return true;
|
|
case "save": if (!editorPluginVisible) void save(); return true;
|
|
case "open-workspace": void chooseWorkspace(); return true;
|
|
case "new-file": void newFile(); return true;
|
|
case "toggle-layout": if (!editorPluginVisible) toggleChrome(); return true;
|
|
case "toggle-reading": if (!editorPluginVisible && readable) setReading(!reading); return true;
|
|
case "toggle-terminal": if (!terminalEnabled) return false; toggleTerminal(); return true;
|
|
case "close-tab":
|
|
if (editorPluginVisible) { if (activeTabPath) void closeTab(activeTabPath); }
|
|
else if (activePath) closeTab(activePath);
|
|
return true;
|
|
case "toggle-sidebar": if (!transferredWindow) leftOpen = !leftOpen; return true;
|
|
case "rename": if (!editorPluginVisible && !(leftOpen && leftView === "files")) void renameActive(); return true;
|
|
}
|
|
}
|
|
|
|
function onPreferencesKeydown(event: KeyboardEvent) {
|
|
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
|
const command = workbenchCommand(event, preferenceKeys);
|
|
if (command && runCommand(command)) { event.preventDefault(); event.stopPropagation(); }
|
|
}
|
|
|
|
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 = terminalEnabled ? terminalShortcut(event) : null;
|
|
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;
|
|
const command = workbenchCommand(event);
|
|
if (command && runCommand(command)) event.preventDefault();
|
|
}
|
|
|
|
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($t("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;
|
|
if (!await session.rename(from, plan.to) || documents !== current) return;
|
|
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 {
|
|
if (!await session.rename(from, plan.to) || documents !== current) return;
|
|
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 () => {
|
|
const targets = await session.linkTargets(origin, link.target, link.kind);
|
|
if ("ambiguous" in targets) throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: targets.ambiguous.join(", ") }));
|
|
for (const path of targets.paths) {
|
|
if (!valid()) throw new Error($t("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($t("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;
|
|
if (!await session.rename(file.rel_path, to) || !valid()) return;
|
|
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 => {
|
|
await session.marks.update(marks => marks.bookmarks.includes(file.rel_path) ? marks : { ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
|
|
if (valid()) status = $t("Bookmarked {name}", { name: file.name });
|
|
}) },
|
|
{ label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
|
|
{ label: $t(revealLabel()), 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;
|
|
const targets = await session.linkTargets(origin, target, kind);
|
|
if (documents !== current || workspace?.root !== root) return;
|
|
if ("ambiguous" in targets) {
|
|
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: targets.ambiguous.join(", ") });
|
|
return;
|
|
}
|
|
const rels = targets.paths;
|
|
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 - 44));
|
|
}
|
|
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));
|
|
}
|
|
}
|
|
|
|
// A splitter takes keyboard focus. The arrow keys move it by 16 pixels, and Home and End go to its limits.
|
|
function splitterKey(event: KeyboardEvent, pane: "left" | "right" | "bottom") {
|
|
const steps: Record<string, number> = pane === "bottom" ? { ArrowUp: 16, ArrowDown: -16 } : pane === "left" ? { ArrowRight: 16, ArrowLeft: -16 } : { ArrowLeft: 16, ArrowRight: -16 };
|
|
const [min, max] = pane === "bottom" ? [80, Math.max(80, (centerStack?.getBoundingClientRect().height ?? 400) - 80)] : [160, 480];
|
|
const current = pane === "left" ? leftWidth : pane === "right" ? rightWidth : bottomHeight;
|
|
const next = event.key === "Home" ? min : event.key === "End" ? max : event.key in steps ? current + steps[event.key] : null;
|
|
if (next === null) return;
|
|
event.preventDefault();
|
|
const value = Math.min(max, Math.max(min, next));
|
|
if (pane === "left") leftWidth = value; else if (pane === "right") rightWidth = value; else bottomHeight = value;
|
|
}
|
|
|
|
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 = $t("Could not read your layout. Default layout applies for this window."); }
|
|
});
|
|
|
|
// Side panes give way when the window becomes narrow: the outline below 1100 pixels, and the side pane below 800 pixels.
|
|
// They come back when the window grows again. A pane that the user opens in a narrow window stays open.
|
|
// At startup the saved layout applies as it is.
|
|
let windowWidth = $state(window.innerWidth);
|
|
let measured = false;
|
|
const narrow = { left: false, right: false };
|
|
const wide = { left: true, right: true };
|
|
$effect(() => {
|
|
if (!layoutReady || transferredWindow) return;
|
|
const left = windowWidth < 800, right = windowWidth < 1100;
|
|
untrack(() => {
|
|
if (!measured) { measured = true; Object.assign(narrow, { left, right }); Object.assign(wide, { left: leftOpen, right: rightOpen }); return; }
|
|
if (right !== narrow.right) {
|
|
if (right) { wide.right = rightOpen; rightOpen = false; } else rightOpen = wide.right;
|
|
narrow.right = right;
|
|
}
|
|
if (left !== narrow.left) {
|
|
if (left) { wide.left = leftOpen; leftOpen = false; } else leftOpen = wide.left;
|
|
narrow.left = left;
|
|
}
|
|
});
|
|
});
|
|
|
|
// The saved layout keeps the choice of a wide window.
|
|
$effect(() => {
|
|
if (!layoutReady || transferredWindow) return;
|
|
const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen };
|
|
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView }); }
|
|
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
|
|
});
|
|
|
|
onMount(() => {
|
|
try { settings = readSettings(); }
|
|
catch { error = $t("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($t("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;
|
|
if (!await session.rename(from, plan.to) || documents !== current) throw new Error($t("The workspace changed. Reopen the document."));
|
|
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.");
|
|
}));
|
|
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
|
void onWorkspaceEvent((event) => {
|
|
if (event.root === workspace?.root) session.watched(event.paths);
|
|
}).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 ? $t("Unsaved edits will be discarded.") : "", terminalStarted ? $t("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));
|
|
// Focus checks only the open documents. The file watcher reports the other changes.
|
|
const focus = () => { void documents?.refresh(); };
|
|
window.addEventListener("focus", focus);
|
|
return () => {
|
|
disposed = true;
|
|
documents?.dispose();
|
|
unlisteners.forEach(off => off());
|
|
window.removeEventListener("focus", focus);
|
|
};
|
|
});
|
|
|
|
</script>
|
|
|
|
<svelte:window bind:innerWidth={windowWidth} 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 palette}<CommandPalette commands={paletteCommands()} onClose={() => palette = false} />{/if}
|
|
{#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false}
|
|
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if}
|
|
|
|
<div
|
|
class="shell"
|
|
class:detached={transferredWindow}
|
|
class:has-ribbon={!transferredWindow}
|
|
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>
|
|
<WorkbenchHeader
|
|
detached={transferredWindow}
|
|
{desktop}
|
|
{leftOpen}
|
|
{leftView}
|
|
{sidebarNavigation}
|
|
onSelectLeft={selectLeft}
|
|
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); } }}
|
|
onNewTab={newTab}
|
|
canOpenBrowser={!!browserContribution?.newTab}
|
|
{browserOpening}
|
|
onOpenBrowser={() => void openBrowser()}
|
|
saveDisabled={editorPluginVisible || !dirty || saving}
|
|
onSave={() => void save()}
|
|
{terminalEnabled}
|
|
{terminalOpen}
|
|
onToggleTerminal={toggleTerminal}
|
|
{rightOpen}
|
|
onToggleRight={() => (rightOpen = !rightOpen)}
|
|
onError={(message) => error = message}
|
|
/>
|
|
|
|
{#if !transferredWindow}<PluginRibbon items={ribbonNavigation} actions={!leftOpen} bind:workspaceAnchor
|
|
canOpenBrowser={!!browserContribution?.newTab} {browserOpening} onOpenBrowser={() => void openBrowser()} {terminalEnabled} {terminalOpen} onToggleTerminal={toggleTerminal} onChooseWorkspace={chooseWorkspace} onHelp={() => preferences = "help"} onSettings={() => void openSettings()} />{/if}
|
|
|
|
{#if leftOpen && !transferredWindow}
|
|
<LeftPane
|
|
bind:fileTree
|
|
bind:workspaceAnchor
|
|
{workspace}
|
|
{session}
|
|
{leftView}
|
|
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
|
showInternal={settings.showInternalFolder}
|
|
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
|
{searchRequest}
|
|
onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
|
|
onCreated={(entry) => { void openCreatedFile(entry); }}
|
|
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
|
|
onManageTemplates={() => templateManager = true}
|
|
onStatus={(message) => { status = message; error = null; }}
|
|
onChooseWorkspace={chooseWorkspace}
|
|
onHelp={() => preferences = "help"}
|
|
onSettings={() => void openSettings()}
|
|
/>
|
|
|
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
|
<div
|
|
class="gutter gutter-v"
|
|
role="separator"
|
|
tabindex="0"
|
|
aria-orientation="vertical"
|
|
aria-label={$t("Resize the side pane")}
|
|
aria-valuenow={leftWidth}
|
|
aria-valuemin={160}
|
|
aria-valuemax={480}
|
|
onpointerdown={() => (dragging = "left")}
|
|
onkeydown={(event) => splitterKey(event, "left")}
|
|
></div>
|
|
{/if}
|
|
|
|
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
|
|
<DocumentArea
|
|
bind:pluginPaneComponents
|
|
bind:paneComponents
|
|
{editorPluginVisible}
|
|
split={!!activeSplit}
|
|
{pluginBounds}
|
|
tabBar={tabBarProps}
|
|
{documentViews}
|
|
activePane={documentPanes.active}
|
|
{documents}
|
|
{tabs}
|
|
hasWorkspace={!!workspace}
|
|
{browserOpening}
|
|
{focusLine}
|
|
onFocusPane={(id) => focusDocumentPane(id)}
|
|
onCloseSplit={closeSplit}
|
|
onSaveCopy={(tab) => void saveCopy(tab)}
|
|
onOpenWorkspace={() => void chooseWorkspace()}
|
|
onNewFile={() => void newFile()}
|
|
onNewNote={(event) => { void newNote(event); }}
|
|
onQuickOpen={() => quickOpen = true}
|
|
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
|
|
{onChange}
|
|
onInsertImage={(file, tab) => insertImage(file, tab)}
|
|
onRenameTitle={renameNoteTitle}
|
|
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
|
|
linkActions={(pane) => ({
|
|
// "Open link in app browser" always opens a browser tab. Without an engine, the tab shows the engine setup.
|
|
browser: browserContribution?.newTab ? async target => { await browserContribution?.newTab?.(target); } : undefined,
|
|
defaultBrowser: target => openUrl(target),
|
|
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
|
|
})}
|
|
onView={(pane, next) => setDocumentView(pane.id, next)}
|
|
onSplitView={(pane, next) => setSplitView(pane.id, next)}
|
|
onCursor={(pane, line, column) => { if (pane.id === documentPanes.active) cursor = { line, column }; }}
|
|
onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
|
|
/>
|
|
{#if terminalEnabled && terminalStarted}
|
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
|
<div
|
|
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
|
role="separator"
|
|
tabindex="0"
|
|
aria-orientation="horizontal"
|
|
aria-label={$t("Resize the terminal")}
|
|
aria-valuenow={bottomHeight}
|
|
aria-valuemin={80}
|
|
onpointerdown={() => (dragging = "bottom")}
|
|
onkeydown={(event) => splitterKey(event, "bottom")}
|
|
></div>
|
|
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
|
{#if workspace}
|
|
{#key workspace.root}
|
|
<TerminalHost bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
|
|
onOpenSettings={() => void openSettings()}
|
|
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}
|
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
|
<div
|
|
class="gutter gutter-v"
|
|
role="separator"
|
|
tabindex="0"
|
|
aria-orientation="vertical"
|
|
aria-label={$t("Resize the outline")}
|
|
aria-valuenow={rightWidth}
|
|
aria-valuemin={160}
|
|
aria-valuemax={480}
|
|
onpointerdown={() => (dragging = "right")}
|
|
onkeydown={(event) => splitterKey(event, "right")}
|
|
></div>
|
|
<RightPane
|
|
{outlineItems}
|
|
onJump={(line) => {
|
|
pluginEditorActive.set(false);
|
|
setReading(false);
|
|
focusLine = null;
|
|
queueMicrotask(() => {
|
|
focusLine = line;
|
|
});
|
|
}}
|
|
showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
|
|
{backlinks}
|
|
{session}
|
|
onOpenBacklink={(entry) => void openBacklink(entry)}
|
|
/>
|
|
{/if}
|
|
|
|
<StatusBar message={error ?? status} polling={workspace?.watch_mode === "poll"} view={documentActive ? viewMode : null} facts={documentFacts} />
|
|
</div>
|
|
|
|
<style>
|
|
.terminal-hidden { display: none !important; }
|
|
.terminal-maximized > :global(.center), .terminal-maximized > .gutter-h { display: none; }
|
|
.terminal-maximized > .bottom { flex: 1; height: auto; }
|
|
.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);
|
|
}
|
|
|
|
/* The layer styles are in src/lib/theme/background.css. */
|
|
.workarea-background {
|
|
position: absolute;
|
|
inset: var(--rs-titlebar-height) 0 22px;
|
|
z-index: -1;
|
|
}
|
|
|
|
.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); }
|
|
|
|
.bottom,
|
|
.center-stack {
|
|
min-width: 0;
|
|
min-height: 0;
|
|
overflow: hidden;
|
|
background: transparent;
|
|
}
|
|
|
|
.center-stack {
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.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;
|
|
}
|
|
</style>
|