Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/ui-platform.md
Original file line number Diff line number Diff line change
@@ -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 });
```
11 changes: 7 additions & 4 deletions packages/ui/bench/helpers.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
Expand Down Expand Up @@ -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<void> | undefined;
const { texts } = createTree({ document: ui.document, nodeCount, shape });
const initialWrites = writes;
let started = false;
Expand All @@ -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();
},
Expand Down
4 changes: 4 additions & 0 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
15 changes: 15 additions & 0 deletions packages/ui/src/index.browser.ts
Original file line number Diff line number Diff line change
@@ -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<UI> {
return startUI(createXtermPlatform(options.output), options.signal);
}
10 changes: 9 additions & 1 deletion packages/ui/src/index.ts
Original file line number Diff line number Diff line change
@@ -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<UI> {
return startUI(createNodePlatform(options), options.signal);
}
150 changes: 150 additions & 0 deletions packages/ui/src/platform.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.fn<(size: Size) => void>>;
interrupt: ReturnType<typeof vi.fn<() => 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('');
}
}
29 changes: 29 additions & 0 deletions packages/ui/src/platform.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
/** Deliver host events to `events` until `signal` aborts. */
listen(events: PlatformEvents, signal: AbortSignal): void;
}
46 changes: 46 additions & 0 deletions packages/ui/src/platform/node.ts
Original file line number Diff line number Diff line change
@@ -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<void>();
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 },
);
},
};
}
27 changes: 27 additions & 0 deletions packages/ui/src/platform/xterm.ts
Original file line number Diff line number Diff line change
@@ -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<void>();
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 });
},
};
}
2 changes: 1 addition & 1 deletion packages/ui/src/ui.lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
Loading
Loading