Add completion, browser integration, and workspace improvements

This commit is contained in:
Knotty Wyvern
2026-10-07 11:25:17 -07:00
parent dd9fc64676
commit a8b1defb9d
86 changed files with 3524 additions and 203 deletions
+62
View File
@@ -0,0 +1,62 @@
import { Prec, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView, keymap, ViewPlugin, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { completionHub } from "./hub";
import type { CompletionHandle } from "./contracts";
class Ghost extends WidgetType {
constructor(readonly text: string) { super(); }
eq(other: Ghost) { return other.text === this.text; }
toDOM() { const span = document.createElement("span"); span.className = "rs-completion-ghost"; span.textContent = this.text; span.setAttribute("aria-hidden", "true"); return span; }
}
const preview = StateEffect.define<{ text: string; caret: number } | null>();
const ghosts = StateField.define({
create: () => Decoration.none,
update(value, transaction) {
if (transaction.docChanged || transaction.selection) value = Decoration.none;
for (const effect of transaction.effects) if (effect.is(preview)) value = effect.value
? Decoration.set([Decoration.widget({ widget: new Ghost(effect.value.text), side: 1 }).range(effect.value.caret)]) : Decoration.none;
return value;
},
provide: field => EditorView.decorations.from(field),
});
const handles = new WeakMap<EditorView, CompletionHandle>();
export function completionExtension(documentId: string) {
return [ghosts, EditorView.baseTheme({ ".rs-completion-ghost": { opacity: "0.65", fontStyle: "italic", pointerEvents: "none" } }),
ViewPlugin.fromClass(class {
handle: CompletionHandle;
disposed = false;
sequence = 0;
revision = 0;
constructor(readonly view: EditorView) {
this.handle = completionHub.registerSurface({
id: `writer:${documentId}:${crypto.randomUUID()}`,
snapshot: () => ({ documentId, revision: this.revision, text: view.state.doc.toString(), caret: view.state.selection.main.head,
selectionEnd: view.state.selection.ranges.length > 1 ? -1 : view.state.selection.main.anchor,
focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, kind: "prose", language: "markdown" }),
preview: text => {
const sequence = ++this.sequence, caret = view.state.selection.main.head;
queueMicrotask(() => { if (!this.disposed && this.sequence === sequence) view.dispatch({ effects: preview.of(text ? { text, caret } : null) }); });
},
insert: (text, expected) => {
if (this.revision !== expected.revision || view.state.selection.main.head !== expected.caret) return false;
view.dispatch({ changes: { from: expected.caret, insert: text }, selection: { anchor: expected.caret + text.length }, userEvent: "input.complete", annotations: isolateHistory.of("full") });
return true;
},
});
handles.set(view, this.handle);
}
update(update: import("@codemirror/view").ViewUpdate) {
if (update.docChanged) this.revision++;
if (update.docChanged || update.selectionSet || update.focusChanged) this.handle.changed();
}
destroy() { this.disposed = true; this.handle.dispose(); handles.delete(this.view); }
}),
Prec.high(keymap.of([
{ key: "Tab", run: view => !view.composing && !!handles.get(view)?.accept() },
{ key: "Escape", run: view => !!handles.get(view)?.dismiss() },
{ key: "Mod-Alt-Space", run: view => { handles.get(view)?.request(); return true; } },
{ key: "Mod-Alt-ArrowRight", run: view => !!handles.get(view)?.accept(true) },
])),
EditorView.domEventHandlers({ compositionstart: (_event, view) => { handles.get(view)?.dismiss(); } }),
];
}
+58
View File
@@ -0,0 +1,58 @@
export type CompletionDispose = () => void;
export interface CompletionSnapshot {
documentId: string;
revision: string | number;
text: string;
caret: number;
selectionEnd: number;
focused: boolean;
composing?: boolean;
sensitive?: boolean;
readOnly?: boolean;
kind: "prose" | "code";
language?: string;
}
export interface CompletionRequest {
surfaceId: string;
documentId: string;
revision: string | number;
prefix: string;
suffix: string;
kind: "prose" | "code";
language: string;
manual: boolean;
signal: AbortSignal;
}
export interface CompletionProvider {
id: string;
delayMs?: number;
timeoutMs?: number;
complete(request: CompletionRequest, publish: (text: string) => void): Promise<string | null>;
}
export interface CompletionSurface {
id: string;
snapshot(): CompletionSnapshot;
preview(text: string | null): void;
insert(text: string, expected: CompletionSnapshot): boolean;
}
export interface CompletionHandle {
changed(): void;
request(): void;
accept(word?: boolean): boolean;
dismiss(): boolean;
dispose(): void;
}
export interface CompletionTransportRequest {
endpoint: string;
route: "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate";
body?: string;
timeoutMs?: number;
}
export interface CompletionApi {
version: 1;
registerProvider(provider: CompletionProvider): CompletionDispose;
registerSurface(surface: CompletionSurface): CompletionHandle;
registerInput(element: HTMLInputElement | HTMLTextAreaElement, options: { id: string; kind?: "prose" | "code"; sensitive?: boolean }): CompletionHandle;
invalidate(): void;
transport?(request: CompletionTransportRequest, signal: AbortSignal, onLine: (line: string) => void): Promise<void>;
}
+89
View File
@@ -0,0 +1,89 @@
import type { CompletionHandle, CompletionProvider, CompletionSnapshot, CompletionSurface } from "./contracts.ts";
export function eligible(s: CompletionSnapshot): boolean {
if (!s.focused || s.composing || s.sensitive || s.readOnly || s.caret !== s.selectionEnd || s.caret < 0 || s.caret > s.text.length) return false;
if (s.kind === "code") return true;
const before = s.text.slice(0, s.caret), line = before.slice(before.lastIndexOf("\n") + 1);
if (/^\s*\|/.test(line) || /\]\([^)]*$/.test(line) || /<[^>]*$/.test(line)) return false;
if ((line.match(/`/g)?.length ?? 0) % 2) return false;
if (/^---\r?\n/.test(s.text) && !/^---\r?$/m.test(before.slice(before.indexOf("\n") + 1))) return false;
let fence = "";
for (const part of before.split("\n")) {
const match = /^\s{0,3}(`{3,}|~{3,})/.exec(part);
if (match) { if (!fence) fence = match[1]; else if (match[1][0] === fence[0] && match[1].length >= fence.length) fence = ""; }
}
return !fence;
}
function same(a: CompletionSnapshot, b: CompletionSnapshot) {
return a.documentId === b.documentId && a.revision === b.revision && a.caret === b.caret && a.selectionEnd === b.selectionEnd && eligible(b);
}
export class CompletionHub {
private provider?: CompletionProvider;
private surfaces = new Map<string, CompletionHandle>();
private cancelActive?: () => void;
registerProvider(provider: CompletionProvider): () => void {
if (this.provider) throw new Error("Another autocomplete provider is active.");
if (!provider.id || typeof provider.complete !== "function") throw new Error("Invalid autocomplete provider.");
this.provider = provider;
return () => { if (this.provider === provider) { this.provider = undefined; this.invalidate(); } };
}
invalidate() { for (const handle of this.surfaces.values()) handle.dismiss(); }
registerSurface(surface: CompletionSurface): CompletionHandle {
if (!surface.id || this.surfaces.has(surface.id)) throw new Error("Duplicate completion field.");
let timer: ReturnType<typeof setTimeout> | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | undefined;
let expected: CompletionSnapshot | undefined;
let candidate = "", disposed = false, serial = 0;
const dismiss = () => {
const visible = !!candidate;
serial++; clearTimeout(timer); clearTimeout(timeout); controller?.abort(); controller = undefined;
candidate = ""; expected = undefined; surface.preview(null);
return visible;
};
const run = async (manual: boolean) => {
if (disposed || !this.provider) return;
const snapshot = surface.snapshot(), provider = this.provider;
if (!eligible(snapshot) || !snapshot.text.slice(0, snapshot.caret).trim()) return;
this.cancelActive?.(); dismiss(); this.cancelActive = dismiss;
const version = serial, abort = new AbortController(); controller = abort; expected = snapshot;
timeout = setTimeout(() => {
if (serial !== version) return;
if (candidate && same(snapshot, surface.snapshot())) abort.abort();
else dismiss();
}, manual ? 10000 : Math.max(300, Math.min(provider.timeoutMs ?? 1000, 5000)));
const publish = (text: string) => {
if (disposed || serial !== version || abort.signal.aborted || this.provider !== provider || !same(snapshot, surface.snapshot())) return;
if (typeof text !== "string" || text.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) return;
candidate = text; surface.preview(text || null);
};
try {
const result = await provider.complete({ surfaceId: surface.id, documentId: snapshot.documentId, revision: snapshot.revision,
prefix: snapshot.text.slice(Math.max(0, snapshot.caret - 3000), snapshot.caret), suffix: snapshot.text.slice(snapshot.caret, snapshot.caret + 600),
kind: snapshot.kind, language: snapshot.language ?? "", manual, signal: abort.signal }, publish);
if (result) publish(result);
} catch { if (serial === version) dismiss(); }
finally { if (serial === version) { clearTimeout(timeout); controller = undefined; } }
};
const handle: CompletionHandle = {
changed: () => {
dismiss();
if (disposed || !this.provider || !eligible(surface.snapshot())) return;
timer = setTimeout(() => { void run(false); }, Math.max(100, Math.min(this.provider.delayMs ?? 200, 1000)));
},
request: () => { dismiss(); void run(true); },
dismiss,
accept: (word = false) => {
if (!candidate || !expected || !same(expected, surface.snapshot())) { dismiss(); return false; }
const text = word ? (candidate.match(/^\s*\S+\s*/u)?.[0] ?? candidate) : candidate;
const snapshot = expected;
dismiss();
return surface.insert(text, snapshot);
},
dispose: () => { if (disposed) return; disposed = true; dismiss(); this.surfaces.delete(surface.id); if (this.cancelActive === dismiss) this.cancelActive = undefined; },
};
this.surfaces.set(surface.id, handle);
return handle;
}
}
export const completionHub = new CompletionHub();
+47
View File
@@ -0,0 +1,47 @@
import { completionHub } from "./hub.ts";
import type { CompletionApi, CompletionHandle } from "./contracts.ts";
export const registerCompletionInput: CompletionApi["registerInput"] = (element, options) => {
let revision = 0, composing = false;
const hint = document.createElement("div");
hint.className = "rs-completion-hint";
hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius,6px);background:var(--rs-bg,#20242a);color:var(--rs-text,#eee);border:1px solid currentColor;font:inherit;white-space:pre-wrap";
hint.hidden = true;
hint.setAttribute("aria-hidden", "true");
document.body.append(hint);
const handle = completionHub.registerSurface({
id: options.id,
snapshot: () => ({ documentId: options.id, revision, text: element.value, caret: element.selectionStart ?? 0, selectionEnd: element.selectionEnd ?? 0,
focused: document.activeElement === element, composing, readOnly: element.readOnly || element.disabled,
sensitive: options.sensitive || element instanceof HTMLInputElement && !["text", "search"].includes(element.type), kind: options.kind ?? "prose" }),
preview: text => { hint.hidden = !text; hint.textContent = text ? `${text}\nTab to accept · Escape to dismiss` : ""; const r = element.getBoundingClientRect(); hint.style.left = `${Math.max(0, Math.min(r.left, innerWidth - 350))}px`; hint.style.top = `${Math.min(r.bottom + 4, innerHeight - 100)}px`; },
insert: (text, expected) => {
if (element.value !== expected.text || element.selectionStart !== expected.caret || element.selectionEnd !== expected.caret) return false;
// The native edit command keeps input and textarea undo history intact.
element.focus();
return document.execCommand("insertText", false, text);
},
});
const changed = () => { revision++; handle.changed(); };
const select = () => handle.dismiss();
const start = () => { composing = true; handle.dismiss(); };
const end = () => { composing = false; changed(); };
const key: EventListener = raw => {
const event = raw as KeyboardEvent;
if (event.isComposing || composing) return;
if (event.key === "Tab" && !event.shiftKey && !event.altKey && !event.ctrlKey && handle.accept()) { event.preventDefault(); event.stopPropagation(); }
else if (event.key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === " ") { event.preventDefault(); handle.request(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === "ArrowRight" && handle.accept(true)) event.preventDefault();
};
element.addEventListener("input", changed); element.addEventListener("keydown", key); element.addEventListener("blur", select);
element.addEventListener("pointerdown", select); element.addEventListener("select", select);
element.addEventListener("compositionstart", start); element.addEventListener("compositionend", end);
const dispose = () => {
handle.dispose(); hint.remove();
element.removeEventListener("input", changed); element.removeEventListener("keydown", key); element.removeEventListener("blur", select);
element.removeEventListener("pointerdown", select); element.removeEventListener("select", select);
element.removeEventListener("compositionstart", start); element.removeEventListener("compositionend", end);
};
return { ...handle, dispose } satisfies CompletionHandle;
};
+51
View File
@@ -0,0 +1,51 @@
import type * as Monaco from "monaco-editor";
import { completionHub } from "./hub";
export function connectMonacoCompletion(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, documentId: string, prose: boolean) {
const model = view.getModel()!;
let composing = false;
const decoration = view.createDecorationsCollection();
if (!document.getElementById("rs-completion-style")) {
const style = document.createElement("style"); style.id = "rs-completion-style";
style.textContent = ".rs-completion-ghost{opacity:.65;font-style:italic;pointer-events:none}";
document.head.append(style);
}
const handle = completionHub.registerSurface({
id: `source:${documentId}:${crypto.randomUUID()}`,
snapshot: () => {
const selection = view.getSelection(), position = view.getPosition();
return { documentId, revision: model.getVersionId(), text: model.getValue(), caret: position ? model.getOffsetAt(position) : 0,
selectionEnd: (view.getSelections()?.length === 1 && selection?.isEmpty()) && position ? model.getOffsetAt(position) : -1,
focused: view.hasTextFocus(), composing, readOnly: view.getOption(monaco.editor.EditorOption.readOnly), kind: prose ? "prose" : "code", language: model.getLanguageId() };
},
preview: text => {
const p = view.getPosition();
decoration.set(text && p ? [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), options: {
after: { content: text.replace(/\r?\n/g, " ↵ "), inlineClassName: "rs-completion-ghost", cursorStops: monaco.editor.InjectedTextCursorStops.None },
showIfCollapsed: true,
} }] : []);
},
insert: (text, expected) => {
if (model.getVersionId() !== expected.revision || !view.getSelection()?.isEmpty()) return false;
const p = model.getPositionAt(expected.caret);
view.pushUndoStop();
const done = view.executeEdits("autocomplete", [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), text }]);
view.setPosition(model.getPositionAt(expected.caret + text.length)); view.pushUndoStop(); return done;
},
});
const listeners = [model.onDidChangeContent(() => handle.changed()), view.onDidChangeCursorSelection(() => handle.changed()),
view.onDidFocusEditorText(() => handle.changed()), view.onDidBlurEditorText(() => handle.dismiss()),
view.onDidCompositionStart(() => { composing = true; handle.dismiss(); }), view.onDidCompositionEnd(() => { composing = false; handle.changed(); }),
view.onKeyDown(event => {
if (composing) return;
const key = event.browserEvent.key;
if (key === "Tab" && !event.shiftKey && !event.ctrlKey && !event.altKey) {
if (view.getDomNode()?.querySelector(".suggest-widget.visible")) { handle.dismiss(); return; }
if (handle.accept()) { event.preventDefault(); event.stopPropagation(); }
} else if (key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === " ") { event.preventDefault(); event.stopPropagation(); handle.request(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === "ArrowRight" && handle.accept(true)) { event.preventDefault(); event.stopPropagation(); }
}),
];
return () => { handle.dispose(); decoration.clear(); listeners.forEach(item => item.dispose()); };
}
+33
View File
@@ -0,0 +1,33 @@
import { EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { history, historyKeymap, defaultKeymap } from '@codemirror/commands';
import { completionExtension } from './codemirror';
import { connectMonacoCompletion } from './monaco';
import { completionHub } from './hub';
import { ExternalSession } from '../plugins/externalSession';
import { monaco } from '../editor/monacoEnv';
const writer = new EditorView({ parent: document.querySelector('#writer')!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension('fixture')] }) });
const model = monaco.editor.createModel('The ', 'markdown');
const source = monaco.editor.create(document.querySelector('#source') as HTMLElement, { model, theme: 'vs-dark', automaticLayout: true });
const stopSource = connectMonacoCompletion(monaco, source, 'fixture-source', true);
source.setPosition({ lineNumber: 1, column: 5 });
let stopProvider = completionHub.registerProvider({ id: 'fixture', delayMs: 100, complete: async () => 'quiet harbor.' });
Object.assign(window, { completionTest: { writer, source, model, completionHub, stopProvider,
async plugin(code: string) {
stopProvider();
const session = new ExternalSession('test.autocomplete', {
settings: { read: async () => ({ enabled: true, endpoint: 'http://127.0.0.1:8012' }), write: async () => {} },
workspace: { list: async () => [], read: async () => '', write: async () => {} }, assets: { read: async () => new Uint8Array() },
completionTransport: async (request, signal, onLine) => {
if (request.route === '/v1/models') { onLine('{"data":[{"id":"fixture-model"}]}'); return; }
await new Promise(resolve => setTimeout(resolve, 25));
if (!signal.aborted) onLine('data: {"choices":[{"delta":{"content":"quiet harbor."}}]}\n');
},
}, () => {}, () => {});
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
try { await session.start(await import(/* @vite-ignore */ url)); } finally { URL.revokeObjectURL(url); }
await session.mount('settings', document.querySelector('#plugin') as HTMLElement);
return session;
},
destroy() { stopProvider(); stopSource(); writer.destroy(); source.dispose(); model.dispose(); },
} });
+16
View File
@@ -0,0 +1,16 @@
import { Channel, invoke } from "@tauri-apps/api/core";
import type { CompletionApi } from "./contracts.ts";
export const completionTransport: NonNullable<CompletionApi["transport"]> = async (request, signal, onLine) => {
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
const id = crypto.randomUUID();
let parseError: unknown;
const channel = new Channel<string>();
channel.onmessage = line => {
if (signal.aborted || parseError) return;
try { onLine(line); } catch (error) { parseError = error; cancel(); }
};
const cancel = () => { void invoke("completion_cancel", { id }).catch(() => {}); };
signal.addEventListener("abort", cancel, { once: true });
try { await invoke("completion_request", { id, request, onLine: channel }); if (parseError) throw parseError; }
finally { signal.removeEventListener("abort", cancel); }
};
+4
View File
@@ -6,6 +6,7 @@
import { editorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { TableContextActions } from "./tableCellActions";
@@ -85,6 +86,7 @@
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseCompletion: (() => void) | undefined;
const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco }) => {
if (cancelled || !el.isConnected) {
@@ -144,6 +146,7 @@
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
}
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view);
ready += 1;
@@ -160,6 +163,7 @@
const view = editor;
if (view && session) session.view = view.saveViewState();
contentListener?.dispose();
releaseCompletion?.();
releaseSelection?.();
menu?.destroy();
releaseDrop?.();
+2
View File
@@ -24,6 +24,7 @@
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
type Props = {
buffer: OpenBuffer;
@@ -138,6 +139,7 @@
if (model.getValue() !== lastValue) model.setValue(lastValue);
model.pushStackElement();
const extensions = [
completionExtension(current.id),
EditorState.lineSeparator.of(model.getEOL()),
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
// Rich cell serialization can change delimiters away from the caret.
+4 -1
View File
@@ -208,7 +208,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
return [imageSource, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state, value.map(transaction.changes)) : value;
return transaction.docChanged || transaction.selection
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource))
? build(transaction.state, value.map(transaction.changes)) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
+2
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { loadMarks } from "$lib/workspace/marks";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import type { TreeEntry } from "$lib/workspace/types";
type Props = {
@@ -20,6 +21,7 @@
<div class="pane">
<div class="pane-label">Bookmarks</div>
<BrowserSlot kind="bookmarks" />
{#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p>
{:else}
+121
View File
@@ -0,0 +1,121 @@
<script lang="ts">
import { tick, untrack } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { pluginHost } from "$lib/plugins/registry";
import { pluginEditors, pluginView, pluginSplits, externalErrors, pluginServiceError, selectPluginEditor, closePluginEditor, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
import TabBar from "./TabBar.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import WindowControls from "$lib/ui/WindowControls.svelte";
let error = $state("");
let opening = $state(false);
let hadTabs = false;
const browser = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
const tabs = $derived<WorkbenchTab[]>($pluginEditors.map(view => ({
id: view.key, relPath: view.key, name: view.title, title: view.title,
pinned: !!view.pinned, draggable: view.draggable, icon: "globe", iconImage: view.iconImage, panelId: `plugin-editor-${view.key}`,
})));
const active = $derived($pluginView?.key ?? null);
const split = $derived($pluginSplits.find(tree => active && containsPane(tree, active)));
const bounds = $derived(split ? paneBounds(split) : active ? paneBounds(active) : {});
const message = $derived(error || $externalErrors["runestone.browser"] || $pluginServiceError);
$effect(() => {
if (tabs.length) hadTabs = true;
else if (hadTabs) void tick().then(() => {
if (!untrack(() => $pluginEditors.length)) void getCurrentWindow().destroy().catch(reason => error = String(reason));
});
});
function select(path: string) {
const view = $pluginEditors.find(view => view.key === path);
if (view) selectPluginEditor(view);
}
function move(path: string, index: number) {
pluginEditors.update(views => {
const from = views.findIndex(view => view.key === path);
if (from < 0) return views;
const ordered = [...views], [view] = ordered.splice(from, 1);
ordered.splice(Math.max(0, Math.min(index, ordered.length)), 0, view);
return ordered;
});
}
function close(path: string, scope: TabCloseScope = "one") {
for (const tab of tabsToClose(tabs, path, scope)) closePluginEditor(tab.id);
}
function actions(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabActions(view) : [];
}
function dragData(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabDragData(view) : undefined;
}
async function receive(data: string, index: number) {
try { await dropPluginTab(data); if ($pluginView) move($pluginView.key, index); error = ""; }
catch (reason) { error = String(reason); }
}
async function newTab() {
if (opening || !browser?.newTab) return;
opening = true;
try { await browser.newTab(); error = ""; } catch (reason) { error = String(reason); }
finally { opening = false; }
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented || !(event.ctrlKey || event.metaKey) || event.shiftKey || event.altKey) return;
if (event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
if (event.key.toLowerCase() === "t") { event.preventDefault(); void newTab(); }
if (event.key.toLowerCase() === "w" && active) { event.preventDefault(); close(active); }
if (event.key.toLowerCase() === "f" && $pluginView && findPluginEditor($pluginView)) event.preventDefault();
}
</script>
<svelte:window onkeydown={keydown} />
<div class="browser-window" role="application" aria-label="RuneStone browser">
<header class="header" data-tauri-drag-region>
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
<IconButton icon="plus" label="New browser tab (Ctrl T)" disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<div class="window-drag-space" data-tauri-drag-region></div>
<WindowControls onError={message => error = message} />
</header>
{#if message}<p class="error" role="alert">{message}</p>{/if}
<main class="pages">
{#each $pluginEditors as view (view.key)}
{@const position = bounds[view.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Input selects its browser pane.) -->
<div class="pane" class:inactive={!position} class:split={!!split} class:focused={active === view.key}
style:left={`${position?.left ?? 0}%`} style:top={`${position?.top ?? 0}%`}
style:width={`${position?.width ?? 100}%`} style:height={`${position?.height ?? 100}%`}
onfocusin={() => { if (active !== view.key) select(view.key); }}
onpointerdown={() => { if (active !== view.key) select(view.key); }}>
{#if split && position}
<TabBar tabs={tabs.filter(tab => tab.id === view.key)} activePath={active}
onSelect={select} onClose={close} onCloseTabs={close} onMove={move} onPin={pinPluginEditor}
fileActions={() => []} tabActions={actions} tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
{/if}
<PluginEditor {view} />
</div>
{/each}
{#if !tabs.length}<p class="placeholder">{browser ? "Open a browser tab with the + button." : "Loading browser…"}</p>{/if}
</main>
</div>
<style>
.browser-window { height: 100vh; display: flex; flex-direction: column; background: var(--rs-bg); }
.header { display: flex; align-items: center; height: 36px; flex-shrink: 0; background: var(--rs-bg-elevated); border-bottom: 1px solid var(--rs-border); }
.header :global(.tabs) { flex: 0 1 auto; min-width: 80px; height: 100%; border-bottom: 0; }
.window-drag-space { flex: 1; min-width: 40px; align-self: stretch; }
.pages { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
.pane.inactive { display: none; }
.pane.split { border: 1px solid var(--rs-border); }
.pane.split.focused { border-color: var(--rs-accent); }
.placeholder { padding: 24px; color: var(--rs-text-dim); }
.error { margin: 0; padding: 8px; color: var(--rs-error); }
</style>
+4 -1
View File
@@ -26,11 +26,13 @@
onOpenWorkspace: () => void;
onNewFile: () => void;
onQuickOpen: () => void;
onOpenBrowser?: () => void;
browserOpening?: boolean;
hasWorkspace: boolean;
tableActions?: TableContextActions;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null);
@@ -94,6 +96,7 @@
<h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1>
<p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p>
<div class="welcome-actions">
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if hasWorkspace}
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
+14 -1
View File
@@ -559,7 +559,20 @@
function menuItems(entry: TreeEntry | null): MenuItem[] {
if (!entry) {
return paneMenuItems("");
return [
...paneMenuItems(""),
{ kind: "sep" },
{
kind: "action",
label: "Show in Explorer",
icon: "folder",
run: () => {
void workspaceReveal("").catch((err) => {
error = err instanceof Error ? err.message : String(err);
});
},
},
];
}
const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry);
const multiple = entries.length > 1;
+25 -6
View File
@@ -1,22 +1,28 @@
<script lang="ts">
import PluginManager from "$lib/plugins/PluginManager.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import PluginSettings from "$lib/plugins/PluginSettings.svelte";
import { installedPlugins, pluginTools } from "$lib/plugins/external";
import { pluginHost } from "$lib/plugins/registry";
import { onMount, untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
import { version, license } from "../../../package.json";
let { settings, help = false, onSave, onClose }: {
let { settings, help = false, standalone = false, windowError = "", onSave, onClose }: {
settings: AppSettings;
help?: boolean;
standalone?: boolean;
windowError?: string;
onSave: (value: AppSettings) => void;
onClose: () => void;
} = $props();
type Section = "general" | "plugins" | "about";
type Section = string;
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
];
let section = $state<Section>(untrack(() => help ? "about" : "general"));
let query = $state("");
@@ -24,8 +30,15 @@
let message = $state("");
let error = $state("");
let dialog: HTMLDialogElement;
const matches = $derived(sections.filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const browserEnabled = $derived.by(() => { void $pluginHost; return !!pluginHost.get("browser"); });
const pluginSections = $derived($pluginTools.filter(tool => tool.surface === "settings").map(tool => ({
id: `plugin:${tool.owner}:${tool.id}`, owner: tool.owner, view: tool.id,
label: tool.title, icon: "settings" as const,
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
})));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: "Browser", icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
$effect(() => { seconds = settings.autosaveSeconds; });
onMount(() => {
@@ -54,7 +67,7 @@
function trapFocus(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest("dialog") !== dialog) return;
if (event.key !== "Tab") return;
const controls = [...dialog.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), summary")]
const controls = [...dialog.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], summary, [tabindex]:not([tabindex='-1'])")]
.filter(element => element.getClientRects().length > 0);
const first = controls[0], last = controls.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
@@ -62,7 +75,7 @@
}
</script>
<dialog bind:this={dialog} class:help aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
<dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
<header>
<h1 id="settings-title">{help ? "Help and about" : "Settings"}</h1>
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
@@ -81,6 +94,7 @@
</aside>
{/if}
<div class="content">
{#if windowError}<p class="error" role="alert">{windowError}</p>{/if}
{#if !selected}
<h2>No settings found</h2>
<p>Try “save”, “plug-ins”, or “help”.</p>
@@ -105,6 +119,10 @@
<p class="saved" role="status">{message}</p>
{:else if selected.id === "plugins"}
<PluginManager />
{:else if selected.id === "browser"}
<BrowserSlot kind="settings" />
{:else if selectedPlugin}
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
{:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div>
<div class="card help-card">
@@ -121,6 +139,7 @@
<style>
dialog { width: min(920px, calc(100vw - 32px)); height: min(650px, calc(100dvh - 32px)); max-width: none; max-height: none; padding: 0; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 12px; box-shadow: 0 24px 80px #0008; overflow: hidden; }
dialog::backdrop { background: #0008; }
dialog.standalone { width: 100vw; height: 100dvh; margin: 0; border: 0; border-radius: 0; box-shadow: none; }
dialog.help { width: min(650px, calc(100vw - 32px)); }
header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
h1 { font-size: 14px; font-weight: 600; margin: 0; }
+35
View File
@@ -0,0 +1,35 @@
<script lang="ts">
import { onMount } from "svelte";
import { isTauri } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import SettingsDialog from "./SettingsDialog.svelte";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
let error = $state("");
function read() {
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
}
onMount(() => {
read();
const sync = (event: StorageEvent) => {
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) read();
};
window.addEventListener("storage", sync);
window.addEventListener("focus", read);
return () => { window.removeEventListener("storage", sync); window.removeEventListener("focus", read); };
});
function save(next: AppSettings) {
saveSettings(localStorage, next);
settings = { ...next };
error = "";
}
async function close() {
if (!isTauri()) { window.location.assign("/"); return; }
try { await getCurrentWindow().close(); }
catch (reason) { error = `Could not close settings: ${String(reason)}`; }
}
</script>
<SettingsDialog {settings} standalone windowError={error} onSave={save} onClose={() => void close()} />
+76 -13
View File
@@ -2,21 +2,26 @@
import { onDestroy, tick } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons";
import TabIcon from "$lib/ui/TabIcon.svelte";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { OpenBuffer } from "$lib/workspace/types";
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
type Props = {
tabs: OpenBuffer[];
tabs: WorkbenchTab[];
activePath: string | null;
onSelect: (relPath: string) => void;
onClose: (relPath: string) => void;
onMove: (relPath: string, index: number) => void;
onCloseTabs: (relPath: string, scope: TabCloseScope) => void;
onPin: (relPath: string) => void;
fileActions: (tab: OpenBuffer) => ActionMenuItem[];
fileActions: (tab: WorkbenchTab) => ActionMenuItem[];
tabActions?: (tab: WorkbenchTab) => ActionMenuItem[];
tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => void;
};
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions }: Props = $props();
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab }: Props = $props();
const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement;
let dragged = $state<string | null>(null);
let dropBefore = $state<string | null>(null);
@@ -27,6 +32,48 @@
let menu: HTMLElement | undefined;
let menuAnchor: HTMLButtonElement | undefined;
let menuPath = $state<string | null>(null);
let receiving = $state(false);
function startTabTransfer(event: DragEvent, tab: WorkbenchTab) {
const data = tabDragData(tab);
if (!data || !event.dataTransfer) { event.preventDefault(); return; }
cancelDrag(); closeMenu();
dragged = tab.relPath;
suppressClick = true;
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(transferType, data);
}
function transferIndex(x: number) {
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== dragged);
const before = others.findIndex(row => { const bounds = row.getBoundingClientRect(); return x < bounds.left + bounds.width / 2; });
dropBefore = before < 0 ? null : others[before].dataset.path!;
dropAfter = before < 0 ? others.at(-1)?.dataset.path ?? null : null;
return before < 0 ? others.length : before;
}
function dragOver(event: DragEvent) {
if (!event.dataTransfer?.types.includes(transferType) || (!dragged && !onDropTab)) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
receiving = true;
const bounds = bar.getBoundingClientRect();
if (event.clientX < bounds.left + 28) bar.scrollLeft -= 10;
else if (event.clientX > bounds.right - 28) bar.scrollLeft += 10;
transferIndex(event.clientX);
}
function finishTabTransfer() { dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; }
function dropTab(event: DragEvent) {
const data = event.dataTransfer?.getData(transferType);
if (!data) return;
event.preventDefault(); event.stopPropagation();
const path = dragged, index = transferIndex(event.clientX);
finishTabTransfer();
if (path) void move(path, index);
else onDropTab?.(data, index);
}
$effect(() => {
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
@@ -78,8 +125,11 @@
closing("Close others", "others"),
closing("Close tabs after", "after"),
closing("Close all", "all"),
{ separator: true },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin", run: run(() => onPin(path)) },
...(tabs[index].pinned !== undefined ? [
{ separator: true as const },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin" as const, run: run(() => onPin(path)) },
] : []),
...wrapActions(tabActions(tabs[index])),
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
{ separator: true },
{ label: "Move tab", icon: "swap", children: [
@@ -197,8 +247,10 @@
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<div bind:this={bar} class="tabs" role="tablist" aria-label="Open files">
{#each tabs as tab (tab.relPath)}
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label="Working tabs" tabindex="-1"
ondragover={dragOver} ondrop={dropTab}
ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}>
{#each tabs as tab (tab.id)}
<div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath}
class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}>
<button
@@ -207,19 +259,23 @@
data-path={tab.relPath}
tabindex={tab.relPath === activePath ? 0 : -1}
aria-selected={tab.relPath === activePath}
aria-controls={tab.panelId}
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.kind === "empty" ? tab.name : tab.relPath}\nDrag to reorder. Right-click for tab actions.`}
title={`${tab.title}\n${tab.draggable ? "Drag to reorder or move to another RuneStone window." : "Drag to reorder."} Right-click for tab actions.`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => startDrag(event, tab.relPath)}
ondragstart={(event) => event.preventDefault()}
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
draggable={!!tab.draggable}
ondragstart={(event) => startTabTransfer(event, tab)}
ondragend={finishTabTransfer}
onkeydown={(event) => onKey(event, tab.relPath)}
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
>
{#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if}
{tab.name}{tab.contents !== tab.saved ? " •" : ""}
<TabIcon image={tab.iconImage} icon={tab.icon} />
<span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span>
</button>
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if}
<button
@@ -246,6 +302,8 @@
background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border);
}
.tabs:empty { min-width: 80px; }
.tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); }
.tab {
position: relative;
@@ -281,6 +339,9 @@
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.tab > button:first-child {
display: flex;
align-items: center;
gap: 7px;
border-radius: var(--rs-control-radius);
touch-action: none;
user-select: none;
@@ -302,7 +363,9 @@
color: var(--rs-text-strong);
}
.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; }
.tab-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tab :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
.pin { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.close {
border: 0;
+169 -25
View File
@@ -1,25 +1,29 @@
<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 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 { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, tick } from "svelte";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts";
import { isTauri } from "@tauri-apps/api/core";
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 type { ActionMenuItem } from "$lib/ui/actionMenu";
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 FileTree from "./FileTree.svelte";
import EditorPane from "./EditorPane.svelte";
@@ -55,6 +59,15 @@
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();
@@ -81,6 +94,28 @@
let terminalDock: TerminalSlot | undefined = $state();
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
const terminalEnabled = $derived(!!terminalContribution);
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) {
@@ -113,6 +148,41 @@
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));
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(
@@ -213,6 +283,38 @@
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);
return tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
}
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;
@@ -231,19 +333,27 @@
async function closeTabs(path: string, scope: TabCloseScope) {
const current = documents;
if (!current || closingTabs || switching) return;
if (closingTabs || switching) return;
closingTabs = true;
try {
const targets = tabsToClose(current.buffers, path, scope);
const targets = tabsToClose(workingTabs, path, scope);
for (const target of targets) {
if (documents !== current || switching) break;
const tab = current.buffers.find(item => item.id === target.id);
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;
current.close(tab.relPath);
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; }
@@ -437,7 +547,7 @@
function onPreferencesKeydown(event: KeyboardEvent) {
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 === ",") {
event.preventDefault(); event.stopPropagation(); preferences = "settings";
event.preventDefault(); event.stopPropagation(); void openSettings();
}
if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
event.preventDefault(); event.stopPropagation(); preferences = "help";
@@ -445,7 +555,11 @@
}
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)) {
@@ -488,7 +602,7 @@
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
event.preventDefault();
if (editorPluginVisible) {
if ($pluginView) closePluginEditor($pluginView.key);
if (activeTabPath) void closeTab(activeTabPath);
} else if (activePath) {
closeTab(activePath);
}
@@ -561,7 +675,10 @@
async function openLink(kind: "md" | "wiki", target: string) {
if (/^(https?:\/\/|mailto:)/i.test(target)) {
try { await openUrl(target); } catch (err) { error = String(err); }
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);
@@ -718,17 +835,17 @@
/>
</div>
<div class="header-center" data-tauri-drag-region>
{#if tabs.length > 0}
<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 />
<TabBar tabs={workingTabs} activePath={activeTabPath} onSelect={selectWorkingTab} onClose={closeTab}
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={pinWorkingTab}
fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
<PluginAccessMenu surface="open" />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div>
<div class="header-right" data-tauri-drag-region>
<PluginTools />
<PluginAccessMenu surface="commands" />
<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
@@ -744,7 +861,7 @@
<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"}
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" ? item.icon : "puzzle"}
label={item.title}
side="right"
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
@@ -757,7 +874,7 @@
<aside class="left">
<div class="left-body">
{#if !workspace}
<p class="placeholder">No folder is open.</p>
{#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"}>
@@ -793,7 +910,7 @@
</div>
<div class="footer-actions">
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => preferences = "settings"} />
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => void openSettings()} />
</div>
</div>
</aside>
@@ -807,7 +924,25 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<main class="center">
{#each $pluginEditors as view (view.key)}<PluginEditor {view} />{/each}
<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>
@@ -827,6 +962,8 @@
onOpenWorkspace={() => void chooseWorkspace()}
onNewFile={() => void newFile()}
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{browserOpening}
{buffer}
chrome={view}
{reading}
@@ -997,6 +1134,7 @@
background: transparent;
border-bottom: 0;
}
.header-center :global(.tabs:empty) { min-width: 80px; }
.header-center :global(.tab) {
max-width: 180px;
@@ -1047,6 +1185,12 @@
}
.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 {
+22
View File
@@ -0,0 +1,22 @@
<script lang="ts">
import { untrack } from "svelte";
import { pluginHost } from "./registry";
let { kind }: { kind: "settings" | "bookmarks" } = $props();
let element: HTMLDivElement | undefined = $state();
let error = $state("");
$effect(() => {
void $pluginHost;
const browser = pluginHost.get("browser"), target = element;
if (!browser || !target) return;
let disposed = false;
let cleanup: (() => void | Promise<void>) | undefined;
error = "";
void Promise.resolve(untrack(() => kind === "settings" ? browser.mountSettings(target) : browser.mountBookmarks(target)))
.then(value => { if (disposed) void value(); else cleanup = value; })
.catch(reason => { error = String(reason); });
return () => { disposed = true; void cleanup?.(); };
});
</script>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div bind:this={element}></div>
<style>.error { color: var(--rs-error); padding: 10px; }</style>
+42
View File
@@ -0,0 +1,42 @@
<script lang="ts">
import { untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, pluginTools, openPluginView, runPluginCommand } from "./external";
let { surface }: { surface: "commands" | "open" } = $props();
let anchor = $state<HTMLButtonElement>();
let position = $state<{ x: number; y: number } | null>(null);
let error = $state("");
let pointerWasOpen = false;
const label = $derived(surface === "open" ? "Open tab or view" : "Commands");
const tools = $derived($pluginTools.filter(tool => tool.surface === surface));
const signature = $derived(JSON.stringify([tools, $installedPlugins.plugins.map(row => [row.manifest.id, row.manifest.name])]));
const items: MenuItem[] = $derived.by(() => { void signature; return untrack(() => tools.map(tool => ({
kind: "action" as const,
label: `${tool.title} · ${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner}`,
icon: tool.icon === "list" ? "bullet" as const : tool.icon ?? (tool.owner === "runestone.browser" && tool.id === "new-tab" ? "globe" as const : tool.kind === "command" && surface === "commands" ? "code" as const : "plus" as const),
run: () => {
error = "";
if (tool.kind === "view") openPluginView(tool.owner, tool.id);
else void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason));
},
}))); });
</script>
{#if tools.length}
<button class="access-button" bind:this={anchor} aria-haspopup="menu" aria-expanded={position !== null} title={label}
onpointerdown={() => pointerWasOpen = position !== null}
onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}>
<Icon icon={surface === "open" ? "chevron-down" : "code"} /><span>{label}</span>
</button>
{/if}
{#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if}
{#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
<style>
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
.access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
.error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
</style>
+2 -3
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { untrack } from "svelte";
import { pluginView, pluginEditorActive, mountPluginView, type OpenPluginView } from "./external";
import { mountPluginView, type OpenPluginView } from "./external";
let { view }: { view: OpenPluginView } = $props();
let host: HTMLDivElement | undefined = $state();
let error = $state("");
@@ -22,7 +22,7 @@
});
</script>
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane" class:inactive={!$pluginEditorActive || $pluginView?.key !== view.key}
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
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>
@@ -30,7 +30,6 @@
<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
@@ -1,31 +0,0 @@
<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>
+23
View File
@@ -0,0 +1,23 @@
<script lang="ts">
import { untrack } from "svelte";
import { mountPluginView } from "./external";
let { owner, id }: { owner: string; id: string } = $props();
const pluginOwner = $derived(owner);
const viewId = $derived(id);
let element: HTMLDivElement | undefined = $state();
let error = $state("");
$effect(() => {
const target = element, plugin = pluginOwner, view = viewId;
if (!target) return;
let disposed = false;
let cleanup: (() => void | Promise<void>) | undefined;
error = "";
void untrack(() => mountPluginView(plugin, view, target, undefined, "settings")).then(value => {
if (disposed) void Promise.resolve(value()).catch(() => {}); else cleanup = value;
}).catch(reason => { if (!disposed) error = String(reason); });
return () => { disposed = true; void Promise.resolve(cleanup?.()).catch(() => {}); };
});
</script>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div bind:this={element}></div>
<style>.error { color: var(--rs-error); }</style>
+2 -26
View File
@@ -1,9 +1,7 @@
<script lang="ts">
import { onMount } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { pluginTools, pluginView, openPluginView, runPluginCommand, mountPluginView } from "./external";
let menu = $state(false);
import { pluginView, mountPluginView } from "./external";
let error = $state("");
let dialog: HTMLDialogElement | undefined = $state();
let host: HTMLDivElement | undefined = $state();
@@ -22,25 +20,8 @@
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => { cancelled = true; void Promise.resolve(cleanup?.()).catch(reason => error = String(reason)); modal.close(); previous?.focus(); };
});
onMount(() => {
const close = (event: PointerEvent) => { if (!(event.target as Element)?.closest(".plugin-tools")) menu = false; };
window.addEventListener("pointerdown", close);
return () => window.removeEventListener("pointerdown", close);
});
</script>
{#if $pluginTools.length}
<div class="plugin-tools">
<IconButton icon="puzzle" label="Plugin commands and views" active={menu} onclick={() => menu = !menu} />
{#if menu}
<div class="tools" role="group" aria-label="Plugin commands and views">
{#each $pluginTools as tool (`${tool.owner}:${tool.kind}:${tool.id}`)}
<button onkeydown={event => { if (event.key === "Escape") menu = false; }} onclick={() => { menu = false; if (tool.kind === "view") openPluginView(tool.owner, tool.id); else void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); }}><Icon icon={tool.kind === "view" ? "panel-right" : "code"} /><span>{tool.title}<small>{tool.owner}</small></span></button>
{/each}
</div>
{/if}
</div>
{/if}
{#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); }}>
@@ -50,11 +31,6 @@
</dialog>
{/if}
<style>
.plugin-tools { position: relative; }
.tools { position: absolute; right: 0; top: 38px; width: 280px; max-height: 60vh; overflow: auto; z-index: 50; padding: 6px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 8px 24px #0008; }
.tools button { display: flex; gap: 10px; align-items: center; text-align: left; width: 100%; padding: 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; }
.tools button:hover { background: var(--rs-bg-active); }
small { display: block; color: var(--rs-text-dim); margin-top: 4px; }
dialog { width: min(800px, 90vw); max-height: 85vh; padding: 20px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
dialog::backdrop { background: #0008; }
header { display: flex; justify-content: space-between; align-items: center; }
+21
View File
@@ -0,0 +1,21 @@
import type { PluginCommand, PluginView } from "./sdk.ts";
export type PluginTool = {
owner: string; id: string; title: string; kind: "command" | "view";
surface: "commands" | "open" | "settings";
icon?: PluginView["icon"];
};
export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): PluginTool[] {
const result: PluginTool[] = [];
for (const command of commands) {
const legacyOpen = owner === "runestone.browser" && command.id === "new-tab";
result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" || (command.category === undefined && legacyOpen) ? "open" : "commands" });
}
for (const view of views) {
const settings = view.settings ?? (owner === "runestone.local-autocomplete" && view.id === "settings");
if (!settings && (view.launcher === false || (view.launcher === undefined && owner === "runestone.browser"))) continue;
result.push({ owner, id: view.id, title: view.title, kind: "view", surface: settings ? "settings" : "open", icon: view.icon });
}
return result;
}
+6
View File
@@ -15,6 +15,12 @@ export interface TerminalMount {
export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!";
export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode };
export interface Contributions {
browser: {
newTab?(): Promise<void>;
mountSettings(container: HTMLElement): Dispose | Promise<Dispose>;
mountBookmarks(container: HTMLElement): Dispose | Promise<Dispose>;
open(url: string): Promise<boolean>;
};
terminal: {
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
+62 -14
View File
@@ -1,16 +1,42 @@
import { get, writable } from "svelte/store";
import { completionTransport } from "../completion/transport";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
import { ExternalSession, deadline } from "./externalSession";
import { pluginAccess, type PluginTool } from "./access";
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
import type { PluginViewOpenOptions } 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 interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" }
export const pluginTools = writable<PluginTool[]>([]);
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
export const pluginView = writable<OpenPluginView | null>(null);
export const pluginEditors = writable<OpenPluginView[]>([]);
export const pluginSplits = writable<SplitLayout[]>([]);
export function pinPluginEditor(key: string) {
pluginEditors.update(views => views.map(view => view.key === key ? { ...view, pinned: !view.pinned } : view));
}
export function pluginTabActions(view: OpenPluginView) { return sessions.get(view.owner)?.session.views.get(view.id)?.tabActions?.({ pinned: !!view.pinned }) ?? []; }
export function pluginTabDragData(view: OpenPluginView): string | undefined {
const data = sessions.get(view.owner)?.session.views.get(view.id)?.tabDragData?.({ pinned: !!view.pinned });
return data === undefined ? undefined : JSON.stringify({ owner: view.owner, data });
}
export async function dropPluginTab(data: string) {
if (data.length > 8192) throw new Error("Invalid tab transfer.");
const payload = JSON.parse(data);
if (!payload || typeof payload.owner !== "string" || typeof payload.data !== "string") throw new Error("Invalid tab transfer.");
const session = sessions.get(payload.owner)?.session;
if (!session) throw new Error("Enable this tab's plugin before moving it to this window.");
await session.dropTab(payload.data);
}
export function findPluginEditor(view: OpenPluginView): boolean {
const find = sessions.get(view.owner)?.session.views.get(view.id)?.find;
if (!find) return false;
find(); return true;
}
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"] }[]>([]);
@@ -23,6 +49,7 @@ const errors: Record<string, string> = {};
const restarted = new Set<string>();
let queue: Promise<void> = Promise.resolve();
let started = false;
let allowedPlugins: string[] | undefined;
let generation = 0;
let documentOpenVersion = 0;
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
@@ -41,10 +68,12 @@ export function notifyPluginWorkspace() { for (const listener of workspaceListen
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
export function closePluginEditor(key: string) {
cancelPluginDocumentOpen();
const group = get(pluginSplits).find(tree => containsPane(tree, key));
const remaining = get(pluginEditors).filter(view => view.key !== key);
pluginSplits.update(trees => trees.flatMap(tree => { const next = removePane(tree, key); return next === null || typeof next === "string" ? [] : [next]; }));
pluginEditors.set(remaining);
if (get(pluginView)?.key === key) {
pluginView.set(remaining.at(-1) ?? null);
pluginView.set(remaining.find(view => group && containsPane(group, view.key)) ?? remaining.at(-1) ?? null);
pluginEditorActive.set(remaining.length > 0);
}
}
@@ -114,12 +143,10 @@ export async function createPluginDocument(owner: string, id: string, path: stri
}
function publish() {
pluginEditors.update(views => views.map(view => view.document ? view : { ...view, title: sessions.get(view.owner)?.session.views.get(view.id)?.title ?? view.title, iconImage: sessions.get(view.owner)?.session.views.get(view.id)?.iconImage }));
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 })),
]));
pluginTools.set([...sessions].flatMap(([owner, { session }]) => pluginAccess(owner, session.commands.values(), session.views.values())));
externalErrors.set({ ...errors });
}
function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); }
@@ -138,13 +165,22 @@ async function stop(id: string) {
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
await release(id, error); publish();
}
function show(owner: string, id: string) {
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
const view = sessions.get(owner)?.session.views.get(id);
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 };
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(view.icon === "globe" ? { icon: "globe" as const } : {}) };
if (!existing && options) {
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
pluginSplits.update(trees => {
const index = trees.findIndex(tree => containsPane(tree, source.key));
if (index < 0) return [...trees, splitPane(source.key, source.key, editor.key, options.split)];
return trees.map((tree, i) => i === index ? splitPane(tree, source.key, editor.key, options.split) : tree);
});
}
if (!existing) pluginEditors.update(views => [...views, editor]);
selectPluginEditor(editor); return;
}
@@ -159,8 +195,10 @@ async function activate(row: InstalledPlugin) {
const id = row.manifest.id;
let leased = false;
const session = new ExternalSession(id, {
completionTransport,
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
readBytes: workspaceReadBytes,
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
@@ -168,11 +206,19 @@ async function activate(row: InstalledPlugin) {
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); },
},
settings: {
subscribe: listener => {
let disposed = false;
let off: (() => void) | undefined;
void listen<string>("plugin-settings-changed", event => { if (!disposed && event.payload === id) listener(); })
.then(unlisten => { if (disposed) unlisten(); else off = unlisten; })
.catch(reason => report(id, reason));
return () => { disposed = true; off?.(); };
},
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), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => {
}, publish, (view, options) => show(id, view, options), 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)
@@ -180,7 +226,7 @@ async function activate(row: InstalledPlugin) {
if (!renameDocument) throw new Error("Document renaming is unavailable.");
canWrite(document.path);
return renameDocument(document.path, name);
});
}, viewId => { for (const view of get(pluginEditors)) if (view.owner === id && view.id === viewId) closePluginEditor(view.key); });
try {
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
@@ -214,6 +260,7 @@ export function refreshPlugins(): Promise<void> {
}
for (const row of snapshot.plugins) {
const id = row.manifest.id;
if (allowedPlugins && !allowedPlugins.includes(id)) continue;
if (!row.enabled) { failures.delete(id); continue; }
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
}
@@ -230,14 +277,15 @@ 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, document?: PluginDocumentContext): Promise<Dispose> {
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
const session = sessions.get(owner)?.session;
if (!session) throw new Error("The plugin is disabled.");
return session.mount(id, element, document);
return session.mount(id, element, document, surface);
}
export function startExternalPlugins(): () => void {
export function startExternalPlugins(allowed?: string[]): () => void {
if (!isTauri() || started) return () => {};
started = true;
allowedPlugins = allowed;
let disposed = false;
let off: (() => void) | undefined;
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
+49 -9
View File
@@ -1,4 +1,6 @@
import { pluginHost, type ContributionRegistry } from "./registry.ts";
import { completionHub } from "../completion/hub.ts";
import { registerCompletionInput } from "../completion/input.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -21,14 +23,17 @@ export class ExternalSession {
private contributions: Dispose[] = [];
private registry: ContributionRegistry;
readonly id: string;
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private changed: () => void;
private show: (id: string) => void;
private show: PluginApi["openView"];
private close?: PluginApi["closeView"];
private receiveTab?: (data: string) => void | Promise<void>;
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"]) {
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"]) {
this.openDocument = openDocument;
this.renameDocument = renameDocument;
this.close = close;
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."); }
@@ -40,9 +45,30 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
completion: {
version: 1,
registerProvider: provider => { this.check(); const off = completionHub.registerProvider({ ...provider, id: this.id + ":" + provider.id }); this.contributions.push(off); return off; },
registerSurface: surface => { this.check(); const handle = completionHub.registerSurface({ ...surface, id: this.id + ":" + surface.id }); this.contributions.push(handle.dispose); return handle; },
registerInput: (element, options) => { this.check(); const handle = registerCompletionInput(element, { ...options, id: this.id + ":" + options.id }); this.contributions.push(handle.dispose); return handle; },
invalidate: () => { this.check(); completionHub.invalidate(); },
...(this.services.completionTransport ? { transport: (request, signal, onLine) => {
this.check(); return this.services.completionTransport!(request, AbortSignal.any([signal, this.controller.signal]), onLine);
} } : {}),
},
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 (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); },
registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
registerView: item => { if ([item.settings, item.launcher].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); 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); },
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
updateViewTitle: (id, title) => {
this.check(); const view = this.views.get(id);
if (!view || typeof title !== "string" || !title.trim() || title.length > 200) throw new Error("Invalid view title.");
if (view.title !== title) { view.title = title; this.changed(); }
},
updateViewIcon: (id, image) => {
this.check(); const view = this.views.get(id);
if (!view || (image !== null && (typeof image !== "string" || image.length > 90_000 || !/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(image)))) throw new Error("Invalid view icon.");
if (view.iconImage !== image) { view.iconImage = image; this.changed(); }
},
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.");
@@ -51,7 +77,8 @@ export class ExternalSession {
},
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); },
openView: (id, options) => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id, options); },
...(this.close ? { closeView: (id: string) => { this.check(); this.close!(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) => {
@@ -65,6 +92,7 @@ export class ExternalSession {
this.cleanups.push(cleanup); return cleanup;
} } : {}),
list: path => { this.check(); return this.services.workspace.list(path); },
...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}),
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); } } : {}),
@@ -72,6 +100,13 @@ export class ExternalSession {
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: {
...(this.services.settings.subscribe ? { subscribe: (listener: () => void) => {
this.check();
const off = this.services.settings.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;
} } : {}),
read: () => { this.check(); return this.services.settings.read(); },
write: value => { this.check(); return this.services.settings.write(value); },
},
@@ -88,10 +123,15 @@ 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, document?: PluginDocumentContext): Promise<Dispose> {
async dropTab(data: string) {
this.check();
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
await this.receiveTab(data);
}
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): 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 document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element); });
const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element, { surface }); });
const cleanup = () => {
cleaning ??= (async () => {
const dispose = await pending;
@@ -107,7 +147,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.documentTypes.clear(); this.changed();
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => {
const errors: unknown[] = [];
+1 -1
View File
@@ -9,7 +9,7 @@ export class ContributionRegistry {
return this.entries.get(key)?.value as Contributions[K] | undefined;
}
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
if (key !== "terminal" && key !== "tableFormulas") throw new Error("Unknown plugin contribution.");
if (key !== "terminal" && key !== "tableFormulas" && key !== "browser") throw new Error("Unknown plugin contribution.");
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
const entry = { owner, value };
this.entries.set(key, entry); this.emit();
+13 -4
View File
@@ -1,8 +1,11 @@
import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.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; placement?: "dialog" | "editor"; navigation?: boolean; icon?: "list" | "kanban" | "puzzle"; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
export interface PluginCommand { id: string; title: string; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor"; navigation?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string }
export interface PluginDocumentType {
id: string;
@@ -15,18 +18,24 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
completion?: CompletionApi;
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;
registerTabDrop?(receive: (data: string) => void | Promise<void>): void;
updateViewTitle?(id: string, title: string): void;
updateViewIcon?(id: string, image: string | null): void;
registerDocumentType(type: PluginDocumentType): void;
openDocument(path: string): Promise<void>;
renameDocument?(document: PluginDocumentContext, name: string): Promise<string>;
openView(id: string): void;
openView(id: string, options?: PluginViewOpenOptions): void;
closeView?(id: string): void;
onDispose(cleanup: Dispose): void;
workspace: {
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
listMarkdown?(): Promise<string[]>;
read(path: string): Promise<string>;
readBytes?(path: string): Promise<Uint8Array>;
readOptional?(path: string): Promise<string | null>;
@@ -34,7 +43,7 @@ export interface PluginApi {
write(path: string, contents: string, expected: string): Promise<void>;
subscribe?(listener: () => void): Dispose;
};
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void>; subscribe?(listener: () => void): Dispose };
assets: { read(path: string): Promise<Uint8Array> };
}
export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise<void | Dispose> }
+10
View File
@@ -6,6 +6,16 @@
<svg viewBox="0 0 24 24" aria-hidden="true">
{#if icon === "settings"}
<path d="m9 3-1 3-3 1-2 3 2 2v3l3 2 1 4h5l1-3 3-1 3-4-2-2V8l-3-2-1-3Z" /><circle cx="12" cy="12" r="3" />
{:else if icon === "globe"}
<circle cx="12" cy="12" r="9" /><ellipse cx="12" cy="12" rx="4" ry="9" /><path d="M3 12h18" />
{:else if icon === "arrow-left"}
<path d="M20 12H4m6-6-6 6 6 6" />
{:else if icon === "arrow-right"}
<path d="M4 12h16m-6-6 6 6-6 6" />
{:else if icon === "copy"}
<rect x="8" y="8" width="12" height="12" rx="2" /><path d="M16 8V4H4v12h4" />
{:else if icon === "stop"}
<rect x="5" y="5" width="14" height="14" rx="2" />
{:else if icon === "help"}
<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"}
+5
View File
@@ -2,6 +2,11 @@
import { onDestroy } from "svelte";
import Icon from "./Icon.svelte";
export type IconName =
| "globe"
| "arrow-left"
| "arrow-right"
| "copy"
| "stop"
| "settings"
| "help"
| "puzzle"
+16
View File
@@ -0,0 +1,16 @@
<script lang="ts">
import Icon from "./Icon.svelte";
import type { IconName } from "./IconButton.svelte";
let { image, icon }: { image?: string | null; icon?: IconName } = $props();
let failed = $state<string | null>(null);
</script>
{#if image && image !== failed}
<img class="tab-icon" src={image} alt="" width="16" height="16" draggable="false" onerror={() => { failed = image ?? null; }} />
{:else if icon}
<Icon {icon} />
{/if}
<style>
.tab-icon { width: 16px; height: 16px; flex-shrink: 0; object-fit: contain; }
</style>
+4
View File
@@ -1,5 +1,9 @@
// Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = {
globe: '<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/>',
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"/>',
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
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"/>',
+1
View File
@@ -76,6 +76,7 @@ export class Documents {
const index = this.buffers.indexOf(previous);
const opened = this.buffers.find(b => b.relPath === entry.rel_path);
if (index !== -1 && opened) {
opened.tabId = previous.tabId ?? previous.id;
this.buffers = this.buffers.filter(b => b !== opened);
this.buffers.splice(this.buffers.indexOf(previous), 1, opened);
}
+25
View File
@@ -0,0 +1,25 @@
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
export type PaneBounds = { left: number; top: number; width: number; height: number };
export function containsPane(tree: SplitLayout, key: string): boolean {
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
}
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down"): SplitLayout {
if (typeof tree === "string") return tree === key ? { direction, first: tree, second: next } : tree;
return { ...tree, first: splitPane(tree.first, key, next, direction), second: splitPane(tree.second, key, next, direction) };
}
export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
if (typeof tree === "string") return tree === key ? null : tree;
const first = removePane(tree.first, key), second = removePane(tree.second, key);
return first === null ? second : second === null ? first : { ...tree, first, second };
}
export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> {
if (typeof tree === "string") return { [tree]: bounds };
const a = { ...bounds }, b = { ...bounds };
if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; }
else { a.height /= 2; b.height /= 2; b.top += a.height; }
return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) };
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { OpenBuffer } from "./types";
export type TabCloseScope = "one" | "others" | "after" | "all";
export function tabsToClose(tabs: OpenBuffer[], path: string, scope: TabCloseScope): OpenBuffer[] {
export function tabsToClose<T extends Pick<OpenBuffer, "relPath" | "pinned">>(tabs: T[], path: string, scope: TabCloseScope): T[] {
const index = tabs.findIndex(tab => tab.relPath === path);
if (index < 0) return [];
if (scope === "one") return [tabs[index]];
+1
View File
@@ -22,6 +22,7 @@ export type WorkspaceEvent = {
export type OpenBuffer = {
id: string;
tabId?: string;
relPath: string;
name: string;
contents: string;
+27
View File
@@ -0,0 +1,27 @@
import type { IconName } from "../ui/IconButton.svelte";
export type WorkbenchTab = {
id: string;
relPath: string;
name: string;
title: string;
dirty?: boolean;
pinned?: boolean;
draggable?: boolean;
icon?: IconName;
iconImage?: string | null;
panelId?: string;
};
export function orderWorkbenchTabs<T extends { id: string }>(tabs: T[], order: string[]): T[] {
const remaining = new Map(tabs.map(tab => [tab.id, tab]));
const ordered: T[] = [];
for (const id of order) {
const tab = remaining.get(id);
if (tab) {
ordered.push(tab);
remaining.delete(id);
}
}
return [...ordered, ...remaining.values()];
}