Files
RuneStone/plugins/terminal/TerminalDock.svelte
T

262 lines
20 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<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>