feat(web): add xterm terminal panel (#5)
Use @xterm/xterm for terminal emulation and its official @xterm/addon-fit for container sizing. Lazy-load both on first open to keep them out of the main bundle. Preserve the mounted terminal on collapse and offer explicit reconnect; provide an echo transport for demos.
This commit is contained in:
@@ -17,7 +17,9 @@
|
|||||||
"@codemirror/lang-markdown": "^6.3.1",
|
"@codemirror/lang-markdown": "^6.3.1",
|
||||||
"@codemirror/view": "^6.35.0",
|
"@codemirror/view": "^6.35.0",
|
||||||
"codemirror": "^6.0.1",
|
"codemirror": "^6.0.1",
|
||||||
"highlight.js": "^11.10.0"
|
"highlight.js": "^11.10.0",
|
||||||
|
"@xterm/xterm": "^5.5.0",
|
||||||
|
"@xterm/addon-fit": "^0.10.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "^18.3.12",
|
"@types/react": "^18.3.12",
|
||||||
|
|||||||
+13
-3
@@ -29,7 +29,9 @@ import type { Api } from "./api";
|
|||||||
import { emptySession, eventReducer, stepKey } from "./events";
|
import { emptySession, eventReducer, stepKey } from "./events";
|
||||||
import { ParamsForm } from "./ParamsForm";
|
import { ParamsForm } from "./ParamsForm";
|
||||||
import { StepCard } from "./StepCard";
|
import { StepCard } from "./StepCard";
|
||||||
import { TerminalSlot } from "./TerminalSlot";
|
const TerminalSlot = lazy(() =>
|
||||||
|
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
|
||||||
|
);
|
||||||
const Editor = lazy(() =>
|
const Editor = lazy(() =>
|
||||||
import("./Editor").then((module) => ({ default: module.Editor })),
|
import("./Editor").then((module) => ({ default: module.Editor })),
|
||||||
);
|
);
|
||||||
@@ -53,6 +55,7 @@ export function App({ api }: { api: Api }) {
|
|||||||
const [values, setValues] = useState<ParamValues>({});
|
const [values, setValues] = useState<ParamValues>({});
|
||||||
const [edit, setEdit] = useState(false);
|
const [edit, setEdit] = useState(false);
|
||||||
const [terminal, setTerminal] = useState(false);
|
const [terminal, setTerminal] = useState(false);
|
||||||
|
const [terminalOpened, setTerminalOpened] = useState(false);
|
||||||
const [conflict, setConflict] = useState(false);
|
const [conflict, setConflict] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [connected, setConnected] = useState(false);
|
const [connected, setConnected] = useState(false);
|
||||||
@@ -348,7 +351,10 @@ export function App({ api }: { api: Api }) {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
aria-expanded={terminal}
|
aria-expanded={terminal}
|
||||||
onClick={() => setTerminal(!terminal)}
|
onClick={() => {
|
||||||
|
setTerminalOpened(true);
|
||||||
|
setTerminal(!terminal);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Terminal {terminal ? "→" : "←"}
|
Terminal {terminal ? "→" : "←"}
|
||||||
</button>
|
</button>
|
||||||
@@ -460,7 +466,11 @@ export function App({ api }: { api: Api }) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
{terminal && <TerminalSlot />}
|
{terminalOpened && (
|
||||||
|
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||||
|
<TerminalSlot collapsed={!terminal} />
|
||||||
|
</Suspense>
|
||||||
|
)}
|
||||||
{confirm && (
|
{confirm && (
|
||||||
<div className="modal-backdrop">
|
<div className="modal-backdrop">
|
||||||
<section
|
<section
|
||||||
|
|||||||
@@ -1,9 +1,123 @@
|
|||||||
export function TerminalSlot() {
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { Terminal } from "@xterm/xterm";
|
||||||
|
import { FitAddon } from "@xterm/addon-fit";
|
||||||
|
import "@xterm/xterm/css/xterm.css";
|
||||||
|
import { terminalTransport } from "./terminalTransport";
|
||||||
|
import type { TerminalTransport } from "./terminalTransport";
|
||||||
|
import type { TerminalClientMessage } from "@shellbook/core";
|
||||||
|
|
||||||
|
export function TerminalSlot({
|
||||||
|
collapsed = false,
|
||||||
|
connect = terminalTransport,
|
||||||
|
}: {
|
||||||
|
collapsed?: boolean;
|
||||||
|
connect?: (session: string) => TerminalTransport;
|
||||||
|
}) {
|
||||||
|
const container = useRef<HTMLDivElement>(null);
|
||||||
|
const refit = useRef<() => void>(() => {});
|
||||||
|
const [attempt, setAttempt] = useState(0);
|
||||||
|
const [state, setState] = useState("Connecting");
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
let ready = false;
|
||||||
|
setState("Connecting");
|
||||||
|
const terminal = new Terminal({
|
||||||
|
cursorBlink: true,
|
||||||
|
fontSize: 13,
|
||||||
|
scrollback: 5000,
|
||||||
|
});
|
||||||
|
const fit = new FitAddon();
|
||||||
|
terminal.loadAddon(fit);
|
||||||
|
terminal.open(container.current!);
|
||||||
|
const media = window.matchMedia?.("(prefers-color-scheme: light)");
|
||||||
|
const theme = () => {
|
||||||
|
terminal.options.theme = media?.matches
|
||||||
|
? { background: "#ffffff", foreground: "#233244", cursor: "#197b59" }
|
||||||
|
: { background: "#10151c", foreground: "#dce3ec", cursor: "#86dab9" };
|
||||||
|
};
|
||||||
|
theme();
|
||||||
|
media?.addEventListener("change", theme);
|
||||||
|
let socket: TerminalTransport;
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
const send = (message: TerminalClientMessage) => {
|
||||||
|
if (ready) socket.send(JSON.stringify(message));
|
||||||
|
};
|
||||||
|
const resize = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
if (!active || !container.current?.getBoundingClientRect().width)
|
||||||
|
return;
|
||||||
|
fit.fit();
|
||||||
|
send({
|
||||||
|
type: "resize",
|
||||||
|
cols: Math.min(1000, Math.max(1, terminal.cols)),
|
||||||
|
rows: Math.min(1000, Math.max(1, terminal.rows)),
|
||||||
|
});
|
||||||
|
}, 100);
|
||||||
|
};
|
||||||
|
refit.current = resize;
|
||||||
|
const observer =
|
||||||
|
typeof ResizeObserver === "undefined"
|
||||||
|
? undefined
|
||||||
|
: new ResizeObserver(resize);
|
||||||
|
observer?.observe(container.current!);
|
||||||
|
window.addEventListener("resize", resize);
|
||||||
|
const input = terminal.onData((data) => send({ type: "input", data }));
|
||||||
|
try {
|
||||||
|
socket = connect("main");
|
||||||
|
socket.onopen = () => {
|
||||||
|
if (active) {
|
||||||
|
ready = true;
|
||||||
|
setState("Connected");
|
||||||
|
resize();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
socket.onmessage = (event) => {
|
||||||
|
if (active) terminal.write(event.data);
|
||||||
|
};
|
||||||
|
const disconnected = () => {
|
||||||
|
if (active) {
|
||||||
|
ready = false;
|
||||||
|
setState("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
socket.onclose = disconnected;
|
||||||
|
socket.onerror = () => {
|
||||||
|
disconnected();
|
||||||
|
socket.close();
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
setState("Disconnected");
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
ready = false;
|
||||||
|
clearTimeout(timer);
|
||||||
|
observer?.disconnect();
|
||||||
|
window.removeEventListener("resize", resize);
|
||||||
|
media?.removeEventListener("change", theme);
|
||||||
|
input.dispose();
|
||||||
|
socket?.close();
|
||||||
|
terminal.dispose();
|
||||||
|
};
|
||||||
|
}, [attempt, connect]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!collapsed) refit.current();
|
||||||
|
}, [collapsed]);
|
||||||
return (
|
return (
|
||||||
<aside className="terminal" aria-label="Terminal panel">
|
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
|
||||||
<h2>Terminal</h2>
|
<h2>Terminal · main</h2>
|
||||||
<p>Claude Code terminal · M4</p>
|
<p>
|
||||||
<div className="terminal-slot" />
|
Run `claude` here — it edits notebooks in this workspace; the view
|
||||||
|
reloads live.
|
||||||
|
</p>
|
||||||
|
<div className="actions">
|
||||||
|
<span role="status">{state}</span>
|
||||||
|
{state === "Disconnected" && (
|
||||||
|
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="terminal-screen" ref={container} />
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -439,3 +439,28 @@ a {
|
|||||||
min-height: 200px;
|
min-height: 200px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.terminal[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.terminal {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
height: 100vh;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.terminal-screen {
|
||||||
|
height: calc(100% - 160px);
|
||||||
|
min-height: 220px;
|
||||||
|
}
|
||||||
|
.with-terminal {
|
||||||
|
grid-template-columns: 230px minmax(0, 1fr) minmax(300px, 40vw);
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.with-terminal {
|
||||||
|
grid-template-columns: 170px minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
.terminal {
|
||||||
|
position: static;
|
||||||
|
height: 500px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import type { TerminalClientMessage } from "@shellbook/core";
|
||||||
|
|
||||||
|
export interface TerminalTransport {
|
||||||
|
onopen: (() => void) | null;
|
||||||
|
onclose: (() => void) | null;
|
||||||
|
onerror: (() => void) | null;
|
||||||
|
onmessage: ((event: { data: string }) => void) | null;
|
||||||
|
send(data: string): void;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
export function terminalTransport(session: string): TerminalTransport {
|
||||||
|
if (import.meta.env.VITE_MOCK !== "1")
|
||||||
|
return new WebSocket(
|
||||||
|
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/terminal?session=${encodeURIComponent(session)}`,
|
||||||
|
) as unknown as TerminalTransport;
|
||||||
|
let closed = false;
|
||||||
|
const transport: TerminalTransport = {
|
||||||
|
onopen: null,
|
||||||
|
onclose: null,
|
||||||
|
onerror: null,
|
||||||
|
onmessage: null,
|
||||||
|
send(data) {
|
||||||
|
const message = JSON.parse(data) as TerminalClientMessage;
|
||||||
|
if (!closed && message.type === "input")
|
||||||
|
transport.onmessage?.({ data: message.data.replace(/\r/g, "\r\n") });
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
closed = true;
|
||||||
|
transport.onclose?.();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (closed) return;
|
||||||
|
transport.onopen?.();
|
||||||
|
transport.onmessage?.({
|
||||||
|
data: "ShellBook demo terminal (echo only)\r\n$ ",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return transport;
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import {
|
||||||
|
act,
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { afterEach, expect, it, vi } from "vitest";
|
||||||
|
const xterm = vi.hoisted(() => ({ instances: [] as any[] }));
|
||||||
|
vi.mock("@xterm/xterm", () => ({
|
||||||
|
Terminal: class {
|
||||||
|
cols = 80;
|
||||||
|
rows = 24;
|
||||||
|
options = {};
|
||||||
|
write = vi.fn();
|
||||||
|
dispose = vi.fn();
|
||||||
|
input?: (data: string) => void;
|
||||||
|
constructor() {
|
||||||
|
xterm.instances.push(this);
|
||||||
|
}
|
||||||
|
loadAddon() {}
|
||||||
|
open() {}
|
||||||
|
onData(callback: (data: string) => void) {
|
||||||
|
this.input = callback;
|
||||||
|
return { dispose: vi.fn() };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@xterm/addon-fit", () => ({
|
||||||
|
FitAddon: class {
|
||||||
|
fit = vi.fn();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
import { TerminalSlot } from "../TerminalSlot";
|
||||||
|
class FakeSocket {
|
||||||
|
static instances: FakeSocket[] = [];
|
||||||
|
onopen?: () => void;
|
||||||
|
onclose?: () => void;
|
||||||
|
onerror?: () => void;
|
||||||
|
onmessage?: (event: { data: string }) => void;
|
||||||
|
send = vi.fn();
|
||||||
|
close = vi.fn();
|
||||||
|
constructor(public url: string) {
|
||||||
|
FakeSocket.instances.push(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
FakeSocket.instances = [];
|
||||||
|
xterm.instances = [];
|
||||||
|
});
|
||||||
|
it("frames input and fitted resize, renders raw output and preserves connection when collapsed", async () => {
|
||||||
|
vi.stubGlobal("WebSocket", FakeSocket);
|
||||||
|
const { rerender, container } = render(<TerminalSlot />);
|
||||||
|
const socket = FakeSocket.instances[0]!;
|
||||||
|
expect(socket.url).toBe(`ws://${location.host}/api/terminal?session=main`);
|
||||||
|
const element = container.querySelector(".terminal-screen")!;
|
||||||
|
vi.spyOn(element, "getBoundingClientRect").mockReturnValue({
|
||||||
|
width: 500,
|
||||||
|
} as DOMRect);
|
||||||
|
act(() => socket.onopen?.());
|
||||||
|
expect(screen.getByRole("status")).toHaveTextContent("Connected");
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(socket.send).toHaveBeenCalledWith(
|
||||||
|
JSON.stringify({ type: "resize", cols: 80, rows: 24 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
act(() => xterm.instances[0].input("claude\r"));
|
||||||
|
expect(socket.send).toHaveBeenCalledWith(
|
||||||
|
JSON.stringify({ type: "input", data: "claude\r" }),
|
||||||
|
);
|
||||||
|
act(() => socket.onmessage?.({ data: "\u001b[31mraw output" }));
|
||||||
|
expect(xterm.instances[0].write).toHaveBeenCalledWith("\u001b[31mraw output");
|
||||||
|
rerender(<TerminalSlot collapsed />);
|
||||||
|
expect(container.querySelector("aside")).toHaveAttribute("hidden");
|
||||||
|
expect(socket.close).not.toHaveBeenCalled();
|
||||||
|
act(() => socket.onmessage?.({ data: "still receiving" }));
|
||||||
|
rerender(<TerminalSlot />);
|
||||||
|
expect(FakeSocket.instances).toHaveLength(1);
|
||||||
|
expect(xterm.instances[0].write).toHaveBeenCalledWith("still receiving");
|
||||||
|
expect(xterm.instances[0].dispose).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it("offers explicit reconnect after close and cleans up the old connection", () => {
|
||||||
|
vi.stubGlobal("WebSocket", FakeSocket);
|
||||||
|
const view = render(<TerminalSlot />);
|
||||||
|
act(() => FakeSocket.instances[0]!.onclose?.());
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
|
||||||
|
expect(FakeSocket.instances).toHaveLength(2);
|
||||||
|
expect(FakeSocket.instances[0]!.close).toHaveBeenCalledTimes(1);
|
||||||
|
act(() => FakeSocket.instances[1]!.onopen?.());
|
||||||
|
expect(screen.getByRole("status")).toHaveTextContent("Connected");
|
||||||
|
view.unmount();
|
||||||
|
expect(FakeSocket.instances[1]!.close).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses a fake echo terminal in demo mode without a server", async () => {
|
||||||
|
vi.stubEnv("VITE_MOCK", "1");
|
||||||
|
const { terminalTransport } = await import("../terminalTransport");
|
||||||
|
try {
|
||||||
|
const socket = terminalTransport("main");
|
||||||
|
const opened = vi.fn();
|
||||||
|
const output = vi.fn();
|
||||||
|
socket.onopen = opened;
|
||||||
|
socket.onmessage = output;
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(opened).toHaveBeenCalledOnce();
|
||||||
|
socket.send(JSON.stringify({ type: "input", data: "hello\r" }));
|
||||||
|
expect(output).toHaveBeenLastCalledWith({ data: "hello\r\n" });
|
||||||
|
socket.close();
|
||||||
|
socket.send(JSON.stringify({ type: "input", data: "closed" }));
|
||||||
|
expect(output).toHaveBeenCalledTimes(2);
|
||||||
|
} finally {
|
||||||
|
vi.unstubAllEnvs();
|
||||||
|
}
|
||||||
|
});
|
||||||
Generated
+20
@@ -69,6 +69,12 @@ importers:
|
|||||||
'@shellbook/core':
|
'@shellbook/core':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/core
|
version: link:../../packages/core
|
||||||
|
'@xterm/addon-fit':
|
||||||
|
specifier: ^0.10.0
|
||||||
|
version: 0.10.0(@xterm/[email protected])
|
||||||
|
'@xterm/xterm':
|
||||||
|
specifier: ^5.5.0
|
||||||
|
version: 5.5.0
|
||||||
codemirror:
|
codemirror:
|
||||||
specifier: ^6.0.1
|
specifier: ^6.0.1
|
||||||
version: 6.0.2
|
version: 6.0.2
|
||||||
@@ -1062,6 +1068,14 @@ packages:
|
|||||||
'@vitest/[email protected]':
|
'@vitest/[email protected]':
|
||||||
resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
|
resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
|
||||||
|
|
||||||
|
'@xterm/[email protected]':
|
||||||
|
resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
|
||||||
|
peerDependencies:
|
||||||
|
'@xterm/xterm': ^5.0.0
|
||||||
|
|
||||||
|
'@xterm/[email protected]':
|
||||||
|
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
|
resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
|
||||||
|
|
||||||
@@ -2971,6 +2985,12 @@ snapshots:
|
|||||||
loupe: 3.2.1
|
loupe: 3.2.1
|
||||||
tinyrainbow: 1.2.0
|
tinyrainbow: 1.2.0
|
||||||
|
|
||||||
|
'@xterm/[email protected](@xterm/[email protected])':
|
||||||
|
dependencies:
|
||||||
|
'@xterm/xterm': 5.5.0
|
||||||
|
|
||||||
|
'@xterm/[email protected]': {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user