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
+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 () => {};