terminal 0.0.1-preview.1

Colors, layout, a spinner and prompts for command-line programs

Readme Files Dependencies Versions

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. waitFor shows the spinner until a future completes, and run turns an exception into a failure.
  • terminal/prompts — Prompts: text, password, confirm, select and multiselect.
  • terminal/keys — the keys pressed in the terminal (TerminalKeys), and keys given in advance for testing prompts (ScriptedKeys).
  • terminal/colors — the Colors palette, whether to use color (shouldUseColor), and visibleLength, 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

6.5 KiB Raw
/**
 * Terminal rail, step, log block, and box layout utilities.
 *
 * Structures command-line output along a left-hand guide rail (`┌`, `│`,
 * `└`) with geometric status markers (`◇`, `◆`, `○`, `▲`, `■`), indented
 * log blocks for captured command output, and boxed notes.
 */

import {StringBuilder} from 'zena:core';
import {div} from 'zena:math';
import {Colors, visibleLength} from './colors.zena';

/** Top cap of a vertical rail (`┌`). */
export let BAR_START = '┌';

/** Vertical rail segment (`│`). */
export let BAR = '│';

/** Bottom cap of a vertical rail (`└`). */
export let BAR_END = '└';

/** Horizontal box line (`─`). */
export let BAR_H = '─';

/** Top-right rounded box corner (`╮`). */
export let CORNER_TOP_RIGHT = '╮';

/** Bottom-right rounded box corner (`╯`). */
export let CORNER_BOTTOM_RIGHT = '╯';

/** Left T-junction on the rail (`├`). */
export let CONNECT_LEFT = '├';

/** Completed / succeeded step marker (`◇`). */
export let STEP_SUBMIT = '◇';

/** Active / restored / running service step marker (`◆`). */
export let STEP_ACTIVE = '◆';

/** Idle / fresh step marker (`○`). */
export let STEP_IDLE = '○';

/** Warning / skipped step marker (`▲`). */
export let STEP_WARN = '▲';

/** Canceled / failed step marker (`■`). */
export let STEP_CANCEL = '■';

/** Semantic status kind for a step on the rail. */
export enum StepKind {
  Success,
  Active,
  Fresh,
  Warning,
  Error,
}

/** Repeats `unit` `count` times. */
export function repeatString(unit: String, count: i32): String {
  if (count <= 0 || unit == '') {
    return '';
  }
  let sb = new StringBuilder(unit.length * count);
  for (var i = 0; i < count; i += 1) {
    sb.append(unit);
  }
  return sb.toString();
}

/** Pads `text` on the right with spaces to `width` visible columns. */
export function padVisibleRight(text: String, width: i32): String {
  let len = visibleLength(text);
  if (len >= width) {
    return text;
  }
  return text + repeatString(' ', width - len);
}

/**
 * Formats a duration in milliseconds: `42ms` under a second, or `1.4s`
 * at one second and above.
 */
export function formatDuration(ms: i64): String {
  let clamped = if (ms < (0 as i64)) 0 as i64 else ms;
  if (clamped < (1000 as i64)) {
    return `${i64ToString(clamped)}ms`;
  }
  let secs = div(clamped, 1000 as i64);
  let tenths = div(clamped % (1000 as i64), 100 as i64);
  return `${i64ToString(secs)}.${i64ToString(tenths)}s`;
}

/** Splits `text` into display lines, trimming one trailing `\n` and `\r`s. */
export function splitLines(text: String): Array<String> {
  if (text == '') {
    return [];
  }
  let trimmed = if (text.endsWith('\n'))
    text.sliceBytes(0, text.length - 1)
  else
    text;
  let raw = trimmed.split('\n');
  let lines = new GrowableArray<String>();
  for (let line in raw) {
    lines.push(
      if (line.endsWith('\r')) line.sliceBytes(0, line.length - 1) else line,
    );
  }
  return lines;
}

/** Formatter for rail layouts parameterized by a `Colors` palette. */
export class RailLayout {
  colors: Colors;

  new(this.colors = new Colors());

  /**
   * Formats a pill badge (` bgCyan(black(" label ")) ` when color is
   * enabled, or `[label]` in plain text).
   */
  badge(label: String): String {
    if (this.colors.enabled) {
      return this.colors.bgCyan(this.colors.black(` ${label} `));
    }
    return `[${label}]`;
  }

  /** Formats the opening rail line (`┌  <title>`). */
  intro(title: String): String {
    return `${this.colors.gray(BAR_START)}  ${title}`;
  }

  /** Formats a bare vertical guide line (`│`). */
  bar(): String {
    return this.colors.gray(BAR);
  }

  /** Formats a line indented along the rail (`│  <text>`). */
  barLine(text: String): String {
    return `${this.colors.gray(BAR)}  ${text}`;
  }

  /** Returns the styled symbol for `kind`. */
  symbolFor(kind: StepKind): String {
    if (kind == StepKind.Success) {
      return this.colors.green(STEP_SUBMIT);
    }
    if (kind == StepKind.Active) {
      return this.colors.cyan(STEP_ACTIVE);
    }
    if (kind == StepKind.Fresh) {
      return this.colors.dim(STEP_IDLE);
    }
    if (kind == StepKind.Warning) {
      return this.colors.yellow(STEP_WARN);
    }
    return this.colors.red(STEP_CANCEL);
  }

  /**
   * Formats a step line on the rail (`<symbol>  <message>` with an
   * optional dimmed `detail` suffix).
   */
  step(kind: StepKind, message: String, detail: String = ''): String {
    let sym = this.symbolFor(kind);
    if (detail == '') {
      return `${sym}  ${message}`;
    }
    return `${sym}  ${message} ${this.colors.dim(detail)}`;
  }

  /**
   * Formats multi-line command output as rail-indented lines (`│  ...`).
   * Uses a red guide bar when `isError` is true.
   */
  logBlock(text: String, isError: boolean = false): Array<String> {
    let lines = splitLines(text);
    let out = new GrowableArray<String>();
    let rail = if (isError) this.colors.red(BAR) else this.colors.gray(BAR);
    for (let line in lines) {
      if (line == '') {
        out.push(rail);
      } else {
        out.push(`${rail}  ${line}`);
      }
    }
    return out;
  }

  /**
   * Formats a boxed note attached to the rail (`├`, `╮`, `╯`).
   */
  note(body: String, title: String = ''): String {
    let lines = splitLines(body);
    var maxLen = visibleLength(title);
    for (let line in lines) {
      let len = visibleLength(line);
      if (len > maxLen) {
        maxLen = len;
      }
    }
    let innerWidth = maxLen + 2;
    let c = this.colors;
    let sb = new StringBuilder();
    if (title != '') {
      let titleLen = visibleLength(title);
      let topBars = if (innerWidth - titleLen - 1 > 1)
        innerWidth - titleLen - 1
      else
        1;
      sb.append(
        `${c.gray(STEP_SUBMIT)}  ${title} ${c.gray(repeatString(BAR_H, topBars) + CORNER_TOP_RIGHT)}\n`,
      );
    } else {
      sb.append(
        `${c.gray(CONNECT_LEFT + repeatString(BAR_H, innerWidth + 2) + CORNER_TOP_RIGHT)}\n`,
      );
    }
    sb.append(
      `${c.gray(BAR)}  ${repeatString(' ', innerWidth)}${c.gray(BAR)}\n`,
    );
    for (let line in lines) {
      sb.append(
        `${c.gray(BAR)}  ${padVisibleRight(line, innerWidth)}${c.gray(BAR)}\n`,
      );
    }
    sb.append(
      `${c.gray(BAR)}  ${repeatString(' ', innerWidth)}${c.gray(BAR)}\n`,
    );
    sb.append(
      `${c.gray(CONNECT_LEFT + repeatString(BAR_H, innerWidth + 2) + CORNER_BOTTOM_RIGHT)}`,
    );
    return sb.toString();
  }

  /** Formats the closing rail line (`└  <message>`). */
  outro(message: String): String {
    return `${this.colors.gray(BAR_END)}  ${message}`;
  }
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none