~/components/terminal-shell
Terminal Shell
An interactive fake shell: you pass the commands, it handles the prompt, history, tab completion, help, clear and Ctrl+L.
"use client";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { TerminalWindow } from "./terminal-window";
/** What a command prints: one node, several lines, or nothing. */
export type ShellOutput = ReactNode | ReactNode[];
export type ShellContext = {
/** Every command entered so far, oldest first. */
history: string[];
/** Empties the screen. */
clear: () => void;
/** Prints extra lines right away (handy before an async command resolves). */
print: (output: ShellOutput) => void;
};
export type ShellCommand = {
/** One line shown by the built-in `help`. */
description?: string;
/** Usage shown by `help`, e.g. "theme <dark|light>". @default the command name */
usage?: string;
/** Leave it out of `help` and tab completion (easter eggs). @default false */
hidden?: boolean;
/** Runs the command. `args` are the words after the name. May be async. */
run: (args: string[], ctx: ShellContext) => ShellOutput | void | Promise<ShellOutput | void>;
};
export type TerminalShellProps = {
/** Your commands, by name. A plain function works too. @default {} */
commands?: Record<string, ShellCommand | ShellCommand["run"]>;
/** Add the built-in `help`, `clear` and `history` commands (yours win on a name clash). @default true */
builtins?: boolean;
/** Lines printed when the shell starts. @default ['Type "help" to list commands.'] */
welcome?: ReactNode[];
/** Prompt in front of the input and of every past command. @default "$" */
prompt?: string;
/** Text in the title bar. @default "~ — sh" */
title?: ReactNode;
/** Output for an unknown command. @default `${name}: command not found. Type "help".` */
notFound?: (name: string) => ShellOutput;
/** Accessible name of the input. @default "Terminal input" */
inputLabel?: string;
/** Placeholder in the empty input. */
placeholder?: string;
/** Focus the input on mount. Leave off unless the shell is the main thing on screen. @default false */
autoFocus?: boolean;
/** Show the key-hint footer. @default true */
hints?: boolean;
/** Most lines kept on screen; older ones are dropped. @default 300 */
maxLines?: number;
/** When set, the title bar gets an "esc" close button, and Esc in the input calls it. */
onClose?: () => void;
/** Extra classes for the window. */
className?: string;
/** Extra classes for the scrolling screen (set its height here). @default "h-72" */
screenClassName?: string;
};
type Entry = { id: number; kind: "cmd" | "out"; content: ReactNode };
function cx(...parts: (string | false | undefined)[]): string {
return parts.filter(Boolean).join(" ");
}
function toLines(out: ShellOutput | void): ReactNode[] {
if (out === undefined || out === null || out === false) return [];
return Array.isArray(out) ? out : [out];
}
function normalize(c: ShellCommand | ShellCommand["run"]): ShellCommand {
return typeof c === "function" ? { run: c } : c;
}
const DEFAULT_WELCOME: ReactNode[] = ['Type "help" to list commands.'];
/**
* An interactive fake shell in a terminal window. You pass the commands; it
* handles the prompt, history (↑ ↓), tab completion, Ctrl+L and Ctrl+C, and
* the built-in `help`, `clear` and `history`.
*/
export function TerminalShell({
commands = {},
builtins = true,
welcome = DEFAULT_WELCOME,
prompt = "$",
title = "~ — sh",
notFound = (name) => `${name}: command not found. Type "help".`,
inputLabel = "Terminal input",
placeholder,
autoFocus = false,
hints = true,
maxLines = 300,
onClose,
className,
screenClassName = "h-72",
}: TerminalShellProps) {
const idRef = useRef(0);
const [entries, setEntries] = useState<Entry[]>(() => welcome.map((content, i) => ({ id: -1 - i, kind: "out", content })));
const [value, setValue] = useState("");
const [history, setHistory] = useState<string[]>([]);
const [hIndex, setHIndex] = useState(-1);
const [busy, setBusy] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const screenRef = useRef<HTMLDivElement>(null);
const inputId = useId();
useEffect(() => {
const el = screenRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [entries]);
useEffect(() => {
if (autoFocus) inputRef.current?.focus({ preventScroll: true });
}, [autoFocus]);
// Your commands plus the built-ins.
const table: Record<string, ShellCommand> = {};
if (builtins) {
table.help = {
description: "list commands",
run: () => {
const rows = Object.entries(table).filter(([, c]) => !c.hidden);
const width = Math.max(...rows.map(([n, c]) => (c.usage ?? n).length)) + 3;
return rows.map(([n, c]) => `${(c.usage ?? n).padEnd(width)}${c.description ?? ""}`);
},
};
table.clear = { description: "clear the screen (Ctrl+L)", run: (_, ctx) => ctx.clear() };
table.history = {
description: "show past commands",
run: (_, ctx) => ctx.history.map((h, i) => `${String(i + 1).padStart(4)} ${h}`),
};
}
for (const [name, c] of Object.entries(commands)) table[name.toLowerCase()] = normalize(c);
const names = Object.keys(table).filter((n) => !table[n].hidden);
function push(kind: Entry["kind"], lines: ReactNode[]) {
if (lines.length === 0) return;
setEntries((prev) => {
const next = [...prev, ...lines.map((content) => ({ id: idRef.current++, kind, content }))];
return next.length > maxLines ? next.slice(-maxLines) : next;
});
}
async function submit() {
const raw = value;
const trimmed = raw.trim();
setValue("");
setHIndex(-1);
push("cmd", [raw]);
if (!trimmed) return;
const nextHistory = [...history, trimmed];
setHistory(nextHistory);
const [name, ...args] = trimmed.split(/\s+/);
const cmd = table[name.toLowerCase()];
if (!cmd) {
push("out", toLines(notFound(name)));
return;
}
const ctx: ShellContext = {
history: nextHistory,
clear: () => setEntries([]),
print: (out) => push("out", toLines(out)),
};
try {
const result = cmd.run(args, ctx);
if (result instanceof Promise) {
setBusy(true);
push("out", toLines(await result));
} else {
push("out", toLines(result));
}
} catch (err) {
push("out", [`${name}: ${err instanceof Error ? err.message : "failed"}`]);
} finally {
setBusy(false);
inputRef.current?.focus({ preventScroll: true });
}
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter") {
e.preventDefault();
if (!busy) void submit();
} else if (e.key === "ArrowUp") {
e.preventDefault();
const n = Math.min(hIndex + 1, history.length - 1);
if (n >= 0) {
setHIndex(n);
setValue(history[history.length - 1 - n]);
}
} else if (e.key === "ArrowDown") {
e.preventDefault();
const n = Math.max(hIndex - 1, -1);
setHIndex(n);
setValue(n < 0 ? "" : history[history.length - 1 - n]);
} else if (e.key === "Tab" && value.trim() && !value.includes(" ")) {
// Only complete the command name; an empty input lets Tab move focus as usual.
e.preventDefault();
const word = value.trim().toLowerCase();
const matches = names.filter((n) => n.startsWith(word));
if (matches.length === 1) setValue(`${matches[0]} `);
else if (matches.length > 1) {
push("cmd", [value]);
push("out", [matches.join(" ")]);
}
} else if (e.ctrlKey && e.key.toLowerCase() === "l") {
e.preventDefault();
setEntries([]);
} else if (e.ctrlKey && e.key.toLowerCase() === "c" && !window.getSelection()?.toString()) {
e.preventDefault();
push("cmd", [`${value}^C`]);
setValue("");
setHIndex(-1);
} else if (e.key === "Escape" && onClose) {
e.preventDefault();
onClose();
}
}
return (
<TerminalWindow title={title} onClose={onClose} idlePrompt={false}
className={cx("transition-colors focus-within:border-mpk-blue", className)}
bodyClassName="p-0"
>
<div
ref={screenRef}
className={cx("overflow-y-auto px-4 py-3", screenClassName)}
onClick={() => {
// Clicking the screen focuses the input, unless the user is selecting text.
if (!window.getSelection()?.toString()) inputRef.current?.focus({ preventScroll: true });
}}
>
<div role="log" aria-live="polite" aria-relevant="additions">
{entries.map((entry) =>
entry.kind === "cmd" ? (
<div key={entry.id} className="break-words whitespace-pre-wrap text-mpk-ink">
<span className="mr-2 text-mpk-amber">{prompt}</span>
{entry.content}
</div>
) : (
<div key={entry.id} className="break-words whitespace-pre-wrap text-mpk-dim">
{entry.content === "" ? " " : entry.content}
</div>
),
)}
</div>
<div className="flex items-center">
<label htmlFor={inputId} className="mr-2 text-mpk-amber">
<span aria-hidden="true">{prompt}</span>
<span className="sr-only">{inputLabel}</span>
</label>
<input
ref={inputRef}
id={inputId}
value={value}
onChange={(e) => {
setValue(e.target.value);
setHIndex(-1);
}}
onKeyDown={onKeyDown}
placeholder={placeholder}
aria-busy={busy || undefined}
spellCheck={false}
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
enterKeyHint="go"
className="min-w-0 flex-1 bg-transparent text-mpk-ink caret-mpk-blue outline-none placeholder:text-mpk-dim2"
/>
</div>
</div>
{hints && (
<div className="border-t border-mpk-line px-4 py-1.5 text-[11px] text-mpk-dim2">
⏎ run · tab complete · ↑↓ history · ctrl+l clear{onClose ? " · esc close" : ""}
</div>
)}
</TerminalWindow>
);
}Installation
npx mpkcn add terminal-shell01Add mpkcn-theme.css if you haven't yet (see Installation)
02Copy the source into your components folder
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
export type TerminalLine = {
/** Command typed out after the prompt. Leave it out for an output-only line. */
command?: string;
/** Shown once the command has been typed (or right away for an output-only line). */
output?: ReactNode;
/** Prompt in front of this command. @default the window's `prompt` */
prompt?: string;
};
export type TerminalWindowProps = {
/** Text in the title bar. @default "~ — zsh" */
title?: ReactNode;
/** Lines typed out one after the other: a command, then its output. @default [] */
lines?: TerminalLine[];
/** Prompt in front of every command. @default "$" */
prompt?: string;
/** Milliseconds per typed character. @default 35 */
typingSpeed?: number;
/** Pause after each line before the next one starts, in milliseconds. @default 300 */
lineDelay?: number;
/** Wait until the window scrolls into view before typing. @default true */
startOnView?: boolean;
/** Show an empty prompt with a blinking cursor once everything is typed. @default true */
idlePrompt?: boolean;
/** Show the three window dots in the title bar. @default true */
dots?: boolean;
/** Extra content on the right of the title bar (buttons, a badge…). */
actions?: ReactNode;
/** When set, the title bar gets an "esc" close button that calls it. */
onClose?: () => void;
/** Called once every line has been typed. */
onComplete?: () => void;
/** Type even when the user prefers reduced motion (e.g. behind an explicit "play" button). Use sparingly. @default false */
ignoreReducedMotion?: boolean;
/** Content shown under the typed lines once they finish (or right away when there are none). */
children?: ReactNode;
/** Extra classes for the window. */
className?: string;
/** Extra classes for the body (padding, height, overflow…). */
bodyClassName?: string;
};
type Pos = { line: number; chars: number; out: boolean };
function cx(...parts: (string | false | undefined)[]): string {
return parts.filter(Boolean).join(" ");
}
/** A blinking block cursor. Stops blinking under reduced motion. */
export function TerminalCursor({ className }: { className?: string }) {
return (
<span
aria-hidden="true"
className={cx(
"ml-0.5 inline-block h-[1.05em] w-[0.55em] translate-y-[0.15em] animate-mpk-blink bg-mpk-blue motion-reduce:animate-none",
className,
)}
/>
);
}
/**
* A terminal window: title bar with dots, then a body that types out `lines`
* (command, then output) and finally shows its `children`.
* Under prefers-reduced-motion every line appears at once.
* Change its `key` to replay the typing.
*/
export function TerminalWindow({
title = "~ — zsh",
lines = [],
prompt = "$",
typingSpeed = 35,
lineDelay = 300,
startOnView = true,
idlePrompt = true,
dots = true,
actions,
onClose,
onComplete,
ignoreReducedMotion = false,
children,
className,
bodyClassName,
}: TerminalWindowProps) {
const rootRef = useRef<HTMLDivElement>(null);
const [started, setStarted] = useState(!startOnView);
const [pos, setPos] = useState<Pos>({ line: 0, chars: 0, out: false });
const onCompleteRef = useRef(onComplete);
useEffect(() => {
onCompleteRef.current = onComplete;
}, [onComplete]);
const total = lines.length;
const done = pos.line >= total;
const current = lines[pos.line];
const cmdLen = current?.command?.length ?? 0;
const hasCmd = current?.command !== undefined;
// Start when scrolled into view.
useEffect(() => {
if (started) return;
const el = rootRef.current;
if (!el || typeof IntersectionObserver === "undefined") {
const t = window.setTimeout(() => setStarted(true), 0);
return () => window.clearTimeout(t);
}
const io = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
setStarted(true);
io.disconnect();
}
},
{ threshold: 0.2 },
);
io.observe(el);
return () => io.disconnect();
}, [started]);
// Reduced motion: show everything at once.
useEffect(() => {
if (done || ignoreReducedMotion) return;
if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const t = window.setTimeout(() => setPos({ line: total, chars: 0, out: false }), 0);
return () => window.clearTimeout(t);
}, [done, ignoreReducedMotion, total]);
// Typing engine: one step per timeout.
useEffect(() => {
if (!started || done) return;
let next: Pos;
let delay: number;
if (pos.chars < cmdLen) {
next = { ...pos, chars: pos.chars + 1 };
delay = pos.chars === 0 ? Math.max(typingSpeed, 120) : typingSpeed;
} else if (!pos.out) {
next = { ...pos, out: true };
delay = hasCmd ? 140 : 0;
} else {
next = { line: pos.line + 1, chars: 0, out: false };
delay = lineDelay;
}
const t = window.setTimeout(() => setPos(next), delay);
return () => window.clearTimeout(t);
}, [started, done, pos, cmdLen, hasCmd, typingSpeed, lineDelay]);
useEffect(() => {
if (done) onCompleteRef.current?.();
}, [done]);
const visible = lines.slice(0, Math.min(pos.line + 1, total));
return (
<div
ref={rootRef}
className={cx("w-full overflow-hidden border border-mpk-line bg-mpk-bg-soft font-mpk-mono text-mpk-ink", className)}
>
<div className="flex items-center gap-3 border-b border-mpk-line px-3.5 py-2 text-xs text-mpk-dim">
{dots && (
<span aria-hidden="true" className="flex gap-1.5">
<i className="size-2.5 bg-mpk-amber" />
<i className="size-2.5 bg-mpk-dim2" />
<i className="size-2.5 bg-mpk-blue" />
</span>
)}
<span className="min-w-0 truncate">{title}</span>
{(actions || onClose) && (
<span className="ml-auto flex items-center gap-2">
{actions}
{onClose && (
<button
type="button"
onClick={onClose}
aria-label="Close"
className="border border-mpk-line px-1.5 py-px text-[11px] text-mpk-dim transition-colors hover:border-mpk-blue hover:text-mpk-blue focus-visible:outline focus-visible:outline-1 focus-visible:outline-mpk-amber"
>
esc
</button>
)}
</span>
)}
</div>
<div className={cx("p-4 text-[13px] leading-relaxed", bodyClassName)}>
{visible.map((line, i) => {
const isCurrent = i === pos.line;
const typed = isCurrent ? (line.command ?? "").slice(0, pos.chars) : line.command;
const showOut = !isCurrent || pos.out;
const typing = isCurrent && line.command !== undefined && !pos.out;
return (
<div key={i} className="mb-1 last:mb-0">
{line.command !== undefined && (
<div className="break-words whitespace-pre-wrap">
<span className="mr-2 text-mpk-amber">{line.prompt ?? prompt}</span>
<span aria-hidden="true">{typed}</span>
<span className="sr-only">{line.command}</span>
{typing && <TerminalCursor />}
</div>
)}
{showOut && line.output !== undefined && line.output !== null && (
<div className="break-words whitespace-pre-wrap text-mpk-dim">{line.output}</div>
)}
</div>
);
})}
{done && children}
{done && idlePrompt && (
<div className={total > 0 || children ? "mt-1" : undefined}>
<span className="mr-2 text-mpk-amber">{prompt}</span>
<TerminalCursor />
</div>
)}
</div>
</div>
);
}"use client";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { TerminalWindow } from "./terminal-window";
/** What a command prints: one node, several lines, or nothing. */
export type ShellOutput = ReactNode | ReactNode[];
export type ShellContext = {
/** Every command entered so far, oldest first. */
history: string[];
/** Empties the screen. */
clear: () => void;
/** Prints extra lines right away (handy before an async command resolves). */
print: (output: ShellOutput) => void;
};
export type ShellCommand = {
/** One line shown by the built-in `help`. */
description?: string;
/** Usage shown by `help`, e.g. "theme <dark|light>". @default the command name */
usage?: string;
/** Leave it out of `help` and tab completion (easter eggs). @default false */
hidden?: boolean;
/** Runs the command. `args` are the words after the name. May be async. */
run: (args: string[], ctx: ShellContext) => ShellOutput | void | Promise<ShellOutput | void>;
};
export type TerminalShellProps = {
/** Your commands, by name. A plain function works too. @default {} */
commands?: Record<string, ShellCommand | ShellCommand["run"]>;
/** Add the built-in `help`, `clear` and `history` commands (yours win on a name clash). @default true */
builtins?: boolean;
/** Lines printed when the shell starts. @default ['Type "help" to list commands.'] */
welcome?: ReactNode[];
/** Prompt in front of the input and of every past command. @default "$" */
prompt?: string;
/** Text in the title bar. @default "~ — sh" */
title?: ReactNode;
/** Output for an unknown command. @default `${name}: command not found. Type "help".` */
notFound?: (name: string) => ShellOutput;
/** Accessible name of the input. @default "Terminal input" */
inputLabel?: string;
/** Placeholder in the empty input. */
placeholder?: string;
/** Focus the input on mount. Leave off unless the shell is the main thing on screen. @default false */
autoFocus?: boolean;
/** Show the key-hint footer. @default true */
hints?: boolean;
/** Most lines kept on screen; older ones are dropped. @default 300 */
maxLines?: number;
/** When set, the title bar gets an "esc" close button, and Esc in the input calls it. */
onClose?: () => void;
/** Extra classes for the window. */
className?: string;
/** Extra classes for the scrolling screen (set its height here). @default "h-72" */
screenClassName?: string;
};
type Entry = { id: number; kind: "cmd" | "out"; content: ReactNode };
function cx(...parts: (string | false | undefined)[]): string {
return parts.filter(Boolean).join(" ");
}
function toLines(out: ShellOutput | void): ReactNode[] {
if (out === undefined || out === null || out === false) return [];
return Array.isArray(out) ? out : [out];
}
function normalize(c: ShellCommand | ShellCommand["run"]): ShellCommand {
return typeof c === "function" ? { run: c } : c;
}
const DEFAULT_WELCOME: ReactNode[] = ['Type "help" to list commands.'];
/**
* An interactive fake shell in a terminal window. You pass the commands; it
* handles the prompt, history (↑ ↓), tab completion, Ctrl+L and Ctrl+C, and
* the built-in `help`, `clear` and `history`.
*/
export function TerminalShell({
commands = {},
builtins = true,
welcome = DEFAULT_WELCOME,
prompt = "$",
title = "~ — sh",
notFound = (name) => `${name}: command not found. Type "help".`,
inputLabel = "Terminal input",
placeholder,
autoFocus = false,
hints = true,
maxLines = 300,
onClose,
className,
screenClassName = "h-72",
}: TerminalShellProps) {
const idRef = useRef(0);
const [entries, setEntries] = useState<Entry[]>(() => welcome.map((content, i) => ({ id: -1 - i, kind: "out", content })));
const [value, setValue] = useState("");
const [history, setHistory] = useState<string[]>([]);
const [hIndex, setHIndex] = useState(-1);
const [busy, setBusy] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const screenRef = useRef<HTMLDivElement>(null);
const inputId = useId();
useEffect(() => {
const el = screenRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [entries]);
useEffect(() => {
if (autoFocus) inputRef.current?.focus({ preventScroll: true });
}, [autoFocus]);
// Your commands plus the built-ins.
const table: Record<string, ShellCommand> = {};
if (builtins) {
table.help = {
description: "list commands",
run: () => {
const rows = Object.entries(table).filter(([, c]) => !c.hidden);
const width = Math.max(...rows.map(([n, c]) => (c.usage ?? n).length)) + 3;
return rows.map(([n, c]) => `${(c.usage ?? n).padEnd(width)}${c.description ?? ""}`);
},
};
table.clear = { description: "clear the screen (Ctrl+L)", run: (_, ctx) => ctx.clear() };
table.history = {
description: "show past commands",
run: (_, ctx) => ctx.history.map((h, i) => `${String(i + 1).padStart(4)} ${h}`),
};
}
for (const [name, c] of Object.entries(commands)) table[name.toLowerCase()] = normalize(c);
const names = Object.keys(table).filter((n) => !table[n].hidden);
function push(kind: Entry["kind"], lines: ReactNode[]) {
if (lines.length === 0) return;
setEntries((prev) => {
const next = [...prev, ...lines.map((content) => ({ id: idRef.current++, kind, content }))];
return next.length > maxLines ? next.slice(-maxLines) : next;
});
}
async function submit() {
const raw = value;
const trimmed = raw.trim();
setValue("");
setHIndex(-1);
push("cmd", [raw]);
if (!trimmed) return;
const nextHistory = [...history, trimmed];
setHistory(nextHistory);
const [name, ...args] = trimmed.split(/\s+/);
const cmd = table[name.toLowerCase()];
if (!cmd) {
push("out", toLines(notFound(name)));
return;
}
const ctx: ShellContext = {
history: nextHistory,
clear: () => setEntries([]),
print: (out) => push("out", toLines(out)),
};
try {
const result = cmd.run(args, ctx);
if (result instanceof Promise) {
setBusy(true);
push("out", toLines(await result));
} else {
push("out", toLines(result));
}
} catch (err) {
push("out", [`${name}: ${err instanceof Error ? err.message : "failed"}`]);
} finally {
setBusy(false);
inputRef.current?.focus({ preventScroll: true });
}
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter") {
e.preventDefault();
if (!busy) void submit();
} else if (e.key === "ArrowUp") {
e.preventDefault();
const n = Math.min(hIndex + 1, history.length - 1);
if (n >= 0) {
setHIndex(n);
setValue(history[history.length - 1 - n]);
}
} else if (e.key === "ArrowDown") {
e.preventDefault();
const n = Math.max(hIndex - 1, -1);
setHIndex(n);
setValue(n < 0 ? "" : history[history.length - 1 - n]);
} else if (e.key === "Tab" && value.trim() && !value.includes(" ")) {
// Only complete the command name; an empty input lets Tab move focus as usual.
e.preventDefault();
const word = value.trim().toLowerCase();
const matches = names.filter((n) => n.startsWith(word));
if (matches.length === 1) setValue(`${matches[0]} `);
else if (matches.length > 1) {
push("cmd", [value]);
push("out", [matches.join(" ")]);
}
} else if (e.ctrlKey && e.key.toLowerCase() === "l") {
e.preventDefault();
setEntries([]);
} else if (e.ctrlKey && e.key.toLowerCase() === "c" && !window.getSelection()?.toString()) {
e.preventDefault();
push("cmd", [`${value}^C`]);
setValue("");
setHIndex(-1);
} else if (e.key === "Escape" && onClose) {
e.preventDefault();
onClose();
}
}
return (
<TerminalWindow title={title} onClose={onClose} idlePrompt={false}
className={cx("transition-colors focus-within:border-mpk-blue", className)}
bodyClassName="p-0"
>
<div
ref={screenRef}
className={cx("overflow-y-auto px-4 py-3", screenClassName)}
onClick={() => {
// Clicking the screen focuses the input, unless the user is selecting text.
if (!window.getSelection()?.toString()) inputRef.current?.focus({ preventScroll: true });
}}
>
<div role="log" aria-live="polite" aria-relevant="additions">
{entries.map((entry) =>
entry.kind === "cmd" ? (
<div key={entry.id} className="break-words whitespace-pre-wrap text-mpk-ink">
<span className="mr-2 text-mpk-amber">{prompt}</span>
{entry.content}
</div>
) : (
<div key={entry.id} className="break-words whitespace-pre-wrap text-mpk-dim">
{entry.content === "" ? " " : entry.content}
</div>
),
)}
</div>
<div className="flex items-center">
<label htmlFor={inputId} className="mr-2 text-mpk-amber">
<span aria-hidden="true">{prompt}</span>
<span className="sr-only">{inputLabel}</span>
</label>
<input
ref={inputRef}
id={inputId}
value={value}
onChange={(e) => {
setValue(e.target.value);
setHIndex(-1);
}}
onKeyDown={onKeyDown}
placeholder={placeholder}
aria-busy={busy || undefined}
spellCheck={false}
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
enterKeyHint="go"
className="min-w-0 flex-1 bg-transparent text-mpk-ink caret-mpk-blue outline-none placeholder:text-mpk-dim2"
/>
</div>
</div>
{hints && (
<div className="border-t border-mpk-line px-4 py-1.5 text-[11px] text-mpk-dim2">
⏎ run · tab complete · ↑↓ history · ctrl+l clear{onClose ? " · esc close" : ""}
</div>
)}
</TerminalWindow>
);
}03Update the import paths to match your project
It installs Terminal Window too, which draws the frame.
Usage
Give it your commands. Each one gets the words typed after its name and returns what to print: a string, a React node, or an array of lines.
"use client";
import { TerminalShell } from "@/components/mpkcn/terminal-shell";
export function Shell() {
return (
<TerminalShell
title="guest@site: ~"
commands={{
whoami: { description: "who you are", run: () => "guest" },
echo: { description: "print text", usage: "echo <text>", run: (args) => args.join(" ") },
about: () => ["A terminal-style site.", "Type help for more."],
}}
/>
);
}help, clear and history are built in (turn them off with builtins={false}). The prompt handles ↑ ↓ history, Tab completion of command names, Ctrl+L to clear and Ctrl+C to drop the line.
Examples
Async commands
run can return a promise. The input waits until it settles; use ctx.print to show progress first. A thrown error is printed as name: message.
<TerminalShell
commands={{
weather: {
description: "today's weather",
run: async ([city = "Tunis"], ctx) => {
ctx.print(`fetching ${city}…`);
const res = await fetch(`/api/weather?city=${encodeURIComponent(city)}`);
return (await res.json()).summary;
},
},
}}
/>Hidden commands
hidden: true keeps a command out of help and Tab completion: room for easter eggs.
commands={{ sudo: { hidden: true, run: () => "nice try." } }}In a popup
The shell renders inline. To open it over the page, put it in your dialog and pass onClose: the title bar gets an "esc" button and Esc in the input calls it too.
<TerminalShell autoFocus onClose={() => setOpen(false)} commands={commands} />Props
| Prop | Type | Default | Description |
|---|---|---|---|
| commands | Record<string, ShellCommand | ShellCommand["run"]> | {} | Your commands by name: { description?, usage?, hidden?, run(args, ctx) }, or just the run function. |
| builtins | boolean | true | Add help, clear and history. Yours win on a name clash. |
| welcome | ReactNode[] | ['Type "help" to list commands.'] | Lines printed when the shell starts. |
| prompt | string | "$" | Prompt in front of the input and past commands. |
| title | ReactNode | "~ — sh" | Text in the title bar. |
| notFound | (name: string) => ShellOutput | command not found | Output for an unknown command. |
| inputLabel | string | "Terminal input" | Accessible name of the input. |
| placeholder | string | — | Placeholder in the empty input. |
| autoFocus | boolean | false | Focus the input on mount. |
| hints | boolean | true | Show the key-hint footer. |
| maxLines | number | 300 | Most lines kept on screen. |
| onClose | () => void | — | Adds an "esc" button; Esc in the input calls it. |
| className | string | — | Extra classes for the window. |
| screenClassName | string | "h-72" | Extra classes for the scrolling screen; set its height here. |
run receives ctx: { history: string[]; clear(): void; print(output): void }.
Accessibility
- The input has a real label ("Terminal input" by default) and the window shows a focus border when it is focused.
- Output lands in a
role="log"region, so screen readers announce new lines as they print. - Tab only completes when there is a partial command name; on an empty input it moves focus as usual, so keyboard users are never trapped.
- Clicking the screen focuses the input, unless you are selecting text to copy.