Release RuneStone 0.1.4 with installable plugins and settings
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
@@ -33,8 +34,10 @@
|
||||
focusLine?: number | null;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
focusTitle?: boolean;
|
||||
onTitleFocused?: () => void;
|
||||
};
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
let error = $state("");
|
||||
@@ -234,7 +237,7 @@
|
||||
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
||||
focus() { view.focus(); },
|
||||
}, untrack(() => tableActions), message => { error = message; });
|
||||
if (shouldFocusOnMount()) view.focus();
|
||||
if (!focusTitle && shouldFocusOnMount()) view.focus();
|
||||
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -251,12 +254,25 @@
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
void $pluginHost;
|
||||
editor?.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const name = markdownTitle(buffer.relPath);
|
||||
const view = editor;
|
||||
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!focusTitle || !editor) return;
|
||||
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
|
||||
if (!button) return;
|
||||
button.click();
|
||||
onTitleFocused?.();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const value = buffer.contents;
|
||||
const path = buffer.relPath;
|
||||
|
||||
@@ -10,6 +10,9 @@ import { imageControls } from "./imageControls";
|
||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
@@ -54,20 +57,22 @@ class Checkbox extends WidgetType {
|
||||
}
|
||||
|
||||
class Preview extends WidgetType {
|
||||
readonly formulas = pluginHost.get("tableFormulas");
|
||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
|
||||
get estimatedHeight() { return this.height.value; }
|
||||
eq(other: Preview) { return other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||
measure(dom: HTMLElement, view: EditorView) {
|
||||
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
|
||||
}
|
||||
updateDOM(dom: HTMLElement, view: EditorView) {
|
||||
if (tableEditors.get(dom)?.source !== this.source) return false;
|
||||
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
|
||||
this.measure(dom, view);
|
||||
return true;
|
||||
}
|
||||
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement("div");
|
||||
previewFormulas.set(dom, this.formulas);
|
||||
dom.className = "reading writer-preview";
|
||||
dom.innerHTML = this.html;
|
||||
tableControls(dom, view, this.source, this.actions);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { isTableFormula } from "./tableFormulas.ts";
|
||||
// Preserve formula source even when calculation is disabled.
|
||||
const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||
|
||||
// Extract inline content into a note without confusing literal <br> in code
|
||||
// with actual cell hard breaks.
|
||||
|
||||
@@ -11,8 +11,7 @@ import { tableSelectionControls } from "./tableSelectionControls";
|
||||
import { tableDragControls } from "./tableDragControls";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas";
|
||||
import { tableFormulaHtml } from "../workspace/noteHtml";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
const cellFormats = ["math", "comment"].map(name => Mark.create({
|
||||
name,
|
||||
@@ -36,6 +35,7 @@ const CellImage = Image.extend({
|
||||
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
|
||||
|
||||
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
|
||||
const formulas = pluginHost.get("tableFormulas");
|
||||
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
||||
const table = scroll?.querySelector("table");
|
||||
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
||||
@@ -76,17 +76,17 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
|
||||
function refreshFormulas() {
|
||||
const parsed = parseMarkdownTable(controller.source);
|
||||
if (!parsed) return;
|
||||
if (!parsed || !formulas) return;
|
||||
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
|
||||
const results = evaluateTableFormulas(grid);
|
||||
const results = formulas.evaluateTableFormulas(grid);
|
||||
for (const row of table!.rows) for (const cell of row.cells) {
|
||||
const result = results[row.rowIndex]?.[cell.cellIndex];
|
||||
const address = cellAddress(row.rowIndex, cell.cellIndex);
|
||||
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
|
||||
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
|
||||
if (result && cell !== active) cell.innerHTML = tableFormulaHtml(result);
|
||||
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
|
||||
if (cell === active) {
|
||||
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
|
||||
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
|
||||
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
|
||||
formulaHint.hidden = !formulaHint.textContent;
|
||||
}
|
||||
}
|
||||
@@ -156,9 +156,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
// leave its previous active line so its Markdown markers render again.
|
||||
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
|
||||
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
|
||||
const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||
const formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||
const html = cell.innerHTML;
|
||||
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
|
||||
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)} · Type = to calculate` : "";
|
||||
cell.innerHTML = "";
|
||||
cell.classList.add("is-editing");
|
||||
editor = new Editor({
|
||||
@@ -239,7 +239,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
|
||||
if (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
|
||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||
else editor?.commands.setHardBreak();
|
||||
return true;
|
||||
@@ -301,48 +301,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "table-footer";
|
||||
const formulaTools = document.createElement("div");
|
||||
formulaTools.className = "table-formula-tools";
|
||||
const formulaHelp = document.createElement("details");
|
||||
formulaHelp.className = "table-formula-help";
|
||||
const summary = document.createElement("summary");
|
||||
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
|
||||
summary.title = "How to calculate with table cells";
|
||||
// Committing a wrapped formula can shrink its row. Keep the click target in
|
||||
// place until mouseup, then finish editing and give keyboard focus to help.
|
||||
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
|
||||
summary.addEventListener("click", () => { finish(); summary.focus(); });
|
||||
const instructions = document.createElement("div");
|
||||
instructions.className = "table-formula-instructions";
|
||||
const intro = document.createElement("p");
|
||||
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
|
||||
const examples = document.createElement("dl");
|
||||
for (const [formula, description] of [
|
||||
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
|
||||
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
|
||||
["=SUM(B2:B10)", "Add the values in a range."],
|
||||
["=(B2+C2)/2", "Add two values and divide by two."],
|
||||
["=ROUND(B2/3,2)", "Round to two decimal places."],
|
||||
]) {
|
||||
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
|
||||
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
|
||||
examples.append(term, descriptionElement);
|
||||
}
|
||||
const functions = document.createElement("p");
|
||||
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
|
||||
const references = document.createElement("p");
|
||||
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
|
||||
instructions.append(intro, examples, functions, references);
|
||||
formulaHelp.append(summary, instructions);
|
||||
formulaHelp.addEventListener("toggle", () => view.requestMeasure());
|
||||
const formulaStatus = document.createElement("span");
|
||||
formulaStatus.className = "table-formula-status";
|
||||
formulaStatus.textContent = "Type = in a cell to calculate";
|
||||
const formulaHint = document.createElement("div");
|
||||
formulaHint.className = "table-formula-hint";
|
||||
formulaHint.hidden = true;
|
||||
formulaTools.append(formulaHelp, formulaStatus);
|
||||
footer.append(help, formulaTools, formulaHint);
|
||||
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
|
||||
const formulaStatus = tools?.formulaStatus ?? document.createElement("span");
|
||||
const formulaHint = tools?.formulaHint ?? document.createElement("div");
|
||||
footer.append(help);
|
||||
if (tools) footer.append(tools.formulaTools, formulaHint);
|
||||
wrapper.after(footer);
|
||||
for (const kind of ["column", "row"] as const) {
|
||||
const button = document.createElement("button");
|
||||
@@ -365,7 +328,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
}
|
||||
for (const row of table.rows) for (const cell of row.cells) {
|
||||
cell.tabIndex = 0;
|
||||
cell.setAttribute("aria-label", `${cellAddress(row.rowIndex, cell.cellIndex)} · Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
|
||||
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
|
||||
cell.addEventListener("focus", () => activate(cell));
|
||||
}
|
||||
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
// Formulas are plain Markdown cell text. No JavaScript evaluation or external data.
|
||||
export const formulaErrors = {
|
||||
"#ERROR!": "Invalid formula syntax or function arguments",
|
||||
"#REF!": "Cell reference is outside this table",
|
||||
"#VALUE!": "Expected a number",
|
||||
"#NAME?": "Unknown function or cell name",
|
||||
"#DIV/0!": "Cannot divide by zero or average an empty range",
|
||||
"#CYCLE!": "Circular cell reference",
|
||||
"#NUM!": "Result is not a finite number",
|
||||
"#LIMIT!": "Formula is too complex",
|
||||
} as const;
|
||||
type ErrorCode = keyof typeof formulaErrors;
|
||||
export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode };
|
||||
class FormulaError extends Error {
|
||||
code: ErrorCode;
|
||||
constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; }
|
||||
}
|
||||
function fail(code: ErrorCode): never { throw new FormulaError(code); }
|
||||
export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||
|
||||
export function cellAddress(row: number, column: number): string {
|
||||
let letters = "";
|
||||
for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters;
|
||||
return letters + (row + 1);
|
||||
}
|
||||
|
||||
type Scalar = number | string | null;
|
||||
type Value = Scalar | Scalar[];
|
||||
const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!");
|
||||
const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!");
|
||||
const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
|
||||
|
||||
// Header is row 1; the Markdown separator is not a spreadsheet row.
|
||||
export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] {
|
||||
const cache = new Map<string, Scalar | FormulaError>();
|
||||
const visiting = new Set<string>();
|
||||
let budget = 50000;
|
||||
const spend = () => { if (--budget < 0) fail("#LIMIT!"); };
|
||||
function reference(address: string): [number, number] {
|
||||
const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!");
|
||||
let column = 0;
|
||||
for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
|
||||
const row = Number(match[2]);
|
||||
if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!");
|
||||
return [row - 1, column - 1];
|
||||
}
|
||||
function cell(row: number, column: number): Scalar {
|
||||
spend();
|
||||
const key = `${row}:${column}`;
|
||||
if (visiting.has(key)) fail("#CYCLE!");
|
||||
if (visiting.size >= 128) fail("#LIMIT!");
|
||||
const cached = cache.get(key);
|
||||
if (cached instanceof FormulaError) throw cached;
|
||||
if (cache.has(key)) return cached!;
|
||||
const source = (grid[row]?.[column] || "").trim();
|
||||
if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source;
|
||||
visiting.add(key);
|
||||
try {
|
||||
const value = parse(source.slice(1));
|
||||
cache.set(key, value);
|
||||
return value;
|
||||
} catch (error) {
|
||||
const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!");
|
||||
cache.set(key, problem);
|
||||
throw problem;
|
||||
} finally { visiting.delete(key); }
|
||||
}
|
||||
function parse(source: string): number {
|
||||
if (source.length > 2048) fail("#LIMIT!");
|
||||
const tokens: string[] = [];
|
||||
const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y;
|
||||
let offset = 0;
|
||||
while (offset < source.trimEnd().length) {
|
||||
pattern.lastIndex = offset;
|
||||
const match = pattern.exec(source) || fail("#ERROR!");
|
||||
tokens.push(match[1]); offset = pattern.lastIndex;
|
||||
}
|
||||
let position = 0, depth = 0;
|
||||
const peek = () => tokens[position];
|
||||
const take = () => { spend(); return tokens[position++]; };
|
||||
const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); };
|
||||
function expression(min = 0): Value {
|
||||
if (++depth > 64) fail("#LIMIT!");
|
||||
let left: Value;
|
||||
const token = take();
|
||||
if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1);
|
||||
else if (token === "(") { left = expression(); expect(")"); }
|
||||
else if (token && numeric.test(token)) left = finite(Number(token));
|
||||
else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) {
|
||||
const [row, column] = reference(token);
|
||||
if (peek() === ":") {
|
||||
take(); const [endRow, endColumn] = reference(take() || "");
|
||||
const values: Scalar[] = [];
|
||||
for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) {
|
||||
for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c));
|
||||
}
|
||||
left = values;
|
||||
} else left = cell(row, column);
|
||||
} else if (token && /^[a-z_]+$/i.test(token)) {
|
||||
if (peek() !== "(") fail("#NAME?");
|
||||
take(); const args: Value[] = [];
|
||||
if (peek() !== ")") {
|
||||
do { args.push(expression()); if (peek() !== ",") break; take(); } while (true);
|
||||
}
|
||||
expect(")");
|
||||
left = call(token.toUpperCase(), args);
|
||||
} else fail("#ERROR!");
|
||||
while (true) {
|
||||
const op = peek();
|
||||
if (op === "%") { take(); left = number(left) / 100; continue; }
|
||||
const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1;
|
||||
if (precedence < min) break;
|
||||
take();
|
||||
const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left);
|
||||
left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right);
|
||||
}
|
||||
depth--;
|
||||
return left;
|
||||
}
|
||||
const result = finite(number(expression()));
|
||||
if (position !== tokens.length) fail("#ERROR!");
|
||||
return result;
|
||||
}
|
||||
function call(name: string, args: Value[]): number {
|
||||
if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!");
|
||||
if (name === "ROUND") {
|
||||
if (args.length < 1 || args.length > 2) fail("#ERROR!");
|
||||
const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0;
|
||||
if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!");
|
||||
const factor = 10 ** digits, scaled = Math.abs(value) * factor;
|
||||
return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor);
|
||||
}
|
||||
if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?");
|
||||
const values = args.flat().filter((value): value is number => typeof value === "number");
|
||||
if (name === "COUNT") return values.length;
|
||||
if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0;
|
||||
const sum = finite(values.reduce((a, b) => a + b, 0));
|
||||
return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum;
|
||||
}
|
||||
return grid.map((row, r) => row.map((source, c) => {
|
||||
if (!isTableFormula(source)) return null;
|
||||
const formula = source.trim();
|
||||
try {
|
||||
const value = number(cell(r, c));
|
||||
return { formula, value, text: String(Number(value.toPrecision(12))) };
|
||||
} catch (error) {
|
||||
const code = error instanceof FormulaError ? error.code : "#LIMIT!";
|
||||
return { formula, text: code, error: code };
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -33,7 +33,14 @@
|
||||
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
|
||||
let previewMode = $state<"split" | "preview">("split");
|
||||
let modeControls = $state<HTMLDivElement>();
|
||||
let titleFocusId = $state<string | null>(null);
|
||||
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
|
||||
export function focusTitle(id: string) {
|
||||
titleFocusId = id;
|
||||
}
|
||||
$effect(() => {
|
||||
if (titleFocusId !== buffer?.id) titleFocusId = null;
|
||||
});
|
||||
const previewScroll = new Map<string, { top: number; left: number }>();
|
||||
$effect(() => {
|
||||
const ids = tabs.map(tab => tab.id);
|
||||
@@ -131,7 +138,8 @@
|
||||
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
|
||||
{#key buffer.id}
|
||||
{#if !isIde && canPreview && !reading}
|
||||
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} />
|
||||
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount}
|
||||
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
|
||||
{:else}
|
||||
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
|
||||
{/if}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { tick, type Snippet } from "svelte";
|
||||
import { workspaceReadDataUrl } from "$lib/workspace/api";
|
||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
|
||||
@@ -44,6 +45,7 @@
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void $pluginHost;
|
||||
const path = noteRel;
|
||||
const text = contents;
|
||||
let cancelled = false;
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
<script lang="ts">
|
||||
import PluginManager from "$lib/plugins/PluginManager.svelte";
|
||||
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 }: {
|
||||
settings: AppSettings;
|
||||
help?: boolean;
|
||||
onSave: (value: AppSettings) => void;
|
||||
onClose: () => void;
|
||||
} = $props();
|
||||
type Section = "general" | "plugins" | "about";
|
||||
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
|
||||
{ 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("");
|
||||
let seconds = $state<number | undefined>(untrack(() => settings.autosaveSeconds));
|
||||
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 selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
|
||||
|
||||
$effect(() => { seconds = settings.autosaveSeconds; });
|
||||
onMount(() => {
|
||||
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
dialog.showModal();
|
||||
return () => { dialog.close(); previous?.focus(); };
|
||||
});
|
||||
|
||||
function apply(value: AppSettings) {
|
||||
error = "";
|
||||
try { onSave(value); message = "Changes saved."; }
|
||||
catch { error = "Could not save these settings. Your previous settings still apply. Try again."; message = ""; }
|
||||
}
|
||||
|
||||
function changeInterval() {
|
||||
if (!validAutosaveSeconds(seconds)) {
|
||||
error = "Choose a whole number from 1 to 300 seconds.";
|
||||
message = "";
|
||||
return;
|
||||
}
|
||||
apply({ ...settings, autosaveSeconds: seconds });
|
||||
}
|
||||
|
||||
function select(next: Section) { section = next; error = ""; message = ""; seconds = settings.autosaveSeconds; }
|
||||
|
||||
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")]
|
||||
.filter(element => element.getClientRects().length > 0);
|
||||
const first = controls[0], last = controls.at(-1);
|
||||
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
||||
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<dialog bind:this={dialog} class:help 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} />
|
||||
</header>
|
||||
<div class="body">
|
||||
{#if !help}
|
||||
<aside>
|
||||
<label class="search"><Icon icon="search" /><input aria-label="Search settings" placeholder="Search settings…" bind:value={query} /></label>
|
||||
<p class="nav-heading">Preferences</p>
|
||||
<nav aria-label="Settings categories">
|
||||
{#each matches as item}
|
||||
<button class:active={selected?.id === item.id} aria-current={selected?.id === item.id ? "page" : undefined} onclick={() => select(item.id)}><Icon icon={item.icon} />{item.label}</button>
|
||||
{/each}
|
||||
</nav>
|
||||
<p class="scope">For all workspaces on this device.</p>
|
||||
</aside>
|
||||
{/if}
|
||||
<div class="content">
|
||||
{#if !selected}
|
||||
<h2>No settings found</h2>
|
||||
<p>Try “save”, “plug-ins”, or “help”.</p>
|
||||
<button class="text-button" onclick={() => query = ""}>Clear search</button>
|
||||
{:else if selected.id === "general"}
|
||||
<h2>General</h2>
|
||||
<p class="intro">Choose how RuneStone saves your work.</p>
|
||||
<h3>Files</h3>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><label for="autosave-enabled">Auto-save</label><p id="autosave-description">Save changed notes and scripts, including background tabs.</p></div>
|
||||
<input id="autosave-enabled" class="switch" type="checkbox" role="switch" aria-describedby="autosave-description" checked={settings.autosaveEnabled} onchange={event => { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="autosave-seconds">Auto-save interval</label><p id="interval-description">Time between saves, even while you type. Choose 1–300 seconds.</p></div>
|
||||
<div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>seconds</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="note">{settings.autosaveEnabled ? "Only changed files are saved." : "Auto-save is off. Use Ctrl+S to save your changes."} Disk conflicts keep your edits for review.</p>
|
||||
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>Restore defaults</button><span>Default: every 5 seconds</span></div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
{:else if selected.id === "plugins"}
|
||||
<PluginManager />
|
||||
{: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">
|
||||
<details open><summary><Icon icon="book-open" /> Get started</summary><div class="help-copy"><p>Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.</p><p>Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.</p><p>Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.</p></div></details>
|
||||
<details><summary><Icon icon="save" /> Save your work</summary><div class="help-copy"><p>Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.</p><p>If another app changes a file, RuneStone keeps your edits and offers both versions for review.</p></div></details>
|
||||
<details><summary><Icon icon="code" /> Keyboard shortcuts</summary><dl><div><dt>Open a workspace</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>Find a file</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>Save the active file</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>Search the workspace</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>Open settings</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>Help and about</dt><dd><kbd>F1</kbd></dd></div></dl></details>
|
||||
</div>
|
||||
<p class="about-note">RuneStone is under development. Maintained by kwyvern-gh.</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<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.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; }
|
||||
.body { display: flex; height: calc(100% - 48px); }
|
||||
aside { width: 220px; flex-shrink: 0; padding: 18px 12px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; }
|
||||
.search { display: flex; gap: 7px; align-items: center; background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 8px; color: var(--rs-text-dim); }
|
||||
.search:focus-within { outline: 2px solid var(--rs-accent); }
|
||||
.search input { width: 100%; min-width: 0; border: 0; padding: 0; outline: none; background: transparent; color: var(--rs-text); }
|
||||
.nav-heading { margin: 24px 10px 8px; font-size: 11px; color: var(--rs-text-dim); }
|
||||
nav { display: flex; flex-direction: column; gap: 4px; }
|
||||
nav button { display: flex; align-items: center; gap: 10px; width: 100%; padding: 10px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; }
|
||||
nav button:hover { background: var(--rs-bg-active); }
|
||||
nav button.active { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
|
||||
.scope { margin: auto 10px 0; padding-top: 24px; color: var(--rs-text-dim); font-size: 12px; }
|
||||
.content { padding: 30px 32px; flex: 1; min-width: 0; overflow-y: auto; }
|
||||
h2 { margin: 0; font-size: 23px; font-weight: 600; color: var(--rs-text-strong); }
|
||||
h3 { margin: 28px 0 12px; font-size: 14px; font-weight: 600; }
|
||||
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||
.intro { margin: 7px 0 24px; }
|
||||
.card { padding: 0 20px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: 10px; }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 22px 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.setting-row label { font-weight: 500; }
|
||||
.setting-row p { margin: 5px 0 0; font-size: 12px; }
|
||||
.switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||
.switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; }
|
||||
.switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||
.switch:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||
.interval { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; font-size: 11px; color: var(--rs-text-dim); }
|
||||
.interval input { width: 84px; padding: 9px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 14px; }
|
||||
.interval input:disabled { opacity: .45; }
|
||||
.note, .section-footer, .about-note { font-size: 12px; }
|
||||
.note { margin: 16px 0 24px; }
|
||||
.section-footer { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; color: var(--rs-text-dim); }
|
||||
.text-button { border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); padding: 8px 12px; color: var(--rs-text); }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; }
|
||||
.error { color: var(--rs-error); }
|
||||
.brand { text-align: center; margin-bottom: 26px; }
|
||||
.brand h2 { font-size: 28px; margin-top: 4px; }
|
||||
.brand p { margin: 6px 0; font-size: 12px; }
|
||||
.help-card details + details { border-top: 1px solid var(--rs-border); }
|
||||
summary { display: flex; align-items: center; gap: 12px; padding: 18px 0; cursor: pointer; list-style: none; border-radius: var(--rs-control-radius); }
|
||||
summary::after { content: "+"; margin-left: auto; color: var(--rs-text-dim); }
|
||||
details[open] summary::after { content: "−"; }
|
||||
.help-copy, dl { margin: 0 0 18px 28px; font-size: 12px; }
|
||||
.help-copy p:first-child { margin-top: 0; }
|
||||
dl div { display: flex; justify-content: space-between; gap: 12px; margin: 10px 0; }
|
||||
dd { margin: 0; }
|
||||
kbd { font-family: var(--rs-font-mono); color: var(--rs-text-dim); }
|
||||
.about-note { text-align: center; margin: 20px 0 0; }
|
||||
@media (max-width: 660px) {
|
||||
.body { flex-direction: column; }
|
||||
aside { width: 100%; padding: 12px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; }
|
||||
nav { flex-direction: row; margin-top: 10px; }
|
||||
nav button { width: auto; flex: 1; padding: 8px; gap: 6px; }
|
||||
.nav-heading, .scope { display: none; }
|
||||
.content { padding: 24px 18px; }
|
||||
.setting-row { gap: 14px; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,260 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, tick } from "svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { ptyProfiles, ptyNewWindow, ptyDictation, workspaceRead } from "$lib/workspace/api";
|
||||
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "$lib/terminal/model";
|
||||
import TerminalPicker from "$lib/terminal/TerminalPicker.svelte";
|
||||
import TerminalSettings from "$lib/terminal/TerminalSettings.svelte";
|
||||
import TerminalPane from "./TerminalPane.svelte";
|
||||
|
||||
type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string };
|
||||
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
|
||||
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks }: {
|
||||
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; onClose: () => void; onMaximize?: () => void;
|
||||
activeFile?: boolean; onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
|
||||
} = $props();
|
||||
let sessions = $state<Session[]>([]);
|
||||
let profiles = $state<ShellProfile[]>([]);
|
||||
let settings = $state(readSettings());
|
||||
let activeId = $state("");
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let railWidth = $state(205);
|
||||
let picker = $state<Picker | null>(null);
|
||||
let showSettings = $state(false);
|
||||
let recentCommands = $state<string[]>([]);
|
||||
let recentDirectories = $state<string[]>([]);
|
||||
let menu: HTMLElement | undefined;
|
||||
let menuAnchor: HTMLElement | undefined;
|
||||
let profileAnchor: HTMLDivElement;
|
||||
let moreAnchor: HTMLDivElement;
|
||||
let panes: HTMLDivElement;
|
||||
let sequence = 0;
|
||||
let stopResize: (() => void) | undefined;
|
||||
let ready: Promise<void> = Promise.resolve();
|
||||
const controls = new Map<string, TerminalControl>();
|
||||
const active = $derived(sessions.find(session => session.id === activeId));
|
||||
const group = $derived(sessions.filter(session => session.group === active?.group));
|
||||
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
|
||||
|
||||
function report(reason: unknown) { error = String(reason); }
|
||||
function persist(next: Settings) {
|
||||
settings = { ...next };
|
||||
try { localStorage.setItem("runestone.terminal", JSON.stringify(settings)); } catch (reason) { report(reason); }
|
||||
}
|
||||
function defaultProfile() { return profiles.find(profile => profile.id === settings.defaultProfile) || profiles.find(profile => profile.kind !== "node") || profiles[0]; }
|
||||
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
|
||||
if (!profile) return;
|
||||
const id = crypto.randomUUID();
|
||||
const next = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: "Starting", profile,
|
||||
directory: split && active ? active.directory : cwd, weight: 1, command };
|
||||
if (split) for (const member of group) member.weight = 1;
|
||||
sessions = [...sessions, next]; activeId = id;
|
||||
recentDirectories = remember(recentDirectories, next.directory);
|
||||
}
|
||||
function killSession(id: string) {
|
||||
const previous = sessions.findIndex(session => session.id === id);
|
||||
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
|
||||
sessions = sessions.filter(session => session.id !== id);
|
||||
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
|
||||
void tick().then(() => controls.get(activeId)?.focus());
|
||||
}
|
||||
function select(id: string) { activeId = id; }
|
||||
function closeMenu(focus = false) { menu?.remove(); menu = undefined; if (focus) menuAnchor?.querySelector<HTMLButtonElement>("button")?.focus(); }
|
||||
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
|
||||
const same = menu && menuAnchor === anchor; closeMenu(); if (same) return;
|
||||
menuAnchor = anchor;
|
||||
const wrap = (entries: ActionMenuItem[]): ActionMenuItem[] => entries.map(item => "separator" in item ? item : { ...item,
|
||||
children: item.children ? wrap(item.children) : undefined,
|
||||
run: item.run ? () => { closeMenu(); item.run?.(); } : undefined });
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
menu = actionMenu(bounds.right - 430, bounds.bottom + 4, wrap(items), () => closeMenu(true), name);
|
||||
}
|
||||
function profileMenu() {
|
||||
showMenu(profileAnchor, [
|
||||
{ label: "New Terminal", icon: "plus", shortcut: "Ctrl+Shift+`", run: () => addSession() },
|
||||
{ label: "New Terminal Window", icon: "external", shortcut: "Ctrl+Shift+Alt+`", run: () => void ptyNewWindow().catch(report) },
|
||||
{ label: "Split Terminal", icon: "column", shortcut: "Ctrl+Shift+5", disabled: !active, run: () => addSession(active?.profile, true) },
|
||||
{ separator: true },
|
||||
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? "Node.js REPL with a local inspector. Attach using an external debugger." : undefined, run: () => addSession(profile) })),
|
||||
{ label: "Split Terminal with Profile", icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
|
||||
{ separator: true },
|
||||
{ label: "Configure Terminal Settings", icon: "format", run: () => showSettings = true },
|
||||
{ label: "Select Default Profile", icon: "select", run: () => picker = { title: "Select default terminal profile", items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === settings.defaultProfile ? "Default" : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
|
||||
{ separator: true },
|
||||
{ label: "Run Task…", icon: "task", run: () => void runTask() },
|
||||
{ label: "Configure Tasks…", icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
|
||||
], "Terminal profiles");
|
||||
}
|
||||
async function runFile() {
|
||||
const target = active;
|
||||
if (!target || !onRunFile) return;
|
||||
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
|
||||
}
|
||||
function runSelection() {
|
||||
const text = getSelection();
|
||||
if (!text) { error = "Select text in the editor first."; return; }
|
||||
controls.get(activeId)?.send(text);
|
||||
}
|
||||
function historyPicker(kind: "commands" | "directories") {
|
||||
const target = active;
|
||||
if (!target) return;
|
||||
picker = { title: kind === "commands" ? "Run recent command" : "Go to recent directory",
|
||||
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
|
||||
empty: kind === "commands" ? "No commands yet. Shell commands appear after the next prompt." : "No directories yet.",
|
||||
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
|
||||
}
|
||||
async function runTask() {
|
||||
try {
|
||||
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
|
||||
picker = { title: "Run task", items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: "No tasks configured. Choose Configure Tasks… to add one.", onPick: index => {
|
||||
const task = tasks[Number(index)];
|
||||
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
|
||||
if (!profile) { error = `Task profile is unavailable: ${task.profile}`; return; }
|
||||
addSession(profile, false, task.command, task.label);
|
||||
} };
|
||||
} catch (reason) { error = `Cannot load .runestone/tasks.json. Use Configure Tasks… to create or edit it. ${String(reason)}`; }
|
||||
}
|
||||
function moreMenu() {
|
||||
showMenu(moreAnchor, [
|
||||
{ label: "Scroll to Previous Command", icon: "up", shortcut: "Ctrl+UpArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
|
||||
{ label: "Scroll to Next Command", icon: "down", shortcut: "Ctrl+DownArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
|
||||
{ label: "Clear Terminal", icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
|
||||
{ label: "Run Active File", icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
|
||||
{ label: "Run Selected Text", icon: "select", disabled: !active || !activeFile, run: runSelection },
|
||||
{ label: "Start Dictation", icon: "comment", disabled: !active, title: "Start Windows voice typing in the focused terminal", run: () => { controls.get(activeId)?.focus(); void ptyDictation().catch(report); } },
|
||||
{ separator: true },
|
||||
{ label: "Go to Recent Directory…", icon: "external", shortcut: "Ctrl+G", disabled: !active, run: () => historyPicker("directories") },
|
||||
{ label: "Run Recent Command…", icon: "task", shortcut: "Ctrl+Alt+R", disabled: !active, run: () => historyPicker("commands") },
|
||||
], "Terminal actions");
|
||||
}
|
||||
export async function command(action: "new" | "split" | "window" | "previous" | "next" | "commands" | "directories") {
|
||||
await ready;
|
||||
if (action === "new") addSession();
|
||||
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
|
||||
else if (action === "window") void ptyNewWindow().catch(report);
|
||||
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
|
||||
else historyPicker(action);
|
||||
}
|
||||
function beginResize(event: PointerEvent, update: (x: number) => void) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault(); stopResize?.();
|
||||
const move = (event: PointerEvent) => update(event.clientX);
|
||||
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
|
||||
const stop = () => stopResize?.();
|
||||
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
|
||||
}
|
||||
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
|
||||
function resizeSplit(event: PointerEvent, session: Session) {
|
||||
const index = group.indexOf(session), previous = group[index - 1];
|
||||
if (!previous) return;
|
||||
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
|
||||
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
|
||||
}
|
||||
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = ptyProfiles().then(found => {
|
||||
if (disposed) return;
|
||||
profiles = found;
|
||||
if (!profiles.some(profile => profile.id === settings.defaultProfile)) settings.defaultProfile = defaultProfile()?.id || "";
|
||||
if (profiles.length) addSession(); else error = "No supported shells were found on PATH.";
|
||||
}).catch(report).finally(() => loading = false);
|
||||
const outside = (event: PointerEvent) => { if (menu && !menu.contains(event.target as Node) && !menuAnchor?.contains(event.target as Node)) closeMenu(); };
|
||||
const resize = () => closeMenu();
|
||||
window.addEventListener("pointerdown", outside); window.addEventListener("resize", resize);
|
||||
return () => { disposed = true; closeMenu(); stopResize?.(); window.removeEventListener("pointerdown", outside); window.removeEventListener("resize", resize); };
|
||||
});
|
||||
$effect(() => { if (!visible) { closeMenu(); picker = null; showSettings = false; } });
|
||||
</script>
|
||||
|
||||
<div class="dock" style:--rail="{railWidth}px">
|
||||
<header class="ribbon">
|
||||
<span class="label" title={cwd}>Terminal</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
|
||||
<div class="actions">
|
||||
{#if sessions.length === 1}<span class="single-session" title={`${active?.title} · ${active?.state}`}>{active?.profile.title}</span>{/if}
|
||||
<IconButton icon="plus" label="New terminal" disabled={loading || !profiles.length} onclick={() => addSession()} />
|
||||
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label="Terminal profiles and tasks" disabled={loading} onclick={profileMenu} /></div>
|
||||
<IconButton icon="split" label="Split terminal (Ctrl+Shift+5)" disabled={!active} onclick={() => addSession(active?.profile, true)} />
|
||||
<div bind:this={moreAnchor}><IconButton icon="more" label="More terminal actions" onclick={moreMenu} /></div>
|
||||
<IconButton icon="trash" label="Kill terminal" disabled={!active} onclick={() => killSession(activeId)} />
|
||||
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? "Restore panel" : "Maximize panel"} onclick={onMaximize} />{/if}
|
||||
<IconButton icon="close" label={standalone ? "Close terminal window" : "Hide terminal (sessions keep running)"} onclick={onClose} />
|
||||
</div>
|
||||
</header>
|
||||
{#if error}<div class="error" role="alert"><span>{error}</span><button aria-label="Dismiss terminal error" onclick={() => error = ""}>×</button></div>{/if}
|
||||
<div class="body">
|
||||
<div class="panes" bind:this={panes}>
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
|
||||
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
|
||||
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
|
||||
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings}
|
||||
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
|
||||
onState={state => { session.state = state; if (state === "Running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
|
||||
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
|
||||
onCommand={command => recentCommands = remember(recentCommands, command)}
|
||||
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
|
||||
{#if session.group === active?.group && group.indexOf(session) > 0}
|
||||
<div class="split-gutter" role="separator" aria-label="Resize split terminals" aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if !sessions.length}<div class="empty"><p>{loading ? "Detecting terminal profiles…" : "No terminal sessions."}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>Start a terminal</button></div>{/if}
|
||||
</div>
|
||||
{#if sessions.length > 1}
|
||||
<div class="gutter" role="separator" aria-orientation="vertical" aria-label="Resize terminal list" onpointerdown={resizeRail}></div>
|
||||
<nav class="rail" aria-label="Terminal list">
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
|
||||
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${session.state} · ${session.directory}`} onclick={() => select(session.id)}
|
||||
onkeydown={event => {
|
||||
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
|
||||
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{session.state}</small></span></button>
|
||||
<div class="row-actions">
|
||||
<IconButton icon="split" label={`Split ${session.title}`} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
|
||||
<IconButton icon="trash" label={`Kill ${session.title} (Del)`} onclick={() => killSession(session.id)} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</nav>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
|
||||
{#if showSettings}<TerminalSettings {settings} {profiles} onSave={persist} onClose={() => showSettings = false} />{/if}
|
||||
<style>
|
||||
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||
.ribbon { display: flex; align-items: center; gap: 10px; flex: 0 0 36px; padding: 0 8px; background: var(--rs-bg-elevated); }
|
||||
.label { font-size: 13px; color: var(--rs-text-strong); }
|
||||
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
|
||||
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
|
||||
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
|
||||
.body { display: flex; flex: 1; min-height: 0; }
|
||||
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
|
||||
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
|
||||
.pane.shown { visibility: visible; }
|
||||
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
|
||||
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; }
|
||||
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
|
||||
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
|
||||
.gutter { flex: 0 0 4px; cursor: col-resize; }
|
||||
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
|
||||
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); }
|
||||
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; }
|
||||
.item.grouped { border-left-color: var(--rs-border); }
|
||||
.item.active { background: var(--rs-bg-active); border-left-color: var(--rs-accent); }
|
||||
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; background: transparent; text-align: left; padding: 5px; }
|
||||
.shell-icon { color: var(--rs-text-dim); }
|
||||
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
|
||||
.row-actions { visibility: hidden; }
|
||||
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
|
||||
.error { padding: 7px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
|
||||
.error span { flex: 1; }
|
||||
.error button, .empty button { background: var(--rs-bg-active); border: 1px solid var(--rs-border); padding: 4px 8px; }
|
||||
.empty { padding: 20px; color: var(--rs-text-dim); }
|
||||
@media (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
|
||||
</style>
|
||||
@@ -1,218 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { onMount } from "svelte";
|
||||
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "$lib/workspace/api";
|
||||
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "$lib/terminal/model";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
cwd: string;
|
||||
active: boolean;
|
||||
focused: boolean;
|
||||
profile: ShellProfile;
|
||||
directory: string;
|
||||
settings: TerminalSettings;
|
||||
onFocus: () => void;
|
||||
onControl: (control: TerminalControl | null) => void;
|
||||
onCommand: (command: string) => void;
|
||||
onDirectory: (directory: string) => void;
|
||||
onState: (state: string) => void;
|
||||
};
|
||||
|
||||
let { id, cwd, active, focused, profile, directory, settings, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let focusTerminal: (() => void) | undefined = $state();
|
||||
let instance = $state.raw<Terminal>();
|
||||
let resizeTerminal: (() => void) | undefined;
|
||||
|
||||
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
|
||||
$effect(() => {
|
||||
if (instance) {
|
||||
instance.options.fontSize = settings.fontSize;
|
||||
instance.options.scrollback = settings.scrollback;
|
||||
instance.options.cursorBlink = settings.cursorBlink;
|
||||
requestAnimationFrame(() => resizeTerminal?.());
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
const term = new Terminal({
|
||||
scrollback: settings.scrollback,
|
||||
fontFamily: "Cascadia Code, Cascadia Mono, Consolas, monospace",
|
||||
fontSize: settings.fontSize,
|
||||
cursorBlink: settings.cursorBlink,
|
||||
allowProposedApi: true,
|
||||
theme: {
|
||||
background: "#141414",
|
||||
foreground: "#e6e6e6",
|
||||
cursor: "#82aaff",
|
||||
selectionBackground: "#264f78",
|
||||
black: "#3b4252",
|
||||
red: "#bf616a",
|
||||
green: "#a3be8c",
|
||||
yellow: "#ebcb8b",
|
||||
blue: "#81a1c1",
|
||||
magenta: "#b48ead",
|
||||
cyan: "#88c0d0",
|
||||
white: "#e5e9f0",
|
||||
},
|
||||
});
|
||||
const fit = new FitAddon();
|
||||
term.loadAddon(fit);
|
||||
term.open(host);
|
||||
instance = term;
|
||||
term.attachCustomKeyEventHandler(event => !terminalShortcut(event));
|
||||
let disposed = false;
|
||||
let opened = false;
|
||||
let exited = false;
|
||||
const pendingInput: string[] = [];
|
||||
let writes = Promise.resolve();
|
||||
const unlisteners: (() => void)[] = [];
|
||||
const fail = (err: unknown) => {
|
||||
if (!disposed) term.writeln(`\r\n${String(err)}`);
|
||||
};
|
||||
const resize = () => {
|
||||
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
|
||||
fit.fit();
|
||||
if (opened && !exited) void ptyResize(id, term.cols, term.rows).catch(fail);
|
||||
};
|
||||
resizeTerminal = resize;
|
||||
focusTerminal = () => { resize(); term.focus(); };
|
||||
const send = (data: string) => {
|
||||
if (exited || disposed) return;
|
||||
if (!opened) { pendingInput.push(data); return; }
|
||||
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
|
||||
};
|
||||
const onData = term.onData(send);
|
||||
let markers: import("@xterm/xterm").IMarker[] = [];
|
||||
let prompt: { marker: import("@xterm/xterm").IMarker; column: number } | undefined;
|
||||
const promptParser = term.parser.registerOscHandler(133, data => {
|
||||
if (data === "A") {
|
||||
const marker = term.registerMarker(0);
|
||||
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
|
||||
}
|
||||
if (data === "B") {
|
||||
prompt?.marker.dispose();
|
||||
const marker = term.registerMarker(0);
|
||||
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const integration = term.parser.registerOscHandler(633, data => {
|
||||
const separator = data.indexOf(";");
|
||||
const type = data.slice(0, separator), value = data.slice(separator + 1);
|
||||
try {
|
||||
if (type === "Cwd") onDirectory(value);
|
||||
if (type === "RSCwd" || type === "RSCommand") {
|
||||
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
|
||||
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
|
||||
}
|
||||
} catch { /* Ignore malformed shell integration output. */ }
|
||||
return true;
|
||||
});
|
||||
const keys = term.onKey(({ domEvent }) => {
|
||||
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
|
||||
const buffer = term.buffer.active;
|
||||
let command = "";
|
||||
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
|
||||
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
|
||||
}
|
||||
if (command.trim()) onCommand(command);
|
||||
prompt.marker.dispose(); prompt = undefined;
|
||||
});
|
||||
onControl({
|
||||
focus: () => { resize(); term.focus(); },
|
||||
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
|
||||
scrollCommand: direction => {
|
||||
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
|
||||
const current = term.buffer.active.viewportY;
|
||||
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
|
||||
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
|
||||
},
|
||||
send: (text, execute = true) => {
|
||||
if (exited) return;
|
||||
term.paste(text.replace(/\r?\n/g, "\r"));
|
||||
if (execute) send("\r");
|
||||
term.focus();
|
||||
},
|
||||
});
|
||||
const start = async () => {
|
||||
try {
|
||||
// Subscribe before spawning: shells and agents can print immediately.
|
||||
const offData = await listen<{ id: string; data: number[] }>("pty-data", (event) => {
|
||||
if (!disposed && event.payload.id === id) term.write(new Uint8Array(event.payload.data));
|
||||
});
|
||||
unlisteners.push(offData);
|
||||
if (disposed) return;
|
||||
const offExit = await listen<{ id: string; code: number | null }>("pty-exit", (event) => {
|
||||
if (!disposed && event.payload.id === id) {
|
||||
exited = true;
|
||||
onState(`Exited${event.payload.code === null ? "" : ` (${event.payload.code})`}`);
|
||||
term.writeln(`\r\n[Process exited${event.payload.code === null ? "" : ` with code ${event.payload.code}`} ]`);
|
||||
}
|
||||
});
|
||||
unlisteners.push(offExit);
|
||||
if (disposed) return;
|
||||
resize();
|
||||
await ptyOpen(id, term.cols, term.rows, cwd, profile.id, directory);
|
||||
opened = true;
|
||||
if (disposed) { await ptyClose(id); return; }
|
||||
// Includes xterm's replies to startup cursor-position queries.
|
||||
for (const data of pendingInput.splice(0)) {
|
||||
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
|
||||
}
|
||||
if (!exited) onState("Running");
|
||||
resize();
|
||||
if (active && focused) term.focus();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
if (!disposed) onState("Failed");
|
||||
} finally {
|
||||
if (disposed) unlisteners.splice(0).forEach((off) => off());
|
||||
}
|
||||
};
|
||||
void start();
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(host);
|
||||
return () => {
|
||||
disposed = true;
|
||||
focusTerminal = undefined;
|
||||
instance = undefined;
|
||||
resizeTerminal = undefined;
|
||||
onControl(null);
|
||||
observer.disconnect();
|
||||
onData.dispose();
|
||||
promptParser.dispose(); integration.dispose(); keys.dispose();
|
||||
unlisteners.splice(0).forEach((off) => off());
|
||||
if (opened) void ptyClose(id).catch(() => {});
|
||||
term.dispose();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
|
||||
|
||||
<style>
|
||||
.term {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: 4px;
|
||||
background: #141414;
|
||||
}
|
||||
|
||||
.term :global(.xterm),
|
||||
.term :global(.xterm-viewport) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.term :global(.xterm-viewport) {
|
||||
/* Whole terminal rows can leave a gap above the bottom edge. */
|
||||
background-color: transparent;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,10 @@
|
||||
<script lang="ts">
|
||||
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||
import { onMount, tick } from "svelte";
|
||||
import { selectedEditorText } from "$lib/editor/selection";
|
||||
import { terminalShortcut } from "$lib/terminal/model";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { Contributions } from "$lib/plugins/contracts";
|
||||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
@@ -13,6 +16,8 @@
|
||||
import TextDialog from "./TextDialog.svelte";
|
||||
import QuickOpen from "./QuickOpen.svelte";
|
||||
import WorkspacePicker from "./WorkspacePicker.svelte";
|
||||
import SettingsDialog from "./SettingsDialog.svelte";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
import FileTree from "./FileTree.svelte";
|
||||
import EditorPane from "./EditorPane.svelte";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
@@ -21,7 +26,7 @@
|
||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||
import SearchPane from "./SearchPane.svelte";
|
||||
import BookmarksPane from "./BookmarksPane.svelte";
|
||||
import TerminalDock from "./TerminalDock.svelte";
|
||||
|
||||
import { buildOutline } from "$lib/workspace/outline";
|
||||
import {
|
||||
onWorkspaceEvent,
|
||||
@@ -46,6 +51,9 @@
|
||||
|
||||
let workspace = $state<WorkspaceInfo | null>(null);
|
||||
let workspacePicker: WorkspacePicker;
|
||||
let preferences = $state<"settings" | "help" | null>(null);
|
||||
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
||||
let settingsReady = $state(false);
|
||||
let workspaceAnchor: HTMLDivElement | undefined = $state();
|
||||
const desktop = isTauri();
|
||||
let tabs = $state<OpenBuffer[]>([]);
|
||||
@@ -67,7 +75,16 @@
|
||||
let quickOpen = $state(false);
|
||||
let terminalStarted = $state(false);
|
||||
let terminalMaximized = $state(false);
|
||||
let terminalDock: TerminalDock | undefined = $state();
|
||||
let terminalDock: TerminalSlot | undefined = $state();
|
||||
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||
const terminalEnabled = $derived(!!terminalContribution);
|
||||
|
||||
$effect(() => {
|
||||
if (!terminalEnabled) {
|
||||
terminalOpen = false; terminalStarted = false; terminalMaximized = false;
|
||||
}
|
||||
});
|
||||
|
||||
let saving = $state(false);
|
||||
let switching = false;
|
||||
let documents: Documents | null = null;
|
||||
@@ -110,18 +127,20 @@
|
||||
}
|
||||
|
||||
function toggleTerminal() {
|
||||
if (!terminalEnabled) return;
|
||||
terminalOpen = !terminalOpen;
|
||||
if (terminalOpen) terminalStarted = true;
|
||||
if (terminalOpen) { terminalStarted = true; }
|
||||
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
||||
}
|
||||
|
||||
async function terminalAction(action: Exclude<ReturnType<typeof terminalShortcut>, null | "toggle">) {
|
||||
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
|
||||
if (!terminalEnabled) return;
|
||||
if (!workspace) { error = "Open a workspace to start a terminal."; return; }
|
||||
const started = terminalStarted;
|
||||
terminalStarted = true; terminalOpen = true;
|
||||
if (bottomHeight < 220) bottomHeight = 260;
|
||||
await tick();
|
||||
if (action !== "new" || started) await terminalDock?.command(action);
|
||||
if (terminalEnabled && (action !== "new" || started)) await terminalDock?.command(action);
|
||||
}
|
||||
|
||||
async function terminalFile(): Promise<string | null> {
|
||||
@@ -269,6 +288,14 @@
|
||||
} catch (err) { if (documents === current) error = String(err); }
|
||||
}
|
||||
|
||||
async function openCreatedFile(entry: TreeEntry) {
|
||||
const current = documents;
|
||||
await openFile(entry);
|
||||
if (documents !== current || current?.active?.relPath !== entry.rel_path || !isMarkdownPath(entry.rel_path)) return;
|
||||
reading = false;
|
||||
editorPane?.focusTitle(current.active.id);
|
||||
}
|
||||
|
||||
function readFileDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
@@ -384,7 +411,7 @@
|
||||
try {
|
||||
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
||||
refreshToken += 1;
|
||||
await openFile({
|
||||
await openCreatedFile({
|
||||
name: name.split("/").pop() ?? name,
|
||||
rel_path: name.replaceAll("\\", "/"),
|
||||
kind: "file",
|
||||
@@ -394,9 +421,19 @@
|
||||
}
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||
event.preventDefault(); event.stopPropagation(); preferences = "help";
|
||||
}
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
||||
const action = terminalShortcut(event);
|
||||
const action = pluginHost.get("terminal")?.shortcut(event);
|
||||
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
||||
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
|
||||
event.preventDefault();
|
||||
@@ -431,7 +468,7 @@
|
||||
event.preventDefault();
|
||||
toggleChrome();
|
||||
}
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === "`") {
|
||||
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
|
||||
event.preventDefault();
|
||||
toggleTerminal();
|
||||
}
|
||||
@@ -540,14 +577,38 @@
|
||||
}
|
||||
}
|
||||
|
||||
function updateSettings(next: AppSettings) {
|
||||
saveSettings(localStorage, next);
|
||||
settings = { ...next };
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
||||
settingsReady = true;
|
||||
const syncSettings = (event: StorageEvent) => {
|
||||
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) settings = parseSettings(event.newValue);
|
||||
};
|
||||
window.addEventListener("storage", syncSettings);
|
||||
window.addEventListener("keydown", onPreferencesKeydown, true);
|
||||
return () => {
|
||||
window.removeEventListener("storage", syncSettings);
|
||||
window.removeEventListener("keydown", onPreferencesKeydown, true);
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!desktop || !settingsReady || !settings.autosaveEnabled) return;
|
||||
const timer = setInterval(() => { void autosave(); }, settings.autosaveSeconds * 1000);
|
||||
return () => clearInterval(timer);
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (!isTauri()) { status = "Desktop features require pnpm tauri dev"; return; }
|
||||
void restoreLast();
|
||||
let disposed = false;
|
||||
const unlisteners: (() => void)[] = [];
|
||||
let refreshTimer: ReturnType<typeof setTimeout>;
|
||||
// A fixed interval also saves during continuous typing; clean files never write.
|
||||
const autosaveTimer = setInterval(() => { void autosave(); }, 5_000);
|
||||
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
||||
void onWorkspaceEvent((event) => {
|
||||
if (event.root !== workspace?.root || event.kind === "access") return;
|
||||
@@ -576,7 +637,6 @@
|
||||
documents?.dispose();
|
||||
clearTimeout(refreshTimer);
|
||||
unlisteners.forEach(off => off());
|
||||
clearInterval(autosaveTimer);
|
||||
window.removeEventListener("focus", focus);
|
||||
};
|
||||
});
|
||||
@@ -586,6 +646,7 @@
|
||||
<svelte:window onkeydown={onKeydown} onbeforeunload={(event) => { if (hasDirty) { event.preventDefault(); event.returnValue = ""; } }} />
|
||||
<TextDialog />
|
||||
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
||||
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
|
||||
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
||||
|
||||
<div
|
||||
@@ -632,8 +693,9 @@
|
||||
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
||||
</div>
|
||||
<div class="header-right" data-tauri-drag-region>
|
||||
<PluginTools />
|
||||
<IconButton icon="save" label="Save" disabled={!dirty || saving} onclick={() => void save()} />
|
||||
<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />
|
||||
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
|
||||
<IconButton
|
||||
icon="panel-right"
|
||||
label={rightOpen ? "Hide outline" : "Show outline"}
|
||||
@@ -659,7 +721,7 @@
|
||||
{refreshToken}
|
||||
keysActive={leftView === "files"}
|
||||
onCreated={(entry) => {
|
||||
void openFile(entry);
|
||||
void openCreatedFile(entry);
|
||||
}}
|
||||
onStatus={(message) => {
|
||||
status = message;
|
||||
@@ -682,6 +744,10 @@
|
||||
<IconButton icon="folder-open" label="Open folder" onclick={chooseWorkspace} />
|
||||
<span class="ws">{workspace ? workspace.name : "No workspace"}</span>
|
||||
</div>
|
||||
<div class="footer-actions">
|
||||
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
|
||||
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => preferences = "settings"} />
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -727,7 +793,7 @@
|
||||
/>
|
||||
</div>
|
||||
</main>
|
||||
{#if terminalStarted}
|
||||
{#if terminalContribution && terminalStarted}
|
||||
<div
|
||||
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
||||
role="separator"
|
||||
@@ -736,7 +802,7 @@
|
||||
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
||||
{#if workspace}
|
||||
{#key workspace.root}
|
||||
<TerminalDock bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={toggleTerminal}
|
||||
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={toggleTerminal}
|
||||
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
||||
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
||||
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
||||
@@ -973,12 +1039,16 @@
|
||||
}
|
||||
|
||||
.footer-start {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.footer-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
|
||||
.footer-actions :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
||||
|
||||
.placeholder {
|
||||
margin: 12px;
|
||||
color: var(--rs-text-dim);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from "svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
||||
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
|
||||
const desktop = isTauri();
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
let message = $state("");
|
||||
let candidates = $state<Candidate[]>([]);
|
||||
let selected = $state<string[]>([]);
|
||||
let plan = $state<RemovalPlan | null>(null);
|
||||
let modal: HTMLDialogElement | undefined = $state();
|
||||
let cancelButton: HTMLButtonElement | undefined = $state();
|
||||
let previous: HTMLElement | null = null;
|
||||
const external = $derived($installedPlugins.plugins);
|
||||
$effect(() => {
|
||||
if (modal && (plan || candidates.length)) {
|
||||
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
|
||||
if (!busy) cancelButton?.focus();
|
||||
}
|
||||
});
|
||||
function tokens() { return [...candidates.map(item => item.token), ...(plan ? [plan.token] : [])]; }
|
||||
async function cancel() {
|
||||
if (busy) return;
|
||||
const pending = tokens();
|
||||
plan = null; candidates = []; selected = [];
|
||||
modal?.close(); previous?.focus();
|
||||
if (pending.length) await invoke("plugins_cancel", { tokens: pending }).catch(reason => error = String(reason));
|
||||
}
|
||||
onDestroy(() => { const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
|
||||
async function run(action: () => Promise<void>) {
|
||||
busy = true; error = ""; message = "";
|
||||
try { await action(); } catch (reason) { error = String(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
async function choose(folder: boolean) {
|
||||
await run(async () => {
|
||||
candidates = await invoke<Candidate[]>("plugins_choose", { folder });
|
||||
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
|
||||
});
|
||||
}
|
||||
async function install(enabled: boolean) {
|
||||
await run(async () => {
|
||||
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
|
||||
message = result.filter(item => !item.error).map(item => `${item.name} installed${enabled ? " and enabled" : ""}.`).join(" ");
|
||||
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
|
||||
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
|
||||
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
|
||||
});
|
||||
}
|
||||
async function toggle(id: string, enabled: boolean, hash?: string) {
|
||||
await run(async () => {
|
||||
await setPluginEnabled(id, enabled, hash);
|
||||
message = "Changes saved.";
|
||||
});
|
||||
}
|
||||
async function prepare(plugin: InstalledPlugin) {
|
||||
await run(async () => { plan = await invoke<RemovalPlan>("plugins_prepare_remove", { id: plugin.manifest.id }); });
|
||||
}
|
||||
async function remove() {
|
||||
if (!plan) return;
|
||||
const current = plan;
|
||||
await run(async () => {
|
||||
try { await invoke("plugins_remove", { token: current.token }); message = `${current.plugin.manifest.name} uninstalled. Settings and workspace documents were kept.`; }
|
||||
finally { plan = null; await refreshPlugins(); previous?.focus(); }
|
||||
});
|
||||
}
|
||||
async function reveal(id?: string) { await run(async () => { await invoke("plugins_reveal", { id: id ?? null }); }); }
|
||||
function trap(event: KeyboardEvent) {
|
||||
event.stopPropagation();
|
||||
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
|
||||
if (event.key !== "Tab" || !modal) return;
|
||||
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled)")];
|
||||
const first = controls[0], last = controls.at(-1);
|
||||
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
||||
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<h2>Plug-ins</h2>
|
||||
<p>Install a package file or select a folder containing plugins.</p>
|
||||
<div class="toolbar">
|
||||
<button disabled={!desktop || busy} onclick={() => choose(false)}><Icon icon="file-plus" />Install from file</button>
|
||||
<button disabled={!desktop || busy} onclick={() => choose(true)}><Icon icon="folder-plus" />Install from folder</button>
|
||||
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} />
|
||||
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button>
|
||||
</div>
|
||||
{#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if}
|
||||
{#if !desktop}<p>Installation requires the RuneStone desktop app.</p>{/if}
|
||||
{#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if}
|
||||
<h3>Installed plugins</h3>
|
||||
<p class="note">Plugins run with RuneStone's access. Only enable code you trust.</p>
|
||||
{#if !external.length}<p>No plugins installed.</p>{/if}
|
||||
{#each external as plugin (plugin.manifest.id)}
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<div><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small></div>
|
||||
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.enabled} disabled={busy || plugin.removal} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||
</div>
|
||||
<p class="path">{plugin.path}</p>
|
||||
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||
<div class="actions">
|
||||
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
|
||||
<button disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)}><Icon icon="folder-open" />Show files</button>
|
||||
{#if plugin.removal}
|
||||
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
|
||||
{:else}
|
||||
<button class="danger" disabled={busy} aria-label={`Uninstall ${plugin.manifest.name}`} onclick={() => prepare(plugin)}><Icon icon="trash" />Uninstall</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
|
||||
{#if candidates.length || plan}
|
||||
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
|
||||
{#if plan}
|
||||
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
|
||||
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
|
||||
<p class="path">{plan.plugin.path}</p>
|
||||
<p>This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.</p>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<footer>
|
||||
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button>
|
||||
<button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>Disable instead</button>
|
||||
<button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? "Removing…" : "Uninstall and delete files"}</button>
|
||||
</footer>
|
||||
{:else}
|
||||
<h2 id="plugin-dialog-title">Review plugin installation</h2>
|
||||
<p>Plugins run with RuneStone's access. Only enable code you trust.</p>
|
||||
{#each candidates as candidate (candidate.token)}
|
||||
<div class="candidate">
|
||||
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? "Invalid package"}</label>
|
||||
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">Destination: {$installedPlugins.root}\{candidate.manifest.id}</p>{/if}
|
||||
<p class="path">Source: {candidate.source}</p>
|
||||
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button disabled={busy || !selected.length} onclick={() => install(false)}>Install</button><button disabled={busy || !selected.length} onclick={() => install(true)}>Install and enable</button></footer>
|
||||
{/if}
|
||||
</dialog>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
h2 { margin: 0; font-size: 23px; color: var(--rs-text-strong); }
|
||||
h3 { font-size: 14px; margin: 24px 0 10px; }
|
||||
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||
button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled { opacity: .5; }
|
||||
.toolbar, .actions, footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 18px 14px; margin-bottom: 12px; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 18px 0; }
|
||||
.row p { margin: 5px 0; font-size: 12px; }
|
||||
label { font-weight: 500; }
|
||||
.path { overflow-wrap: anywhere; font-size: 11px; }
|
||||
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
|
||||
.badge { margin-right: auto; }
|
||||
.error { color: var(--rs-error); white-space: pre-wrap; }
|
||||
.saved { color: var(--rs-ok); min-height: 20px; }
|
||||
.danger { color: var(--rs-error); }
|
||||
input[role=switch] { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||
input[role=switch]::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; }
|
||||
input[role=switch]:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||
input[role=switch]:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 24px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
dialog::backdrop { background: #0009; }
|
||||
footer { justify-content: flex-end; margin-top: 24px; }
|
||||
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
|
||||
.candidate label { display: flex; gap: 8px; }
|
||||
</style>
|
||||
@@ -0,0 +1,64 @@
|
||||
<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);
|
||||
let error = $state("");
|
||||
let dialog: HTMLDialogElement | undefined = $state();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let previous: HTMLElement | null = null;
|
||||
$effect(() => {
|
||||
const view = $pluginView;
|
||||
const element = host;
|
||||
const modal = dialog;
|
||||
if (!view || !element || !modal) return;
|
||||
previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
modal.showModal(); error = "";
|
||||
let cancelled = false;
|
||||
let cleanup: (() => void | Promise<void>) | undefined;
|
||||
void mountPluginView(view.owner, view.id, element).then(dispose => {
|
||||
if (cancelled) void Promise.resolve(dispose()).catch(reason => error = String(reason)); else cleanup = dispose;
|
||||
}).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}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
|
||||
{#if $pluginView}
|
||||
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
|
||||
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<div class="plugin-content" bind:this={host}></div>
|
||||
</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; }
|
||||
h2 { font-size: 18px; }
|
||||
.plugin-content { min-height: 140px; }
|
||||
.error { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import type { Contributions, TerminalProps, TerminalMount, TerminalAction } from "./contracts";
|
||||
let { contribution, ...props }: TerminalProps & { contribution: Contributions["terminal"] } = $props();
|
||||
let container: HTMLDivElement;
|
||||
let mounted = $state.raw<TerminalMount>();
|
||||
let error = $state("");
|
||||
onMount(() => {
|
||||
try { mounted = contribution.mount(container, { ...props }); }
|
||||
catch (reason) { error = String(reason); }
|
||||
return () => { void Promise.resolve(mounted?.dispose()).catch(reason => error = String(reason)); mounted = undefined; };
|
||||
});
|
||||
$effect(() => { mounted?.update({ ...props }); });
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await mounted?.command(action); }
|
||||
</script>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
<div class="plugin-terminal" bind:this={container}></div>
|
||||
<style>.plugin-terminal { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }</style>
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Token } from "markdown-it";
|
||||
import type { Dispose } from "./sdk.ts";
|
||||
|
||||
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
||||
export interface TerminalProps {
|
||||
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean;
|
||||
onClose: () => void; onMaximize?: () => void; activeFile?: boolean;
|
||||
onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
|
||||
}
|
||||
export interface TerminalMount {
|
||||
update(props: TerminalProps): void;
|
||||
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
|
||||
dispose: Dispose;
|
||||
}
|
||||
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 {
|
||||
terminal: {
|
||||
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
|
||||
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
|
||||
};
|
||||
tableFormulas: {
|
||||
formulaErrors: Record<FormulaErrorCode, string>;
|
||||
isTableFormula(text: string): boolean;
|
||||
cellAddress(row: number, column: number): string;
|
||||
evaluateTableFormulas(rows: string[][]): (FormulaResult | null)[][];
|
||||
tableFormulaHtml(result: FormulaResult): string;
|
||||
renderTableFormulas(tokens: Token[]): void;
|
||||
createFormulaTools(finish: () => void, measure: () => void): { formulaTools: HTMLDivElement; formulaStatus: HTMLSpanElement; formulaHint: HTMLDivElement };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { writable } from "svelte/store";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { workspaceList, workspaceRead, workspaceWrite } from "../workspace/api";
|
||||
import { ExternalSession, deadline } from "./externalSession";
|
||||
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose } from "./sdk";
|
||||
|
||||
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||
export const externalErrors = writable<Record<string, string>>({});
|
||||
export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]);
|
||||
export const pluginView = writable<{ owner: string; id: string; title: string } | null>(null);
|
||||
export const pluginServiceError = writable("");
|
||||
export const restartPlugins = writable<string[]>([]);
|
||||
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
|
||||
const failures = new Map<string, string>();
|
||||
const errors: Record<string, string> = {};
|
||||
const restarted = new Set<string>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let started = false;
|
||||
let generation = 0;
|
||||
|
||||
function publish() {
|
||||
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 })),
|
||||
]));
|
||||
externalErrors.set({ ...errors });
|
||||
}
|
||||
function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); }
|
||||
async function release(id: string, error?: string) {
|
||||
await invoke("plugins_release", { id, error: error ?? null });
|
||||
}
|
||||
async function stop(id: string) {
|
||||
const loaded = sessions.get(id);
|
||||
if (!loaded) return;
|
||||
sessions.delete(id);
|
||||
pluginView.update(view => view?.owner === id ? null : view);
|
||||
restarted.add(id); restartPlugins.set([...restarted]);
|
||||
let error: string | undefined;
|
||||
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
|
||||
await release(id, error); publish();
|
||||
}
|
||||
function show(owner: string, id: string) {
|
||||
const view = sessions.get(owner)?.session.views.get(id);
|
||||
if (view) pluginView.set({ owner, id, title: view.title });
|
||||
}
|
||||
async function activate(row: InstalledPlugin) {
|
||||
const id = row.manifest.id;
|
||||
let leased = false;
|
||||
const session = new ExternalSession(id, {
|
||||
workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, write: workspaceWrite },
|
||||
settings: {
|
||||
read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })),
|
||||
write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); },
|
||||
},
|
||||
assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) },
|
||||
}, publish, view => show(id, view));
|
||||
try {
|
||||
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
|
||||
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
|
||||
let module: PluginModule;
|
||||
try { module = await deadline(import(/* @vite-ignore */ url)); }
|
||||
catch (reason) { await release(id, String(reason)); leased = false; throw reason; }
|
||||
finally { URL.revokeObjectURL(url); }
|
||||
sessions.set(id, { hash: row.hash, session });
|
||||
await session.start(module);
|
||||
delete errors[id]; publish();
|
||||
} catch (reason) {
|
||||
failures.set(id, row.hash); report(id, reason);
|
||||
let cleanupError: string | undefined;
|
||||
try { await session.stop(); } catch (error) { cleanupError = String(error); }
|
||||
sessions.delete(id);
|
||||
if (leased) await release(id, cleanupError);
|
||||
publish();
|
||||
}
|
||||
}
|
||||
export function refreshPlugins(): Promise<void> {
|
||||
if (!isTauri()) return Promise.resolve();
|
||||
const version = generation;
|
||||
const job = async () => {
|
||||
try {
|
||||
const snapshot = await invoke<PluginSnapshot | null>("plugins_snapshot");
|
||||
if (!snapshot || version !== generation) return;
|
||||
installedPlugins.set(snapshot); pluginServiceError.set("");
|
||||
for (const id of sessions.keys()) {
|
||||
const row = snapshot.plugins.find(row => row.manifest.id === id);
|
||||
if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id);
|
||||
}
|
||||
for (const row of snapshot.plugins) {
|
||||
const id = row.manifest.id;
|
||||
if (!row.enabled) { failures.delete(id); continue; }
|
||||
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
|
||||
}
|
||||
} catch (reason) { pluginServiceError.set(String(reason)); }
|
||||
};
|
||||
queue = queue.then(job, job);
|
||||
return queue;
|
||||
}
|
||||
export async function setPluginEnabled(id: string, enabled: boolean, hash?: string) {
|
||||
await invoke("plugins_set_enabled", { id, enabled, hash: hash ?? null });
|
||||
await refreshPlugins();
|
||||
}
|
||||
export async function runPluginCommand(owner: string, id: string) {
|
||||
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
|
||||
}
|
||||
export function openPluginView(owner: string, id: string) { show(owner, id); }
|
||||
export async function mountPluginView(owner: string, id: string, element: HTMLElement): Promise<Dispose> {
|
||||
const session = sessions.get(owner)?.session;
|
||||
if (!session) throw new Error("The plugin is disabled.");
|
||||
return session.mount(id, element);
|
||||
}
|
||||
export function startExternalPlugins(): () => void {
|
||||
if (!isTauri() || started) return () => {};
|
||||
started = true;
|
||||
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)));
|
||||
void refreshPlugins();
|
||||
const focus = () => { void refreshPlugins(); };
|
||||
window.addEventListener("focus", focus);
|
||||
// Also detects changes made in a file manager while this window stays open.
|
||||
const timer = setInterval(focus, 5000);
|
||||
return () => {
|
||||
disposed = true; started = false; generation++; off?.(); clearInterval(timer); window.removeEventListener("focus", focus);
|
||||
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
||||
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView } from "./sdk.ts";
|
||||
|
||||
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
return Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Plugin cleanup or activation timed out. Restart RuneStone.")), milliseconds); })]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** Revokes host access before cleanup, including when activation is still pending. */
|
||||
export class ExternalSession {
|
||||
readonly controller = new AbortController();
|
||||
readonly commands = new Map<string, PluginCommand>();
|
||||
readonly views = new Map<string, PluginView>();
|
||||
private cleanups: Dispose[] = [];
|
||||
private stopped = false;
|
||||
private activation: Promise<void> = Promise.resolve();
|
||||
private stopping?: Promise<void>;
|
||||
private lateCleanup?: Promise<void>;
|
||||
private mounted = new Set<Dispose>();
|
||||
private contributions: Dispose[] = [];
|
||||
private registry: ContributionRegistry;
|
||||
readonly id: string;
|
||||
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
|
||||
private changed: () => void;
|
||||
private show: (id: string) => void;
|
||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost) {
|
||||
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."); }
|
||||
async start(module: PluginModule) {
|
||||
const register = <T extends { id: string; title: string }>(map: Map<string, T>, item: T) => {
|
||||
this.check();
|
||||
if (!/^[a-z][a-z0-9.-]*$/.test(item.id) || !item.title?.trim() || map.has(item.id)) throw new Error("Invalid or duplicate plugin contribution.");
|
||||
map.set(item.id, item); this.changed();
|
||||
};
|
||||
const api: PluginApi = {
|
||||
id: this.id, signal: this.controller.signal,
|
||||
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
||||
registerCommand: item => { if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
|
||||
registerView: item => { if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||
openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); },
|
||||
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
|
||||
workspace: {
|
||||
list: path => { this.check(); return this.services.workspace.list(path); },
|
||||
read: path => { this.check(); return this.services.workspace.read(path); },
|
||||
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: {
|
||||
read: () => { this.check(); return this.services.settings.read(); },
|
||||
write: value => { this.check(); return this.services.settings.write(value); },
|
||||
},
|
||||
assets: { read: path => { this.check(); return this.services.assets.read(path); } },
|
||||
};
|
||||
this.activation = Promise.resolve().then(() => {
|
||||
if (typeof module.activate !== "function") throw new Error("The plugin must export activate(api).");
|
||||
this.check(); return module.activate(api);
|
||||
}).then(async cleanup => {
|
||||
if (typeof cleanup === "function") {
|
||||
if (this.stopped) { this.lateCleanup = Promise.resolve().then(cleanup); await this.lateCleanup; } else this.cleanups.push(cleanup);
|
||||
}
|
||||
});
|
||||
await deadline(this.activation);
|
||||
}
|
||||
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
|
||||
async mount(id: string, element: HTMLElement): Promise<Dispose> {
|
||||
this.check(); const view = this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
|
||||
let cleaning: Promise<void> | undefined;
|
||||
const pending = Promise.resolve().then(() => { this.check(); return view.mount(element); });
|
||||
const cleanup = () => {
|
||||
cleaning ??= (async () => {
|
||||
const dispose = await pending;
|
||||
if (typeof dispose === "function") await dispose();
|
||||
element.replaceChildren(); this.mounted.delete(cleanup);
|
||||
})();
|
||||
return cleaning;
|
||||
};
|
||||
this.mounted.add(cleanup);
|
||||
try { await deadline(pending); } catch (error) { await deadline(cleanup()).catch(() => {}); throw error; }
|
||||
if (this.stopped) await cleanup();
|
||||
return cleanup;
|
||||
}
|
||||
stop(): Promise<void> {
|
||||
if (this.stopping) return this.stopping;
|
||||
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.changed();
|
||||
for (const remove of this.contributions.splice(0)) remove();
|
||||
this.stopping = (async () => {
|
||||
const errors: unknown[] = [];
|
||||
// Activation rejection is reported by start. A timeout still blocks removal.
|
||||
try { await deadline(this.activation.catch(() => {})); } catch (error) { errors.push(error); }
|
||||
if (this.lateCleanup) { try { await deadline(this.lateCleanup); } catch (error) { errors.push(error); } }
|
||||
for (const cleanup of [...this.mounted, ...this.cleanups.reverse()]) {
|
||||
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
|
||||
}
|
||||
this.cleanups = [];
|
||||
if (errors.length) throw new Error(errors.map(String).join("\n"));
|
||||
})();
|
||||
return this.stopping;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Contributions } from "./contracts.ts";
|
||||
|
||||
/** Contributions belong to installed package sessions. This registry never loads code. */
|
||||
export class ContributionRegistry {
|
||||
private entries = new Map<keyof Contributions, { owner: string; value: Contributions[keyof Contributions] }>();
|
||||
private listeners = new Set<(revision: number) => void>();
|
||||
private revision = 0;
|
||||
get<K extends keyof Contributions>(key: K): Contributions[K] | undefined {
|
||||
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 (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
|
||||
const entry = { owner, value };
|
||||
this.entries.set(key, entry); this.emit();
|
||||
return () => {
|
||||
if (this.entries.get(key) !== entry) return;
|
||||
this.entries.delete(key); this.emit();
|
||||
};
|
||||
}
|
||||
subscribe = (listener: (revision: number) => void) => {
|
||||
this.listeners.add(listener); listener(this.revision);
|
||||
return () => { this.listeners.delete(listener); };
|
||||
};
|
||||
private emit() { this.revision++; for (const listener of this.listeners) listener(this.revision); }
|
||||
}
|
||||
export const pluginHost = new ContributionRegistry();
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Contributions } from "./contracts.ts";
|
||||
/** Package API v1. Compiled plugins export activate(api). */
|
||||
export type Dispose = () => void | Promise<void>;
|
||||
export interface PluginCommand { id: string; title: string; run: () => void | Promise<void> }
|
||||
export interface PluginView { id: string; title: string; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
|
||||
export interface PluginApi {
|
||||
readonly id: string;
|
||||
readonly signal: AbortSignal;
|
||||
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
|
||||
registerCommand(command: PluginCommand): void;
|
||||
registerView(view: PluginView): void;
|
||||
openView(id: string): void;
|
||||
onDispose(cleanup: Dispose): void;
|
||||
workspace: {
|
||||
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
|
||||
read(path: string): Promise<string>;
|
||||
write(path: string, contents: string, expected: string): Promise<void>;
|
||||
};
|
||||
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
|
||||
assets: { read(path: string): Promise<Uint8Array> };
|
||||
}
|
||||
export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise<void | Dispose> }
|
||||
export interface ExternalManifest {
|
||||
schemaVersion: 1; id: string; name: string; author: string; description: string;
|
||||
version: string; apiVersion: 1; entry: string; access: "full-app";
|
||||
}
|
||||
export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; path: string; error: string | null; removal: boolean }
|
||||
export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] }
|
||||
export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null }
|
||||
export interface RemovalPlan { token: string; plugin: InstalledPlugin }
|
||||
@@ -1,43 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, tick } from "svelte";
|
||||
let { title, items, onPick, onClose, empty = "No entries yet." }: {
|
||||
title: string; items: { label: string; detail?: string; value: string }[];
|
||||
onPick: (value: string) => void; onClose: () => void; empty?: string;
|
||||
} = $props();
|
||||
let query = $state("");
|
||||
let selected = $state(0);
|
||||
let dialog: HTMLDialogElement;
|
||||
let input: HTMLInputElement;
|
||||
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
|
||||
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
|
||||
onMount(() => { dialog.showModal(); input.focus(); });
|
||||
</script>
|
||||
<dialog bind:this={dialog} oncancel={onClose} aria-label={title}>
|
||||
<header>{title}<button aria-label="Close picker" onclick={onClose}>×</button></header>
|
||||
<input bind:this={input} bind:value={query} aria-label={title} placeholder="Type to filter…" oninput={() => selected = 0} onkeydown={event => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]?.value); }
|
||||
}} />
|
||||
<div class="results">
|
||||
{#each matches as item, index}
|
||||
<button data-index={index} class:selected={index === selected} onclick={() => pick(item.value)}><span>{item.label}</span>{#if item.detail}<small>{item.detail}</small>{/if}</button>
|
||||
{/each}
|
||||
{#if !matches.length}<p>{query ? "No matching entries." : empty}</p>{/if}
|
||||
</div>
|
||||
<footer>↑ ↓ select · Enter choose · Esc close</footer>
|
||||
</dialog>
|
||||
<style>
|
||||
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; }
|
||||
dialog::backdrop { background: #0008; }
|
||||
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
|
||||
input { width: 100%; padding: 14px; background: var(--rs-bg); color: var(--rs-text-strong); border: 0; }
|
||||
.results { max-height: 50vh; overflow: auto; padding: 6px; }
|
||||
button { background: transparent; border: 0; padding: 8px; }
|
||||
.results button { display: flex; flex-direction: column; width: 100%; text-align: left; gap: 4px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
button.selected, button:hover { background: var(--rs-bg-active); }
|
||||
small, footer, p { color: var(--rs-text-dim); }
|
||||
footer { padding: 10px 14px; border-top: 1px solid var(--rs-border); font-size: 12px; }
|
||||
</style>
|
||||
@@ -1,30 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack } from "svelte";
|
||||
import type { TerminalSettings, ShellProfile } from "./model";
|
||||
let { settings, profiles, onSave, onClose }: { settings: TerminalSettings; profiles: ShellProfile[]; onSave: (settings: TerminalSettings) => void; onClose: () => void } = $props();
|
||||
let value = $state(untrack(() => ({ ...settings })));
|
||||
let dialog: HTMLDialogElement;
|
||||
onMount(() => dialog.showModal());
|
||||
</script>
|
||||
<dialog bind:this={dialog} oncancel={onClose} aria-label="Terminal settings">
|
||||
<form onsubmit={event => { event.preventDefault(); onSave(value); onClose(); }}>
|
||||
<h2>Terminal settings</h2>
|
||||
<label>Default profile<select aria-label="Default profile" bind:value={value.defaultProfile}>{#each profiles.filter(p => p.kind !== "node") as profile}<option value={profile.id}>{profile.title}</option>{/each}</select></label>
|
||||
<label>Font size<input type="number" min="9" max="28" required bind:value={value.fontSize} /></label>
|
||||
<label>Scrollback lines<input type="number" min="100" max="100000" step="100" required bind:value={value.scrollback} /></label>
|
||||
<label class="check"><input type="checkbox" bind:checked={value.cursorBlink} />Blink cursor</label>
|
||||
<p>Appearance applies to open sessions. The default profile applies to new terminals.</p>
|
||||
<footer><button type="button" onclick={onClose}>Cancel</button><button type="submit">Save settings</button></footer>
|
||||
</form>
|
||||
</dialog>
|
||||
<style>
|
||||
dialog { width: min(450px, 90vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; padding: 24px; }
|
||||
dialog::backdrop { background: #0008; }
|
||||
h2 { font-size: 18px; margin: 0 0 8px; }
|
||||
form { display: flex; flex-direction: column; gap: 16px; }
|
||||
label { display: flex; flex-direction: column; gap: 6px; }
|
||||
label.check { flex-direction: row; }
|
||||
input, select, button { background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); padding: 7px; }
|
||||
p { color: var(--rs-text-dim); font-size: 12px; margin: 0; }
|
||||
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
</style>
|
||||
@@ -1,19 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import TerminalDock from "$lib/layout/TerminalDock.svelte";
|
||||
import { terminalShortcut } from "./model";
|
||||
let { cwd }: { cwd: string } = $props();
|
||||
let dock: TerminalDock;
|
||||
let error = $state("");
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
||||
const action = terminalShortcut(event);
|
||||
if (action && action !== "toggle") { event.preventDefault(); void dock.command(action); }
|
||||
}
|
||||
</script>
|
||||
<svelte:window onkeydown={keydown} />
|
||||
<div class="window">
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
<TerminalDock bind:this={dock} {cwd} visible standalone onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
||||
</div>
|
||||
<style>.window { height: 100vh; display: flex; flex-direction: column; }</style>
|
||||
@@ -1,70 +0,0 @@
|
||||
export type ShellProfile = { id: string; title: string; kind: "powershell" | "bash" | "cmd" | "node" };
|
||||
export type TerminalSettings = { defaultProfile: string; fontSize: number; scrollback: number; cursorBlink: boolean };
|
||||
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
|
||||
export type TerminalTask = { label: string; command: string; profile?: string };
|
||||
export const defaultSettings: TerminalSettings = { defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true };
|
||||
|
||||
export function readSettings(): TerminalSettings {
|
||||
try {
|
||||
const value = JSON.parse(localStorage.getItem("runestone.terminal") || "{}");
|
||||
return { defaultProfile: typeof value.defaultProfile === "string" ? value.defaultProfile : "",
|
||||
fontSize: Number.isFinite(value.fontSize) ? Math.min(28, Math.max(9, value.fontSize)) : 13,
|
||||
scrollback: Number.isFinite(value.scrollback) ? Math.min(100000, Math.max(100, value.scrollback)) : 10000,
|
||||
cursorBlink: typeof value.cursorBlink === "boolean" ? value.cursorBlink : true };
|
||||
} catch { return { ...defaultSettings }; }
|
||||
}
|
||||
|
||||
export function quoteShell(value: string, kind: ShellProfile["kind"]): string {
|
||||
if (/[\r\n\0]/.test(value)) throw new Error("Paths cannot contain line breaks or null characters.");
|
||||
if (kind === "cmd") {
|
||||
// Expansion happens even inside cmd quotes. Reject rather than execute a different path.
|
||||
if (/["%!]/.test(value)) throw new Error("Use PowerShell for paths containing quotes, % or !.");
|
||||
return `"${value}"`;
|
||||
}
|
||||
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export function directoryCommand(path: string, kind: ShellProfile["kind"]): string {
|
||||
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
|
||||
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
|
||||
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
|
||||
}
|
||||
|
||||
export function fileCommand(path: string, kind: ShellProfile["kind"]): string {
|
||||
if (kind === "node") throw new Error("Choose a shell terminal to run files. The debug terminal is a Node.js REPL.");
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
|
||||
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
|
||||
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
|
||||
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
|
||||
if (runner === null) throw new Error("No runner for this file type. Use Run Selected Text or configure a task.");
|
||||
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
|
||||
}
|
||||
|
||||
export function parseTasks(text: string): TerminalTask[] {
|
||||
const value = JSON.parse(text);
|
||||
if (!Array.isArray(value.tasks)) throw new Error('Tasks must contain a "tasks" array.');
|
||||
return value.tasks.map((task: unknown) => {
|
||||
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|
||||
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|
||||
|| ("profile" in task && typeof task.profile !== "string")) throw new Error("Each task needs a label, command, and optional profile ID.");
|
||||
return task as TerminalTask;
|
||||
});
|
||||
}
|
||||
|
||||
export function remember(items: string[], value: string): string[] {
|
||||
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
|
||||
}
|
||||
|
||||
export function terminalShortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories" | null {
|
||||
if (!event.ctrlKey && !event.metaKey) return null;
|
||||
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
|
||||
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
|
||||
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
|
||||
return null;
|
||||
}
|
||||
@@ -4,7 +4,13 @@
|
||||
let { icon }: { icon: IconName } = $props();
|
||||
</script>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
{#if icon === "up" || icon === "down"}
|
||||
{#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 === "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"}
|
||||
<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" />
|
||||
{:else if icon === "up" || icon === "down"}
|
||||
{@html actionIcons[icon]}
|
||||
{:else if icon === "more"}
|
||||
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
|
||||
@@ -25,6 +31,8 @@
|
||||
<path d="M12 4v16M6 8h3M6 12h3M15 8h3M15 12h3M15 16h3" />
|
||||
{:else if icon === "text"}
|
||||
<path d="M4 6h16M4 10h16M4 14h10M4 18h13" />
|
||||
{:else if icon === "refresh"}
|
||||
<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1" />
|
||||
{:else if icon === "folder-open"}
|
||||
<path d="M6 14l1.5-2.9A2 2 0 0 1 9.2 10H20a2 2 0 0 1 1.8 2.8l-1.5 3.2A2 2 0 0 1 18.5 17H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3.7a2 2 0 0 1 1.4.6L10 6h8a2 2 0 0 1 2 2" />
|
||||
{:else if icon === "file-plus"}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { onDestroy } from "svelte";
|
||||
import Icon from "./Icon.svelte";
|
||||
export type IconName =
|
||||
| "settings"
|
||||
| "help"
|
||||
| "puzzle"
|
||||
| "split"
|
||||
| "more"
|
||||
| "chevron-down"
|
||||
@@ -12,6 +15,7 @@
|
||||
| "window-maximize"
|
||||
| "window-restore"
|
||||
| "restore"
|
||||
| "refresh"
|
||||
| "text"
|
||||
| "folder-open"
|
||||
| "file-plus"
|
||||
|
||||
@@ -95,30 +95,6 @@ export function workspaceSearch(query: string): Promise<SearchHit[]> {
|
||||
return invoke("workspace_search", { query });
|
||||
}
|
||||
|
||||
export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise<void> {
|
||||
return invoke("pty_open", { id, cols, rows, cwd, profile, directory });
|
||||
}
|
||||
|
||||
export function ptyProfiles(): Promise<import("$lib/terminal/model").ShellProfile[]> {
|
||||
return invoke("pty_profiles");
|
||||
}
|
||||
export function ptyNewWindow(): Promise<void> {
|
||||
return invoke("pty_new_window", { id: crypto.randomUUID() });
|
||||
}
|
||||
export function ptyDictation(): Promise<void> { return invoke("pty_dictation"); }
|
||||
|
||||
export function ptyWrite(id: string, data: string): Promise<void> {
|
||||
return invoke("pty_write", { id, data });
|
||||
}
|
||||
|
||||
export function ptyResize(id: string, cols: number, rows: number): Promise<void> {
|
||||
return invoke("pty_resize", { id, cols, rows });
|
||||
}
|
||||
|
||||
export function ptyClose(id: string): Promise<void> {
|
||||
return invoke("pty_close", { id });
|
||||
}
|
||||
|
||||
export function onWorkspaceEvent(
|
||||
handler: (event: WorkspaceEvent) => void,
|
||||
): Promise<UnlistenFn> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
import { inlineMathEnd } from "./inlineMath.ts";
|
||||
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "../editor/tableFormulas.ts";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
||||
export const escapeHtml = markdown.utils.escapeHtml;
|
||||
@@ -156,31 +156,8 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
|
||||
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
||||
|
||||
export function tableFormulaHtml(result: FormulaResult): string {
|
||||
const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`;
|
||||
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
|
||||
}
|
||||
|
||||
// Work from raw inline content, before Markdown formatting can interpret * or $.
|
||||
// Each table gets its own reference scope, including in nested lists/callouts.
|
||||
markdown.core.ruler.after("inline", "table_formulas", state => {
|
||||
let rows: Token[][] | undefined;
|
||||
for (const token of state.tokens) {
|
||||
if (token.type === "table_open") rows = [];
|
||||
else if (rows && token.type === "tr_open") rows.push([]);
|
||||
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
|
||||
else if (rows && token.type === "table_close") {
|
||||
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
|
||||
rows.forEach((row, r) => row.forEach((cell, c) => {
|
||||
const result = results[r][c];
|
||||
if (!result) return;
|
||||
const output = new MarkdownIt.Token("html_inline", "", 0);
|
||||
output.content = tableFormulaHtml(result);
|
||||
cell.children = [output];
|
||||
}));
|
||||
rows = undefined;
|
||||
}
|
||||
}
|
||||
pluginHost.get("tableFormulas")?.renderTableFormulas(state.tokens);
|
||||
});
|
||||
|
||||
function documentParts(contents: string) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
export const SETTINGS_KEY = "runestone.settings";
|
||||
export const MIN_AUTOSAVE_SECONDS = 1;
|
||||
export const MAX_AUTOSAVE_SECONDS = 300;
|
||||
|
||||
export interface AppSettings {
|
||||
autosaveEnabled: boolean;
|
||||
autosaveSeconds: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
|
||||
autosaveEnabled: true,
|
||||
autosaveSeconds: 5,
|
||||
};
|
||||
|
||||
export function validAutosaveSeconds(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isInteger(value)
|
||||
&& value >= MIN_AUTOSAVE_SECONDS && value <= MAX_AUTOSAVE_SECONDS;
|
||||
}
|
||||
|
||||
export function parseSettings(raw: string | null): AppSettings {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
return {
|
||||
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||
};
|
||||
} catch { return { ...DEFAULT_SETTINGS }; }
|
||||
}
|
||||
|
||||
export function saveSettings(storage: Pick<Storage, "setItem">, settings: AppSettings): void {
|
||||
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
||||
throw new Error("Choose a whole number from 1 to 300 seconds.");
|
||||
}
|
||||
storage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||
}
|
||||
+27
-3
@@ -1,7 +1,31 @@
|
||||
<script lang="ts">
|
||||
import { startExternalPlugins } from "$lib/plugins/external";
|
||||
import { onMount } from "svelte";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import Workbench from "$lib/layout/Workbench.svelte";
|
||||
import TerminalWindow from "$lib/terminal/TerminalWindow.svelte";
|
||||
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
|
||||
let dock: TerminalSlot | undefined = $state();
|
||||
let error = $state("");
|
||||
const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||
onMount(startExternalPlugins);
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
||||
const action = terminal?.shortcut(event);
|
||||
if (action && action !== "toggle") { event.preventDefault(); void dock?.command(action).catch(reason => error = String(reason)); }
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if terminalRoot}<TerminalWindow cwd={terminalRoot} />{:else}<Workbench />{/if}
|
||||
<svelte:window onkeydown={keydown} />
|
||||
{#if terminalRoot}
|
||||
<div class="terminal-window">
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#if terminal}
|
||||
{#key terminal}
|
||||
<TerminalSlot bind:this={dock} contribution={terminal} cwd={terminalRoot} visible standalone
|
||||
onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
||||
{/key}
|
||||
{:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if}
|
||||
</div>
|
||||
{:else}<Workbench />{/if}
|
||||
<style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style>
|
||||
|
||||
Reference in New Issue
Block a user