Skip to content

Commit 653d87a

Browse files
committed
spike: platform bindings for node and xterm
1 parent 5c6d3d4 commit 653d87a

12 files changed

Lines changed: 330 additions & 30 deletions

File tree

‎.changeset/ui-platform.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
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.
6+
7+
In the browser, pass an xterm.js terminal as `output`:
8+
9+
```js
10+
const ui = await createUI({ output: terminal, signal });
11+
```

‎packages/ui/bench/helpers.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* oxlint-disable bombshell-dev/exported-function-async */
22
import { PassThrough, Writable } from 'node:stream';
33
import type { Document, Element, Text } from '../src/dom.ts';
4-
import { createUI, type UI } from '../src/ui.ts';
4+
import { createUI, type UI } from '../src/index.ts';
55

66
/** Wait until an asynchronous render callback has completed. */
77
export async function waitFor(predicate: () => boolean): Promise<void> {
@@ -95,7 +95,9 @@ export async function setupUI(
9595
});
9696
},
9797
});
98-
const ui = await createUI({ input, output, width: 80, height: 24 });
98+
const controller = new AbortController();
99+
const ui = await createUI({ input, output, width: 80, height: 24, signal: controller.signal });
100+
let running: Promise<void> | undefined;
99101
const { texts } = createTree({ document: ui.document, nodeCount, shape });
100102
const initialWrites = writes;
101103
let started = false;
@@ -110,11 +112,12 @@ export async function setupUI(
110112
async start() {
111113
if (started) return;
112114
started = true;
113-
void ui.main();
115+
running = ui.main();
114116
await waitFor(() => writes > initialWrites);
115117
},
116118
async close() {
117-
await ui[Symbol.asyncDispose]();
119+
controller.abort();
120+
await running;
118121
input.destroy();
119122
output.destroy();
120123
},

‎packages/ui/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
"type": "module",
2020
"exports": {
2121
".": {
22+
"browser": {
23+
"types": "./dist/index.browser.d.mts",
24+
"default": "./dist/index.browser.mjs"
25+
},
2226
"types": "./dist/index.d.mts",
2327
"import": "./dist/index.mjs"
2428
},

‎packages/ui/src/index.browser.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { createXtermPlatform, type XtermTerminal } from './platform/xterm.ts';
2+
import { startUI, type UI } from './ui.ts';
3+
4+
export type { UI } from './ui.ts';
5+
6+
export interface UIOptions {
7+
/** The xterm.js terminal to render into. Browsers have no default terminal. */
8+
output: XtermTerminal;
9+
signal?: AbortSignal;
10+
}
11+
12+
/** Create a UI on an xterm.js terminal. */
13+
export async function createUI(options: UIOptions): Promise<UI> {
14+
return startUI(createXtermPlatform(options.output), options.signal);
15+
}

‎packages/ui/src/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,9 @@
1-
export { createUI } from './ui.ts';
1+
import { createNodePlatform } from './platform/node.ts';
2+
import { startUI, type UI, type UIOptions } from './ui.ts';
3+
4+
export type { UI, UIOptions } from './ui.ts';
5+
6+
/** Create a UI on this process's terminal. */
7+
export async function createUI(options: UIOptions = {}): Promise<UI> {
8+
return startUI(createNodePlatform(options), options.signal);
9+
}

‎packages/ui/src/platform.test.ts‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import process from 'node:process';
2+
import { Writable } from 'node:stream';
3+
import { describe, expect, test, vi } from 'vitest';
4+
import { createUI as createBrowserUI } from './index.browser.ts';
5+
import { createUI } from './index.ts';
6+
import { createNodePlatform } from './platform/node.ts';
7+
import { createXtermPlatform, type XtermTerminal } from './platform/xterm.ts';
8+
import type { Size } from './platform.ts';
9+
10+
describe('node platform', () => {
11+
test('reports the TTY size and follows resizes until aborted', () => {
12+
const output = tty(100, 30);
13+
const platform = createNodePlatform({ output, signal: AbortSignal.abort() });
14+
const events = createEvents();
15+
const controller = new AbortController();
16+
17+
platform.listen(events, controller.signal);
18+
expect(platform.size()).toEqual({ width: 100, height: 30 });
19+
20+
output.columns = 120;
21+
output.emit('resize');
22+
expect(events.resize).toHaveBeenLastCalledWith({ width: 120, height: 30 });
23+
24+
controller.abort();
25+
output.emit('resize');
26+
expect(events.resize).toHaveBeenCalledTimes(1);
27+
});
28+
29+
test('prefers explicit width and height over the TTY size', () => {
30+
const platform = createNodePlatform({ output: tty(100, 30), width: 40, height: 10 });
31+
expect(platform.size()).toEqual({ width: 40, height: 10 });
32+
});
33+
34+
test('falls back to 80×24 when output is not a TTY', () => {
35+
const platform = createNodePlatform({ output: sink() });
36+
expect(platform.size()).toEqual({ width: 80, height: 24 });
37+
});
38+
39+
test('interrupts on SIGINT only when the caller passed no signal', () => {
40+
const before = process.listenerCount('SIGINT');
41+
const controller = new AbortController();
42+
43+
createNodePlatform({ signal: controller.signal }).listen(createEvents(), controller.signal);
44+
expect(process.listenerCount('SIGINT')).toBe(before);
45+
46+
const events = createEvents();
47+
createNodePlatform({}).listen(events, controller.signal);
48+
process.emit('SIGINT', 'SIGINT');
49+
expect(events.interrupt).toHaveBeenCalledTimes(1);
50+
51+
controller.abort();
52+
expect(process.listenerCount('SIGINT')).toBe(before);
53+
});
54+
55+
test('createUI() without a signal stops on SIGINT', async () => {
56+
const ui = await createUI({ output: tty(10, 1) });
57+
const running = ui.main();
58+
await new Promise((resolve) => setImmediate(resolve));
59+
60+
process.emit('SIGINT', 'SIGINT');
61+
await running;
62+
expect(ui.main()).toBe(running);
63+
});
64+
});
65+
66+
describe('xterm platform', () => {
67+
test('writes bytes and follows resizes until aborted', async () => {
68+
const terminal = new FakeXterm(80, 24);
69+
const platform = createXtermPlatform(terminal);
70+
const events = createEvents();
71+
const controller = new AbortController();
72+
73+
platform.listen(events, controller.signal);
74+
await platform.write(new Uint8Array([104, 105]));
75+
expect(terminal.written).toEqual([new Uint8Array([104, 105])]);
76+
77+
terminal.resize(100, 40);
78+
expect(events.resize).toHaveBeenLastCalledWith({ width: 100, height: 40 });
79+
expect(platform.size()).toEqual({ width: 100, height: 40 });
80+
81+
controller.abort();
82+
terminal.resize(10, 10);
83+
expect(events.resize).toHaveBeenCalledTimes(1);
84+
});
85+
86+
test('the browser createUI() renders into the terminal until aborted', async () => {
87+
const terminal = new FakeXterm(20, 2);
88+
const controller = new AbortController();
89+
const ui = await createBrowserUI({ output: terminal, signal: controller.signal });
90+
const running = ui.main();
91+
92+
ui.document.documentElement.appendChild(ui.document.createTextNode('hello'));
93+
await vi.waitFor(() => expect(terminal.text()).toContain('hello'));
94+
95+
terminal.resize(30, 3);
96+
const frames = terminal.written.length;
97+
await vi.waitFor(() => expect(terminal.written.length).toBeGreaterThan(frames));
98+
99+
controller.abort();
100+
await running;
101+
expect(terminal.listeners.size).toBe(0);
102+
});
103+
});
104+
105+
function createEvents(): {
106+
resize: ReturnType<typeof vi.fn<(size: Size) => void>>;
107+
interrupt: ReturnType<typeof vi.fn<() => void>>;
108+
} {
109+
return { resize: vi.fn<(size: Size) => void>(), interrupt: vi.fn<() => void>() };
110+
}
111+
112+
function sink(): Writable {
113+
return new Writable({ write: (_chunk, _encoding, done) => done() });
114+
}
115+
116+
function tty(columns: number, rows: number): Writable & { columns: number; rows: number } {
117+
return Object.assign(sink(), { columns, rows });
118+
}
119+
120+
class FakeXterm implements XtermTerminal {
121+
cols: number;
122+
rows: number;
123+
written: Uint8Array[] = [];
124+
listeners = new Set<(size: { cols: number; rows: number }) => void>();
125+
126+
constructor(cols: number, rows: number) {
127+
this.cols = cols;
128+
this.rows = rows;
129+
}
130+
131+
write(data: Uint8Array, callback?: () => void): void {
132+
this.written.push(data);
133+
queueMicrotask(() => callback?.());
134+
}
135+
136+
onResize(listener: (size: { cols: number; rows: number }) => void): { dispose(): void } {
137+
this.listeners.add(listener);
138+
return { dispose: () => this.listeners.delete(listener) };
139+
}
140+
141+
resize(cols: number, rows: number): void {
142+
this.cols = cols;
143+
this.rows = rows;
144+
for (const listener of this.listeners) listener({ cols, rows });
145+
}
146+
147+
text(): string {
148+
return this.written.map((bytes) => new TextDecoder().decode(bytes)).join('');
149+
}
150+
}

‎packages/ui/src/platform.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/** Terminal dimensions in cells. */
2+
export interface Size {
3+
width: number;
4+
height: number;
5+
}
6+
7+
/** Host events a UI reacts to while it runs. */
8+
export interface PlatformEvents {
9+
/** The terminal changed size. */
10+
resize(size: Size): void;
11+
/** The host asked the program to stop, such as SIGINT. */
12+
interrupt(): void;
13+
}
14+
15+
/**
16+
* Everything a UI needs from its host that isn't portable JavaScript.
17+
*
18+
* Bindings for each host live in one place so the rest of the UI stays
19+
* runtime-agnostic. Each package entry point picks the binding for its runtime
20+
* through export conditions and builds it from `createUI()` options.
21+
*/
22+
export interface Platform {
23+
/** Current terminal size. */
24+
size(): Size;
25+
/** Write bytes to the terminal; resolves once the host has accepted them. */
26+
write(bytes: Uint8Array): Promise<void>;
27+
/** Deliver host events to `events` until `signal` aborts. */
28+
listen(events: PlatformEvents, signal: AbortSignal): void;
29+
}

‎packages/ui/src/platform/node.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import process from 'node:process';
2+
import type { Platform, Size } from '../platform.ts';
3+
import type { UIOptions } from '../ui.ts';
4+
5+
/** Signals that stop a UI when the caller didn't pass its own `signal`. */
6+
const interrupts: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM'];
7+
8+
/** Bind a UI to a Node-compatible process: Node, Bun, or Deno. */
9+
export function createNodePlatform(options: UIOptions): Platform {
10+
const output: UIOptions['output'] & { columns?: number; rows?: number } =
11+
options.output ?? process.stdout;
12+
const signals = options.signal ? [] : interrupts;
13+
14+
const size = (): Size => ({
15+
width: options.width ?? output.columns ?? 80,
16+
height: options.height ?? output.rows ?? 24,
17+
});
18+
19+
return {
20+
size,
21+
write(bytes) {
22+
const result = Promise.withResolvers<void>();
23+
output.write(bytes, (error) => (error ? result.reject(error) : result.resolve()));
24+
return result.promise;
25+
},
26+
listen(events, signal) {
27+
const resize = (): void => events.resize(size());
28+
const interrupt = (): void => events.interrupt();
29+
30+
output.on('resize', resize);
31+
for (const name of signals) process.on(name, interrupt);
32+
// Signal listeners don't keep Node's event loop alive; the UI should until it stops.
33+
const alive = setInterval(() => {}, 2 ** 30);
34+
35+
signal.addEventListener(
36+
'abort',
37+
() => {
38+
clearInterval(alive);
39+
output.off('resize', resize);
40+
for (const name of signals) process.off(name, interrupt);
41+
},
42+
{ once: true },
43+
);
44+
},
45+
};
46+
}

‎packages/ui/src/platform/xterm.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { Platform } from '../platform.ts';
2+
3+
/** The slice of xterm.js's `Terminal` this binding uses. */
4+
export interface XtermTerminal {
5+
readonly cols: number;
6+
readonly rows: number;
7+
write(data: Uint8Array, callback?: () => void): void;
8+
onResize(listener: (size: { cols: number; rows: number }) => void): { dispose(): void };
9+
}
10+
11+
/** Bind a UI to an xterm.js terminal. Browsers have no process signals to interrupt it. */
12+
export function createXtermPlatform(terminal: XtermTerminal): Platform {
13+
return {
14+
size: () => ({ width: terminal.cols, height: terminal.rows }),
15+
write(bytes) {
16+
const result = Promise.withResolvers<void>();
17+
terminal.write(bytes, () => result.resolve());
18+
return result.promise;
19+
},
20+
listen(events, signal) {
21+
const subscription = terminal.onResize(({ cols, rows }) =>
22+
events.resize({ width: cols, height: rows }),
23+
);
24+
signal.addEventListener('abort', () => subscription.dispose(), { once: true });
25+
},
26+
};
27+
}

‎packages/ui/src/ui.lifecycle.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { once } from 'node:events';
22
import { PassThrough, Writable } from 'node:stream';
33
import { alternateBuffer, cursor, settings } from '@bomb.sh/tty';
44
import { describe, expect, test, vi } from 'vitest';
5-
import { createUI } from './ui.ts';
5+
import { createUI } from './index.ts';
66

77
const terminalSettings = settings(cursor(false), alternateBuffer());
88
const apply = Buffer.from(terminalSettings.apply).toString('utf8');

0 commit comments

Comments
 (0)