All 42 libraries

SugarWidgets

Ready-made TUI components — tables, tabs, progress bars, spinners, and more

inspired by charmbracelet/bubbles components widgets forms input

SugarWidgets code coverage

Table, Tabs, Tree, Progress, Paginator, Help, Key, Timer, Stopwatch, Button and Rule — first-party components — plus the btop render helpers Input\TextEdit and Menu\OptionRow, and the deprecated alias re-exports from sugarcraft/sugar-forms — the canonical counted inventory lives in the README: depend on sugarcraft/sugar-forms directly for those, the re-exports here exist only for migration. Everything you'd hand-roll on day one of a TUI project, ready to drop into your Model.

Install

composer require sugarcraft/sugar-widgets

Quickstart

use SugarCraft\Forms\TextInput\TextInput;
use SugarCraft\Forms\Spinner\Spinner;
use SugarCraft\Core\{Cmd, Model, Msg, Program, Subscriptions};
use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Core\KeyType;

final class Search implements Model {
    public function __construct(
        public readonly TextInput $ti,
        public readonly Spinner $sp,
    ) {}

    public function init(): ?\Closure { return $this->sp->tick(); }
    public function subscriptions(): ?Subscriptions { return null; }

    public function update(Msg $msg): array {
        if ($msg instanceof KeyMsg && $msg->type === KeyType::Enter) {
            return [$this, Cmd::quit()];
        }
        [$ti, $cmd]  = $this->ti->update($msg);
        [$sp, $cmd2] = $this->sp->update($msg);
        return [new self($ti, $sp), Cmd::batch($cmd, $cmd2)];
    }

    public function view(): string {
        return $this->sp->view().' '.$this->ti->view();
    }
}

[$input] = TextInput::new()->focus();   // focus() returns [TextInput, ?Cmd]
(new Program(new Search($input, Spinner::new())))->run();

What's in the box

Spinner12 styles — line, dot, miniDot, points, pulse, globe, meter, jump, moon, monkey, hamburger, ellipsis.
ProgressStatic Progress + spring-physics AnimatedProgress driven by SugarSpring.
TextInput / TextAreaSingle + multi-line. Autocomplete, validators, ValidateOn timing control, keystroke restrict pattern filter, line numbers, soft-wrap, dynamic-height growth.
ItemListSelectable, scrollable, filterable — status messages and cursor tracking included.
TableSelectable data table with Column DTOs, header highlight, vertical nav, per-cell styleFunc(row, col) => Style, multi-column sort with withSort() / thenSortBy() / clearSort(), filtering with withFilterable() / withFilter() / withFilterPredicate() (default: case-insensitive substring match over every cell of every row), and pagination with withPageSize() / paginator() / withPage() / nextPage() / prevPage() / pageFirst() / pageLast() — integrates with sort and filter.
TreeInteractive tree view — cursor nav, expand / collapse, viewport scroll, g / G jump.
ViewportScrollable text region. Mouse wheel, scrollbar, keyboard nav.
FilePickerDirectory browser with icons, size, sort modes.
TextEdit + OptionRowbtop-derived helpers: Input\TextEdit is an immutable inline editor with an underline caret (no hardware cursor), grapheme-cluster editing, cell-budget windowing and a digits-only mode; Menu\OptionRow::renderRow() draws btop's one-line options row (the two-line render() is deprecated). Progress::withColorFunc closures also receive the bar width for position-colored ramps.
Paginator + Help + KeyDot / arabic page indicator, key-help footer, KeyMap binding DSL.

TextEdit + OptionRow

use SugarCraft\Widgets\Input\TextEdit;
use SugarCraft\Widgets\Menu\OptionRow;

$edit = TextEdit::new('firefox')->home()->right()->right();
echo $edit->view();      // "fi\e[4mr\e[24mefox" — underline caret on "r"

echo OptionRow::renderRow('Update ms', TextEdit::new('2000', numeric: true),
    selected: true, editing: true, hasArrows: true, editable: true);

Source & demos

Try the quickstart →

API

ClassMethodDescription
TextInputnew()Create a new text input instance (deprecated alias — depend on sugarcraft/sugar-forms)
TextInputupdate(Msg)Handle input events
TextInputwithValidateOn(ValidateOn)Set validation timing — None (default) and Change validate on every edit; Blur and Submit defer validation
TextInputwithRestrict(string $pattern)PCRE regex filter — only matching keystrokes are accepted
ValidateOnenumCases: None (default) / Change — validate on every edit; Blur / Submit — deferred until focus loss or submit
TextAreanew()Create a multi-line text area (deprecated alias — depend on sugarcraft/sugar-forms)
Spinnernew(?Style $style = null)Create spinner; style optional (defaults to line) (deprecated alias — depend on sugarcraft/sugar-forms)
Spinnertick()Return tick command for animation
Tablenew(headers, rows)Create data table
TablewithSort(string $column, SortDirection $dir = Asc)Set primary sort column and direction — clears prior sort chain
TablethenSortBy(string $column, SortDirection $dir = Asc)Add secondary (or further) sort tiebreaker
TableclearSort()Remove all sort criteria, restoring insertion order
TablesortState(): SortStateReturn current sort criteria (readonly)
TablestyleFunc(?Closure)Per-cell style composer fn(int $row, int $col): Style (row -1 = header). Each returned style is merged under the row's selection/header style via Style::inherit(), so the cursor inversion always wins over cell decoration
TablegetStyleFunc(): ?ClosureReturn the current composer (seam for host-side re-composition)
TablewithFilterable(bool)Enable or disable the filter feature
TablewithFilter(string $query)Set filter query string — default: case-insensitive substring match on all visible columns
TablewithFilterPredicate(?Closure(list<string>): bool)Custom filter callable — null restores the default
Tablefilterable(): boolReturn whether filtering is enabled
Tablefilter(): stringReturn the current filter query string
TablefilterPredicate(): ?ClosureReturn the current custom filter predicate
SortDirectionenumCases: Asc / Desc — use toggle() to flip direction
SortStateDTOImmutable list of (column index, SortDirection) pairs
TablewithPageSize(int $size)Set rows per page — 0 disables pagination, ≥1 enables it
TablewithPage(int $page)Navigate to a zero-based page (clamps to valid range)
TablenextPage()Advance one page — returns new Table
TableprevPage()Retreat one page — returns new Table
TablepageFirst()Jump to the first page — returns new Table
TablepageLast()Jump to the last page — returns new Table
TablepageSize(): intReturn rows per page (0 = pagination disabled)
TablecurrentPage(): intReturn the current zero-based page
PaginatortotalPages(): intReturn total page count (via the table's paginator)
Tablepaginator(): PaginatorReturn a Paginator wired to the table's current page state
Treenew(Node ...$roots)Create tree view from root nodes via the Tree::new() factory — immutable-fluent; the constructor itself is private
TreewithStyle(...)Immutable override of the chrome knobs — cursorPrefix / unselectedPrefix / expandedGlyph / collapsedGlyph / leafGlyph (sanitized to single-line)
Viewportnew(width = 80, height = 24)Create scrollable viewport; content arrives via setContent(string) (deprecated alias — depend on sugarcraft/sugar-forms)
Progressnew(ratio)Create progress bar from a 0.0–1.0 ratio (clamped; NaN renders 0%)
ProgresswithPercent(float)Return a new bar at the given ratio (same clamp; accepts NaN → 0%)
ProgresswithColorFunc(?Closure)Per-filled-cell color fn(int $i, int $filledCells, float $percent, int $barWidth): Color — the 4th arg (true bar width) enables btop position-colored ramps; 3-arg closures still work
ProgresswithRenderMode(ProgressRenderMode)Switch the glyph set — Block / Line / Slim render modes
ProgresswithPercentFormat(string $fmt)Custom % suffix printf format receiving the 0–100 integer (default '%3d%%')
Timernew(float $duration, float $interval = 1.0)Countdown; duration is required. start() returns the next [model, Cmd] pair and subscriptions() arms the tick loop; the epoch on each TickMsg refuses counts from stopped generations
Stopwatchnew(float $interval = 1.0)Count-up; elapsed is a tick-count accumulator (ticks × interval), not wall-clock
Buttonnew(string $label)One-line [ Label ] push button — a SugarCraft original; withFocused() / withDisabled() / withStyles() / withZoneManager(); Enter, Space or a click on its sugar-mouse zone makes update() return a Cmd yielding a ButtonPressedMsg; a disabled button is inert
Rulenew(int $length = 0)Horizontal or vertical divider (vertical()), optional withTitle(), withRune() (one cell), withStyle() — a SugarCraft original; length 0 = auto (40 cells), unstyled output has no SGR
Helpnew(separator, keyDescGap, columnGap, showAll, maxWidth, ellipsis, fullSeparator, styles)Keybinding help overlay — all params optional; withKeyDescGap() / withColumnGap() / withWidth() return new instances
PaginatorwithTotalPages(int)Set page count directly (converts via perPage); setTotalPages() is the deprecated spelling
TabswithZoneManager(?Manager)Mouse-zone opt-in — zones are emitted only when a supplied sugar-mouse Manager is attached; passing null detaches it again
TabswithZoneKey(string $key)Pins the bar's zone-id prefix. Bars derived from one template share its key, so give each bar its own withZoneKey() when they share a sugar-mouse Manager. Keys must be non-empty and unique per manager (an empty key throws \InvalidArgumentException).
OptionRowrenderRow(...)One-line btop options row sized to the field width — the primary API
TextEditnew(text, ?caret, numeric)Immutable inline editor (btop Draw::TextEdit); underline caret, grapheme-cluster caret
TextEditleft() / right() / home() / end() / withCaret(int)Caret movement (clamped)
TextEditinsert(string) / backspace() / delete() / clear()Edits; numeric mode rejects non-digit input
TextEditwithNumeric(bool)Digits-only mode — strips existing non-digits
TextEditview(int $limit = 0)Render with SGR 4 underline caret, windowed to $limit display cells
OptionRowrender(name, value, selected, editing, hasArrows, …)btop options-menu two-line row (bold centered name + ← value → / ↵) (deprecated — use renderRow() for the width-correct single-line row)
FilePickernew(?string $cwd = null, int $height = 10)Create file picker — cwd optional (defaults to the process cwd), height in rows (deprecated alias — depend on sugarcraft/sugar-forms)
ItemListnew(items)Create selectable item list; items are Item/StringItem values (deprecated alias — depend on sugarcraft/sugar-forms)

Demos.

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

Spinner gallery All 12 spinner styles ticking in parallel.
TextInput

TextInput

Single-line input with autocomplete + placeholder.
text-input-enhanced

Enhanced TextInput

Custom placeholder styling, prefix and suffix variants.
TextArea

TextArea

Multi-line editor with line numbers + soft-wrap.
ItemList

ItemList

Filterable scrollable list with status messages.
Table

Table

Selectable data table with per-cell styleFunc + sort/filter/pagination.
Tree

Tree

Interactive tree — cursor, expand / collapse, scroll.
Viewport

Viewport

Scrollable text region with mouse wheel + scrollbar.
FilePicker

FilePicker

Directory browser with icons + size + sort.
Progress

Progress

Progress bars driven by the example loop — percent labels, gradients and render modes (AnimatedProgress adds the spring physics).
Cursor

Cursor

Animated text cursor with BlinkMsg tick.
Help

Help

Short / full key-help footer from a KeyMap.
Paginator

Paginator

Dot + arabic page indicator.
Stopwatch

Stopwatch

Elapsed-time counter.
Timer

Timer

Countdown timer.