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
/**
* Prompts: questions on the rail that the user answers with the
* keyboard.
*
* `Prompts` asks with `text`, `password`, `confirm`, `select` and
* `multiselect`. Each is drawn on the rail and drawn again after
* every key, and the answer stays on the rail once it is given. 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,
* `Prompts.interactive` is false and a prompt throws `PromptUnavailable`,
* so a command checks `interactive` before it asks, and says which flag
* answers the question instead.
*/
import {Future} from 'zena:async';
import {getEnv} from 'zena:cli';
import {logString} from 'zena:console';
import {Some, join} from 'zena:core';
import {Size, stdoutSize} from 'zena:host/terminal';
import {div} from 'zena:math';
import {CURSOR_HIDE, CURSOR_SHOW} from './animation.zena';
import {Colors, ESC, isTerminalStdin, isTerminalStdout, visibleLength} from './colors.zena';
import {BAR, BAR_END, STEP_ACTIVE, STEP_CANCEL, STEP_SUBMIT, STEP_WARN, repeatString} from './layout.zena';
import {Key, KeyInput, KeyKind, TerminalKeys} from './keys.zena';
/** A filled radio button (`●`): the answer a `confirm` or `select` is on. */
export let RADIO_ACTIVE = '●';
/** An empty radio button (`○`). */
export let RADIO_INACTIVE = '○';
/** An unticked box (`◻`). */
export let CHECKBOX_INACTIVE = '◻';
/** A ticked box (`◼`). */
export let CHECKBOX_SELECTED = '◼';
/** What a password prompt shows for each character (`▪`). */
export let PASSWORD_MASK = '▪';
/** Thrown by a prompt its user cancelled with Escape or Ctrl+C. */
export class PromptCancelled extends Error {
new() : super('The prompt was cancelled');
}
/** Thrown by a prompt that has no terminal to ask in. */
export class PromptUnavailable extends Error {
new(message: String) : super(message);
}
/** Where a prompt is: being answered, showing why an answer was refused, answered, or cancelled. */
export enum PromptState {
Active,
Error,
Submit,
Cancel,
}
/** One of the answers a `select` or `multiselect` offers. */
export class Choice<T> {
value: T;
label: String;
/** Shown dimmed beside the label while the cursor is on it. */
hint: String;
new(this.value, this.label, this.hint = '');
}
/** A terminal's size, in character cells. */
export type TerminalSize = {columns: i32, rows: i32};
/** The size of stdout's terminal, or 80 by 24 when it has none. */
export function terminalSize(): TerminalSize {
let size = stdoutSize();
if (size is Some<Size>) {
return {columns: size.value.columns as i32, rows: size.value.rows as i32};
}
return {columns: 80, rows: 24};
}
/**
* Whether a prompt can ask: stdin and stdout are both terminals, and
* `TERM` is not `dumb`.
*/
export function canPrompt(
stdinIsTty: boolean = isTerminalStdin(),
stdoutIsTty: boolean = isTerminalStdout(),
env: (name: String) => String? = getEnv,
): boolean {
return stdinIsTty && stdoutIsTty && env('TERM') != 'dumb';
}
/**
* The rows a terminal `columns` wide gives `frame` above the row the
* cursor ends on, once it is written from the start of a row: each line
* takes the rows its text wraps onto, and the cursor is on the last
* line's last row.
*/
export function rowsAbove(frame: String, columns: i32): i32 {
let lines = frame.split('\n');
let width = if (columns > 0) columns else 80;
var rows = 0;
for (var i = 0; i < lines.length; i += 1) {
let length = visibleLength(lines[i]);
let taken = if (length == 0) 1 else div(length + width - 1, width);
rows += if (i == lines.length - 1) taken - 1 else taken;
}
return rows;
}
/** A validation that accepts every answer. */
function anything(value: String): String? {
return null;
}
/** The marker a prompt in `state` has on the rail. */
function symbolFor(colors: Colors, state: PromptState) {
if (state == PromptState.Submit) {
return colors.green(STEP_SUBMIT);
}
if (state == PromptState.Cancel) {
return colors.red(STEP_CANCEL);
}
if (state == PromptState.Error) {
return colors.yellow(STEP_WARN);
}
return colors.cyan(STEP_ACTIVE);
}
/** The rail and the question above a prompt's answer. */
function titleOf(colors: Colors, state: PromptState, message: String) {
return `${colors.gray(BAR)}\n${symbolFor(colors, state)} ${message}`;
}
/** Whether `key` moves a list's cursor back: Up, Left, `k` or `h`. */
function isBack(key: Key) {
return key.kind == KeyKind.Up || key.kind == KeyKind.Left ||
(key.kind == KeyKind.Text && (key.text == 'k' || key.text == 'h'));
}
/** Whether `key` moves a list's cursor on: Down, Right, `j` or `l`. */
function isOn(key: Key) {
return key.kind == KeyKind.Down || key.kind == KeyKind.Right ||
(key.kind == KeyKind.Text && (key.text == 'j' || key.text == 'l'));
}
/** What a prompt draws and how it answers keys. */
interface Question {
/** The prompt as it is drawn in `state`. */
render(state: PromptState): String;
/** Answers `key`, returning the state the prompt is in after it. */
key(key: Key): PromptState;
}
/**
* A line of text being typed, with a cursor in it. It is kept as the
* text before the cursor and the text after it, and the cursor moves a
* grapheme at a time.
*/
class TextQuestion implements Question {
#colors: Colors;
#message: String;
#placeholder: String;
#defaultValue: String;
#validate: (value: String) => String?;
/** What each grapheme is shown as, or '' to show the text. */
#mask: String;
var #before: String;
var #after = '';
var #error = '';
new(
colors: Colors,
message: String,
placeholder: String,
initial: String,
defaultValue: String,
validate: (value: String) => String?,
mask: String,
) : #colors = colors,
#message = message,
#placeholder = placeholder,
#defaultValue = defaultValue,
#validate = validate,
#mask = mask,
#before = initial;
/** The text typed. */
value: String {
get {
return this.#before + this.#after;
}
}
key(key: Key): PromptState {
let kind = key.kind;
if (kind == KeyKind.Enter) {
let answer = if (this.value == '') this.#defaultValue else this.value;
let problem = this.#validate(answer);
if (problem != null) {
this.#error = problem;
return PromptState.Error;
}
this.#before = answer;
this.#after = '';
return PromptState.Submit;
}
let before = this.#before;
let after = this.#after;
if (kind == KeyKind.Text) {
this.#before = before + key.text;
} else if (kind == KeyKind.Backspace && before != '') {
this.#before = before.slice(before.startIndex, before.indexBefore(before.endIndex));
} else if (kind == KeyKind.Delete && after != '') {
this.#after = after.slice(after.indexAfter(after.startIndex));
} else if (kind == KeyKind.Left && before != '') {
let at = before.indexBefore(before.endIndex);
this.#before = before.slice(before.startIndex, at);
this.#after = before.slice(at) + after;
} else if (kind == KeyKind.Right && after != '') {
let at = after.indexAfter(after.startIndex);
this.#before = before + after.slice(after.startIndex, at);
this.#after = after.slice(at);
} else if (kind == KeyKind.Home) {
this.#before = '';
this.#after = before + after;
} else if (kind == KeyKind.End) {
this.#before = before + after;
this.#after = '';
}
return PromptState.Active;
}
/** `text` as it is shown: itself, or a mask for each grapheme. */
#shown(text: String): String {
let mask = this.#mask;
if (mask == '') {
return text;
}
var count = 0;
for (let grapheme in text.graphemes) {
count += 1;
}
return repeatString(mask, count);
}
/** The text being typed, with the cursor drawn as an inverted cell. */
#withCursor(): String {
let c = this.#colors;
if (this.value == '') {
let placeholder = this.#placeholder;
if (placeholder == '') {
return c.inverse(' ');
}
let first = placeholder.indexAfter(placeholder.startIndex);
return c.inverse(placeholder.slice(placeholder.startIndex, first)) +
c.dim(placeholder.slice(first));
}
let before = this.#shown(this.#before);
let after = this.#after;
if (after == '') {
return before + c.inverse(' ');
}
let next = after.indexAfter(after.startIndex);
return before + c.inverse(this.#shown(after.slice(after.startIndex, next))) +
this.#shown(after.slice(next));
}
render(state: PromptState): String {
let c = this.#colors;
let title = titleOf(c, state, this.#message);
if (state == PromptState.Submit) {
return `${title}\n${c.gray(BAR)} ${c.dim(this.#shown(this.value))}`;
}
if (state == PromptState.Cancel) {
let shown = this.#shown(this.value);
let line = `${title}\n${c.gray(BAR)} ${c.strikethrough(c.dim(shown))}`;
return if (shown.trim() == '') line else `${line}\n${c.gray(BAR)}`;
}
let input = this.#withCursor();
if (state == PromptState.Error) {
return `${title}\n${c.yellow(BAR)} ${input}\n${c.yellow(BAR_END)} ${c.yellow(this.#error)}\n`;
}
return `${title}\n${c.cyan(BAR)} ${input}\n${c.cyan(BAR_END)}\n`;
}
}
/** Yes or no, with the cursor keys to switch and `y` or `n` to answer at once. */
class ConfirmQuestion implements Question {
#colors: Colors;
#message: String;
#active: String;
#inactive: String;
var #value: boolean;
new(colors: Colors, message: String, initial: boolean, active: String, inactive: String)
: #colors = colors,
#message = message,
#value = initial,
#active = active,
#inactive = inactive;
value: boolean {
get {
return this.#value;
}
}
key(key: Key): PromptState {
if (key.kind == KeyKind.Enter) {
return PromptState.Submit;
}
if (key.kind == KeyKind.Text && (key.text == 'y' || key.text == 'Y')) {
this.#value = true;
return PromptState.Submit;
}
if (key.kind == KeyKind.Text && (key.text == 'n' || key.text == 'N')) {
this.#value = false;
return PromptState.Submit;
}
if (isBack(key) || isOn(key)) {
this.#value = !this.#value;
}
return PromptState.Active;
}
#option(label: String, on: boolean): String {
let c = this.#colors;
return if (on) `${c.green(RADIO_ACTIVE)} ${label}` else `${c.dim(RADIO_INACTIVE)} ${c.dim(label)}`;
}
render(state: PromptState): String {
let c = this.#colors;
let title = titleOf(c, state, this.#message);
let answer = if (this.#value) this.#active else this.#inactive;
if (state == PromptState.Submit) {
return `${title}\n${c.gray(BAR)} ${c.dim(answer)}`;
}
if (state == PromptState.Cancel) {
return `${title}\n${c.gray(BAR)} ${c.strikethrough(c.dim(answer))}\n${c.gray(BAR)}`;
}
let yes = this.#option(this.#active, this.#value);
let no = this.#option(this.#inactive, !this.#value);
return `${title}\n${c.cyan(BAR)} ${yes} ${c.dim('/')} ${no}\n${c.cyan(BAR_END)}\n`;
}
}
/**
* The choices of a list that fit on the screen, around the cursor:
* Clack's `limitOptions`. A list longer than `maxItems`, or than the
* terminal's rows leave room for, shows a window onto it, with `...`
* in place of the first or last choice shown when there are more above
* or below.
*/
function windowOf(cursor: i32, count: i32, maxItems: i32, rows: i32): (i32, i32) {
let fit = if (rows - 4 > 0) rows - 4 else 0;
let wanted = if (maxItems > 0 && maxItems < count) maxItems else count;
let atLeastFive = if (wanted > 5) wanted else 5;
let shown = if (fit < atLeastFive) fit else atLeastFive;
var start = 0;
if (cursor >= shown - 3) {
let last = count - shown;
let wantedStart = cursor - shown + 3;
start = if (wantedStart < last) wantedStart else last;
if (start < 0) {
start = 0;
}
}
return (start, shown);
}
/** The lines `render` draws for the choices `windowOf` shows. */
function listLines(count: i32, cursor: i32, maxItems: i32, rows: i32, colors: Colors,
line: (index: i32, isCursor: boolean) => String): Array<String> {
let (start, shown) = windowOf(cursor, count, maxItems, rows);
let end = if (start + shown < count) start + shown else count;
let lines = new GrowableArray<String>();
for (var i = start; i < end; i += 1) {
let clipped = shown < count &&
((i == start && start > 0) || (i == end - 1 && end < count));
lines.push(if (clipped) colors.dim('...') else line(i, i == cursor));
}
return lines;
}
/** One of a list of choices, picked with the cursor keys. */
class SelectQuestion<T> implements Question {
#colors: Colors;
#message: String;
#choices: Array<Choice<T>>;
#maxItems: i32;
#size: () => TerminalSize;
var #cursor: i32;
new(colors: Colors, message: String, choices: Array<Choice<T>>, initial: i32, maxItems: i32,
size: () => TerminalSize)
: #colors = colors,
#message = message,
#choices = choices,
#cursor = initial,
#maxItems = maxItems,
#size = size;
value: T {
get {
return this.#choices[this.#cursor].value;
}
}
key(key: Key): PromptState {
let count = this.#choices.length;
if (key.kind == KeyKind.Enter) {
return PromptState.Submit;
}
if (isBack(key)) {
this.#cursor = if (this.#cursor == 0) count - 1 else this.#cursor - 1;
} else if (isOn(key)) {
this.#cursor = if (this.#cursor == count - 1) 0 else this.#cursor + 1;
}
return PromptState.Active;
}
#line(index: i32, isCursor: boolean): String {
let c = this.#colors;
let choice = this.#choices[index];
if (!isCursor) {
return `${c.dim(RADIO_INACTIVE)} ${c.dim(choice.label)}`;
}
let hint = if (choice.hint == '') '' else ` ${c.dim(`(${choice.hint})`)}`;
return `${c.green(RADIO_ACTIVE)} ${choice.label}${hint}`;
}
render(state: PromptState): String {
let c = this.#colors;
let title = titleOf(c, state, this.#message);
let label = this.#choices[this.#cursor].label;
if (state == PromptState.Submit) {
return `${title}\n${c.gray(BAR)} ${c.dim(label)}`;
}
if (state == PromptState.Cancel) {
return `${title}\n${c.gray(BAR)} ${c.strikethrough(c.dim(label))}\n${c.gray(BAR)}`;
}
let lines = listLines(this.#choices.length, this.#cursor, this.#maxItems, this.#size().rows,
c, (index, isCursor) => this.#line(index, isCursor));
return `${title}\n${c.cyan(BAR)} ${join(lines, `\n${c.cyan(BAR)} `)}\n${c.cyan(BAR_END)}\n`;
}
}
/** Any number of a list of choices, ticked with space. */
class MultiselectQuestion<T> implements Question {
#colors: Colors;
#message: String;
#choices: Array<Choice<T>>;
#required: boolean;
#maxItems: i32;
#size: () => TerminalSize;
#ticked: FixedArray<boolean>;
var #cursor = 0;
new(colors: Colors, message: String, choices: Array<Choice<T>>, initial: Array<i32>,
required: boolean, maxItems: i32, size: () => TerminalSize)
: #colors = colors,
#message = message,
#choices = choices,
#required = required,
#maxItems = maxItems,
#size = size,
#ticked = new FixedArray<boolean>(choices.length, false) {
for (let index in initial) {
this.#ticked[index] = true;
}
}
/** The values of the choices ticked, in the order they are offered. */
value: Array<T> {
get {
let values = new GrowableArray<T>();
for (var i = 0; i < this.#choices.length; i += 1) {
if (this.#ticked[i]) {
values.push(this.#choices[i].value);
}
}
return values;
}
}
#tickedCount(): i32 {
var count = 0;
for (let ticked in this.#ticked) {
if (ticked) {
count += 1;
}
}
return count;
}
key(key: Key): PromptState {
let count = this.#choices.length;
if (key.kind == KeyKind.Enter) {
if (this.#required && this.#tickedCount() == 0) {
return PromptState.Error;
}
return PromptState.Submit;
}
if (isBack(key)) {
this.#cursor = if (this.#cursor == 0) count - 1 else this.#cursor - 1;
} else if (isOn(key)) {
this.#cursor = if (this.#cursor == count - 1) 0 else this.#cursor + 1;
} else if (key.kind == KeyKind.Text && key.text == ' ') {
this.#ticked[this.#cursor] = !this.#ticked[this.#cursor];
} else if (key.kind == KeyKind.Text && key.text == 'a') {
let all = this.#tickedCount() == count;
for (var i = 0; i < count; i += 1) {
this.#ticked[i] = !all;
}
}
return PromptState.Active;
}
#line(index: i32, isCursor: boolean): String {
let c = this.#colors;
let choice = this.#choices[index];
let hint = if (choice.hint == '') '' else ` ${c.dim(`(${choice.hint})`)}`;
if (this.#ticked[index]) {
return if (isCursor) `${c.green(CHECKBOX_SELECTED)} ${choice.label}${hint}`
else `${c.green(CHECKBOX_SELECTED)} ${c.dim(choice.label)}`;
}
return if (isCursor) `${c.cyan(CHECKBOX_INACTIVE)} ${choice.label}${hint}`
else `${c.dim(CHECKBOX_INACTIVE)} ${c.dim(choice.label)}`;
}
/** The labels of the choices ticked, as the answer shows them. */
#answer(): String {
let labels = new GrowableArray<String>();
for (var i = 0; i < this.#choices.length; i += 1) {
if (this.#ticked[i]) {
labels.push(this.#choices[i].label);
}
}
return join(labels, ', ');
}
render(state: PromptState): String {
let c = this.#colors;
let title = titleOf(c, state, this.#message);
if (state == PromptState.Submit) {
let answer = this.#answer();
return `${title}\n${c.gray(BAR)} ${if (answer == '') c.dim('none') else c.dim(answer)}`;
}
if (state == PromptState.Cancel) {
let answer = this.#answer();
let line = `${title}\n${c.gray(BAR)} ${c.strikethrough(c.dim(answer))}`;
return if (answer == '') line else `${line}\n${c.gray(BAR)}`;
}
let rail = if (state == PromptState.Error) c.yellow(BAR) else c.cyan(BAR);
let lines = listLines(this.#choices.length, this.#cursor, this.#maxItems, this.#size().rows,
c, (index, isCursor) => this.#line(index, isCursor));
let list = `${title}\n${rail} ${join(lines, `\n${rail} `)}`;
if (state == PromptState.Error) {
return `${list}\n${c.yellow(BAR_END)} ${c.yellow('Choose at least one: space ticks a choice, enter answers.')}\n`;
}
return `${list}\n${c.cyan(BAR_END)}\n`;
}
}
/**
* Asks questions in the terminal.
*
* Each prompt opens its key input for as long as it asks, so between
* prompts the terminal is as it was, and Ctrl+C ends the program as
* usual. The answer is left on the rail, followed by a new line.
*/
export class Prompts {
/** Whether there is a terminal to ask in; a prompt throws `PromptUnavailable` when not. */
interactive: boolean;
colors: Colors;
#keys: KeyInput;
#write: (text: String) => void;
#size: () => TerminalSize;
new(
interactive: boolean = canPrompt(),
colors: Colors = new Colors(),
keys: KeyInput = new TerminalKeys(),
write: (text: String) => void = logString,
size: () => TerminalSize = terminalSize,
) : interactive = interactive,
colors = colors,
#keys = keys,
#write = write,
#size = size;
/**
* Asks for a line of text. `placeholder` is shown dimmed while nothing
* is typed, and `defaultValue` is the answer when nothing is.
* `validate` returns why an answer is refused, or null to accept it.
*/
async text(
message: String,
placeholder: String = '',
initial: String = '',
defaultValue: String = '',
validate: (value: String) => String? = anything,
): Future<String> {
let question = new TextQuestion(this.colors, message, placeholder, initial, defaultValue,
validate, '');
await this.#ask(question, message);
return question.value;
}
/** Asks for text that is not shown: a mask stands in for each character. */
async password(
message: String,
validate: (value: String) => String? = anything,
): Future<String> {
let question = new TextQuestion(this.colors, message, '', '', '', validate, PASSWORD_MASK);
await this.#ask(question, message);
return question.value;
}
/** Asks yes or no, as `active` and `inactive`; `y` and `n` answer at once. */
async confirm(
message: String,
initial: boolean = true,
active: String = 'Yes',
inactive: String = 'No',
): Future<boolean> {
let question = new ConfirmQuestion(this.colors, message, initial, active, inactive);
await this.#ask(question, message);
return question.value;
}
/**
* Asks for one of `choices`, starting on the one at `initial`. At most
* `maxItems` are shown at once (0 for as many as the terminal has room
* for).
*/
async select<T>(
message: String,
choices: Array<Choice<T>>,
initial: i32 = 0,
maxItems: i32 = 0,
): Future<T> {
if (choices.length == 0) {
throw new Error(`${message}: there is nothing to choose from`);
}
let question = new SelectQuestion<T>(this.colors, message, choices, initial, maxItems,
this.#size);
await this.#ask(question, message);
return question.value;
}
/**
* Asks for any of `choices`, starting with those at `initial` ticked.
* When `required`, the answer must tick at least one.
*/
async multiselect<T>(
message: String,
choices: Array<Choice<T>>,
initial: Array<i32> = [],
required: boolean = true,
maxItems: i32 = 0,
): Future<Array<T>> {
if (choices.length == 0) {
throw new Error(`${message}: there is nothing to choose from`);
}
let question = new MultiselectQuestion<T>(this.colors, message, choices, initial, required,
maxItems, this.#size);
await this.#ask(question, message);
return question.value;
}
/** Draws `question` and answers keys until it is answered or cancelled. */
async #ask(question: Question, message: String): Future<void> {
if (!this.interactive) {
throw new PromptUnavailable(`${message}: there is no terminal to ask in`);
}
let state = await this.#answer(question);
if (state == PromptState.Cancel) {
throw new PromptCancelled();
}
}
/** Opens the keys and asks, closing them however the asking ends. */
async #answer(question: Question): Future<PromptState> {
let keys = this.#keys;
keys.open();
try {
return await this.#loop(question, keys);
} finally {
keys.close();
let write = this.#write;
write(`\n${CURSOR_SHOW}`);
}
}
async #loop(question: Question, keys: KeyInput): Future<PromptState> {
let write = this.#write;
var state = PromptState.Active;
var frame = question.render(state);
write(CURSOR_HIDE + frame);
while (state == PromptState.Active || state == PromptState.Error) {
let key = await keys.next();
let kind = key.kind;
state = if (kind == KeyKind.Escape || kind == KeyKind.Interrupt || kind == KeyKind.EndOfInput)
PromptState.Cancel
else
question.key(key);
let next = question.render(state);
if (next != frame) {
write(this.#redraw(frame, next));
frame = next;
}
}
return state;
}
/** What replaces `previous`, which the cursor is at the end of, with `next`. */
#redraw(previous: String, next: String): String {
let up = rowsAbove(previous, this.#size().columns);
let move = if (up > 0) `${ESC}[${up}A` else '';
return `\r${move}${ESC}[J${next}`;
}
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 | none |
|