Search by

nahkampf / nitzer

nahkampf

Oldschool BBS-style textmode interfaces and effects for PHP: ANSI, xterm, 16/256/truecolor.

Package info

github.com/nahkampf/nitzer

pkg:composer/nahkampf/nitzer

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.1 2026-11-28 02:59 UTC

This package is auto-updated.

Last update: 2026-11-28 02:59:58 UTC


README

NITZER: That Total Terminal

Nitzer

Oldschool BBS-style text-mode interfaces and effects for PHP: ANSI art, lightbar menus, input fields, tables, progress bars, spinners and color effects. Supports a selection of ANSI.SYS-style sequences as well as modern xterm in 16, 256 or truecolor.

composer require nahkampf/nitzer

Requirements

  • PHP 7.1 or newer. No PHP extensions are needed for line output (Console). Supporting as far back as 7.1 was a deliberate choice.

  • Full screen (keypresses as they are typed) needs a way to put the terminal in raw mode:

    • the stty command, run through shell_exec() (any Unix-like system: Linux, macOS, BSD, WSL). This is the default; stty also reports the terminal size. shell_exec must not be in disable_functions.
    • or, when there is no stty, ext-readline, used only to switch the mode (keys are always read straight from STDIN). Force it with 'input' => 'readline' in the Config.

    Without either, Terminal::enter() throws a RuntimeException.

  • Optional: ext-pcntl, so that Ctrl-C and SIGTERM restore the terminal before the program exits.

  • NOTE: As of writing this will not work on (non WSL) windows machines, as stty is not available and the windows version of PHP relies on a feature-incomplete Readline.

To see everything working, run the showcase in a terminal:

php examples/showcase.php                      # auto-detects the terminal
php examples/showcase.php terminal=ansi ice=1  # the BBS look: 16 colors, iCE backgrounds

Contents

Two ways to draw

Nitzer has two ways of putting things on the screen; pick the one that fits the program.

Line output (Console) prints line after line, like echo with colors, tables and progress bars. Use it for command-line tools and scripts. Nothing needs to be set up.

use Nitzer\Color;
use Nitzer\Console;

$c = new Console();
$c->out('Hello, caller!', Color::ansi(Color::YELLOW))
  ->line()
  ->table([['Phantom', 2400], ['Zero Cool', 14400]], ['headers' => ['Handle', 'Baud']]);

Full screen (Terminal, Screen, Canvas, Loop) takes over the whole terminal: you draw on a grid of cells, and only the cells that changed are sent. Use it for interactive programs: menus, input fields, animation. All widgets and effects draw on a Canvas.

use Nitzer\{Canvas, Color, Config, Input, Loop, Screen, Terminal};

$term = new Terminal(new Config());
$term->enter();                       // raw keys, no echo, cursor hidden, alt screen on xterm
try {
    (new Loop(new Screen($term), new Input(), 30))->run(function (float $dt, array $keys, Canvas $c) {
        $c->clear();
        $c->text(2, 1, 'Press any key to leave', Color::ansi(Color::LIGHT_CYAN));

        return $keys === [];          // return false to stop
    });
} finally {
    $term->leave();                   // always restore the terminal
}

Configuration

Config holds the settings. Anything not set here Nitzer will attempt to detect from the environment.

use Nitzer\Config;

$cfg = new Config([
    'terminal' => 'ansi',      // 'ansi' (ANSI.SYS/DOS style), 'xterm', or 'auto' (default)
    'colors'   => 16,          // 16, 256, 'truecolor', or 'auto' (default); capped to 16 on 'ansi'
    'ice'      => true,        // iCE colors: blink bit = bright background (ansi profile only)
    'blink'    => 'software',  // 'software' (Screen blinks cells) or 'native' (SGR 5)
    'size'     => [80, 25],    // [cols, rows], or null to detect (default)
    'input'    => 'auto',      // 'auto', 'stty' or 'readline'
    'charset'  => 'utf-8',
]);

$cfg = Config::bbs();          // A shorthand to load the classic DOS style (ansi profile, 16 colors, 80x25)

Unknown options throw an InvalidArgumentException. Read the effective values back with terminal(), colors() (a Color::DEPTH_* value), ice(), blink(), size() and input().

The output is profile-specific: the same code sends ESC[1;33m to an ANSI terminal and ESC[93m to an xterm.

Colors

Color is immutable. The 16 classic colors are numbered in DOS order throughout Nitzer:

# Constant # Constant
0 Color::BLACK 8 Color::DARK_GRAY
1 Color::BLUE 9 Color::LIGHT_BLUE
2 Color::GREEN 10 Color::LIGHT_GREEN
3 Color::CYAN 11 Color::LIGHT_CYAN
4 Color::RED 12 Color::LIGHT_RED
5 Color::MAGENTA 13 Color::LIGHT_MAGENTA
6 Color::BROWN 14 Color::YELLOW
7 Color::LIGHT_GRAY 15 Color::WHITE
use Nitzer\Color;

Color::ansi(Color::YELLOW);   // one of the 16 (DOS numbers: Color::ansi(1) is blue)
Color::xterm(208);            // xterm-256 index (xterm's own numbering)
Color::rgb(255, 136, 0);      // truecolor
Color::fromSgr(1);            // one of the 16 by its escape-code number (ESC[31m = red); for reading ANSI

A color the terminal can't show is replaced by the nearest one it can (downgrade()), so you can always ask for truecolor. Everywhere a color is taken, null means the terminal's default.

Attributes

Attributes are bit flags on Nitzer\Ansi, combined with |:

Constant Effect
Ansi::BOLD bold (on the ansi profile: a bright foreground)
Ansi::UNDERLINE underline
Ansi::REVERSE swap foreground and background
Ansi::BLINK blink; on a Screen drawn by Nitzer itself like DOS (see blink in Config)
Ansi::BLINK_NATIVE always the terminal's own blink (SGR 5)

Ansi is also where every escape sequence is built. You rarely need it directly, but it is there:

use Nitzer\Ansi;

$ansi = new Ansi($cfg);
echo $ansi->wrap('OK', Color::ansi(Color::GREEN), null, Ansi::BOLD), "\n";
echo $ansi->sgr($fg, $bg, $attrs);   // the style alone (always starts with a reset)
echo $ansi->reset();                 // ESC[0m

Line output: Console

new Console(?Terminal $term = null, ?int $width = null) writes to STDOUT with settings from the environment. Every method returns the console, so calls chain.

Method Does
out(string $text = '', ?Color $fg, ?Color $bg, int $attrs = 0) print a line; "\n" makes several
inline(string $text, ?Color $fg, ?Color $bg, int $attrs = 0) print without the line break
br(int $count = 1) blank lines
tab(int $count = 1) indent the next output ($tabWidth spaces each, default 4)
center() center the next output; a table or block keeps its shape
line(string $pattern = '─', ?Color $fg, ?Color $bg, ?int $width) a rule: '=', '=-', '<>'...
wrap(string $text, ?int $width, bool $hyphenate = false, string $align = 'left', ?Color $fg, ?Color $bg) word-wrapped text; align left, right, center, justify
table($rows, array $options = []) see Tables
columns(array $items, ?int $count = null, int $gap = 2) see Columns
tree(array $items, array $guides = Tree::UTF8) see Trees
progress(int $total, int $barWidth = 30) returns a ProgressBar, see below
parse(string $markup): string see Markup
write(string $raw) send a string as it is: escape sequences included, no indent, no newline
width() / setWidth(?int $width) the width used for layout (the terminal's, read once)
$c = new Console();
$c->center()->out('*** NITZER BBS ***', Color::ansi(Color::LIGHT_CYAN))
  ->line('=-', Color::ansi(Color::BLUE))
  ->tab()->wrap($longText, 60, true, 'justify')
  ->br();

Cursor control

All of these send the matching ANSI sequence and return the console.

Method Sequence
up(n = 1), down(n = 1), right(n = 1), left(n = 1) CSI n A/B/C/D (a count below 1 does nothing)
bol() / eol() start / end of the line
ctl(), ctr(), cbl(), cbr() the corners: top left, top right, bottom left, bottom right
locate(int $row, int $col) row, column, 1-based
saveDec() / restoreDec() save / restore the cursor, DEC style (ESC 7 / ESC 8; also the colors)
saveSco() / restoreSco() save / restore the cursor, SCO style (CSI s / CSI u)
hideCursor() / showCursor() CSI ?25l / CSI ?25h

Moves stop at the screen edge, so the corners and eol() use 999 for "as far as it goes" and work at any size.

Screen: save, restore and clear

Method Does
clear() reset the colors, erase the screen, cursor home
reset() back to the default colors and attributes (ESC[0m)
saveScreen() / restoreScreen() xterm's alternate screen (CSI ?1049h / l): keeps the screen and the cursor, instantiates a blank one, and can restore the saved one. Only on the xterm profile; ANSI.SYS didn't support it, so on that profile it sends nothing

For a saved screen that works on every terminal, see Screen::save() under Full screen.

Tables

A table in the open style: green lines, white headings, yellow and gray columns, the third one wrapping

use Nitzer\Table;

$c->table($rows, $options);                 // or build one and reuse it:
$t = new Table($rows, $options);
echo implode("\n", $t->lines(80)), "\n";               // plain text, at most 80 cells wide
echo implode("\n", $t->lines(80, $ansi)), "\n";        // with colors
$linesDrawn = $t->draw($canvas, $x, $y, $maxWidth);    // on a Canvas

$rows is a list of arrays: lists, or associative arrays whose keys become the headings. null is an empty cell, true/false print as such, arrays as JSON, objects through __toString(). A "\n" makes a multi-line cell.

Option Value
headers string[]; optional
style single (default), double, ascii, none, or open (lines between columns and rules only, no frame)
align left, right, center or justify: for all columns, or an array keyed by column index or heading
wrap break-word (default: wrap at spaces, cut a word longer than the column) or hyphenate
padding blank cells each side of a cell's text, default 1
rowLines a rule between rows, default false
columns per column, keyed by index or heading: width (fixed; the column wraps), align, wrap, fg, bg, headerFg, headerBg
rowColors a list of [fg, bg] pairs used in turn: [[null, null], [null, $blue]] stripes the rows
fg, bg, borderFg, borderBg, headerFg, headerBg, headerAttrs the defaults for the whole table (also public properties); headerAttrs defaults to Ansi::BOLD

A cell takes its row's color, else its column's, else the table's, for foreground and background separately. A table wider than the room shrinks its widest columns without a fixed width first.

$c->table($rows, [
    'headers'  => ['Column heading 1', 'Column heading 2', 'Column heading 3'],
    'style'    => 'open',
    'rowLines' => true,
    'borderFg' => Color::ansi(Color::GREEN),
    'headerFg' => Color::ansi(Color::WHITE),
    'columns'  => [
        ['fg' => Color::ansi(Color::YELLOW)],
        ['fg' => Color::ansi(Color::YELLOW), 'align' => 'right'],
        ['fg' => Color::ansi(Color::LIGHT_GRAY), 'width' => 30, 'wrap' => 'hyphenate'],
    ],
]);

Columns

A list of BBS message areas laid out in five columns, filled down then across

$c->columns($names);              // as many columns as fit, filled down then across like ls
$c->columns($names, 4);           // four columns
$c->columns($names, null, 4);     // a gap of 4 cells
$c->columns([['Gary', 'Mary'], [1.2, 4.3]]);   // rows: each kept on its line, the cells lined up

$lines = Nitzer\Columns::lines($items, $width, $count, $gap);   // the lines, to draw anywhere

Trees

A static tree, every branch open: Nitzer, with src, Widget, examples and their files

$c->tree(['Files' => ['Uploads' => ['demo.zip', 'tune.mod'], 'readme.txt'], 'Messages']);
//  ▾ Files
//  ├─ ▾ Uploads
//  │  ├─ demo.zip
//  │  └─ tune.mod
//  └─ readme.txt
//  Messages

$lines = Nitzer\Widget\Tree::lines($items, Nitzer\Widget\Tree::ASCII);   // |- `- | + -

A key with an array is a branch titled by the key; any other value is a leaf titled by the value. For an interactive tree, see Tree view.

Progress bar (Console)

$bar = $c->progress(count($files));          // drawn at once, on its own line
foreach ($files as $f) {
    // ...
    $bar->advance(1, $f);                     // the label is optional
}
// it ends its line by itself once the total is reached; $bar->finish() jumps there

set(int $value, ?string $label), advance(int $step = 1, ?string $label), finish(), value(), total(), percent(), done(). Public properties: $fillFg, $emptyFg, $textFg, $fillChar (█), $emptyChar (░), $width. render(?Ansi $ansi, ?int $maxWidth) builds the line without printing it.

Markup

Text with @@tags@@ for colors, attributes and the cursor, turned into terminal sequences.

$s = $c->parse('@@reset@@Hello! @@fg:15@@this is white text, @@bg:1@@now with blue background@@reset@@');
$c->write($s);                                   // or keep $s and send it later, anywhere

use Nitzer\Markup;
$s = (new Markup($term->ansi()))->parse($text);   // the same, outside a Console
(new Markup())->draw($canvas, $text, $x, $y);     // drawn on a Canvas instead
Tag Does
@@fg:N@@, @@bg:N@@ N is 0-15 (DOS numbers), a name (yellow, light_cyan, ... as the Color constants, lowercase), 16-255 (xterm-256), #rrggbb, or default
@@bold@@, @@underline@@, @@reverse@@ on; @@/bold@@ etc. turns one off
@@blink@@ the terminal's blink (SGR 5)
@@nblink@@ Nitzer's blink: really blinks on a Canvas; in a string it can only be SGR 5
@@reset@@ everything back to the default
@@cls@@ reset, clear the screen, cursor home
@@eraseeol@@ erase to the end of the line
@@up@@, @@down@@, @@left@@, @@right@@ move the cursor; @@up:3@@ moves three
@@bol@@, @@eol@@ start / end of the line
@@ctl@@, @@ctr@@, @@cbl@@, @@cbr@@ the corners
@@locate:R,C@@ row R, column C (1-based)
@@savedec@@, @@restoredec@@, @@savesco@@, @@restoresco@@ save / restore the cursor
@@hidecursor@@, @@showcursor@@
@@br@@ a new line
@@@@ a literal @@

Tag names are case-insensitive and have no spaces. Anything else between @@ and @@ stays in the text as it is. Tags add up: @@bg:1@@ keeps the foreground from an earlier @@fg:15@@. The string depends on the terminal's settings, so parse with the Ansi of the terminal it is for (Console::parse() does).

On a Canvas the drawing position plays the cursor: $x, $y is row 1, column 1 for locate, and where bol and br return to.

Full screen

Terminal

new Terminal(Config $config, $out = STDOUT, $in = STDIN). enter() switches to raw keys (no echo, no line buffering), hides the cursor and, on xterm, uses the alternate screen; leave() undoes all of it and is safe to call twice. Call it in a finally. size() is [cols, rows], write($s) sends raw output, ansi() and config() give the settings.

Ctrl-C is a signal, not a key: with ext-pcntl Nitzer restores the terminal on it.

Screen and Canvas

$screen = new Screen($term);       // a Canvas the size of the terminal
$c = $screen->canvas();
$c->text(2, 1, 'Hello');
$screen->flush();                  // sends only the cells that changed since the last flush

Canvas is a grid of cells, each [char, ?Color $fg, ?Color $bg, int $attrs]. Drawing is clipped to the grid, so nothing needs bounds checks.

Method Does
put(x, y, string $char, ?Color $fg, ?Color $bg, int $attrs = 0) one cell
text(x, y, string $s, ?Color $fg, ?Color $bg, int $attrs = 0) a string
fill(x, y, w, h, string $char = ' ', ?Color $fg, ?Color $bg, int $attrs = 0) a rectangle
box(x, y, w, h, string $style = 'single', ?Color $fg, ?Color $bg, int $attrs = 0, string $title = '') a border; styles single, double, block, solid, turbo (Canvas::styles())
shadow(x, y, w, h, ?Color $fg, ?Color $bg) recolor what's underneath, dark gray on black by default; draw at x + 2, y + 1, then the box over it
clear(), cell(x, y), cells(), width(), height()

Screen also has:

  • invalidate(): the next flush repaints everything (after a resize or a stray write)
  • save(): Canvas / restore(Canvas $saved): a copy of the frame, and putting it back (resending every cell). A saved screen that works on any terminal, BBS ones included

Loop and Input

new Loop(Screen $screen, Input $input, int $fps = 30) and run(callable $tick) call $tick(float $dt, string[] $keys, Canvas $canvas) every frame and flush after it; return false to stop. $dt is the seconds since the previous frame, which is what the effects and spinners advance by.

Keys are plain strings: printable characters as themselves ('a', 'é'), 'space', 'enter', 'tab', 'backspace', 'esc', 'up', 'down', 'left', 'right', 'home', 'end', 'insert', 'delete', 'pageup', 'pagedown', 'f1'..'f12', with prefixes ctrl-, alt-, shift- ('ctrl-d', 'shift-tab'). ANSI-BBS page keys (CSI V, CSI U) arrive as pageup / pagedown. Input::char($key) is the character a key types, or null. Outside a Loop, (new Input())->poll($timeout) returns the keys that arrived.

Widgets

Widgets live in Nitzer\Widget. They all work the same way: build one with a position, pass it keys from the Loop with handle($key), and draw($canvas) it every frame. Their colors are public properties you can change at any time. Interactive ones have a public $active (default true): set it to false to hide the cursor or highlight while another widget has the focus.

Menus

Lightbar: Menu

A lightbar menu in a double box: the headings Messages and Files, a separator, Read messages highlighted

use Nitzer\Widget\Menu;

$menu = new Menu(4, 4, [
    Menu::heading('Messages'),          // text the highlight skips
    'Read messages',
    'Post a message',
    Menu::separator(),                  // ─── across the width; Menu::separator(['-', '=']) for your own
    'Goodbye',
], $height = null);                     // visible rows; it scrolls when there are more items

// in the loop:
$i = $menu->handle($key);              // the chosen index on enter or a first-letter hotkey, else null
if ($i !== null) { /* $menu->label($i) */ }
$menu->draw($c);

Keys: up/down (wrapping), home/end, pageup/pagedown, enter, and a first letter. Headings and separators are skipped but keep their place in the indexes (above, 'Goodbye' is index 4). selected(), select($i), label($i), isSeparator($i), isHeading($i), width(). Colors: $fg, $bg, $selFg, $selBg, $separatorFg, $headingFg.

Horizontal lightbar

Three horizontal lightbars: Yes No Cancel, the days of the week, and xterm-256 grays with amber

use Nitzer\Widget\HorizontalLightbar;

$bar = new HorizontalLightbar(4, 6, ['Yes', 'No', 'Cancel'], $fg, $bg, $activeFg, $activeBg, $gap = 1);
$i = $bar->handle($key);               // left/right (wrapping), home/end; enter or a first letter: the index

Menu bar with dropdowns

A gray menu bar with the File dropdown open: New, Open..., Save, a separator and Exit, with a drop shadow

use Nitzer\Widget\MenuBar;

$bar = new MenuBar(0, 0, ['File' => ['New', 'Open', '-', 'Exit'], 'Edit' => ['Undo'], 'Help'], $gap = 0);
$path = $bar->handle($key);            // 'Help' or 'File/Open' when activated, else null
$bar->draw($c);                        // draw it last: the dropdown goes over the rest

'-' in a dropdown is a separator. Colors: $fg, $bg, $selFg, $selBg, $dropFg, $dropBg, $dropSelFg, $dropSelBg, $borderFg, $shadowFg, $shadowBg; also $style (a box style) and $shadow. isOpen(), close().

Tree view

An interactive tree: Message bases open, Local highlighted with its two areas, the other branches closed

use Nitzer\Widget\Tree;

$tree = new Tree(2, 3, 40, 15, $items, $open = false);   // x, y, width, height
if ($tree->handle($key)) {             // true when enter picked a leaf
    $id = $tree->selectedId();         // the keys that lead to it: ['File areas', 'Uploads', 1]
    $node = $items[$id[0]][$id[1]][$id[2]];
}
$tree->draw($c);

A key with an array is a branch titled by the key; any other value is a leaf titled by its value. Keys: up/down, home/end, pageup/pagedown; right opens a branch (or steps into it), left closes it (or steps out); space toggles; enter toggles a branch or picks a leaf. selectedId() is unique even when titles repeat; selected() gives the titles, for showing. $guides = Tree::UTF8 (├─ └─ │ ▸ ▾) or Tree::ASCII. Colors: $guideFg, $branchFg, $leafFg, $bg, $focusFg, $focusBg.

A static tree, every branch open: new Tree(..., true) with $active = false, never given keys. As text: Tree::lines() or Console::tree().

Input fields

Line input: Prompt

Two line inputs: a Handle field and a Password field that shows stars, with a block cursor

use Nitzer\Widget\Prompt;

$name = new Prompt(4, 5, 'Handle:', $width = 16, $max = null, $mask = null);
$pass = new Prompt(4, 7, 'Password:', 12, null, '*');      // shows * for each character
$amount = new Prompt(4, 9, 'Amount:', 10, PHP_INT_MAX);    // any length; it scrolls
$amount->allow = Prompt::DIGITS;                           // only digits are typed; LETTERS, ALNUM, or a regex

if ($name->handle($key)) {             // true on enter
    echo $name->text();
}

$max defaults to the width. Keys: left/right, home/end, backspace/delete, ctrl-a/e (home/end), ctrl-k (cut to the end), esc or ctrl-u (clear). $allow is a pattern each character must match ('/^[0-9a-fA-F]$/'); any other key is dropped before it is drawn. Colors: $labelFg, $fg, $bg.

Formatted fields: MaskedField

Six formatted fields with their masks: phone, date, time, IP address, card number and a postcode

A field that only takes what its mask allows and puts in the punctuation itself.

use Nitzer\Widget\MaskedField;

$phone = new MaskedField(4, 5, 'Phone:', MaskedField::PHONE_INTL);   // +009-000 000 999 999
$date  = new MaskedField(4, 7, 'Date:', MaskedField::DATE);          // 0000-00-00
$code  = new MaskedField(4, 9, 'Postcode:', 'LL-000 00');           // a mask of your own

if ($phone->handle($key)) {            // true on enter once every required slot is filled
    $phone->value();                   // '+46-701 234 567'
    $phone->raw();                     // '46701234567'
}
Mask Takes
0 / 9 a digit, required / optional
L / ? a letter, required / optional
A / a a letter or digit, required / optional
& / C any character, required / optional
\x a literal x
anything else a literal, put in by the field

Presets: PHONE_INTL, DATE, TIME, IPV4, CARD. A mask of one class makes a fixed-length restricted field: '0000' is exactly four digits, 'aaaaaaaa' up to eight letters or digits.

The cursor only ever stands on a slot: typing, left/right, home/end and backspace jump over the literals. Right skips an empty optional slot, and so does typing the literal after it (46- in the phone mask). complete(), clear(), type($text), cursor(). Colors: $labelFg, $fg, $bg, $hintFg (the mask's literals and placeholders); $placeholder ('_').

Multiline: TextArea

A message editor on a blue text area, with two checkboxes below it: Post anonymously and Email me the replies

use Nitzer\Widget\TextArea;

$area = new TextArea(4, 4, 60, 8, $saveKey = 'ctrl-d', $text = "Dear sysop,\n\n");
if ($area->handle($key)) {             // true on the save key: hand the text over, move the focus on
    $message = $area->text();
}

It scrolls both ways. Keys: arrows, home/end, pageup/pagedown, backspace/delete (joining lines), ctrl-k. Tab is not typed, so it can move the focus. setText(), cursor() ([row, col]).

The save key defaults to ctrl-d because Nitzer leaves the terminal's flow control on, so ctrl-s and ctrl-z never reach the program.

Checkboxes and radio buttons: Choices

Three columns of checkboxes: ascii [X], utf-8 ☐ and ☑, and custom markers <-> and <*>

use Nitzer\Widget\Choices;

$boxes = new Choices(4, 5, ['ANSI graphics', 'Hot keys'], true);                       // [X] Hot keys
$boxes = new Choices(4, 5, ['ANSI graphics', 'Hot keys'], true, ...Choices::UTF8_BOX);  // ☑ Hot keys
$radio = new Choices(4, 9, ['300', '2400'], false, ...Choices::ASCII_RADIO);           // (∙) 2400
$radio = new Choices(4, 9, ['300', '2400'], false, ...Choices::UTF8_RADIO);            // ◉ 2400
$mine  = new Choices(4, 9, $items, true, '<', '>', '-', '*');  // left, right, off and on markers

if ($boxes->handle($key)) {            // true when space or enter turned something on or off
    $boxes->checked();                 // the indexes that are on
}

$multiple = true gives checkboxes (any number on), false radio buttons (exactly one on). The four characters are the left border ([), right border (]), unselected marker (' ') and selected marker ('X'). Up/down move. isChecked($i), set($i, $on), focus(). Colors: $leftFg, $rightFg, $offFg, $onFg, $labelFg, $bg, $focusFg, $focusBg.

Validation

Nitzer doesn't validate; you'll have to write your own validatation. Prompt, MaskedField and TextArea can however be marked like so:

if (!checkdate($m, $d, $y)) {
    $date->invalid();                                   // red background, the field's own text color
    $date->invalid(Color::ansi(Color::YELLOW));         // yellow text, red background
    $date->invalid(null, Color::ansi(Color::MAGENTA));  // only the background
} else {
    $date->valid();                                     // back to its own colors
}
$date->isInvalid();
[$x, $y, $width, $height] = $date->area();              // where the field is on screen

Progress bars

Five simple progress bars: the defaults, ascii dashes, spaces on backgrounds, shades, and whole steps

use Nitzer\Widget\ProgressBar;
use Nitzer\Widget\HalfStepProgressBar;

$bar = new ProgressBar($x, $y, $width = 40, $value = 0, $max = 100,
    $trackFg, $trackBg, $trackChar = '░', $fillFg, $fillBg, $fillChar = '█');
$bar->value = 42;
$bar->draw($c);

$half = new HalfStepProgressBar($x, $y, 40, 0, 100, $trackFg, $trackBg, $fillFg, $fillBg);

Every argument is also a public property. The value is clamped to 0..max; a max of 0 or less draws a full bar. filled() is the number of filled cells (halves() for the half-step bar).

The half-step bar grows half a cell at a time: full cells are █ and the edge is ▌, the fill as the character's color and the track as its background. So the track color must be one of the 8 dark colors, unless iCE is on. The defaults are light magenta on magenta.

The line-oriented bar is Console::progress().

Spinners

use Nitzer\Widget\Spinner;

$spin = new Spinner($x, $y, $frames = Spinner::ASCII_SPIN, ?Color $fg = null, ?Color $bg = null, $interval = 100000);
// in the loop:
$spin->advance($dt);
$spin->draw($c);

$interval is in microseconds, the time each character is shown. It loops.

Frames Characters
Spinner::ASCII_SPIN (default) - \ | /
Spinner::BLOCK ░ ▒ ▓ █ ▓ ▒
Spinner::FLIP _ _ _ - ` ` ' ´ - _ _ _
Spinner::STAR2 + x *
Spinner::DOTS ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
Spinner::ARC ◜ ◠ ◝ ◟ ◡ ◞
Spinner::ARC_QUADRANTS ◜ ◝ ◟ ◞

Any list of characters works as frames. Spinner::pingpong(['a', 'b', 'c']) gives ['a', 'b', 'c', 'b']: forwards, then back. frame() is the character shown now.

Message boxes

A gray Transfer dialog with a drop shadow: Choose a protocol for the download, with Zmodem, Xmodem, Ymodem and Cancel buttons

use Nitzer\Widget\MessageBox;

$box = new MessageBox('Log off', 'Hang up now?', ['Yes', 'No'], $maxWidth = 56);
$i = $box->handle($key);               // the button's index, -1 on esc, null otherwise
$box->draw($c);                        // centered, with a drop shadow

Left/right/tab move, enter or space chooses, a button's first letter jumps to it and chooses. Properties: $style ('double'), $fg, $bg, $borderFg, $titleFg, $selFg, $selBg, $shadow, $shadowFg, $shadowBg.

Pager and ANSI art

Use this to view a textfile or ANSI art. Scrollable up/down. SAUCE records will be read but stripped from output.

use Nitzer\Art;
use Nitzer\Widget\Pager;

$art = Art::load('logo.ans');                          // CP437 or UTF-8, SAUCE record, iCE colors
$pager = new Pager($art->canvas());                    // full screen
$pager = new Pager($art->canvas(), 10, 3, 60, 15);     // a 60x15 window at 10, 3
$pager->handle($key);                                  // up/down, pageup/pagedown, home/end
$pager->draw($c);

$text = Art::fit(file_get_contents('readme.txt'), 76);  // an Art: plain text word-wrapped to 76, art as it is
echo $art->toAnsi(new Nitzer\Ansi($cfg));               // line-oriented output
$art->sauce();                                          // title, author, group, date, width, ice; or null

Art::load() and Art::parse() take ?int $width, ?bool $ice and ?bool $utf8 to override what the file says. UTF-8 is detected by a BOM, or when there is no SAUCE record and the bytes are valid UTF-8.

Effects

Effects animate the color of a text. Each one is fed time and drawn every frame:

use Nitzer\Effect\{Typewriter, Shimmer, Pulse, FadeIn, FadeOut};

$modem = Typewriter::baud("CONNECT 2400\n", 2400);       // or new Typewriter($text, $charsPerSecond)
$modem->shinyCursor([Color::ansi(Color::WHITE), Color::ansi(Color::LIGHT_GRAY)], $width = 2);

// in the loop:
$modem->advance($dt);
$modem->draw($c, $x, $y, $fg, $bg, $attrs);
if ($modem->done()) { /* ... */ }
Effect Constructor Does
Typewriter (string $text, float $charsPerSecond), Typewriter::baud($text, $baud = 2400) types the text out; skip() finishes it; $cursor shows a cursor, shinyCursor($colors, $width) a fading one
Shimmer (string $text, array $colors, $speed = 'medium', $direction = 'right', bool $loop = true) a highlight sweeps along; $colors brightest first
Pulse (string $text, array $colors, $speed = 'medium', bool $loop = true, float $pause = 1.0) the whole text flashes through the colors and back
FadeIn / FadeOut (string $text, array $colors, ?Color $background = null, $speed = 'medium') from the background through the colors to the text's own color, and back

Speeds are 'slow', 'medium' or 'fast'. The text's own color is the $fg you pass to draw().

Text helpers

Nitzer\Text works on UTF-8 without ext-mbstring: chars($s), width($s), pad($s, $width), and wrap($s, $width, $hyphenate = false, $align = 'left'), which returns the lines.

Every character counts as one cell: wide (CJK) and combining characters will misalign.

Examples

File Shows
examples/showcase.php everything, in a menu
examples/bbs.php a small fake BBS: modem connect, login, lightbar menu, dialogs
examples/console.php line output: text, rules, tables, columns, progress, cursor control
examples/view.php the viewer: php examples/view.php file.ans [cols=60] [rows=15]
examples/keys.php prints the name of every key you press
examples/testcard.php, examples/banner.php colors and attributes on your terminal

License

MIT, see LICENSE.