1506 lines
58 KiB
Svelte
1506 lines
58 KiB
Svelte
<script lang="ts">
|
|
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, findPluginEditor } 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, tick, untrack } from "svelte";
|
|
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 { 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 WorkspacePicker from "./WorkspacePicker.svelte";
|
|
import SettingsDialog from "./SettingsDialog.svelte";
|
|
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
|
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
|
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 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,
|
|
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 } from "$lib/workspace/renamePath";
|
|
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
|
|
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
|
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 = `Could not open settings: ${String(reason)}`; }
|
|
finally { openingSettings = false; }
|
|
}
|
|
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
|
let settingsReady = $state(false);
|
|
let workspaceAnchor: HTMLDivElement | undefined = $state();
|
|
const desktop = isTauri();
|
|
let tabs = $state<OpenBuffer[]>([]);
|
|
let activePath = $state<string | null>(null);
|
|
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
|
|
let status = $state("Open a workspace folder");
|
|
let error = $state<string | null>(null);
|
|
let refreshToken = $state(0);
|
|
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(DEFAULT_WORKBENCH_LAYOUT.leftOpen);
|
|
let rightOpen = $state(DEFAULT_WORKBENCH_LAYOUT.rightOpen);
|
|
$effect(() => { if ($pluginSidebar) leftOpen = true; });
|
|
let terminalOpen = $state(false);
|
|
let reading = $state(false);
|
|
let quickOpen = $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" && !item.toolbar));
|
|
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 editorPane: EditorPane | undefined = $state();
|
|
let closingTabs = false;
|
|
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
|
|
|
|
function createDocuments() {
|
|
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;
|
|
if (selected) view = selected.chromeOverride ?? selected.chrome;
|
|
});
|
|
return next;
|
|
}
|
|
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, 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);
|
|
return view ? pluginTabDragData(view) : undefined;
|
|
}
|
|
async function receiveTab(data: string, index: number) {
|
|
try {
|
|
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";
|
|
reading = 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 = "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") {
|
|
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();
|
|
}
|
|
|
|
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 && /^[0-9a-f-]{36}$/i.test(token)) {
|
|
const key = `runestone.tab-transfer.${token}`;
|
|
const raw = localStorage.getItem(key);
|
|
if (raw) {
|
|
const transfer = JSON.parse(raw);
|
|
if (transfer.root === workspace.root && transfer.created > Date.now() - 120000
|
|
&& (transfer.buffer || transfer.plugin)) {
|
|
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") documents.importTab(transfer.buffer);
|
|
else if (transfer.plugin) {
|
|
const deadline = Date.now() + 15000;
|
|
while (!await restorePluginTab(transfer.plugin)) {
|
|
if (Date.now() > deadline) throw new Error("Enable the plugin before moving this tab.");
|
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
}
|
|
} else throw new Error("Invalid tab transfer.");
|
|
reading = transfer.reading === true;
|
|
localStorage.setItem(key + ".accepted", "true");
|
|
localStorage.removeItem(key);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (err) { error = String(err); }
|
|
finally { switching = false; workbenchReady = true; }
|
|
}
|
|
|
|
function selectTab(relPath: string) {
|
|
cancelPluginDocumentOpen();
|
|
pluginEditorActive.set(false);
|
|
focusLine = null;
|
|
documents?.select(relPath);
|
|
status = documents?.active?.kind === "empty" ? "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: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
|
|
}
|
|
async function detachTab(item: WorkbenchTab) {
|
|
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; }
|
|
}
|
|
const current = documents;
|
|
const snapshot = JSON.stringify("buffer" in tab ? tab.buffer : pluginTabState(tab.plugin));
|
|
const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`;
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
const finish = () => {
|
|
window.removeEventListener("storage", accepted);
|
|
clearTimeout(timer);
|
|
localStorage.removeItem(key);
|
|
localStorage.removeItem(key + ".accepted");
|
|
};
|
|
const accepted = (event: StorageEvent) => {
|
|
if (event.key !== key + ".accepted" || event.newValue !== "true") return;
|
|
if ("buffer" in tab) {
|
|
if (documents === current && JSON.stringify(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
|
|
} else if (JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
|
|
finish();
|
|
};
|
|
try {
|
|
localStorage.setItem(key, JSON.stringify({ root: workspace.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
|
|
window.addEventListener("storage", accepted);
|
|
timer = setTimeout(() => { finish(); error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
|
await workspaceOpenWindow(workspace.root, token);
|
|
} catch (reason) { finish(); error = String(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 = "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) {
|
|
if (!tab || (scope !== "one" && tab.pinned)) continue;
|
|
const contents = tab.contents;
|
|
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "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 ? "Copied system path" : "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: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
|
|
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
|
|
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
|
|
);
|
|
}
|
|
items.push({ separator: true },
|
|
{ label: "Rename…", icon: "rename", run: () => { void renameActive(); } },
|
|
);
|
|
if (tab.kind === "text") items.push({ label: "Save a copy…", icon: "copy", run: () => { void saveCopy(); } });
|
|
items.push({ separator: true },
|
|
{ label: "Copy path", icon: "copy", children: [
|
|
{ label: "Workspace path", icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
|
|
{ label: "System path", icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
|
|
] },
|
|
{ label: "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) {
|
|
reading = 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;
|
|
reading = false;
|
|
editorPane?.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): Promise<string | null> {
|
|
if (!buffer || buffer.kind !== "text" || !isMarkdownPath(buffer.relPath)) {
|
|
return null;
|
|
}
|
|
const noteRel = buffer.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): Promise<string | null> {
|
|
const current = documents, note = buffer;
|
|
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("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 = `Extracted selection to ${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 = `Saved ${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 = `Autosaved ${result.saved.length} ${result.saved.length === 1 ? "file" : "files"}`;
|
|
if (result.failed.length) {
|
|
error = result.failed.map(({ path, error }) => `Could not autosave ${path}: ${String(error)}`).join("\n");
|
|
await current.refresh();
|
|
}
|
|
} finally { saving = false; }
|
|
}
|
|
|
|
async function saveCopy() {
|
|
const tab = buffer;
|
|
if (!tab || tab.kind !== "text") return;
|
|
const name = await requestText("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("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("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 = `Saved template: ${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: "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, "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) {
|
|
if (findPluginEditor($pluginView)) { event.preventDefault(); 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(); 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();
|
|
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);
|
|
}
|
|
|
|
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 = `Renamed to ${plan.to}`;
|
|
error = null;
|
|
}
|
|
|
|
async function renameActive() {
|
|
if (!activePath || buffer?.kind === "empty") {
|
|
return;
|
|
}
|
|
const current = documents;
|
|
const from = activePath;
|
|
const typed = await requestText("Rename to", from.split("/").pop() ?? from);
|
|
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 = `Renamed to ${plan.to}`;
|
|
error = null;
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
async function openLink(kind: "md" | "wiki", target: string) {
|
|
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 rels = linkCandidates(activePath ?? "", target, kind);
|
|
for (const rel of rels) {
|
|
try {
|
|
await documents?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" });
|
|
error = null;
|
|
return;
|
|
} catch { /* Try the workspace-root candidate after the note-relative path. */ }
|
|
}
|
|
error = `Could not open ${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) {
|
|
saveSettings(localStorage, next);
|
|
settings = { ...next };
|
|
}
|
|
|
|
onMount(() => {
|
|
try {
|
|
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
|
|
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
|
layoutReady = true;
|
|
} catch { error = "Could not read your layout. Default layout applies for this window."; }
|
|
});
|
|
|
|
$effect(() => {
|
|
if (!layoutReady) 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 = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
|
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
|
settingsReady = true;
|
|
const syncSettings = (event: StorageEvent) => {
|
|
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) settings = parseSettings(event.newValue);
|
|
};
|
|
window.addEventListener("storage", syncSettings);
|
|
window.addEventListener("keydown", onPreferencesKeydown, true);
|
|
return () => {
|
|
window.removeEventListener("storage", syncSettings);
|
|
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) 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}\nClose RuneStone?`, { title: "Close workspace", kind: "warning" })) 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}
|
|
|
|
<div
|
|
class="shell"
|
|
class:has-ribbon={ribbonNavigation.length > 0}
|
|
class:left-open={leftOpen}
|
|
class:right-open={rightOpen}
|
|
role="application"
|
|
aria-label="RuneStone workbench"
|
|
style:--left="{leftWidth}px"
|
|
style:--right="{rightWidth}px"
|
|
style:--bottom="{bottomHeight}px"
|
|
onpointermove={onPointerMove}
|
|
onpointerup={() => (dragging = null)}
|
|
onpointerleave={() => (dragging = null)}
|
|
>
|
|
<header class="header" data-tauri-drag-region>
|
|
<div class="header-left" data-tauri-drag-region>
|
|
<IconButton
|
|
icon="files"
|
|
label="Files"
|
|
active={leftOpen && !$pluginSidebar && leftView === "files"}
|
|
onclick={() => selectLeft("files")}
|
|
/>
|
|
<IconButton
|
|
icon="search"
|
|
label="Search"
|
|
active={leftOpen && !$pluginSidebar && leftView === "search"}
|
|
onclick={() => selectLeft("search")}
|
|
/>
|
|
<IconButton
|
|
icon="bookmark"
|
|
label="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}
|
|
</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="New tab (Ctrl T)" onclick={newTab} />
|
|
<PluginAccessMenu surface="open" compact />
|
|
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
|
</div>
|
|
<div class="header-right" data-tauri-drag-region>
|
|
{#each $pluginNavigation.filter(item => item.toolbar) as item (item.owner + ":" + item.id)}
|
|
<IconButton icon={item.icon ?? "puzzle"} label={item.title}
|
|
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && $pluginEditorActive}
|
|
onclick={() => openPluginView(item.owner, item.id)} />
|
|
{/each}
|
|
<PluginTools />
|
|
<PluginAccessMenu surface="commands" compact />
|
|
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
|
|
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
|
|
<IconButton
|
|
icon="panel-right"
|
|
label={rightOpen ? "Hide outline" : "Show outline"}
|
|
active={rightOpen}
|
|
onclick={() => (rightOpen = !rightOpen)}
|
|
/>
|
|
{#if desktop}<WindowControls onError={(message) => error = message} />{/if}
|
|
</div>
|
|
</header>
|
|
|
|
<nav class="plugin-ribbon" aria-label="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 leftOpen}
|
|
<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">No folder is open.</p>{/if}
|
|
{:else}
|
|
<div class="left-stack">
|
|
<div class="left-layer" class:shown={leftView === "files"}>
|
|
<FileTree
|
|
workspaceRoot={workspace.root}
|
|
showInternal={settings.showInternalFolder}
|
|
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
|
|
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); void documents?.refresh(); }}
|
|
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="Open folder" onclick={chooseWorkspace} />
|
|
<span class="ws">{workspace ? workspace.name : "No workspace"}</span>
|
|
</div>
|
|
<div class="footer-actions">
|
|
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
|
|
<IconButton icon="settings" label="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 view={pane} />
|
|
</div>
|
|
{/each}
|
|
</div>
|
|
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
|
|
{#if buffer?.diskError}
|
|
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
|
|
{:else if buffer?.diskContents != null}
|
|
<div class="conflict" role="alert">
|
|
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span>
|
|
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, true); }}>Use disk version</button>
|
|
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, false); }}>Keep my edits</button>
|
|
<button onclick={() => void saveCopy()}>Save a copy</button>
|
|
</div>
|
|
<details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details>
|
|
{/if}
|
|
<EditorPane
|
|
bind:this={editorPane}
|
|
{tabs}
|
|
hasWorkspace={!!workspace}
|
|
onOpenWorkspace={() => void chooseWorkspace()}
|
|
onNewFile={() => void newFile()}
|
|
onNewNote={(event) => { void newNote(event); }}
|
|
onQuickOpen={() => quickOpen = true}
|
|
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
|
|
{browserOpening}
|
|
{buffer}
|
|
chrome={view}
|
|
{reading}
|
|
{focusLine}
|
|
{onChange}
|
|
onInsertImage={insertImage}
|
|
onRenameTitle={renameNoteTitle}
|
|
tableActions={{ onSearch: searchSelection, onExtract: extractSelection }}
|
|
onToggleReading={() => (reading = !reading)}
|
|
onToggleChrome={toggleChrome}
|
|
onOpenLink={(kind, target) => void openLink(kind, target)}
|
|
/>
|
|
</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={toggleTerminal}
|
|
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
|
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
|
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
|
{/key}
|
|
{:else}
|
|
<p class="placeholder">Open a workspace to start the terminal.</p>
|
|
{/if}
|
|
</section>
|
|
{/if}
|
|
</div>
|
|
|
|
{#if rightOpen}
|
|
<div
|
|
class="gutter gutter-v"
|
|
role="separator"
|
|
onpointerdown={() => (dragging = "right")}
|
|
></div>
|
|
<aside class="right">
|
|
<OutlinePane
|
|
items={outlineItems}
|
|
onJump={(line) => {
|
|
pluginEditorActive.set(false);
|
|
reading = false;
|
|
focusLine = null;
|
|
queueMicrotask(() => {
|
|
focusLine = line;
|
|
});
|
|
}}
|
|
/>
|
|
</aside>
|
|
{/if}
|
|
|
|
<footer class="status">
|
|
<span>{error ?? status}</span>
|
|
{#if workspace}
|
|
<span>{workspace.watch_mode} watch</span>
|
|
{/if}
|
|
<span>{isIde ? "IDE" : "Writer"}</span>
|
|
</footer>
|
|
</div>
|
|
|
|
<style>
|
|
.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 {
|
|
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);
|
|
}
|
|
|
|
.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; }
|
|
|
|
.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-bg-elevated);
|
|
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: var(--rs-bg);
|
|
}
|
|
|
|
.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.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-bg-elevated);
|
|
}
|
|
|
|
.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: var(--rs-bg-elevated);
|
|
}
|
|
|
|
.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>
|