import "@xterm/xterm/css/xterm.css"; import "./style.css"; import { FitAddon } from "@xterm/addon-fit"; import { ImageAddon } from "@xterm/addon-image"; import { Terminal } from "@xterm/xterm"; import { type BootProgress, type KernelInstance, MemoryFs, type Pty, checkSupport, createKernel, } from "unkernel/web"; // Both are hashed assets, so they are cached for good and fetched together. import kernelUrl from "unkernel/unkernel.wasm?url"; import binaryUrl from "./libbui-aarch64.bin?url"; /** Where the guest sees libbui: a 9p mount served from this tab's memory. */ const MOUNT = "/opt/libbui"; /** Every string the script shows, keyed by the page language. */ const STRINGS = { en: { loading: "Loading libbui…", starting: "Starting libbui…", ready: "libbui is ready.", clickToType: "Click the window to type.", tapToType: "Tap the window to type.", typing: "You’re typing in libbui.", failed: "libbui could not start.", failedDetail: "Check your connection and try again.", quit: "libbui has quit. Start it again whenever you like.", crashed: (why: string) => `libbui stopped unexpectedly (${why}).`, ask: "libbui is about a 12 MB download.", copied: "Copied", copyFailed: "Couldn’t copy. Select the command instead.", }, } as const; const text = STRINGS.en; function element(id: string, kind: new () => T): T { const found = document.getElementById(id); if (!(found instanceof kind)) { throw new Error(`#${id} is missing or is not a ${kind.name}`); } return found; } const frame = element("window", HTMLDivElement); const host = element("terminal", HTMLDivElement); const boot = element("boot", HTMLDivElement); const bootLine = element("boot-line", HTMLParagraphElement); const bootDetail = element("boot-detail", HTMLParagraphElement); const bootMeter = element("boot-meter", HTMLDivElement); const bootFill = element("boot-fill", HTMLSpanElement); const begin = element("begin", HTMLButtonElement); const retry = element("retry", HTMLButtonElement); const restart = element("restart", HTMLButtonElement); const help = element("terminal-help", HTMLParagraphElement); const helpLead = element("help-lead", HTMLSpanElement); const keys = element("keys", HTMLDivElement); const announcer = element("announcer", HTMLSpanElement); const theme = { background: "#14110f", foreground: "#ece4d8", cursor: "#f2b84b", cursorAccent: "#14110f", selectionBackground: "#f2b84b55", black: "#1f1a17", red: "#e5786d", green: "#9fc98a", yellow: "#f2b84b", blue: "#8fb3e0", magenta: "#d1a0d8", cyan: "#86cfc4", white: "#d8cfc2", // 4.7:1 on the background; libbui uses it for secondary text. brightBlack: "#8a7e72", brightRed: "#f2958b", brightGreen: "#b6dba4", brightYellow: "#f7cd78", brightBlue: "#aac8ee", brightMagenta: "#e2bbe7", brightCyan: "#a4e0d7", brightWhite: "#fbf6ee", }; const calm = matchMedia("(prefers-reduced-motion: reduce)"); const term = new Terminal({ allowProposedApi: false, convertEol: false, cursorBlink: !calm.matches, fontFamily: '"JetBrains Mono", "Cascadia Mono", "SF Mono", Menlo, Consolas, "Noto Sans Mono CJK SC", monospace', fontSize: 14, lineHeight: 1.1, // Dim text (SGR 2) and dark palette entries still read at WCAG AA. minimumContrastRatio: 4.5, scrollback: 0, // Always on: it adds an offscreen copy of the screen and a live region // for screen readers, and costs sighted visitors nothing they can see. screenReaderMode: true, theme, }); calm.addEventListener("change", () => { term.options.cursorBlink = !calm.matches; }); const fit = new FitAddon(); term.loadAddon(fit); // Sixel and iTerm images, with cell-size reports, so libbui draws covers as // pictures rather than half blocks. Covers are small; keep the cache small. term.loadAddon(new ImageAddon({ pixelLimit: 1024 * 1024, storageLimit: 16, showPlaceholder: false })); term.open(host); // xterm's hidden textarea is what takes focus, so it carries the name and // the way out, not the wrapper around it. const input = host.querySelector("textarea"); if (input === null) throw new Error("xterm did not create its input"); input.setAttribute("aria-label", "libbui"); input.setAttribute("aria-describedby", "terminal-help"); /** libbui's smallest layout. Below it the window pans sideways. */ const MIN_COLS = 64; /** Smaller than this is too hard to read; pan instead. */ const FONT_SIZES = [14, 13, 12, 11, 10]; /** * Widths where libbui shows more, with the smallest font worth shrinking * to for each: the shelf's preview pane is wide enough for a cover from 96 * columns, and a title's own page shows its cover from 72. */ const RICHER_LAYOUTS = [ { cols: 96, minFont: 11 }, { cols: 72, minFont: 12 }, ] as const; /** Columns that fit at `size`, leaving the font set to it. */ function colsAt(size: number): { cols: number; rows: number } | undefined { if (term.options.fontSize !== size) term.options.fontSize = size; return fit.proposeDimensions(); } /** * Fits the terminal at the largest font that gives libbui its richest * layout without going below that layout's smallest font, and otherwise at * the largest font that leaves room for libbui at all. */ function fitTerminal(): void { const choose = (): { cols: number; rows: number } | undefined => { for (const layout of RICHER_LAYOUTS) { for (const size of FONT_SIZES.filter((size) => size >= layout.minFont)) { const proposed = colsAt(size); if (proposed === undefined) return undefined; if (proposed.cols >= layout.cols) return proposed; } } let proposed: { cols: number; rows: number } | undefined; for (const size of FONT_SIZES) { proposed = colsAt(size); if (proposed === undefined || proposed.cols >= MIN_COLS) break; } return proposed; }; const proposed = choose(); if (proposed === undefined) return; const cols = Math.max(MIN_COLS, proposed.cols); if (cols !== term.cols || proposed.rows !== term.rows) term.resize(cols, proposed.rows); host.classList.toggle("pans", proposed.cols < MIN_COLS); } fitTerminal(); // Ctrl+] hands focus back to the page, so keyboard users are never trapped in // the terminal. `code` is the physical key, so it works where ] needs AltGr. term.attachCustomKeyEventHandler((event) => { if (event.type !== "keydown" || !event.ctrlKey) return true; if (event.key === "]" || event.code === "BracketRight") { // The help sits just below the window, so Tab carries on from there. help.focus(); return false; } return true; }); const coarse = matchMedia("(pointer: coarse)"); /** The help's first sentence, which says how to get into libbui from here. */ function typingHint(): string { if (document.activeElement === input) return text.typing; return coarse.matches ? text.tapToType : text.clickToType; } function showTypingHint(): void { const hint = typingHint(); if (helpLead.textContent !== hint) helpLead.textContent = hint; } showTypingHint(); input.addEventListener("focus", showTypingHint); input.addEventListener("blur", showTypingHint); coarse.addEventListener("change", showTypingHint); /** libbui is on screen and taking keys, not loading or failed. */ function live(): boolean { return host.classList.contains("live") && boot.hidden === true; } // A press anywhere in the window goes to libbui, as it would in an app: the // title bar, the border and the margin around the terminal. xterm handles // presses on itself, so selection still works, and controls keep theirs. frame.addEventListener("mousedown", (event) => { if (event.button !== 0 || !(event.target instanceof Element)) return; const target = event.target; // The extra keys send to libbui without taking focus from it. if (keys.contains(target) && target.closest("button") !== null) { event.preventDefault(); return; } if (!live()) return; const own = target.closest(".xterm, button, a, input, select, textarea, [tabindex], [contenteditable]"); if (own !== null && frame.contains(own)) return; // Without this the press would focus the section around the window, which // is a target for the skip link, after we focus libbui. event.preventDefault(); term.focus(); }); /** Set when the visitor presses outside the window or types anywhere. */ let busyElsewhere = false; document.addEventListener( "pointerdown", (event) => { if (!(event.target instanceof Node) || !frame.contains(event.target)) busyElsewhere = true; }, true, ); document.addEventListener( "keydown", () => { busyElsewhere = true; }, true, ); /** * libbui takes focus unasked only from a visitor who is looking at it and * doing nothing else, and never on a phone, where it would open the keyboard. */ function mayTakeFocus(): boolean { const active = document.activeElement; return !coarse.matches && !busyElsewhere && (active === null || active === document.body); } /** At least half the window is on screen. */ let inView = false; /** libbui went live out of sight, and may take focus when first seen. */ let awaitingView = false; const sighting = new IntersectionObserver( (entries) => { const entry = entries.at(-1); inView = entry !== undefined && entry.isIntersecting && entry.intersectionRatio >= 0.5; if (!inView || !awaitingView) return; awaitingView = false; sighting.disconnect(); if (live() && mayTakeFocus()) term.focus(); }, { threshold: 0.5 }, ); sighting.observe(frame); /** Focus for libbui's first start. Returns whether it took focus. */ function focusOnArrival(): boolean { if (!inView) { awaitingView = true; return false; } sighting.disconnect(); if (!mayTakeFocus()) return false; term.focus(); return true; } /** Focus after Start again, which the visitor pressed in the window. */ function focusOnReturn(): boolean { const active = document.activeElement; // Start again hides itself, so focus may have dropped to the page. if (active !== null && active !== document.body && active !== restart) return false; term.focus(); return true; } /** Sets the boot status. Only `line` is in the live region; call it per phase. */ function say(line: string, detail = ""): void { if (bootLine.textContent !== line) bootLine.textContent = line; bootDetail.textContent = detail; } /** The shelf's books, each with the percent it lands at in `data-at`. */ const books = Array.from(boot.querySelectorAll(".shelf .book"), (book) => { const at = Number(book.dataset.at); if (!Number.isInteger(at)) throw new Error(`a shelf book has no landing percent: ${book.dataset.at}`); return { book, at }; }); if (books.length === 0) throw new Error("the boot shelf has no books"); const percentage = new Intl.NumberFormat(document.documentElement.lang, { style: "percent" }); /** Moves the meter and puts each book whose percent has come on the shelf. */ function meter(fraction: number): void { const percent = Math.round(Math.min(1, Math.max(0, fraction)) * 100); bootFill.textContent = percentage.format(percent / 100); bootMeter.setAttribute("aria-valuenow", String(percent)); for (const { book, at } of books) book.classList.toggle("on", percent >= at); } /** * Bytes in and expected for each download, so one meter covers both. These * are unpacked sizes, larger than what crosses the wire, so the page shows a * percentage rather than megabytes that would contradict the size it quotes. */ const transfers = new Map(); function showTransfers(): void { let loaded = 0; let total = 0; for (const t of transfers.values()) { loaded += t.loaded; total += t.total; } if (total > 0) meter(0.9 * (loaded / total)); if (Array.from(transfers.values()).every((t) => t.done)) settle(); } /** * Starts a download and returns a Response whose body counts itself into the * meter. Headers are kept, so the kernel still compiles while it streams. */ async function tracked(name: string, url: string): Promise { // Counted from the start, so a quick download cannot finish before a slow one is known. const entry = { loaded: 0, total: 0, done: false }; transfers.set(name, entry); const response = await fetch(url); if (!response.ok || response.body === null) { throw new Error(`could not fetch ${url} (${response.status} ${response.statusText})`); } // content-length counts compressed bytes; the server also sends the size // the body decodes to. entry.total = Number( response.headers.get("x-decoded-length") ?? (response.headers.has("content-encoding") ? "0" : (response.headers.get("content-length") ?? "0")), ); const counted = response.body.pipeThrough( new TransformStream({ transform(chunk, controller) { entry.loaded += chunk.byteLength; showTransfers(); controller.enqueue(chunk); }, flush() { entry.done = true; showTransfers(); }, }), ); const headers = new Headers(response.headers); headers.delete("content-encoding"); headers.delete("content-length"); return new Response(counted, { headers, status: response.status, statusText: response.statusText }); } /** * Everything is downloaded and libbui is starting. Nothing is left to count, * so the shelf's small pile keeps stacking until the terminal takes over. */ function settle(): void { boot.classList.add("busy"); say(text.starting); meter(0.92); } /** * Follows the machine as it starts. Its own download events re-read the * kernel that `tracked` already counts, and it starts compiling while that * still streams, so only the end of compiling moves the shelf. */ function progress(p: BootProgress): void { if (p.stage === "compiled") meter(0.96); } let vm: KernelInstance | undefined; let pty: Pty | undefined; /** Starts libbui on a fresh pty sized to the terminal. */ async function run(machine: KernelInstance, again = false): Promise { restart.hidden = true; term.reset(); const session = await machine.spawn(`${MOUNT}/libbui`, ["--sample-library"], { cols: term.cols, rows: term.rows, term: "xterm-256color", env: { COLORTERM: "truecolor", HOME: "/root", LANG: "C.UTF-8", TERM: "xterm-256color", }, }); pty = session; const focused = again ? focusOnReturn() : focusOnArrival(); // #boot hides straight away, so the ready line goes to the live region. announcer.textContent = focused ? text.ready : `${text.ready} ${typingHint()}`; boot.hidden = true; host.classList.add("live"); keys.hidden = !coarse.matches; session.output .pipeTo( new WritableStream({ write: (bytes) => { term.write(bytes); }, }), ) .catch(fail); const end = await session.ended; if (pty === session) pty = undefined; const clean = end.type === "exit" && end.code === 0; const why = end.type === "exit" ? `exit ${end.code}` : end.type; term.write(clean ? `\r\n\x1b[2m${text.quit}\x1b[0m\r\n` : `\r\n\x1b[31m${text.crashed(why)}\x1b[0m\r\n`); announcer.textContent = clean ? text.quit : text.crashed(why); restart.hidden = false; // The visitor quit libbui, so focus can follow them to the way back in. restart.focus(); } term.onData((data) => { void pty?.write(data); }); term.onBinary((data) => { void pty?.write(Uint8Array.from(data, (c) => c.charCodeAt(0))); }); term.onResize(({ cols, rows }) => { pty?.resize(cols, rows); }); new ResizeObserver(() => { fitTerminal(); }).observe(host); restart.addEventListener("click", () => { if (vm !== undefined) void run(vm, true).catch(fail); }); retry.addEventListener("click", () => { location.reload(); }); // Keys a phone keyboard does not have. const SEQUENCES: Record = { esc: "\x1b", tab: "\t", up: "\x1b[A", down: "\x1b[B", right: "\x1b[C", left: "\x1b[D", enter: "\r", }; keys.addEventListener("click", (event) => { if (!(event.target instanceof HTMLButtonElement)) return; const sequence = SEQUENCES[event.target.dataset.key ?? ""]; if (sequence === undefined) throw new Error(`unknown key ${event.target.dataset.key}`); void pty?.write(sequence); }); function fail(error: unknown): void { // The details are for whoever opens the console, not for the visitor. console.error(error); boot.hidden = false; boot.classList.remove("busy"); boot.classList.add("failed"); begin.hidden = true; retry.hidden = false; say(text.failed, text.failedDetail); } async function start(): Promise { begin.hidden = true; say(text.loading); meter(0); // Both downloads start now and run side by side. const kernel = tracked("kernel", kernelUrl); const binary = tracked("binary", binaryUrl).then((r) => r.arrayBuffer()); const files = new MemoryFs(); files.writeFile("/libbui", new Uint8Array(await binary), { mode: 0o755 }); vm = await createKernel({ kernel: await kernel, memoryMiB: 512, mounts: { [MOUNT]: files }, consoleSize: { cols: term.cols, rows: term.rows }, onProgress: progress, }); say(text.starting); meter(0.98); await run(vm); } async function main(): Promise { const support = await checkSupport(); if (!support.ok) { console.info("libbui cannot run here:", support.problems); const template = element("unsupported", HTMLTemplateElement); const notice = template.content.cloneNode(true); if (!(notice instanceof DocumentFragment)) throw new Error("the unsupported notice is not a fragment"); boot.replaceChildren(notice); boot.classList.add("failed"); help.hidden = true; return; } // On metered connections and phones, ask before a 12 MB download. const connection: unknown = Reflect.get(navigator, "connection"); const saveData = typeof connection === "object" && connection !== null && Reflect.get(connection, "saveData") === true; if (saveData || matchMedia("(pointer: coarse)").matches) { say(text.ask); begin.hidden = false; begin.addEventListener("click", () => { start().catch(fail); }); return; } await start(); } main().catch(fail); for (const button of document.querySelectorAll("button.copy")) { const label = button.textContent ?? ""; let reset: ReturnType | undefined; button.addEventListener("click", () => { const source = document.getElementById(button.dataset.copy ?? ""); if (source === null) throw new Error(`nothing to copy for ${button.dataset.copy}`); clearTimeout(reset); navigator.clipboard.writeText(source.textContent ?? "").then( () => { button.textContent = text.copied; announcer.textContent = text.copied; reset = setTimeout(() => { button.textContent = label; announcer.textContent = ""; }, 1600); }, (error: unknown) => { console.error(error); announcer.textContent = text.copyFailed; }, ); }); }