/** * 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 { 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) { 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 { let (start, shown) = windowOf(cursor, count, maxItems, rows); let end = if (start + shown < count) start + shown else count; let lines = new GrowableArray(); 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 implements Question { #colors: Colors; #message: String; #choices: Array>; #maxItems: i32; #size: () => TerminalSize; var #cursor: i32; new(colors: Colors, message: String, choices: Array>, 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 implements Question { #colors: Colors; #message: String; #choices: Array>; #required: boolean; #maxItems: i32; #size: () => TerminalSize; #ticked: FixedArray; var #cursor = 0; new(colors: Colors, message: String, choices: Array>, initial: Array, required: boolean, maxItems: i32, size: () => TerminalSize) : #colors = colors, #message = message, #choices = choices, #required = required, #maxItems = maxItems, #size = size, #ticked = new FixedArray(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 { get { let values = new GrowableArray(); 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(); 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 { 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 { 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 { 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( message: String, choices: Array>, initial: i32 = 0, maxItems: i32 = 0, ): Future { if (choices.length == 0) { throw new Error(`${message}: there is nothing to choose from`); } let question = new SelectQuestion(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( message: String, choices: Array>, initial: Array = [], required: boolean = true, maxItems: i32 = 0, ): Future> { if (choices.length == 0) { throw new Error(`${message}: there is nothing to choose from`); } let question = new MultiselectQuestion(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 { 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 { 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 { 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}`; } }