SugarWidgets
Ready-made TUI components — tables, tabs, progress bars, spinners, and more
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
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by bubbles (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| TextInput | new() | Create a new text input instance (deprecated alias — depend on sugarcraft/sugar-forms) |
| TextInput | update(Msg) | Handle input events |
| TextInput | withValidateOn(ValidateOn) | Set validation timing — None (default) and Change validate on every edit; Blur and Submit defer validation |
| TextInput | withRestrict(string $pattern) | PCRE regex filter — only matching keystrokes are accepted |
| ValidateOn | enum | Cases: None (default) / Change — validate on every edit; Blur / Submit — deferred until focus loss or submit |
| TextArea | new() | Create a multi-line text area (deprecated alias — depend on sugarcraft/sugar-forms) |
| Spinner | new(?Style $style = null) | Create spinner; style optional (defaults to line) (deprecated alias — depend on sugarcraft/sugar-forms) |
| Spinner | tick() | Return tick command for animation |
| Table | new(headers, rows) | Create data table |
| Table | withSort(string $column, SortDirection $dir = Asc) | Set primary sort column and direction — clears prior sort chain |
| Table | thenSortBy(string $column, SortDirection $dir = Asc) | Add secondary (or further) sort tiebreaker |
| Table | clearSort() | Remove all sort criteria, restoring insertion order |
| Table | sortState(): SortState | Return current sort criteria (readonly) |
| Table | styleFunc(?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 |
| Table | getStyleFunc(): ?Closure | Return the current composer (seam for host-side re-composition) |
| Table | withFilterable(bool) | Enable or disable the filter feature |
| Table | withFilter(string $query) | Set filter query string — default: case-insensitive substring match on all visible columns |
| Table | withFilterPredicate(?Closure(list<string>): bool) | Custom filter callable — null restores the default |
| Table | filterable(): bool | Return whether filtering is enabled |
| Table | filter(): string | Return the current filter query string |
| Table | filterPredicate(): ?Closure | Return the current custom filter predicate |
| SortDirection | enum | Cases: Asc / Desc — use toggle() to flip direction |
| SortState | DTO | Immutable list of (column index, SortDirection) pairs |
| Table | withPageSize(int $size) | Set rows per page — 0 disables pagination, ≥1 enables it |
| Table | withPage(int $page) | Navigate to a zero-based page (clamps to valid range) |
| Table | nextPage() | Advance one page — returns new Table |
| Table | prevPage() | Retreat one page — returns new Table |
| Table | pageFirst() | Jump to the first page — returns new Table |
| Table | pageLast() | Jump to the last page — returns new Table |
| Table | pageSize(): int | Return rows per page (0 = pagination disabled) |
| Table | currentPage(): int | Return the current zero-based page |
| Paginator | totalPages(): int | Return total page count (via the table's paginator) |
| Table | paginator(): Paginator | Return a Paginator wired to the table's current page state |
| Tree | new(Node ...$roots) | Create tree view from root nodes via the Tree::new() factory — immutable-fluent; the constructor itself is private |
| Tree | withStyle(...) | Immutable override of the chrome knobs — cursorPrefix / unselectedPrefix / expandedGlyph / collapsedGlyph / leafGlyph (sanitized to single-line) |
| Viewport | new(width = 80, height = 24) | Create scrollable viewport; content arrives via setContent(string) (deprecated alias — depend on sugarcraft/sugar-forms) |
| Progress | new(ratio) | Create progress bar from a 0.0–1.0 ratio (clamped; NaN renders 0%) |
| Progress | withPercent(float) | Return a new bar at the given ratio (same clamp; accepts NaN → 0%) |
| Progress | withColorFunc(?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 |
| Progress | withRenderMode(ProgressRenderMode) | Switch the glyph set — Block / Line / Slim render modes |
| Progress | withPercentFormat(string $fmt) | Custom % suffix printf format receiving the 0–100 integer (default '%3d%%') |
| Timer | new(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 |
| Stopwatch | new(float $interval = 1.0) | Count-up; elapsed is a tick-count accumulator (ticks × interval), not wall-clock |
| Button | new(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 |
| Rule | new(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 |
| Help | new(separator, keyDescGap, columnGap, showAll, maxWidth, ellipsis, fullSeparator, styles) | Keybinding help overlay — all params optional; withKeyDescGap() / withColumnGap() / withWidth() return new instances |
| Paginator | withTotalPages(int) | Set page count directly (converts via perPage); setTotalPages() is the deprecated spelling |
| Tabs | withZoneManager(?Manager) | Mouse-zone opt-in — zones are emitted only when a supplied sugar-mouse Manager is attached; passing null detaches it again |
| Tabs | withZoneKey(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). |
| OptionRow | renderRow(...) | One-line btop options row sized to the field width — the primary API |
| TextEdit | new(text, ?caret, numeric) | Immutable inline editor (btop Draw::TextEdit); underline caret, grapheme-cluster caret |
| TextEdit | left() / right() / home() / end() / withCaret(int) | Caret movement (clamped) |
| TextEdit | insert(string) / backspace() / delete() / clear() | Edits; numeric mode rejects non-digit input |
| TextEdit | withNumeric(bool) | Digits-only mode — strips existing non-digits |
| TextEdit | view(int $limit = 0) | Render with SGR 4 underline caret, windowed to $limit display cells |
| OptionRow | render(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) |
| FilePicker | new(?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) |
| ItemList | new(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
Single-line input with autocomplete + placeholder.
Enhanced TextInput
Custom placeholder styling, prefix and suffix variants.
TextArea
Multi-line editor with line numbers + soft-wrap.
ItemList
Filterable scrollable list with status messages.
Table
Selectable data table with per-cell styleFunc + sort/filter/pagination.
Tree
Interactive tree — cursor, expand / collapse, scroll.
Viewport
Scrollable text region with mouse wheel + scrollbar.
FilePicker
Directory browser with icons + size + sort.
Progress
Progress bars driven by the example loop — percent labels, gradients and render modes (AnimatedProgress adds the spring physics).
Cursor
Animated text cursor with BlinkMsg tick.
Help
Short / full key-help footer from a KeyMap.
Paginator
Dot + arabic page indicator.
Stopwatch
Elapsed-time counter.