Release RuneStone 0.1.7 with plugin documents and shared menus

This commit is contained in:
Knotty Wyvern
2026-10-06 09:29:09 -07:00
parent 6b7af0d527
commit 5d0a4a24f9
75 changed files with 2286 additions and 1665 deletions
+32 -161
View File
@@ -1,174 +1,45 @@
<script lang="ts">
import type { MenuAction, MenuItem } from "./menuTypes";
import Icon from "$lib/ui/Icon.svelte";
import { untrack } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import type { MenuItem } from "./menuTypes";
type Props = {
x: number;
y: number;
items: MenuItem[];
onClose: () => void;
label?: string;
};
let { x, y, items, onClose }: Props = $props();
let root: HTMLElement | undefined = $state();
let left = $state(0);
let top = $state(0);
let { x, y, items, onClose, label = "Context actions" }: Props = $props();
$effect(() => {
left = x;
top = y;
void items;
queueMicrotask(() => {
if (!root) {
return;
}
const rect = root.getBoundingClientRect();
left = Math.min(x, window.innerWidth - rect.width - 8);
top = Math.min(y, window.innerHeight - rect.height - 8);
});
const menuX = x, menuY = y, entries = items, name = label;
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
function close(restoreFocus = false) {
root.remove();
if (restoreFocus) previous?.focus({ preventScroll: true });
onClose();
}
function convert(entries: MenuItem[]): ActionMenuItem[] {
return entries.map(item => {
if (item.kind === "sep") return { separator: true };
if (item.kind === "group") return { label: item.label, icon: item.icon, children: convert(item.items) };
return { label: item.label, icon: item.icon, disabled: item.disabled, run: () => {
close(true);
item.run();
} };
});
}
const root = untrack(() => actionMenu(menuX, menuY, convert(entries), () => close(true), name));
const outside = (event: PointerEvent) => { if (!root.contains(event.target as Node)) close(); };
const resize = () => close();
window.addEventListener("pointerdown", outside);
window.addEventListener("resize", resize);
return () => {
root.remove();
window.removeEventListener("pointerdown", outside);
window.removeEventListener("resize", resize);
};
});
function onWindowDown(event: MouseEvent) {
if (root && !root.contains(event.target as Node)) {
onClose();
}
}
function onKey(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
function runAction(item: MenuAction) {
if (item.disabled) {
return;
}
item.run();
onClose();
}
</script>
<svelte:window onmousedown={onWindowDown} onkeydown={onKey} />
<div
bind:this={root}
class="menu"
style:left="{left}px"
style:top="{top}px"
role="menu"
>
{#each items as item, i (i)}
{#if item.kind === "sep"}
<div class="sep"></div>
{:else if item.kind === "group"}
<div class="group">
<div class="group-label" role="none">{item.label}</div>
<div class="flyout" role="menu">
{#each item.items as sub, j (`${i}-${j}`)}
{#if sub.kind === "sep"}
<div class="sep"></div>
{:else if sub.kind === "action"}
<button
type="button"
role="menuitem"
disabled={sub.disabled}
onclick={() => runAction(sub)}
>
{#if sub.icon}<Icon icon={sub.icon} />{/if}
{sub.label}
</button>
{/if}
{/each}
</div>
</div>
{:else}
<button
type="button"
role="menuitem"
disabled={item.disabled}
onclick={() => runAction(item)}
>
{#if item.icon}<Icon icon={item.icon} />{/if}
{item.label}
</button>
{/if}
{/each}
</div>
<style>
.menu,
.flyout {
min-width: 200px;
padding: 4px 0;
background: var(--rs-bg-elevated);
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.menu {
position: fixed;
z-index: 40;
}
.group {
position: relative;
}
.group-label {
padding: 6px 12px;
color: var(--rs-text);
cursor: default;
}
.group-label::after {
content: "▸";
float: right;
color: var(--rs-text-dim);
}
.flyout {
display: none;
position: absolute;
left: 100%;
top: 0;
z-index: 41;
}
.group:hover > .flyout,
.group:focus-within > .flyout {
display: block;
}
button {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
border: 0;
background: transparent;
color: var(--rs-text-strong);
text-align: left;
padding: 6px 12px;
border-radius: var(--rs-control-radius);
}
button:hover,
button:focus-visible {
background: var(--rs-bg-active);
outline: none;
}
button:disabled {
color: var(--rs-text-dim);
opacity: 0.55;
}
.sep {
height: 1px;
margin: 4px 0;
background: var(--rs-border);
}
</style>
+33 -8
View File
@@ -24,13 +24,14 @@
type DropPlace,
type DropTarget,
} from "$lib/workspace/treeDrop";
import { planRename } from "$lib/workspace/renamePath";
import { planRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
import ContextMenu from "./ContextMenu.svelte";
import type { MenuItem } from "./menuTypes";
import TreeNode from "./TreeNode.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { dropWorkspaceImage, highlightImageDrop } from "$lib/editor/workspaceImageDrop";
import { pluginDocuments, pluginDocumentTypes, inspectPluginDocuments, createPluginDocument } from "$lib/plugins/external";
type Props = {
workspaceRoot: string;
@@ -72,6 +73,7 @@
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
let renameRel = $state<string | null>(null);
let renameDraft = $state("");
let renameDocument = false;
let skipClick = false;
let imageLanding = $state(false);
let cancelDrag: (() => void) | undefined;
@@ -117,6 +119,7 @@
try {
const entries = await workspaceList(rel);
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
void inspectPluginDocuments(entries);
error = null;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
@@ -139,6 +142,7 @@
$effect(() => {
void refreshToken;
void $pluginDocumentTypes;
const keys = untrack(() => Object.keys(childrenMap));
for (const key of keys) {
void load(key);
@@ -348,7 +352,8 @@
function startRename(entry: TreeEntry) {
selectOnly(entry.rel_path);
renameRel = entry.rel_path;
renameDraft = entry.name;
renameDocument = entry.kind === "file" && (!!$pluginDocuments[entry.rel_path] || /\.(md|markdown|mdown)$/i.test(entry.name));
renameDraft = renameDocument ? entry.name.replace(/\.[^.]+$/, "") : entry.name;
}
function cancelRename() {
@@ -361,7 +366,7 @@
if (!from) {
return;
}
const plan = planRename(from, renameDraft);
const plan = renameDocument ? planDocumentTitleRename(from, renameDraft) : planRename(from, renameDraft);
cancelRename();
if (plan.action === "noop") {
return;
@@ -531,6 +536,24 @@
void createIn(parent, "note");
},
},
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
run: () => { void (async () => {
const create = type.create!;
const typed = await requestText(create.label, create.defaultName);
if (typed === null) return;
const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), "");
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = "Enter a valid document name."; return; }
const fileName = `${name}.${create.extension}`;
const path = joinRel(parent, fileName);
try {
await createPluginDocument(owner, type.id, path);
expanded = new Set([...expanded, parent]);
await load(parent);
onOpenFile({ name: fileName, rel_path: path, kind: "file" }, true);
} catch (reason) { error = String(reason); }
})(); },
})),
];
}
@@ -551,7 +574,7 @@
{
kind: "action",
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
icon: "files",
icon: "copy",
run: () => { void copyEntries(entries); },
},
{
@@ -569,7 +592,7 @@
{
kind: "action",
label: multiple ? "Copy workspace paths" : "Copy workspace path",
icon: "files",
icon: "copy",
run: () => {
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
},
@@ -577,7 +600,7 @@
{
kind: "action",
label: multiple ? "Copy system paths" : "Copy system path",
icon: "files",
icon: "copy",
run: () => {
void (async () => {
try {
@@ -592,7 +615,7 @@
{
kind: "action",
label: "Show in Explorer",
icon: "folder-open",
icon: "folder",
run: () => {
void (async () => {
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
@@ -604,6 +627,7 @@
{
kind: "action",
label: pinned ? "Unpin" : "Pin",
icon: "pin",
run: () => {
void persistMarks({
...marks,
@@ -614,7 +638,7 @@
{
kind: "action",
label: "Rename",
icon: "pen",
icon: "rename",
disabled: multiple,
run: () => {
startRename(entry);
@@ -714,6 +738,7 @@
{#if menu}
<ContextMenu
label="File actions"
x={menu.x}
y={menu.y}
items={menuItems(menu.entry)}
-3
View File
@@ -303,9 +303,6 @@
}
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
:global(.tab-menu) { width: 244px; border-radius: var(--rs-control-radius); }
:global(.tab-menu button) { border-radius: var(--rs-control-radius); min-height: 30px; }
:global(.tab-menu .table-cell-submenu) { border-radius: var(--rs-control-radius); }
.close {
border: 0;
+6
View File
@@ -4,6 +4,8 @@
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
import { treeFileParts } from "$lib/workspace/chrome";
import TreeNode from "./TreeNode.svelte";
import Icon from "$lib/ui/Icon.svelte";
import { pluginDocuments } from "$lib/plugins/external";
type Props = {
entry: TreeEntry;
@@ -125,6 +127,9 @@
</span>
{/if}
<span class="twist" class:open={isOpen} class:folder={entry.kind === "folder"}></span>
{#if $pluginDocuments[entry.rel_path]}
<span class="document-icon" title={$pluginDocuments[entry.rel_path].title}><Icon icon={$pluginDocuments[entry.rel_path].icon === "kanban" ? "kanban" : "files"} /></span>
{/if}
{#if isRenaming}
<input
class="rename"
@@ -183,6 +188,7 @@
</li>
<style>
.document-icon { display: inline-flex; width: 16px; height: 16px; flex-shrink: 0; margin-right: 5px; }
li {
list-style: none;
}
+88 -17
View File
@@ -1,6 +1,9 @@
<script lang="ts">
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import PluginEditorTab from "$lib/plugins/PluginEditorTab.svelte";
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen } from "$lib/plugins/external";
import { onMount, tick } from "svelte";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
@@ -44,7 +47,7 @@
workspaceWriteBytes,
} from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename } from "$lib/workspace/renamePath";
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";
@@ -109,6 +112,7 @@
let dragging = $state<"left" | "right" | "bottom" | null>(null);
let centerStack: HTMLElement | undefined = $state();
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
const isIde = $derived(view === "Ide");
const outlineItems = $derived(
@@ -202,13 +206,17 @@
}
function selectTab(relPath: string) {
cancelPluginDocumentOpen();
pluginEditorActive.set(false);
focusLine = null;
documents?.select(relPath);
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
}
function newTab() {
cancelPluginDocumentOpen();
if (switching) return;
pluginEditorActive.set(false);
documents ??= createDocuments();
focusLine = null;
documents.newTab();
@@ -276,8 +284,13 @@
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;
@@ -454,7 +467,7 @@
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
event.preventDefault();
void save();
if (!editorPluginVisible) void save();
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
event.preventDefault();
@@ -466,7 +479,7 @@
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "e") {
event.preventDefault();
toggleChrome();
if (!editorPluginVisible) toggleChrome();
}
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
event.preventDefault();
@@ -474,7 +487,9 @@
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
event.preventDefault();
if (activePath) {
if (editorPluginVisible) {
if ($pluginView) closePluginEditor($pluginView.key);
} else if (activePath) {
closeTab(activePath);
}
}
@@ -487,7 +502,7 @@
return;
}
event.preventDefault();
if (!(leftOpen && leftView === "files")) {
if (!editorPluginVisible && !(leftOpen && leftView === "files")) {
void renameActive();
}
}
@@ -495,6 +510,7 @@
function applyPathRename(from: string, to: string) {
documents?.rename(from, to);
renamePluginDocuments(from, to);
}
async function renameNoteTitle(id: string, title: string) {
@@ -566,7 +582,7 @@
const shell = event.currentTarget as HTMLElement;
const rect = shell.getBoundingClientRect();
if (dragging === "left") {
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left));
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - ($pluginNavigation.length ? 44 : 0)));
}
if (dragging === "right") {
rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX));
@@ -608,6 +624,22 @@
void restoreLast();
let disposed = false;
const unlisteners: (() => void)[] = [];
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) => {
@@ -617,6 +649,7 @@
refreshTimer = setTimeout(() => {
refreshToken++;
void documents?.refresh();
notifyPluginWorkspace();
}, 200);
}).then(register).catch(err => error = String(err));
let closing = false;
@@ -651,6 +684,7 @@
<div
class="shell"
class:has-ribbon={$pluginNavigation.length > 0}
class:left-open={leftOpen}
class:right-open={rightOpen}
role="application"
@@ -685,16 +719,17 @@
</div>
<div class="header-center" data-tauri-drag-region>
{#if tabs.length > 0}
<TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab}
<TabBar {tabs} activePath={editorPluginVisible ? null : activePath} onSelect={selectTab} onClose={closeTab}
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)}
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} />
{/if}
<PluginEditorTab />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div>
<div class="header-right" data-tauri-drag-region>
<PluginTools />
<IconButton icon="save" label="Save" disabled={!dirty || saving} onclick={() => void save()} />
<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"
@@ -706,6 +741,18 @@
</div>
</header>
<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={$pluginNavigation.length === 0}>
{#each $pluginNavigation as item (`${item.owner}:${item.id}`)}
<IconButton
icon={item.icon === "list" || item.icon === "kanban" ? item.icon : "puzzle"}
label={item.title}
side="right"
active={$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">
@@ -716,7 +763,7 @@
<div class="left-layer" class:shown={leftView === "files"}>
<FileTree
workspaceRoot={workspace.root}
{activePath}
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
{refreshToken}
keysActive={leftView === "files"}
@@ -727,7 +774,7 @@
status = message;
error = null;
}}
onEntryGone={() => { void documents?.refresh(); }}
onEntryGone={(path) => { removePluginDocuments(path); void documents?.refresh(); }}
onEntryRenamed={applyPathRename}
/>
</div>
@@ -760,7 +807,8 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<main class="center">
<div class="editor-host">
{#each $pluginEditors as view (view.key)}<PluginEditor {view} />{/each}
<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}
@@ -824,6 +872,7 @@
<OutlinePane
items={outlineItems}
onJump={(line) => {
pluginEditorActive.set(false);
reading = false;
focusLine = null;
queueMicrotask(() => {
@@ -855,23 +904,43 @@
.shell {
height: 100vh;
display: grid;
grid-template-columns: minmax(0, 1fr);
--ribbon-width: 0px;
grid-template-columns: var(--ribbon-width) minmax(0, 1fr);
grid-template-rows: 36px minmax(0, 1fr) 22px;
background: var(--rs-bg);
}
.shell.left-open {
grid-template-columns: var(--left) 1px minmax(0, 1fr);
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr);
}
.shell.right-open {
grid-template-columns: minmax(0, 1fr) 1px var(--right);
grid-template-columns: var(--ribbon-width) minmax(0, 1fr) 1px var(--right);
}
.shell.left-open.right-open {
grid-template-columns: var(--left) 1px minmax(0, 1fr) 1px var(--right);
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;
@@ -885,7 +954,7 @@
}
.shell.left-open .header {
grid-template-columns: var(--left) minmax(0, 1fr) auto;
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) auto;
}
.shell.right-open .header {
@@ -893,7 +962,7 @@
}
.shell.left-open.right-open .header {
grid-template-columns: var(--left) minmax(0, 1fr) minmax(max-content, var(--right));
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) minmax(max-content, var(--right));
}
.header-left,
@@ -977,6 +1046,8 @@
position: relative;
}
.editor-host.plugin-covered { display: none; }
.left,
.right {
background: var(--rs-bg-elevated);
+3 -2
View File
@@ -1,11 +1,11 @@
import type { IconName } from "$lib/ui/IconButton.svelte";
import type { ActionIcon } from "$lib/ui/actionIcons";
export type MenuAction = {
kind: "action";
label: string;
run: () => void;
disabled?: boolean;
icon?: IconName;
icon?: ActionIcon;
};
export type MenuSep = { kind: "sep" };
@@ -13,6 +13,7 @@ export type MenuSep = { kind: "sep" };
export type MenuGroup = {
kind: "group";
label: string;
icon?: ActionIcon;
items: MenuItem[];
};
+36
View File
@@ -0,0 +1,36 @@
<script lang="ts">
import { untrack } from "svelte";
import { pluginView, pluginEditorActive, mountPluginView, type OpenPluginView } from "./external";
let { view }: { view: OpenPluginView } = $props();
let host: HTMLDivElement | undefined = $state();
let error = $state("");
$effect(() => {
const element = host;
if (!element) return;
error = "";
let cancelled = false;
let cleanup: (() => void | Promise<void>) | undefined;
void untrack(() => mountPluginView(view.owner, view.id, element, view.document)).then(dispose => {
if (cancelled) void Promise.resolve(dispose()).catch(() => {});
else cleanup = dispose;
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
void Promise.resolve(cleanup?.()).catch(reason => console.error("Plugin view cleanup failed", reason));
};
});
</script>
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane" class:inactive={!$pluginEditorActive || $pluginView?.key !== view.key}
role="tabpanel" aria-label={view.title} tabindex="-1">
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="plugin-editor-content" bind:this={host}></div>
</div>
<style>
.plugin-editor-pane { display: flex; flex: 1; min-height: 0; min-width: 0; flex-direction: column; overflow: hidden; }
.plugin-editor-pane.inactive { display: none; }
.plugin-editor-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; }
.error { color: var(--rs-error); padding: 12px; }
</style>
+31
View File
@@ -0,0 +1,31 @@
<script lang="ts">
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor } from "./external";
</script>
{#if $pluginEditors.length}
<div class="plugin-tabs" role="tablist" aria-label="Plugin views">
{#each $pluginEditors as view (view.key)}
<div class="plugin-tab" class:active={$pluginEditorActive && $pluginView?.key === view.key}>
<button role="tab" aria-selected={$pluginEditorActive && $pluginView?.key === view.key} aria-controls={`plugin-editor-${view.key}`}
title={view.document?.path ?? view.title} onclick={() => selectPluginEditor(view)}
onauxclick={event => { if (event.button === 1) { event.preventDefault(); closePluginEditor(view.key); } }}>
<Icon icon={view.icon === "file" ? "files" : view.icon ?? "puzzle"} /><span>{view.title}</span>
</button>
<IconButton icon="close" label={`Close ${view.title}`} onclick={() => closePluginEditor(view.key)} />
</div>
{/each}
</div>
{/if}
<style>
.plugin-tabs { display: flex; flex-shrink: 1; min-width: 0; max-width: 70%; overflow-x: auto; }
.plugin-tab { display: flex; align-items: center; min-width: 0; border: 1px solid transparent; border-radius: var(--rs-control-radius); }
.plugin-tab.active { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
.plugin-tab:hover { background: var(--rs-bg-active); }
button[role="tab"] { display: flex; align-items: center; gap: 7px; min-width: 0; height: 32px; padding: 0 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
button[role="tab"]:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
:global(.plugin-tab svg) { width: 16px; height: 16px; flex-shrink: 0; }
</style>
+71 -22
View File
@@ -6,18 +6,27 @@
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
const desktop = isTauri();
const installDateFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric", month: "short", day: "numeric",
hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "short",
});
let busy = $state(false);
let error = $state("");
let message = $state("");
let candidates = $state<Candidate[]>([]);
let selected = $state<string[]>([]);
let plan = $state<RemovalPlan | null>(null);
let gitForm = $state(false);
let gitUrl = $state("");
let gitTag = $state("");
let gitToken = $state("");
let disposed = false;
let modal: HTMLDialogElement | undefined = $state();
let cancelButton: HTMLButtonElement | undefined = $state();
let previous: HTMLElement | null = null;
const external = $derived($installedPlugins.plugins);
$effect(() => {
if (modal && (plan || candidates.length)) {
if (modal && (plan || candidates.length || gitForm)) {
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
if (!busy) cancelButton?.focus();
}
@@ -26,19 +35,19 @@
async function cancel() {
if (busy) return;
const pending = tokens();
plan = null; candidates = []; selected = [];
plan = null; candidates = []; selected = []; gitForm = false; gitToken = "";
modal?.close(); previous?.focus();
if (pending.length) await invoke("plugins_cancel", { tokens: pending }).catch(reason => error = String(reason));
}
onDestroy(() => { const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
onDestroy(() => { disposed = true; gitToken = ""; const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
async function run(action: () => Promise<void>) {
busy = true; error = ""; message = "";
try { await action(); } catch (reason) { error = String(reason); }
finally { busy = false; }
}
async function choose(folder: boolean) {
async function choose() {
await run(async () => {
candidates = await invoke<Candidate[]>("plugins_choose", { folder });
candidates = await invoke<Candidate[]>("plugins_choose");
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
});
}
@@ -51,6 +60,17 @@
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
});
}
async function fromGit() {
await run(async () => {
try {
const result = await invoke<Candidate[]>("plugins_from_git", { url: gitUrl.trim(), tag: gitTag.trim(), token: gitToken || null });
if (disposed) { await invoke("plugins_cancel", { tokens: result.map(item => item.token) }); return; }
candidates = result;
selected = result.filter(item => !item.error && item.manifest).map(item => item.token);
gitForm = false;
} finally { gitToken = ""; }
});
}
async function toggle(id: string, enabled: boolean, hash?: string) {
await run(async () => {
await setPluginEnabled(id, enabled, hash);
@@ -73,7 +93,7 @@
event.stopPropagation();
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
if (event.key !== "Tab" || !modal) return;
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled)")];
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled),select:not(:disabled)")];
const first = controls[0], last = controls.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
@@ -81,10 +101,10 @@
</script>
<h2>Plug-ins</h2>
<p>Install a package file or select a folder containing plugins.</p>
<p>Install a plugin ZIP file or get a release from a Git repository link.</p>
<div class="toolbar">
<button disabled={!desktop || busy} onclick={() => choose(false)}><Icon icon="file-plus" />Install from file</button>
<button disabled={!desktop || busy} onclick={() => choose(true)}><Icon icon="folder-plus" />Install from folder</button>
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />Install plugin ZIP</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />Install from Git link</button>
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} />
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button>
</div>
@@ -100,16 +120,26 @@
<div><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small></div>
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.enabled} disabled={busy || plugin.removal} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
</div>
<p class="path">{plugin.path}</p>
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
<div class="actions">
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
<button disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)}><Icon icon="folder-open" />Show files</button>
{#if plugin.removal}
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
{:else}
<button class="danger" disabled={busy} aria-label={`Uninstall ${plugin.manifest.name}`} onclick={() => prepare(plugin)}><Icon icon="trash" />Uninstall</button>
{/if}
<div class="status">
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
<span class="note">
{#if plugin.installedAt != null}
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
{:else}
Install date unknown
{/if}
</span>
</div>
<div class="controls">
<IconButton icon="folder-open" label="Show files" disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
{#if plugin.removal}
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
{:else}
<span class="danger"><IconButton icon="trash" label="Uninstall" disabled={busy} onclick={() => prepare(plugin)} /></span>
{/if}
</div>
</div>
</div>
{/each}
@@ -117,9 +147,21 @@
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
{#if candidates.length || plan}
{#if candidates.length || plan || gitForm}
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
{#if plan}
{#if gitForm}
<h2 id="plugin-dialog-title">Install from Git link</h2>
<p>Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.</p>
<form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}>
<label class="field">Repository link<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
<label class="field">Release tag (optional)<input bind:value={gitTag} disabled={busy} placeholder="Latest release" maxlength="200" /></label>
<label class="field">Access token (optional)<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
<p class="note">Private repositories need a token with read access. RuneStone does not save the token.</p>
{#if gitUrl.trim().startsWith("http:")}<p class="note">HTTP sends the token and package without encryption. Use it only for a trusted local server.</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? "Downloading…" : "Review release"}</button></footer>
</form>
{:else if plan}
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
<p class="path">{plan.plugin.path}</p>
@@ -155,13 +197,18 @@
button:hover:not(:disabled) { background: var(--rs-bg-active); }
button:disabled { opacity: .5; }
.toolbar, .actions, footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 18px 14px; margin-bottom: 12px; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 18px 0; }
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 14px 10px; margin-bottom: 10px; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 14px 0 8px; }
.row > div { min-width: 0; overflow-wrap: anywhere; }
.row p { margin: 5px 0; font-size: 12px; }
label { font-weight: 500; }
.path { overflow-wrap: anywhere; font-size: 11px; }
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
.badge { margin-right: auto; }
.status { display: flex; flex: 1 1 240px; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
.controls { display: flex; align-items: center; gap: 6px; margin-left: auto; }
.controls :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
.controls .danger { display: flex; }
.controls .danger :global(.icon-btn) { color: var(--rs-error); }
.error { color: var(--rs-error); white-space: pre-wrap; }
.saved { color: var(--rs-ok); min-height: 20px; }
.danger { color: var(--rs-error); }
@@ -174,4 +221,6 @@
footer { justify-content: flex-end; margin-top: 24px; }
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
.candidate label { display: flex; gap: 8px; }
.field { display: flex; flex-direction: column; gap: 6px; margin: 14px 0; }
.field input { min-width: 0; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
</style>
+3 -3
View File
@@ -12,7 +12,7 @@
const view = $pluginView;
const element = host;
const modal = dialog;
if (!view || !element || !modal) return;
if (!view || view.placement === "editor" || !element || !modal) return;
previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
modal.showModal(); error = "";
let cancelled = false;
@@ -41,8 +41,8 @@
{/if}
</div>
{/if}
{#if error && !$pluginView}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
{#if $pluginView}
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
{#if $pluginView?.placement === "dialog"}
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header>
{#if error}<p class="error" role="alert">{error}</p>{/if}
+135 -9
View File
@@ -1,14 +1,20 @@
import { writable } from "svelte/store";
import { get, writable } from "svelte/store";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { workspaceList, workspaceRead, workspaceWrite } from "../workspace/api";
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
import { ExternalSession, deadline } from "./externalSession";
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose } from "./sdk";
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
export const externalErrors = writable<Record<string, string>>({});
export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]);
export const pluginView = writable<{ owner: string; id: string; title: string } | null>(null);
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" }
export const pluginView = writable<OpenPluginView | null>(null);
export const pluginEditors = writable<OpenPluginView[]>([]);
export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]);
export const pluginDocuments = writable<Record<string, { icon: "kanban" | "file"; title: string }>>({});
export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]);
export const pluginEditorActive = writable(false);
export const pluginServiceError = writable("");
export const restartPlugins = writable<string[]>([]);
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
@@ -18,8 +24,98 @@ const restarted = new Set<string>();
let queue: Promise<void> = Promise.resolve();
let started = false;
let generation = 0;
let documentOpenVersion = 0;
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
const workspaceListeners = new Set<() => void>();
let renameDocument: ((path: string, name: string) => Promise<string>) | undefined;
export function handlePluginDocumentRename(handler: (path: string, name: string) => Promise<string>): () => void {
renameDocument = handler;
return () => { if (renameDocument === handler) renameDocument = undefined; };
}
let canWrite: (path: string) => void = () => {};
export function guardPluginWrites(guard: (path: string) => void): () => void {
canWrite = guard;
return () => { if (canWrite === guard) canWrite = () => {}; };
}
export function notifyPluginWorkspace() { for (const listener of workspaceListeners) listener(); }
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
export function closePluginEditor(key: string) {
cancelPluginDocumentOpen();
const remaining = get(pluginEditors).filter(view => view.key !== key);
pluginEditors.set(remaining);
if (get(pluginView)?.key === key) {
pluginView.set(remaining.at(-1) ?? null);
pluginEditorActive.set(remaining.length > 0);
}
}
export function renamePluginDocuments(from: string, to: string) {
const editors = get(pluginEditors).map(view => {
const path = view.document?.path;
if (!path || (path !== from && !path.startsWith(from + "/"))) return view;
view.document!.path = to + path.slice(from.length);
return { ...view, title: documentTitle(view.document!.path) };
});
pluginEditors.set(editors);
const selected = editors.find(view => view.key === get(pluginView)?.key);
if (selected) pluginView.set(selected);
pluginDocuments.set({}); notifyPluginWorkspace();
}
export function removePluginDocuments(path: string) {
for (const view of get(pluginEditors)) if (view.document && (view.document.path === path || view.document.path.startsWith(path + "/"))) closePluginEditor(view.key);
pluginDocuments.set({}); notifyPluginWorkspace();
}
const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, "");
async function identifyDocument(path: string) {
const types = get(pluginDocumentTypes).filter(({ type }) => type.extensions.includes(path.split(".").at(-1)!.toLowerCase()));
if (!types.length) return null;
let source: string | undefined;
for (const { owner, type } of types) {
if (!sessions.has(owner)) continue;
try {
if (type.content !== "binary" && source === undefined) source = await workspaceRead(path);
const result = type.identify(path, type.content === "binary" ? "" : source!);
if (result && typeof result.id === "string" && result.id.trim()) return { owner, type, document: { id: result.id, path } };
} catch { /* Invalid documents remain available in the text editor. */ }
}
return null;
}
export async function inspectPluginDocuments(entries: { rel_path: string; kind: string }[]) {
const updates: Record<string, { icon: "kanban" | "file"; title: string } | null> = {};
await Promise.all(entries.filter(entry => entry.kind === "file").map(async entry => {
try { const match = await identifyDocument(entry.rel_path); updates[entry.rel_path] = match ? { icon: match.type.icon ?? "file", title: match.type.title } : null; }
catch { updates[entry.rel_path] = null; }
}));
pluginDocuments.update(current => {
const next = { ...current };
for (const [path, value] of Object.entries(updates)) { if (value) next[path] = value; else delete next[path]; }
return next;
});
}
export async function openPluginDocument(path: string, current: () => boolean = () => true): Promise<boolean> {
const request = ++documentOpenVersion;
const match = await identifyDocument(path);
if (request !== documentOpenVersion || !current()) return true;
if (!match) return false;
const { owner, type, document } = match;
const existing = get(pluginEditors).find(view => view.owner === owner && view.id === type.id && view.document?.path === path && view.document.id === document.id);
if (existing) { selectPluginEditor(existing); return true; }
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon };
pluginEditors.update(views => [...views, view]); selectPluginEditor(view);
return true;
}
export async function createPluginDocument(owner: string, id: string, path: string) {
const session = sessions.get(owner)?.session;
const create = session?.documentTypes.get(id)?.create;
if (!create || session!.controller.signal.aborted) throw new Error("This document type is unavailable.");
const contents = create.contents();
if (typeof contents !== "string") throw new Error("Document contents must be text.");
await invoke("workspace_create", { rel: path, kind: "file", contents });
notifyPluginWorkspace();
}
function publish() {
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon }))));
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
pluginTools.set([...sessions].flatMap(([owner, { session }]) => [
...[...session.commands.values()].map(({ id, title }) => ({ owner, id, title, kind: "command" as const })),
...[...session.views.values()].map(({ id, title }) => ({ owner, id, title, kind: "view" as const })),
@@ -34,6 +130,8 @@ async function stop(id: string) {
const loaded = sessions.get(id);
if (!loaded) return;
sessions.delete(id);
for (const view of get(pluginEditors)) if (view.owner === id) closePluginEditor(view.key);
pluginDocuments.set({});
pluginView.update(view => view?.owner === id ? null : view);
restarted.add(id); restartPlugins.set([...restarted]);
let error: string | undefined;
@@ -42,19 +140,47 @@ async function stop(id: string) {
}
function show(owner: string, id: string) {
const view = sessions.get(owner)?.session.views.get(id);
if (view) pluginView.set({ owner, id, title: view.title });
if (view) {
const placement = view.placement ?? "dialog";
if (placement === "editor") {
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement };
if (!existing) pluginEditors.update(views => [...views, editor]);
selectPluginEditor(editor); return;
}
const current = get(pluginView);
if (current?.owner !== owner || current.id !== id) {
pluginView.set({ key: crypto.randomUUID(), owner, id, title: view.title, placement });
}
pluginEditorActive.set(false);
}
}
async function activate(row: InstalledPlugin) {
const id = row.manifest.id;
let leased = false;
const session = new ExternalSession(id, {
workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, write: workspaceWrite },
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
readBytes: workspaceReadBytes,
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
readOptional: rel => invoke<string | null>("workspace_read", { rel, missingOk: true }),
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); },
},
settings: {
read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })),
write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); },
},
assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) },
}, publish, view => show(id, view));
}, publish, view => show(id, view), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => {
const match = await identifyDocument(document.path);
if (session.controller.signal.aborted) throw new Error("This plugin is disabled.");
if (!match || match.owner !== id || match.document.id !== document.id)
throw new Error("The document changed. Refresh before renaming it.");
if (!renameDocument) throw new Error("Document renaming is unavailable.");
canWrite(document.path);
return renameDocument(document.path, name);
});
try {
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
@@ -104,10 +230,10 @@ export async function runPluginCommand(owner: string, id: string) {
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
}
export function openPluginView(owner: string, id: string) { show(owner, id); }
export async function mountPluginView(owner: string, id: string, element: HTMLElement): Promise<Dispose> {
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
const session = sessions.get(owner)?.session;
if (!session) throw new Error("The plugin is disabled.");
return session.mount(id, element);
return session.mount(id, element, document);
}
export function startExternalPlugins(): () => void {
if (!isTauri() || started) return () => {};
+33 -7
View File
@@ -1,5 +1,5 @@
import { pluginHost, type ContributionRegistry } from "./registry.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView } from "./sdk.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
let timer: ReturnType<typeof setTimeout>;
@@ -11,6 +11,7 @@ export class ExternalSession {
readonly controller = new AbortController();
readonly commands = new Map<string, PluginCommand>();
readonly views = new Map<string, PluginView>();
readonly documentTypes = new Map<string, PluginDocumentType>();
private cleanups: Dispose[] = [];
private stopped = false;
private activation: Promise<void> = Promise.resolve();
@@ -23,7 +24,11 @@ export class ExternalSession {
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
private changed: () => void;
private show: (id: string) => void;
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost) {
private openDocument: (path: string) => Promise<void>;
private renameDocument?: PluginApi["renameDocument"];
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"]) {
this.openDocument = openDocument;
this.renameDocument = renameDocument;
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
}
private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
@@ -37,12 +42,33 @@ export class ExternalSession {
id: this.id, signal: this.controller.signal,
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
registerCommand: item => { if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
registerView: item => { if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
registerView: item => { if (item.placement !== undefined && !["dialog", "editor"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
registerDocumentType: item => {
if (item.content !== undefined && !["text", "binary"].includes(item.content)) throw new Error("Invalid document content type.");
if (typeof item.identify !== "function" || typeof item.mount !== "function" || !Array.isArray(item.extensions) || !item.extensions.length || item.extensions.some(ext => !/^[a-z0-9]+$/.test(ext)) || (item.icon && !["kanban", "file"].includes(item.icon))) throw new Error("Invalid document type.");
if (item.create && (!item.create.label?.trim() || !item.create.defaultName?.trim() || !item.extensions.includes(item.create.extension) || typeof item.create.contents !== "function")) throw new Error("Invalid document creation action.");
register(this.documentTypes, item);
},
openDocument: path => { this.check(); return this.openDocument(path); },
...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}),
openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); },
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
workspace: {
...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => {
this.check(); const off = this.services.workspace.subscribe!(() => { if (!this.stopped) listener(); });
let active = true;
const cleanup: Dispose = () => {
if (!active) return;
active = false; this.cleanups = this.cleanups.filter(item => item !== cleanup);
return off();
};
this.cleanups.push(cleanup); return cleanup;
} } : {}),
list: path => { this.check(); return this.services.workspace.list(path); },
read: path => { this.check(); return this.services.workspace.read(path); },
...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}),
...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}),
...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}),
write: (path, value, expected) => { this.check(); if (typeof expected !== "string") throw new Error("Supply the original file text before writing."); return this.services.workspace.write(path, value, expected); },
},
settings: {
@@ -62,10 +88,10 @@ export class ExternalSession {
await deadline(this.activation);
}
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
async mount(id: string, element: HTMLElement): Promise<Dispose> {
this.check(); const view = this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
this.check(); const view = document ? this.documentTypes.get(id) : this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
let cleaning: Promise<void> | undefined;
const pending = Promise.resolve().then(() => { this.check(); return view.mount(element); });
const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element); });
const cleanup = () => {
cleaning ??= (async () => {
const dispose = await pending;
@@ -81,7 +107,7 @@ export class ExternalSession {
}
stop(): Promise<void> {
if (this.stopping) return this.stopping;
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.changed();
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.changed();
for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => {
const errors: unknown[] = [];
+20 -2
View File
@@ -2,19 +2,37 @@ import type { Contributions } from "./contracts.ts";
/** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
export interface PluginView { id: string; title: string; placement?: "dialog" | "editor"; navigation?: boolean; icon?: "list" | "kanban" | "puzzle"; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
export interface PluginDocumentContext { id: string; path: string }
export interface PluginDocumentType {
id: string;
title: string;
icon?: "kanban" | "file";
extensions: string[];
content?: "text" | "binary";
identify(path: string, source: string): { id: string } | null;
create?: { label: string; defaultName: string; extension: string; contents(): string };
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
readonly id: string;
readonly signal: AbortSignal;
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
registerCommand(command: PluginCommand): void;
registerView(view: PluginView): void;
registerDocumentType(type: PluginDocumentType): void;
openDocument(path: string): Promise<void>;
renameDocument?(document: PluginDocumentContext, name: string): Promise<string>;
openView(id: string): void;
onDispose(cleanup: Dispose): void;
workspace: {
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
read(path: string): Promise<string>;
readBytes?(path: string): Promise<Uint8Array>;
readOptional?(path: string): Promise<string | null>;
create?(path: string, contents: string): Promise<void>;
write(path: string, contents: string, expected: string): Promise<void>;
subscribe?(listener: () => void): Dispose;
};
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
assets: { read(path: string): Promise<Uint8Array> };
@@ -24,7 +42,7 @@ export interface ExternalManifest {
schemaVersion: 1; id: string; name: string; author: string; description: string;
version: string; apiVersion: 1; entry: string; access: "full-app";
}
export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; path: string; error: string | null; removal: boolean }
export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; installedAt: number | null; path: string; error: string | null; removal: boolean }
export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] }
export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null }
export interface RemovalPlan { token: string; plugin: InstalledPlugin }
+7
View File
@@ -1,5 +1,12 @@
:root {
--rs-control-radius: 5px;
--rs-menu-width: 264px;
--rs-menu-padding: 5px;
--rs-menu-row-height: 30px;
--rs-menu-row-padding: 6px 10px;
--rs-menu-icon-size: 17px;
--rs-menu-icon-gap: 10px;
--rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
--rs-item-selection-border: var(--rs-accent);
+1 -1
View File
@@ -10,7 +10,7 @@
<circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" />
{:else if icon === "puzzle"}
<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" />
{:else if icon === "up" || icon === "down"}
{:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link"}
{@html actionIcons[icon]}
{:else if icon === "more"}
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
+2
View File
@@ -5,6 +5,8 @@
| "settings"
| "help"
| "puzzle"
| "link"
| "kanban"
| "split"
| "more"
| "chevron-down"
+5
View File
@@ -1,5 +1,10 @@
// Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = {
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
'folder-plus': '<path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2zM12 10v6M9 13h6"/>',
pin: '<path d="m16 3 5 5-4 1-3 3 1 4-2 2-7-7 2-2 4 1 3-3ZM8 16l-5 5"/>',
book: '<path d="M12 6v15M3 3h5a4 4 0 0 1 4 3 4 4 0 0 1 4-3h5v15h-5a4 4 0 0 0-4 3 4 4 0 0 0-4-3H3Z"/>',
folder: '<path d="M3 7V4h6l3 3h9v13H3Z"/>',
+6 -4
View File
@@ -1,9 +1,9 @@
import { actionIcon, type ActionIcon } from "./actionIcons";
export type ActionMenuItem = { label: string; icon: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") {
const root = document.createElement("div"); root.className = "table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
const root = document.createElement("div"); root.className = "rs-menu table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined;
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
const submenus = new Map<HTMLButtonElement, HTMLElement>();
@@ -25,12 +25,14 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled;
if (item.title) button.title = item.title;
const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label;
button.append(actionIcon(item.icon), label); panel.append(button);
const icon = item.icon ? actionIcon(item.icon) : document.createElement("span");
icon.classList.add("action-icon"); icon.setAttribute("aria-hidden", "true");
button.append(icon, label); panel.append(button);
if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); }
if (item.children) {
button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false");
const arrow = actionIcon("chevron"); arrow.classList.add("action-chevron"); button.append(arrow);
const submenu = document.createElement("div"); submenu.className = "table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
const submenu = document.createElement("div"); submenu.className = "rs-menu table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu);
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
button.addEventListener("click", () => reveal(button, submenu, true));
+42
View File
@@ -0,0 +1,42 @@
.rs-menu {
position: fixed;
z-index: 1000;
width: var(--rs-menu-width);
max-width: calc(100vw - 16px);
max-height: calc(100vh - 16px);
overflow-y: auto;
padding: var(--rs-menu-padding);
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: var(--rs-bg-elevated);
color: var(--rs-text);
box-shadow: var(--rs-menu-shadow);
font: 13px/1.4 var(--rs-font-ui);
}
.rs-menu.table-cell-submenu { z-index: 1001; }
.rs-menu > button {
display: flex;
align-items: center;
gap: var(--rs-menu-icon-gap);
width: 100%;
min-height: var(--rs-menu-row-height);
padding: var(--rs-menu-row-padding);
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.rs-menu > button:disabled { opacity: .4; cursor: default; }
.rs-menu > button:not(:disabled):is(:hover, :focus-visible, [aria-expanded="true"]) {
background: var(--rs-bg-active);
outline: none;
}
.rs-menu > hr { margin: 4px 0; border: 0; border-top: 1px solid var(--rs-border); }
.rs-menu > button > .action-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex-basis: var(--rs-menu-icon-size); }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex-basis: 13px; }
+4
View File
@@ -43,6 +43,10 @@ export function workspaceRead(rel: string): Promise<string> {
return invoke("workspace_read", { rel });
}
export async function workspaceReadBytes(rel: string): Promise<Uint8Array> {
return new Uint8Array(await invoke<ArrayBuffer>("workspace_read_bytes", { rel }));
}
export function workspaceWrite(rel: string, contents: string, expected?: string): Promise<void> {
return invoke("workspace_write", { rel, contents, expected });
}
+8 -2
View File
@@ -43,10 +43,16 @@ export function planTitleRename(fromRel: string, title: string): RenamePlan {
/** The writing title edits the basename, keeping the note's Markdown format. */
export function planMarkdownTitleRename(fromRel: string, title: string): RenamePlan {
const extension = fromRel.match(/\.(?:md|markdown|mdown)$/i)?.[0] ?? ".md";
return planDocumentTitleRename(fromRel, title, extension);
}
export function planDocumentTitleRename(fromRel: string, title: string, extension = fromRel.match(/\.[^./]+$/)?.[0] ?? ""): RenamePlan {
const name = title.trim();
if (!name || name.startsWith(".") || /[<>:"/\\|?*\u0000-\u001f]/.test(name))
return { action: "error", message: "Enter a document name without a leading dot or reserved filename characters." };
const current = fromRel.split("/").pop() ?? fromRel;
if (name === current.slice(0, -extension.length)) return { action: "noop" };
const stem = name.toLowerCase().endsWith(extension.toLowerCase())
if (name === (extension ? current.slice(0, -extension.length) : current)) return { action: "noop" };
const stem = extension && name.toLowerCase().endsWith(extension.toLowerCase())
? name.slice(0, -extension.length).trim() : name;
if (!stem) return { action: "error", message: "Name is empty" };
return planRename(fromRel, stem + extension);