terminal 0.0.1-preview.1
Colors, layout, a spinner and prompts for command-line programs
zena-lang:terminal#
Output and questions for command-line programs written in Zena. A
command's output hangs off a line down the left edge of the terminal: the
line opens with the command's title, each step gets a marker that says how
it went, the output of other programs is indented under the step that ran
them, and the line closes with a summary. A spinner shows work in
progress, boxed notes call out what to do next, and prompts ask questions
that the user answers with the keyboard. Zebra and zena print with it.
┌ zena pkg add
│
◇ Resolved zena-lang:wit-parser 0.0.1-preview.1
│
▲ zena-lang:markdown has no stable release: using 0.0.1-preview.1
│
◇ Fetched 2 packages in 120ms
│ zena-lang:wit-parser 0.0.1-preview.1
│ zena-lang:markdown 0.0.1-preview.1
│
◇ Next ────────────────────────────────────────╮
│ │
│ import {parse} from 'zena-lang:wit-parser'; │
│ │
├───────────────────────────────────────────────╯
│
└ Added 2 packages
In a terminal the line and the box are gray, each marker has its own color
(◇ green, ◆ cyan, ▲ yellow, ■ red), and the text after a step's
message is dimmed. examples/layout.zena prints the output above:
zena run packages/terminal/examples/layout.zena.
import {RailLayout, StepKind} from 'terminal/layout';
let rail = new RailLayout();
console.log(rail.intro('zena pkg add'));
console.log(rail.bar());
console.log(rail.step(StepKind.Success, 'Resolved zena-lang:wit-parser', '0.0.1-preview.1'));
console.log(rail.bar());
console.log(rail.outro('Added 2 packages'));
A prompt asks on the same line. While it waits, it shows the choices, with the one under the cursor filled in:
│
◆ What kind of package is it?
│ ○ Library
│ ● Command (run with zena run)
│ ○ Both
└
Once answered, it leaves the question and the answer:
│
◇ What kind of package is it?
│ Command
import {Choice, Prompts} from 'terminal/prompts';
export async function main(): Future<i32> {
let prompts = new Prompts();
if (!prompts.interactive) {
console.error('There is no terminal to ask in: pass --kind.');
return 1;
}
let kind = await prompts.select<String>('What kind of package is it?', [
new Choice<String>('library', 'Library'),
new Choice<String>('command', 'Command', 'run with zena run'),
new Choice<String>('both', 'Both'),
]);
return 0;
}
examples/prompts.zena asks one question of each kind:
zena run packages/terminal/examples/prompts.zena.
Libraries#
terminal/layout—RailLayout: the line down the left (┌,│,└), steps with their markers (◇done,◆active,○idle,▲warning,■failed), indented blocks of another program's output, and boxed notes.terminal/animation—Spinner: a spinner (◒,◐,◓,◑) on the last line of the terminal, with lines printed above it.terminal/output—Output: prints a command's progress with the layout and the spinner. Steps and the summary go to stdout; warnings and failures go to stderr, in their place on the line, so that a program reading stdout gets the progress alone.waitForshows the spinner until a future completes, andrunturns an exception into a failure.terminal/prompts—Prompts:text,password,confirm,selectandmultiselect.terminal/keys— the keys pressed in the terminal (TerminalKeys), and keys given in advance for testing prompts (ScriptedKeys).terminal/colors— theColorspalette, whether to use color (shouldUseColor), andvisibleLength, the columns a string takes once its escape sequences are left out, for lining up colored text.
Prompts#
The arrow keys move the cursor in a list (and so do h, j, k and l),
space ticks a choice in a multiselect, y and n answer a confirm,
and Enter answers. Escape and Ctrl+C cancel a prompt, which then throws
PromptCancelled.
A prompt needs a terminal on stdin and on stdout. Where there is none,
such as in CI or when input is piped, Prompts.interactive is false and a
prompt throws PromptUnavailable. So a command checks interactive
before it asks, and takes the answer from a flag instead.
While a prompt asks, the terminal sends each key as it is pressed and
does not echo it. Between prompts it behaves as usual. The prompts run on
the zena-component target, under zena run, zena-run or another host
built on zena-runtime, which puts the terminal back however the program
ends.
Color and animation#
Color is on when stdout is a terminal, and off when it is a pipe or a
file, so output saved to a file has no escape sequences in it. Three
environment variables change that, as they do for many command-line
programs, and the first of them that is set decides: NO_COLOR turns
color off, FORCE_COLOR turns it on (and FORCE_COLOR=0 off), and
TERM=dumb, set for a terminal that cannot show color, turns it off.
The spinner draws only in a terminal, and not when CI is set or TERM
is dumb. Elsewhere it draws nothing, and the lines printed through it
(writeLine) are printed as they come.
Every function that makes one of these choices takes it as a parameter, with the environment's answer as the default, so tests can pass it.
Acknowledgements#
The layout, its markers, the spinner and the prompts follow Clack, a JavaScript library for command-line programs.
License#
MIT
/**
* Terminal color and ANSI escape utilities.
*
* Detects whether `stdout` / `stderr` are attached to a terminal via
* `wasi:cli/terminal-stdout` and `wasi:cli/terminal-stderr`, honors
* `NO_COLOR`, `FORCE_COLOR`, and `TERM=dumb`, and provides composable
* SGR styling methods (`Colors`), ANSI stripping (`stripAnsi`), and
* visible column measurement (`visibleLength`).
*/
import {getEnv} from 'zena:cli';
import {Disposable, Some, StringBuilder} from 'zena:core';
import {TerminalInput} from 'wasi:cli/terminal-input';
import {TerminalOutput} from 'wasi:cli/terminal-output';
import {getTerminalStderr} from 'wasi:cli/terminal-stderr';
import {getTerminalStdin} from 'wasi:cli/terminal-stdin';
import {getTerminalStdout} from 'wasi:cli/terminal-stdout';
function makeEsc() {
let sb = new StringBuilder(1);
sb.appendByte(27);
return sb.toString();
}
/** The ASCII escape character (`0x1b`). */
export let ESC = makeEsc();
/** Formats an ANSI SGR sequence (`ESC [ <code> m`). */
export function sgr(code: String): String {
return `${ESC}[${code}m`;
}
/** Whether standard input is connected to an interactive terminal. */
export function isTerminalStdin(): boolean {
let term = getTerminalStdin();
if (term is Some<TerminalInput>) {
term.value.[Disposable.dispose]();
return true;
}
return false;
}
/** Whether standard output is connected to an interactive terminal. */
export function isTerminalStdout(): boolean {
let term = getTerminalStdout();
if (term is Some<TerminalOutput>) {
term.value.[Disposable.dispose]();
return true;
}
return false;
}
/** Whether standard error is connected to an interactive terminal. */
export function isTerminalStderr(): boolean {
let term = getTerminalStderr();
if (term is Some<TerminalOutput>) {
term.value.[Disposable.dispose]();
return true;
}
return false;
}
/**
* Decides whether ANSI colors should be emitted given `isTty` and an
* environment lookup function (`NO_COLOR`, `FORCE_COLOR`, `TERM`).
*/
export function shouldUseColor(
isTty: boolean = isTerminalStdout(),
env: (name: String) => String? = getEnv,
): boolean {
let noColor = env('NO_COLOR');
if (noColor != null && noColor != '') {
return false;
}
let forceColor = env('FORCE_COLOR');
if (forceColor != null && forceColor != '') {
return forceColor != '0' && forceColor != 'false';
}
if (env('TERM') == 'dumb') {
return false;
}
return isTty;
}
/**
* Composable SGR color and text style helpers. Each helper closes only
* its own attribute (`39` for foreground, `49` for background, `22` for
* intensity) so nested calls like `c.bgCyan(c.black(' zebra '))` preserve
* outer styles. When `enabled` is false, all methods return `text`
* unchanged.
*/
export class Colors {
enabled: boolean;
new(this.enabled = shouldUseColor());
/** A palette that always emits ANSI SGR sequences. */
static ansi(): Colors {
return new Colors(true);
}
/** A palette that never emits ANSI SGR sequences. */
static plain(): Colors {
return new Colors(false);
}
#wrap(open: String, close: String, text: String): String {
if (!this.enabled || text == '') {
return text;
}
return `${ESC}[${open}m${text}${ESC}[${close}m`;
}
reset(text: String): String {
return this.#wrap('0', '0', text);
}
bold(text: String): String {
return this.#wrap('1', '22', text);
}
dim(text: String): String {
return this.#wrap('2', '22', text);
}
italic(text: String): String {
return this.#wrap('3', '23', text);
}
underline(text: String): String {
return this.#wrap('4', '24', text);
}
inverse(text: String): String {
return this.#wrap('7', '27', text);
}
strikethrough(text: String): String {
return this.#wrap('9', '29', text);
}
black(text: String): String {
return this.#wrap('30', '39', text);
}
red(text: String): String {
return this.#wrap('31', '39', text);
}
green(text: String): String {
return this.#wrap('32', '39', text);
}
yellow(text: String): String {
return this.#wrap('33', '39', text);
}
blue(text: String): String {
return this.#wrap('34', '39', text);
}
magenta(text: String): String {
return this.#wrap('35', '39', text);
}
cyan(text: String): String {
return this.#wrap('36', '39', text);
}
white(text: String): String {
return this.#wrap('37', '39', text);
}
gray(text: String): String {
return this.#wrap('90', '39', text);
}
bgBlack(text: String): String {
return this.#wrap('40', '49', text);
}
bgRed(text: String): String {
return this.#wrap('41', '49', text);
}
bgGreen(text: String): String {
return this.#wrap('42', '49', text);
}
bgYellow(text: String): String {
return this.#wrap('43', '49', text);
}
bgBlue(text: String): String {
return this.#wrap('44', '49', text);
}
bgMagenta(text: String): String {
return this.#wrap('45', '49', text);
}
bgCyan(text: String): String {
return this.#wrap('46', '49', text);
}
bgWhite(text: String): String {
return this.#wrap('47', '49', text);
}
}
/**
* Returns the index just past the CSI escape sequence starting at
* `start` (`ESC [`), or `start + 1` if `start` is a bare `ESC`.
*/
function skipEscapeAt(text: String, start: i32) {
if (start + 1 >= text.length || text.getByteAt(start + 1) != 91) {
return start + 1;
}
var i = start + 2;
while (i < text.length) {
let b = text.getByteAt(i);
i += 1;
// Final byte of a CSI sequence is in 0x40..=0x7E ('@'..'~').
if (b >= 64 && b <= 126) {
break;
}
}
return i;
}
/** Returns `text` with all ANSI CSI escape sequences removed. */
export function stripAnsi(text: String): String {
var hasEsc = false;
for (var i = 0; i < text.length; i += 1) {
if (text.getByteAt(i) == 27) {
hasEsc = true;
break;
}
}
if (!hasEsc) {
return text;
}
let sb = new StringBuilder(text.length);
var i = 0;
while (i < text.length) {
let b = text.getByteAt(i);
if (b == 27) {
i = skipEscapeAt(text, i);
} else {
sb.appendByte(b);
i += 1;
}
}
return sb.toString();
}
/**
* Visible character count of `text`: skips ANSI CSI sequences and
* counts UTF-8 code points (so multi-byte box-drawing glyphs like `│`
* and `◇` each count as 1 column).
*/
export function visibleLength(text: String): i32 {
var cols = 0;
var i = 0;
while (i < text.length) {
let b = text.getByteAt(i);
if (b == 27) {
i = skipEscapeAt(text, i);
} else {
// Count UTF-8 leading bytes (not continuation bytes 10xxxxxx).
if ((b & 192) != 128) {
cols += 1;
}
i += 1;
}
}
return cols;
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 | none |
|