⌨️ Terminal

How and why this site got a command prompt

Press Cmd/Ctrl + K (or swipe down with three fingers on a touch device) and a small zsh-style terminal opens on top of the page. Type help to see what it can do.

Why

  • It fits. I've spent my career in terminals and editors. A site about my work should let me (and curious visitors) poke at it the way I naturally would.
  • A second way in. Navigation menus are great for browsing; a prompt is great when you already know what you want, like whoami, resume or open rpg-quest.
  • A playground. Small, throwaway commands make it cheap to try ideas without adding yet another page or widget.
  • Personality. A little easter egg goes a long way toward making a personal site feel like mine.

How It Works

  • A native <dialog>:showModal() gives focus trapping, Esc to close and a backdrop for free. Clicking outside the box closes it too.
  • One component, mounted once:Terminal.astro lives in the base layout so every page has it, and the Astro ClientRouter navigation doesn't lose the shortcut.
  • Global built-ins:help, whoami, resume, theme, clear and exit live in a plain object keyed by command name.
  • Per-page commands: pages pass a terminalCommands list to the layout. They show up under "Current page commands" in help, and global names can't be shadowed.
  • Page handlers: anything that isn't a built-in is fired as a cancelable terminal:command event, so a page can implement its commands without the terminal knowing about them.
  • Accessible: a labelled input, described dialog, and plain text output so screen readers can follow along.

Code

Opening it

// Cmd/Ctrl + K opens the terminal from anywhere
document.addEventListener("keydown", (event) => {
  if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "k") return;
  event.preventDefault();
  dialog.showModal();
  input.focus();
});

Adding commands to a page

<!-- Any page can contribute its own commands -->
<BaseLayout terminalCommands={[
  { name: "list", description: "list available experiments" },
  { name: "open <slug>", description: "open an experiment" },
]}>

Handling them

// Unknown commands are dispatched to the page as a cancelable event
const handled = !dialog.dispatchEvent(
  new CustomEvent("terminal:command", { detail: { command, args, raw, print }, cancelable: true })
);
if (!handled) print(`zsh: command not found: ${raw}`, "err");

Try It Yourself

Create a Static HTML sandbox in CodeSandbox, replace the contents of index.html with the example below, and run it. Try help and whoami; use Cmd/Ctrl + K or a three-finger pull-down to open the terminal.

Show the full terminal implementation (~200 lines)
<!doctype html>
<html lang="en" data-theme="dark">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Mini Terminal</title>
  <style>
    :root { color-scheme: dark; }
    html[data-theme="light"] { color-scheme: light; }
    body { font: 16px system-ui; margin: 2rem; background: #16161e; color: #c0caf5; }
    html[data-theme="light"] body { background: #e1e2e7; color: #343b58; }
    button, input { font: inherit; }
    button { padding: .5rem 1rem; }
    .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
    .terminal {
      --term-gap: 0.75rem;
      box-sizing: border-box;
      position: fixed;
      inset: max(var(--term-gap), env(safe-area-inset-top)) max(var(--term-gap), env(safe-area-inset-right)) max(var(--term-gap), env(safe-area-inset-bottom)) max(var(--term-gap), env(safe-area-inset-left));
      display: block;
      width: auto;
      height: auto;
      min-width: 0;
      min-height: 0;
      max-width: none;
      max-height: none;
      margin: 0;
      padding: 1rem;
      background: #1a1b26;
      color: #c0caf5;
      border: 2px solid #7aa2f7;
      box-shadow: 0 0 0 1px rgba(0,0,0,.4), 0 18px 50px rgba(0,0,0,.55), 0 6px 16px rgba(0,0,0,.35);
      font: 0.95rem/1.5 "JetBrainsMono Nerd Font", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
      overflow-wrap: anywhere;
      overflow-y: auto;
      overscroll-behavior: contain;
    }
    .terminal:not([open]) { display: none; }
    .terminal::backdrop { background: rgba(0,0,0,.55); }
    .terminal p { margin: 0 0 .25rem; }
    .terminal-muted { color: #565f89; }
    .terminal code { padding: 0; background: none; color: #7dcfff; font: inherit; }
    .terminal-log div { white-space: pre-wrap; }
    .terminal-log .log-cmd { color: #c0caf5; }
    .terminal-log .log-cmd .prompt { color: #9ece6a; }
    .terminal-log .log-ok { color: #a9b1d6; }
    .terminal-log .log-err { color: #f7768e; }
    .terminal-log .log-table { margin: .5rem 0; overflow-x: auto; white-space: pre; color: #7dcfff; }
    .terminal-line { display: flex; align-items: center; gap: .5rem; margin: .25rem 0 0; }
    .terminal-prompt { flex: none; color: #9ece6a; }
    .terminal-prompt .path { color: #7aa2f7; }
    .terminal-line input { flex: 1; width: auto; min-width: 0; min-height: 44px; margin: 0; padding: 0; background: transparent; border: 0; box-shadow: none; outline: none; color: #c0caf5; font: inherit; font-size: 16px; caret-color: #c0caf5; caret-shape: block; }
    .terminal-line input::placeholder { color: #414868; }
    @media (prefers-reduced-motion: no-preference) {
      .terminal[open] { animation: terminal-slide-down .25s ease-out; }
      @keyframes terminal-slide-down { from { opacity: 0; transform: translateY(calc(-100% - var(--term-gap))); } to { opacity: 1; transform: translateY(0); } }
    }
    @media (max-width: 600px) { .terminal { --term-gap: .5rem; padding: .85rem; } }
  </style>
  <button id="open">Open terminal (⌘/Ctrl + K)</button>
  <p>On a touch screen, pull down with three fingers to open it.</p>
  <dialog class="terminal" id="terminal" aria-labelledby="title" aria-describedby="help">
    <h2 id="title" class="sr-only">Command prompt</h2>
    <p id="help" class="terminal-muted">Type <code>help</code> for commands.</p>
    <div class="terminal-log" id="output" role="log" aria-live="polite"></div>
    <form class="terminal-line" id="form">
      <label for="command" class="sr-only">Command</label>
      <span class="terminal-prompt" aria-hidden="true">vann@site <span class="path">~</span> %</span>
      <input id="command" type="text" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="go">
      <button type="submit" class="sr-only">Run</button>
    </form>
  </dialog>
  <script>
    const dialog = document.querySelector("#terminal");
    const input = document.querySelector("#command");
    const log = document.querySelector("#output");
    const print = (text, kind = "ok") => {
      const line = document.createElement("div");
      line.className = "log-" + kind;
      line.textContent = text;
      log.appendChild(line);
    };
    const echo = (text) => {
      const line = document.createElement("div");
      line.className = "log-cmd";
      const prompt = document.createElement("span");
      prompt.className = "prompt";
      prompt.textContent = "% ";
      line.append(prompt, text);
      log.appendChild(line);
    };
    const openTerminal = () => {
      if (!dialog.open) dialog.showModal();
      input.focus();
    };
    document.querySelector("#open").addEventListener("click", openTerminal);
    dialog.addEventListener("click", (event) => {
      if (event.target !== dialog) return;
      const rect = dialog.getBoundingClientRect();
      const inside = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
      if (!inside) dialog.close();
    });
    const builtins = {
      help: {
        description: "list available commands",
        run: () => print(helpText),
      },
      whoami: {
        description: "a short resume of the human behind the prompt",
        run: () => {
          const rows = [
            ["HUMAN", "Vannarith Ek | Engineering Leader"],
            ["FOCUS", "Collaborative teams. Scalable digital platforms."],
            ["NOW", "Engineering Manager @ Best Buy | Apr 2019-present"],
            ["IMPACT", "Leading 11+ globally distributed engineers; a GCP analytics platform processing millions of events daily."],
            ["DELIVERY", "Cut delivery cycles from weeks to under half a day through CI/CD and automation."],
            ["BEFORE", "Lead Engineer @ Best Buy | 2016-2019"],
            ["", "Senior Developer @ Harbinger Partners | 2015-2016"],
            ["", "Software / Senior Software Engineer @ Code42 | 2010-2015"],
            ["ROOTS", "Systems engineering, community technology, and Rails applications | 2003-2010"],
            ["STACK", "JavaScript / TypeScript, React, React Native, Next.js, Ruby on Rails, GCP, BigQuery, MySQL"],
            ["TOOLBOX", "GitHub Actions, Jenkins, Agile / SCRUM, TDD"],
            ["EDUCATION", "Brown College | Computer Programming Certificate"],
            ["FULL RESUME", "https://thislink.is/vans-resume"],
          ];
          const labelWidth = 11, contentWidth = 53;
          const border = (l, m, r) => l + "─".repeat(labelWidth + 2) + m + "─".repeat(contentWidth + 2) + r;
          const lines = [border("┌", "┬", "┐")];
          rows.forEach(([label, text], index) => {
            const wrapped = [];
            let line = "";
            for (const word of text.split(" ")) {
              if (line && line.length + word.length + 1 > contentWidth) { wrapped.push(line); line = word; }
              else line = line ? line + " " + word : word;
            }
            wrapped.push(line);
            wrapped.forEach((value, i) => lines.push("│ " + (i === 0 ? label : "").padEnd(labelWidth) + " │ " + value.padEnd(contentWidth) + " │"));
            if (index < rows.length - 1 && rows[index + 1][0]) lines.push(border("├", "┼", "┤"));
          });
          lines.push(border("└", "┴", "┘"));
          print(lines.join("\n"), "table");
        },
      },
      resume: {
        description: "open the full resume in a new tab",
        run: () => window.open("https://thislink.is/vans-resume", "_blank", "noopener,noreferrer"),
      },
      theme: {
        description: "set theme: theme [dark|light|toggle]",
        run: (args = []) => {
          const requested = args[0] || "toggle";
          if (!["dark", "light", "toggle"].includes(requested)) {
            print("Usage: theme [dark|light|toggle]", "err");
            return;
          }
          const root = document.documentElement;
          const theme = requested === "toggle" ? (root.dataset.theme === "dark" ? "light" : "dark") : requested;
          root.setAttribute("data-theme", theme);
          print("Theme set to " + theme + ".");
        },
      },
      clear: {
        description: "clear the screen",
        run: () => log.replaceChildren(),
      },
      exit: {
        description: "close the terminal",
        run: () => dialog.close(),
      },
    };
    const width = Math.max(...Object.keys(builtins).map((name) => name.length)) + 2;
    const helpText = Object.entries(builtins).map(([name, { description }]) => name.padEnd(width) + description).join("\n");
    document.querySelector("#form").addEventListener("submit", (event) => {
      event.preventDefault();
      const raw = input.value.trim();
      input.value = "";
      if (!raw) return;
      echo(raw);
      const [command, ...args] = raw.toLowerCase().split(/\s+/);
      if (Object.hasOwn(builtins, command)) builtins[command].run(args);
      else print("zsh: command not found: " + raw, "err");
      dialog.scrollTop = dialog.scrollHeight;
    });
    document.addEventListener("keydown", (event) => {
      if (event.defaultPrevented || event.isComposing || event.repeat || event.altKey || event.shiftKey || !(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "k") return;
      event.preventDefault();
      openTerminal();
    });
    let swipeStart = null;
    document.addEventListener("touchstart", (event) => {
      swipeStart = event.touches.length === 3
        ? Array.from(event.touches).reduce((sum, touch) => sum + touch.clientY, 0) / 3
        : null;
    }, { passive: true });
    document.addEventListener("touchmove", (event) => {
      if (swipeStart === null || event.touches.length !== 3) return;
      const y = Array.from(event.touches).reduce((sum, touch) => sum + touch.clientY, 0) / 3;
      if (y - swipeStart >= 80) {
        swipeStart = null;
        openTerminal();
      }
    }, { passive: true });
    document.addEventListener("touchend", () => { swipeStart = null; }, { passive: true });
  </script>
</html>
Edit terminal-experiment

Things I Learned

  • The native <dialog> removed most of the code I expected to write. The hard part was event cleanup across client-side navigations, not the UI.
  • An event-based extension point kept the component small. Pages own their commands; the terminal owns input, output and history.
  • A shortcut isn't enough. Touch devices have no keyboard shortcut, so the three-finger pull-down gives them a deliberate way to open the terminal without triggering during normal one-finger scrolling.

Try It

On your phone or tablet, visit this page and pull down with three fingers to try the gesture. On desktop, open the terminal now and try whoami, theme toggle or help.


Command prompt

Type help for commands.