From 653d87aeb44ec0cc0649381ffa38aff96960da39 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Sat, 14 Nov 2026 21:00:38 -0500 Subject: [PATCH] spike: platform bindings for node and xterm --- .changeset/ui-platform.md | 11 ++ packages/ui/bench/helpers.ts | 11 +- packages/ui/package.json | 4 + packages/ui/src/index.browser.ts | 15 +++ packages/ui/src/index.ts | 10 +- packages/ui/src/platform.test.ts | 150 +++++++++++++++++++++++++++ packages/ui/src/platform.ts | 29 ++++++ packages/ui/src/platform/node.ts | 46 ++++++++ packages/ui/src/platform/xterm.ts | 27 +++++ packages/ui/src/ui.lifecycle.test.ts | 2 +- packages/ui/src/ui.ts | 53 ++++++---- packages/ui/test/ui.ts | 2 +- 12 files changed, 330 insertions(+), 30 deletions(-) create mode 100644 .changeset/ui-platform.md create mode 100644 packages/ui/src/index.browser.ts create mode 100644 packages/ui/src/platform.test.ts create mode 100644 packages/ui/src/platform.ts create mode 100644 packages/ui/src/platform/node.ts create mode 100644 packages/ui/src/platform/xterm.ts diff --git a/.changeset/ui-platform.md b/.changeset/ui-platform.md new file mode 100644 index 0000000..b0d83c3 --- /dev/null +++ b/.changeset/ui-platform.md @@ -0,0 +1,11 @@ +--- +'@clack/ui': minor +--- + +Makes every `createUI()` option optional. With no options, a UI renders to `process.stdout` at the terminal's size, follows resizes, and stops on SIGINT or SIGTERM. Passing a `signal` still stops it, and SIGINT is left to the caller. Bun and Deno use the same defaults. + +In the browser, pass an xterm.js terminal as `output`: + +```js +const ui = await createUI({ output: terminal, signal }); +``` diff --git a/packages/ui/bench/helpers.ts b/packages/ui/bench/helpers.ts index 05eca85..c8e2858 100644 --- a/packages/ui/bench/helpers.ts +++ b/packages/ui/bench/helpers.ts @@ -1,7 +1,7 @@ /* oxlint-disable bombshell-dev/exported-function-async */ import { PassThrough, Writable } from 'node:stream'; import type { Document, Element, Text } from '../src/dom.ts'; -import { createUI, type UI } from '../src/ui.ts'; +import { createUI, type UI } from '../src/index.ts'; /** Wait until an asynchronous render callback has completed. */ export async function waitFor(predicate: () => boolean): Promise { @@ -95,7 +95,9 @@ export async function setupUI( }); }, }); - const ui = await createUI({ input, output, width: 80, height: 24 }); + const controller = new AbortController(); + const ui = await createUI({ input, output, width: 80, height: 24, signal: controller.signal }); + let running: Promise | undefined; const { texts } = createTree({ document: ui.document, nodeCount, shape }); const initialWrites = writes; let started = false; @@ -110,11 +112,12 @@ export async function setupUI( async start() { if (started) return; started = true; - void ui.main(); + running = ui.main(); await waitFor(() => writes > initialWrites); }, async close() { - await ui[Symbol.asyncDispose](); + controller.abort(); + await running; input.destroy(); output.destroy(); }, diff --git a/packages/ui/package.json b/packages/ui/package.json index 5e696f1..48e20b2 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -19,6 +19,10 @@ "type": "module", "exports": { ".": { + "browser": { + "types": "./dist/index.browser.d.mts", + "default": "./dist/index.browser.mjs" + }, "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, diff --git a/packages/ui/src/index.browser.ts b/packages/ui/src/index.browser.ts new file mode 100644 index 0000000..aa22208 --- /dev/null +++ b/packages/ui/src/index.browser.ts @@ -0,0 +1,15 @@ +import { createXtermPlatform, type XtermTerminal } from './platform/xterm.ts'; +import { startUI, type UI } from './ui.ts'; + +export type { UI } from './ui.ts'; + +export interface UIOptions { + /** The xterm.js terminal to render into. Browsers have no default terminal. */ + output: XtermTerminal; + signal?: AbortSignal; +} + +/** Create a UI on an xterm.js terminal. */ +export async function createUI(options: UIOptions): Promise { + return startUI(createXtermPlatform(options.output), options.signal); +} diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index ca4a46a..9bdc20b 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -1 +1,9 @@ -export { createUI } from './ui.ts'; +import { createNodePlatform } from './platform/node.ts'; +import { startUI, type UI, type UIOptions } from './ui.ts'; + +export type { UI, UIOptions } from './ui.ts'; + +/** Create a UI on this process's terminal. */ +export async function createUI(options: UIOptions = {}): Promise { + return startUI(createNodePlatform(options), options.signal); +} diff --git a/packages/ui/src/platform.test.ts b/packages/ui/src/platform.test.ts new file mode 100644 index 0000000..28f1468 --- /dev/null +++ b/packages/ui/src/platform.test.ts @@ -0,0 +1,150 @@ +import process from 'node:process'; +import { Writable } from 'node:stream'; +import { describe, expect, test, vi } from 'vitest'; +import { createUI as createBrowserUI } from './index.browser.ts'; +import { createUI } from './index.ts'; +import { createNodePlatform } from './platform/node.ts'; +import { createXtermPlatform, type XtermTerminal } from './platform/xterm.ts'; +import type { Size } from './platform.ts'; + +describe('node platform', () => { + test('reports the TTY size and follows resizes until aborted', () => { + const output = tty(100, 30); + const platform = createNodePlatform({ output, signal: AbortSignal.abort() }); + const events = createEvents(); + const controller = new AbortController(); + + platform.listen(events, controller.signal); + expect(platform.size()).toEqual({ width: 100, height: 30 }); + + output.columns = 120; + output.emit('resize'); + expect(events.resize).toHaveBeenLastCalledWith({ width: 120, height: 30 }); + + controller.abort(); + output.emit('resize'); + expect(events.resize).toHaveBeenCalledTimes(1); + }); + + test('prefers explicit width and height over the TTY size', () => { + const platform = createNodePlatform({ output: tty(100, 30), width: 40, height: 10 }); + expect(platform.size()).toEqual({ width: 40, height: 10 }); + }); + + test('falls back to 80×24 when output is not a TTY', () => { + const platform = createNodePlatform({ output: sink() }); + expect(platform.size()).toEqual({ width: 80, height: 24 }); + }); + + test('interrupts on SIGINT only when the caller passed no signal', () => { + const before = process.listenerCount('SIGINT'); + const controller = new AbortController(); + + createNodePlatform({ signal: controller.signal }).listen(createEvents(), controller.signal); + expect(process.listenerCount('SIGINT')).toBe(before); + + const events = createEvents(); + createNodePlatform({}).listen(events, controller.signal); + process.emit('SIGINT', 'SIGINT'); + expect(events.interrupt).toHaveBeenCalledTimes(1); + + controller.abort(); + expect(process.listenerCount('SIGINT')).toBe(before); + }); + + test('createUI() without a signal stops on SIGINT', async () => { + const ui = await createUI({ output: tty(10, 1) }); + const running = ui.main(); + await new Promise((resolve) => setImmediate(resolve)); + + process.emit('SIGINT', 'SIGINT'); + await running; + expect(ui.main()).toBe(running); + }); +}); + +describe('xterm platform', () => { + test('writes bytes and follows resizes until aborted', async () => { + const terminal = new FakeXterm(80, 24); + const platform = createXtermPlatform(terminal); + const events = createEvents(); + const controller = new AbortController(); + + platform.listen(events, controller.signal); + await platform.write(new Uint8Array([104, 105])); + expect(terminal.written).toEqual([new Uint8Array([104, 105])]); + + terminal.resize(100, 40); + expect(events.resize).toHaveBeenLastCalledWith({ width: 100, height: 40 }); + expect(platform.size()).toEqual({ width: 100, height: 40 }); + + controller.abort(); + terminal.resize(10, 10); + expect(events.resize).toHaveBeenCalledTimes(1); + }); + + test('the browser createUI() renders into the terminal until aborted', async () => { + const terminal = new FakeXterm(20, 2); + const controller = new AbortController(); + const ui = await createBrowserUI({ output: terminal, signal: controller.signal }); + const running = ui.main(); + + ui.document.documentElement.appendChild(ui.document.createTextNode('hello')); + await vi.waitFor(() => expect(terminal.text()).toContain('hello')); + + terminal.resize(30, 3); + const frames = terminal.written.length; + await vi.waitFor(() => expect(terminal.written.length).toBeGreaterThan(frames)); + + controller.abort(); + await running; + expect(terminal.listeners.size).toBe(0); + }); +}); + +function createEvents(): { + resize: ReturnType void>>; + interrupt: ReturnType void>>; +} { + return { resize: vi.fn<(size: Size) => void>(), interrupt: vi.fn<() => void>() }; +} + +function sink(): Writable { + return new Writable({ write: (_chunk, _encoding, done) => done() }); +} + +function tty(columns: number, rows: number): Writable & { columns: number; rows: number } { + return Object.assign(sink(), { columns, rows }); +} + +class FakeXterm implements XtermTerminal { + cols: number; + rows: number; + written: Uint8Array[] = []; + listeners = new Set<(size: { cols: number; rows: number }) => void>(); + + constructor(cols: number, rows: number) { + this.cols = cols; + this.rows = rows; + } + + write(data: Uint8Array, callback?: () => void): void { + this.written.push(data); + queueMicrotask(() => callback?.()); + } + + onResize(listener: (size: { cols: number; rows: number }) => void): { dispose(): void } { + this.listeners.add(listener); + return { dispose: () => this.listeners.delete(listener) }; + } + + resize(cols: number, rows: number): void { + this.cols = cols; + this.rows = rows; + for (const listener of this.listeners) listener({ cols, rows }); + } + + text(): string { + return this.written.map((bytes) => new TextDecoder().decode(bytes)).join(''); + } +} diff --git a/packages/ui/src/platform.ts b/packages/ui/src/platform.ts new file mode 100644 index 0000000..afd8eb5 --- /dev/null +++ b/packages/ui/src/platform.ts @@ -0,0 +1,29 @@ +/** Terminal dimensions in cells. */ +export interface Size { + width: number; + height: number; +} + +/** Host events a UI reacts to while it runs. */ +export interface PlatformEvents { + /** The terminal changed size. */ + resize(size: Size): void; + /** The host asked the program to stop, such as SIGINT. */ + interrupt(): void; +} + +/** + * Everything a UI needs from its host that isn't portable JavaScript. + * + * Bindings for each host live in one place so the rest of the UI stays + * runtime-agnostic. Each package entry point picks the binding for its runtime + * through export conditions and builds it from `createUI()` options. + */ +export interface Platform { + /** Current terminal size. */ + size(): Size; + /** Write bytes to the terminal; resolves once the host has accepted them. */ + write(bytes: Uint8Array): Promise; + /** Deliver host events to `events` until `signal` aborts. */ + listen(events: PlatformEvents, signal: AbortSignal): void; +} diff --git a/packages/ui/src/platform/node.ts b/packages/ui/src/platform/node.ts new file mode 100644 index 0000000..ab58db9 --- /dev/null +++ b/packages/ui/src/platform/node.ts @@ -0,0 +1,46 @@ +import process from 'node:process'; +import type { Platform, Size } from '../platform.ts'; +import type { UIOptions } from '../ui.ts'; + +/** Signals that stop a UI when the caller didn't pass its own `signal`. */ +const interrupts: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM']; + +/** Bind a UI to a Node-compatible process: Node, Bun, or Deno. */ +export function createNodePlatform(options: UIOptions): Platform { + const output: UIOptions['output'] & { columns?: number; rows?: number } = + options.output ?? process.stdout; + const signals = options.signal ? [] : interrupts; + + const size = (): Size => ({ + width: options.width ?? output.columns ?? 80, + height: options.height ?? output.rows ?? 24, + }); + + return { + size, + write(bytes) { + const result = Promise.withResolvers(); + output.write(bytes, (error) => (error ? result.reject(error) : result.resolve())); + return result.promise; + }, + listen(events, signal) { + const resize = (): void => events.resize(size()); + const interrupt = (): void => events.interrupt(); + + output.on('resize', resize); + for (const name of signals) process.on(name, interrupt); + // Signal listeners don't keep Node's event loop alive; the UI should until it stops. + const alive = setInterval(() => {}, 2 ** 30); + + signal.addEventListener( + 'abort', + () => { + clearInterval(alive); + output.off('resize', resize); + for (const name of signals) process.off(name, interrupt); + }, + { once: true }, + ); + }, + }; +} diff --git a/packages/ui/src/platform/xterm.ts b/packages/ui/src/platform/xterm.ts new file mode 100644 index 0000000..d9729e6 --- /dev/null +++ b/packages/ui/src/platform/xterm.ts @@ -0,0 +1,27 @@ +import type { Platform } from '../platform.ts'; + +/** The slice of xterm.js's `Terminal` this binding uses. */ +export interface XtermTerminal { + readonly cols: number; + readonly rows: number; + write(data: Uint8Array, callback?: () => void): void; + onResize(listener: (size: { cols: number; rows: number }) => void): { dispose(): void }; +} + +/** Bind a UI to an xterm.js terminal. Browsers have no process signals to interrupt it. */ +export function createXtermPlatform(terminal: XtermTerminal): Platform { + return { + size: () => ({ width: terminal.cols, height: terminal.rows }), + write(bytes) { + const result = Promise.withResolvers(); + terminal.write(bytes, () => result.resolve()); + return result.promise; + }, + listen(events, signal) { + const subscription = terminal.onResize(({ cols, rows }) => + events.resize({ width: cols, height: rows }), + ); + signal.addEventListener('abort', () => subscription.dispose(), { once: true }); + }, + }; +} diff --git a/packages/ui/src/ui.lifecycle.test.ts b/packages/ui/src/ui.lifecycle.test.ts index 0ef1bed..fa675ae 100644 --- a/packages/ui/src/ui.lifecycle.test.ts +++ b/packages/ui/src/ui.lifecycle.test.ts @@ -2,7 +2,7 @@ import { once } from 'node:events'; import { PassThrough, Writable } from 'node:stream'; import { alternateBuffer, cursor, settings } from '@bomb.sh/tty'; import { describe, expect, test, vi } from 'vitest'; -import { createUI } from './ui.ts'; +import { createUI } from './index.ts'; const terminalSettings = settings(cursor(false), alternateBuffer()); const apply = Buffer.from(terminalSettings.apply).toString('utf8'); diff --git a/packages/ui/src/ui.ts b/packages/ui/src/ui.ts index 8889407..fe99645 100644 --- a/packages/ui/src/ui.ts +++ b/packages/ui/src/ui.ts @@ -1,6 +1,7 @@ import { alternateBuffer, createTerm, cursor, settings } from '@bomb.sh/tty'; import type { Readable, Writable } from 'node:stream'; import { Document } from './dom.ts'; +import type { Platform } from './platform.ts'; import { RenderApi } from './render.ts'; import { Layout } from './layout.ts'; @@ -9,21 +10,25 @@ export interface UI { main(): Promise; } +/** Defaults come from the platform for the current runtime. */ export interface UIOptions { height?: number; width?: number; - input: Readable; - output: Writable; - signal: AbortSignal; + input?: Readable; + output?: Writable; + /** Stops the UI. Without one, the platform decides, such as SIGINT on Node. */ + signal?: AbortSignal; } -export async function createUI(options: UIOptions): Promise { - const { output, width = 80, height = 24, signal } = options; +/** Run a UI on `platform` until `signal` aborts or the platform interrupts it. */ +export async function startUI(platform: Platform, signal?: AbortSignal): Promise { + const stop = new AbortController(); + const lifetime = signal ? AbortSignal.any([signal, stop.signal]) : stop.signal; const setup = settings(cursor(false), alternateBuffer()); - const term = await createTerm({ width, height }); - const render = new RenderApi(signal); + const term = await createTerm(platform.size()); + const render = new RenderApi(lifetime); const document = new Document(() => render.request()); @@ -32,35 +37,37 @@ export async function createUI(options: UIOptions): Promise { let running: Promise | undefined = undefined; const run = async () => { - await write(output, setup.apply); + await platform.write(setup.apply); try { + platform.listen( + { + resize({ width, height }) { + platform.write(term.update([{ type: 'resize', width, height }])).then( + () => render.request(), + () => stop.abort(), + ); + }, + interrupt: () => stop.abort(), + }, + lifetime, + ); + for await (const _ of render) { const ops = [...layout.layout()]; const result = term.render(ops); - await write(output, result.output); + await platform.write(result.output); } } finally { - await write(output, setup.revert); + stop.abort(); + await platform.write(setup.revert); } }; return { document, main() { - return running ? running : signal.aborted ? Promise.resolve() : (running = run()); + return running ? running : lifetime.aborted ? Promise.resolve() : (running = run()); }, }; } - -function write(stream: Writable, bytes: Uint8Array): Promise { - const result = Promise.withResolvers(); - stream.write(bytes, (err) => { - if (err) { - result.reject(err); - } else { - result.resolve(); - } - }); - return result.promise; -} diff --git a/packages/ui/test/ui.ts b/packages/ui/test/ui.ts index 3246213..1061768 100644 --- a/packages/ui/test/ui.ts +++ b/packages/ui/test/ui.ts @@ -1,5 +1,5 @@ import type { SyncTestTerminalOptions } from '@termless/test'; -import { createUI, type UI } from '../src/ui.ts'; +import { createUI, type UI } from '../src/index.ts'; import { createTestTerminal, type TestTerminal } from './terminal.ts'; export interface TestUI extends AsyncDisposable {