Release RuneStone 0.1.4 with installable plugins and settings

This commit is contained in:
Knotty Wyvern
2026-10-04 15:05:51 -07:00
parent 0268c5c9f0
commit 6b7af0d527
82 changed files with 4150 additions and 212 deletions
+46
View File
@@ -0,0 +1,46 @@
import { actionIcon } from "../../src/lib/ui/actionIcons.ts";
export function createFormulaTools(finish: () => void, measure: () => void) {
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", measure);
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);
return { formulaTools, formulaStatus, formulaHint };
}
+151
View File
@@ -0,0 +1,151 @@
// 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 };
}
}));
}
+8
View File
@@ -0,0 +1,8 @@
import type { PluginApi } from "../../src/lib/plugins/sdk.ts";
import { createFormulaTools } from "./controls.ts";
import * as formulas from "./formulas.ts";
import { tableFormulaHtml, renderTableFormulas } from "./render.ts";
export function activate(api: PluginApi) {
api.contribute("tableFormulas", { ...formulas, tableFormulaHtml, renderTableFormulas, createFormulaTools });
}
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": 1,
"id": "runestone.table-formulas",
"name": "Table formulas",
"author": "RuneStone",
"description": "Calculate formulas in Markdown tables.",
"version": "1.0.0",
"apiVersion": 1,
"entry": "main.js",
"access": "full-app"
}
+29
View File
@@ -0,0 +1,29 @@
import MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "./formulas.ts";
const escapeHtml = (text: string) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
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>`;
}
export function renderTableFormulas(tokens: Token[]) {
let rows: Token[][] | undefined;
for (const token of 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;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
<script lang="ts">
import { untrack } from "svelte";
import type { TerminalProps, TerminalAction } from "../../src/lib/plugins/contracts";
import TerminalDock from "./TerminalDock.svelte";
let { initial }: { initial: TerminalProps } = $props();
let dockProps = $state<TerminalProps>(untrack(() => initial));
let dock: TerminalDock;
export function update(value: TerminalProps) { dockProps = value; }
export async function command(action: Exclude<TerminalAction, "toggle">) { await dock.command(action); }
</script>
<TerminalDock bind:this={dock} {...dockProps} />
+261
View File
@@ -0,0 +1,261 @@
<script lang="ts">
import { onMount, tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { workspaceRead } from "$lib/workspace/api";
import { ptyProfiles, ptyNewWindow, ptyDictation } from "./api";
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "./model";
import TerminalPicker from "./TerminalPicker.svelte";
import TerminalSettings from "./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>
+218
View File
@@ -0,0 +1,218 @@
<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 "./api";
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "./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>
+43
View File
@@ -0,0 +1,43 @@
<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>
+30
View File
@@ -0,0 +1,30 @@
<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>
+47
View File
@@ -0,0 +1,47 @@
import { invoke } from "@tauri-apps/api/core";
const sessions = new Set<string>();
const opening = new Set<Promise<void>>();
const closing = new Map<string, Promise<void>>();
let stopped = false;
export async function closeTerminals(): Promise<void> {
stopped = true;
await Promise.allSettled([...opening]);
const results = await Promise.allSettled([...sessions].map(ptyClose));
const errors = results.filter(result => result.status === "rejected");
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
}
export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise<void> {
if (stopped) return Promise.reject(new Error("This plugin is disabled."));
sessions.add(id);
const pending = invoke<void>("pty_open", { id, cols, rows, cwd, profile, directory });
opening.add(pending);
void pending.finally(() => opening.delete(pending)).catch(() => {});
return pending;
}
export function ptyProfiles(): Promise<import("./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> {
const pending = closing.get(id);
if (pending) return pending;
const close = invoke<void>("pty_close", { id }).then(() => { sessions.delete(id); }).finally(() => closing.delete(id));
closing.set(id, close);
return close;
}
+29
View File
@@ -0,0 +1,29 @@
import { flushSync, mount, unmount } from "svelte";
import type { PluginApi } from "../../src/lib/plugins/sdk.ts";
import { terminalShortcut } from "./model.ts";
import TerminalBridge from "./TerminalBridge.svelte";
import { closeTerminals } from "./api.ts";
export async function activate(api: PluginApi) {
const css = new TextDecoder().decode(await api.assets.read("style.css"));
if (api.signal.aborted) return;
const style = document.createElement("style");
style.textContent = css;
document.head.append(style);
api.onDispose(() => style.remove());
const mounts = new Set<() => Promise<void>>();
api.onDispose(closeTerminals);
api.onDispose(async () => { await Promise.all([...mounts].map(dispose => dispose())); });
api.contribute("terminal", {
shortcut: terminalShortcut,
mount(container, props) {
if (api.signal.aborted) throw new Error("This plugin is disabled.");
const instance = mount(TerminalBridge, { target: container, props: { initial: props } });
flushSync();
let stopping: Promise<void> | undefined;
const dispose = () => stopping ??= unmount(instance).then(() => { mounts.delete(dispose); });
mounts.add(dispose);
return { update: value => instance.update(value), command: action => instance.command(action), dispose };
},
});
}
+70
View File
@@ -0,0 +1,70 @@
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;
}
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": 1,
"id": "runestone.terminal",
"name": "Terminal",
"author": "RuneStone",
"description": "Run shells, scripts, and workspace tasks.",
"version": "1.0.0",
"apiVersion": 1,
"entry": "main.js",
"access": "full-app"
}