SugarFlexbox
FlexBox layout + delta Table + sticky Viewport + Scrollbar
SugarFlexbox is a layout toolkit for terminal cell grids. It has a ratio-based FlexBox engine, a sortable and filterable model Table with delta rendering, a scrolling Viewport with sticky rows, and a Scrollbar. Viewport and Scrollbar are thin compositions of the canonical sugar-forms classes. The full keyboard-driven data grid belongs to sugar-table. SugarFlexbox is the lighter layout layer beside it.
Install
composer require sugarcraft/sugar-flexbox
Requires PHP 8.3 or newer. Composer pulls in sugarcraft/sugar-core, sugarcraft/sugar-forms and sugarcraft/sugar-cellbuffer. The layout classes need nothing beyond those. TableRenderer uses the cellbuffer for delta rendering.
Quickstart
use SugarCraft\Flexbox\Flex\{FlexBox, FlexItem};
use SugarCraft\Flexbox\Flex\Align;
use SugarCraft\Flexbox\Table\{Table, Column};
$flex = FlexBox::row(
FlexItem::new('LEFT')->withRatio(1),
FlexItem::new('RIGHT')->withRatio(2),
)->withGap(2);
$table = Table::new()
->withColumn(Column::new('Name', 20))
->withColumn(Column::new('Age', 5)->withAlign(Align::End))
->withRow(['Alice', '30'])
->withRow(['Bob', '25'])
->withSort(0);
echo $flex->render(40, 1), PHP_EOL;
echo $table->render(), PHP_EOL;
The FlexBox shares the 38 cells left after the 2-cell gap between its two items in a 1:2 ratio. The table sorts by its first column and right-aligns the Age column. Both calls return strings, so nothing is written to the terminal until you echo them.
Concepts
Every class is an immutable value. Each with*() method returns a new instance and leaves the receiver unchanged. Plain constructor state is a public readonly property, such as Column->title or FlexItem->ratio. Anything derived or guarded is read through a method, such as Table::cursor() or Viewport::yOffset(). The methods are where the settle-and-refuse logic lives.
FlexBox sizes items on one main axis. A basis reserves a fixed number of cells first. The leftover cells are shared by ratio, and an item with ratio 0 keeps its 1-cell floor. Align places items across the cross axis, where Stretch fills the box. Justify and Wrap handle spacing and line breaks along the main axis.
Table renders text. Cell values and column titles are sanitized as untrusted data. render() returns the full frame. TableRenderer keeps the last frame and emits only the rows that changed, which keeps repaints small. Table never wraps: a grid wider than the terminal stays wide, and you scroll it inside a Viewport.
Viewport is a scrolling window over text. It keeps the first or last rows pinned with sticky headers and footers. Its key and mouse handling come from sugar-forms.
Tasks
Split a row by ratio with a fixed sidebar. Give the sidebar a basis and the content a ratio. The basis is taken first and the ratio shares what remains:
$row = FlexBox::row(
FlexItem::new($sidebar)->withBasis(20),
FlexItem::new($content)->withRatio(1),
)->withGap(1);
echo $row->render(100, 24), PHP_EOL;
Sort, then filter, a table. Sort first, then filter. A filter that drops the cursor row moves the cursor to row 0:
$table = Table::new()
->withColumn(Column::new('Name', 16))
->withColumn(Column::new('Score', 6)->withAlign(Align::End))
->withRow(['Mira', '91'])
->withRow(['Oren', '78'])
->withSort(1, false) // column 1, descending
->withFilter('o'); // case-folded substring match
echo $table->render(), PHP_EOL;
Mark the cursor row without color. A cursor style is an SGR string, and a screen reader does not hear color. Add a glyph prefix as well, and read cursor() when focus moves:
$table = $table
->withFilter('') // lift the filter from the Task above
->withCursorStyle('7') // SGR parameter 7: reverse video
->withCursorMarker('> ')
->withCursor(1);
$index = $table->cursor(); // int|null: the settled row index
Redraw only the changes. Use one TableRenderer for the life of the screen. The first frame, and every resized frame, is full. After that only the changed rows are emitted:
use SugarCraft\Flexbox\Table\TableRenderer;
$renderer = TableRenderer::new();
echo $renderer->render($table); // first frame: full
echo $renderer->render($table); // unchanged: no bytes (the delta is empty)
Scroll a long document with a sticky header. Pin the first row, then scroll the rest with the keys in the Keys and controls section:
use SugarCraft\Flexbox\Viewport;
$vp = Viewport::fromContent($document, width: 80, height: 20)
->withStickyHeader(1)
->withSmoothScroll(false) // reduced motion: each scroll settles in one frame
->gotoTop();
What's in the box
Align (Start, Center, End, Stretch) drives both axes, and Justify and Wrap add main-axis spacing and wrapping. There is no CSS justify-content equivalent for the cross axis.Column::sorted()). Filter by a case-folded substring. Cursor navigation is guarded at its door. Each column can carry its own style, and a column can be hidden at width 0. The ruler is themeable. An over-wide grid is reported by computeTotalWidth(), and render() never wraps it.withStickyHeader() and withStickyFooter(). withLinkedViewport() only marks a partner. Scroll state is not shared.API
| Call | Signature | Description |
|---|---|---|
| FlexBox::row() | row(FlexItem ...$items): self | Create a horizontal flexbox. |
| FlexBox::column() | column(FlexItem ...$items): self | Create a vertical flexbox. |
| FlexBox::withGap() | withGap(int $cells): self | Set the gap between items. |
| FlexBox::withAlign() | withAlign(Align $a): self | Set the alignment. It takes the enum, not a string. |
| FlexBox::withJustify() | withJustify(Justify $justify): self | Set main-axis spacing (SpaceBetween, SpaceAround, SpaceEvenly and others). |
| FlexBox::withWrap() | withWrap(Wrap $wrap): self | Enable or disable wrapping onto new lines. |
| FlexBox::withDirection() | withDirection(Direction $d): self | Set the main axis (row or column). |
| FlexBox::render() | render(int $totalWidth, int $totalHeight): string | Lay out the items inside the given box and return the frame. |
| FlexItem::new() | new(string $content = ''): self | Create a flex item. |
| FlexItem::withRatio() | withRatio(int $ratio): self | Growth weight for the leftover main-axis space. 0 never grows and keeps a 1-cell floor. |
| FlexItem::withBasis() | withBasis(int $basis): self | Fixed main-axis reservation, taken before ratios share the rest. |
| FlexItem::withWidth() | withWidth(int $width): self | Deprecated alias of withBasis(). In column mode the reserved axis is the height, so prefer withBasis(). |
| Table::new() | new(): self | Create an empty table. |
| Table::withColumn() | withColumn(Column $col): self | Add a column. addColumn() is the deprecated spelling. |
| Table::withRow() | withRow(array $values): self | Add a row. A surplus value throws at the door. |
| Table::withSort() | withSort(int $colIndex, bool $ascending = true): self | Sort by a column. The selection follows its row through the re-sort. |
| Table::sortByNext() | sortByNext(int $colIndex): self | Toggle ascending and descending on a column. |
| Table::withFilter() | withFilter(string $text): self | Keep rows with a case-folded substring match in any cell. A selection whose row is filtered away falls back to row 0. |
| Table::clearFilter() | clearFilter(): self | Remove the filter. |
| Table::withCursor() | withCursor(int $rowIndex): self | Move the cursor. The door settles the view and refuses an index outside it. |
| Table::cursor() | cursor(): ?int | Cursor index of the settled view. null only while the view has no rows. |
| Table::rawCurrentRow() | rawCurrentRow(): ?array | Stored values of the cursor row, unrendered. |
| Table::rawCurrentCell() | rawCurrentCell(int $colIndex): ?string | One stored cell under the cursor, unrendered. |
| Table::computeTotalWidth() | computeTotalWidth(): int | The full width of the grid. Use it to decide whether a Viewport is needed. |
| Table::withCursorStyle() | withCursorStyle(string $ansiStyle): self | SGR string for the cursor row. The default is an empty string, which marks nothing on screen. |
| Table::withCursorMarker() | withCursorMarker(string $prefix): self | A non-color focus glyph drawn inside the first column's width. |
| Table::withEmptyText() | withEmptyText(?string $text): self | Row spanning the grid when a filter drops every row. |
| Table::withVisibleRange() | withVisibleRange(int $from, ?int $to = null): self | Limit the rendered rows to a range. |
| Table::render() | render(): string | The full frame, pure and stateless. Use TableRenderer for deltas. |
| TableRenderer::new() | new(): self | Create a renderer that keeps the previous frame. |
| TableRenderer::render() | render(Table $table): string | The first and resized frames in full, then only the changed rows. |
| TableRenderer::reset() | reset(): void | Forget the previous frame so the next render is full. |
| Column::new() | new(string $title, int $width): self | Create a column. Its width is in cells. |
| Column::withAlign() | withAlign(Align|string $align): self | Set Start, Center or End. Stretch is FlexBox sizing language and is refused here. |
| Column::withStyle() | withStyle(string $ansiStyle): self | SGR string applied to every cell of the column. The cursor style paints over it. |
| Column::sorted() | sorted(int $direction = 1, int $priority = 0): self | Mark the column as a sort key, with an optional tiebreak priority. |
| Viewport::new() | new(int $width = 80, int $height = 24): self | Create an empty viewport. |
| Viewport::fromContent() | fromContent(string $content, int $width = 80, int $height = 24): self | Create a viewport over a string. |
| Viewport::withStickyHeader() | withStickyHeader(int $rows): self | Pin the first rows across scrolling. A negative count throws. |
| Viewport::withStickyFooter() | withStickyFooter(int $rows): self | Pin the last rows across scrolling. A negative count throws. |
| Viewport::withSmoothScroll() | withSmoothScroll(bool $enable = true): self | Reduced-motion switch. When off, each scroll settles in one frame. |
| Viewport::withMouseWheelEnabled() | withMouseWheelEnabled(bool $on): self | Accept mouse-wheel scroll messages. |
| Viewport::withMouseWheelDelta() | withMouseWheelDelta(int $delta): self | Lines the wheel scrolls per notch. |
| Viewport::showScrollbar() | showScrollbar(bool $on = true): self | Show or hide the scrollbar. |
| Viewport::lineUp() | lineUp(int $n = 1): self, lineDown(int $n = 1): self | Scroll by lines. |
| Viewport::pageUp() | pageUp(): self, pageDown(): self, halfPageUp(): self, halfPageDown(): self | Scroll by a page or half a page. |
| Viewport::gotoTop() | gotoTop(): self, gotoBottom(): self | Jump to the first or last line. |
| Viewport::update() | update(Msg $msg): array | Apply a key or mouse message and return the new viewport and any command. |
| Scrollbar::vertical() | vertical(): self, horizontal(): self | Create a vertical or horizontal scrollbar. |
| Scrollbar::view() | view(ScrollbarState|array $state, int $height): string | Render the scrollbar for a scroll state. |
Only methods declared in sugar-flexbox/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Flexbox
Lang final class
Per-library translation facade for sugar-flexbox.
Scrollbar final readonly class
Immutable scrollbar wrapper over the canonical FormsScrollbar.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static vertical(): self | Vertical scrollbar with defaults (░ track, █ thumb, ▲▼ arrows). |
static horizontal(): self | Horizontal scrollbar with defaults (░ track, █ thumb, no arrows). |
withTrackChar(string $char): self | |
withThumbChar(string $char): self | |
withArrows(bool $show): self | |
widgetScrollbar(): FormsScrollbar | The canonical forms scrollbar this wrapper delegates to (FBX-20: named directly, no alias hop). Needed so Viewport::withVerticalScrollbar() can accept THIS lib's Scrollbar and unwrap it — the wrapper is opaque to the forms delegate otherwise. The method name keeps its historical spelling: renaming a public accessor is vocabulary-owner territory. |
view(ScrollbarState|array $state, int $height): string | Render the scrollbar into $height rows. |
Viewport final readonly class
Immutable viewport wrapper over the canonical FormsViewport.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static new(int $width = 80, int $height = 24): self | Construct with default dimensions (80×24). |
static fromContent(string $content, int $width = 80, int $height = 24): self | Construct a content-carrying viewport. The factory verb is fromContent() (FBX-22): the old name read as the fluent with*Content setter and PHP happily resolved \$vp->withContent() to the static — silently rebuilding an 80×24 box and discarding the receiver's geometry. Instance content changes are self::withContent() (the instance setter, FBX-06 — the retired static BC seat of that name is gone, so a static call now fails with the engine's own "non-static method" Error). |
withStickyHeader(int $rows): self | Pin the FIRST $rows lines as a sticky header region. The count is an ARGUMENT POLICY door (FBX-30): negative refuses loudly naming the value — a silent clamp-to-0 here while Viewport::new() refuses a negative dimension was three-way inconsistency in one class. 0 is legal and means 'no sticky region'; the render-time cap to what the height can show stays a GEOMETRY clamp (lines 240/252 era pins), not an argument judgement. |
withStickyFooter(int $rows): self | Pin the LAST $rows lines as a sticky footer region. The count is an ARGUMENT POLICY door (FBX-30): negative refuses loudly naming the value — a silent clamp-to-0 here while Viewport::new() refuses a negative dimension was three-way inconsistency in one class. 0 is legal and means 'no sticky region'; the render-time cap to what the height can show stays a GEOMETRY clamp (lines 240/252 era pins), not an argument judgement. |
withLinkedViewport(Viewport $other): self | Record $other as this viewport's LINKED viewport. |
hasLinkedViewport(): bool | True when a self::withLinkedViewport() partner is attached. |
syncWith(Viewport $other): self | |
isSynced(): bool | |
init(): ?\Closure | Forward to the canonical forms viewport. |
update(Msg $msg): array | |
subscriptions(): ?Subscriptions | |
view(): string | |
withContent(string $content): self | Returns a new Viewport; the receiver is unchanged (fluent house law). |
setContent(string $content): self | BC forwarder onto the single content spelling. |
withSize(int $width, int $height): self | Resize — THE single sizing spelling of this lib (FBX-06). Returns a new Viewport; the receiver is unchanged (fluent house law). Unlike FlexBox::render()'s clamp-tolerant geometry, the forms delegate THROWS InvalidArgumentException on a negative dimension — see the README argument policy. |
setWidth(int $width): self | BC forwarder onto the single sizing spelling. |
setHeight(int $height): self | BC forwarder onto the single sizing spelling. |
width(): int | |
height(): int | |
getWidth(): int | BC forwarder for the pre-rename accessor name. |
getHeight(): int | BC forwarder for the pre-rename accessor name. |
withYOffset(int $offset): self | Returns a new Viewport; the receiver is unchanged (fluent house law). |
setYOffset(int $offset): self | BC forwarder onto self::withYOffset(). |
yOffset(): int | |
withXOffset(int $offset): self | Returns a new Viewport; the receiver is unchanged (fluent house law). |
setXOffset(int $offset): self | BC forwarder onto self::withXOffset(). |
xOffset(): int | |
withHorizontalStep(int $step): self | |
withMouseWheelEnabled(bool $on): self | |
withMouseWheelDelta(int $delta): self | |
showScrollbar(bool $on = true): self | Toggle the scrollbar column on/off. |
withScrollbar(bool $on = true): self | BC forwarder for the pre-rename toggle name. |
withScrollbarRunes(string $thumb, string $track): self | |
withVerticalScrollbar(Scrollbar $scrollbar): self | Attach the lib's own Scrollbar component and render it. |
withSmoothScroll(bool $enable = true): self | |
lineUp(int $n = 1): self | |
lineDown(int $n = 1): self | |
halfPageUp(): self | |
halfPageDown(): self | |
pageUp(): self | |
pageDown(): self | |
scrollLeft(int $n = 1): self | |
scrollRight(int $n = 1): self | |
gotoTop(): self | |
gotoBottom(): self | |
totalLineCount(): int | |
visibleLineCount(): int | |
atTop(): bool | |
atBottom(): bool | |
atLeftmost(): bool | |
atRightmost(): bool | |
scrollPercent(): float | |
horizontalScrollPercent(): float |
SugarCraft\Flexbox\Flex
Align enum
Item alignment within a FlexBox.
Cases: Start · Center · End · Stretch
PHP also provides cases().
Direction enum
FlexBox main-axis direction — equivalent to CSS flex-direction.
Cases: Row · Column
PHP also provides cases().
FlexBox final readonly class
CSS flexbox-like layout for terminal UIs.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static row(FlexItem ...$items): self | |
static column(FlexItem ...$items): self | |
withDirection(Direction $d): self | |
withAlign(Align $a): self | |
withGap(int $cells): self | |
withJustify(Justify $justify): self | Distribute leftover main-axis cells (see Justify). Leftover exists only where no ratio item absorbs it, as in CSS. |
withWrap(Wrap $wrap): self | Break a row-direction box onto further lines when its items overflow the width (see Wrap). Column boxes ignore it. |
addItem(FlexItem $item): self | Append one item. |
withItems(FlexItem ...$items): self | Bulk path: replace the whole item list in a single copy. Building N items with chained addItem() calls is O(N²) in list copies; withItems() is the O(N) construction the row()/column() factories use. |
render(int $totalWidth, int $totalHeight): string | Render the FlexBox into a string within the given viewport. |
FlexItem final class
A single item inside a FlexBox.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
lines(): array | The raw content split on newlines, once per instance. |
measuredWidth(): int | Natural content width — the widest raw line, measured on the UNSWEPT string (the renderer sanitizes per line later; see the "Trust boundary" disclosure). Cached: content is fixed at construction, so this is pure derivation with a safe memo. |
measuredHeight(): int | Natural content height — the raw line count (same raw-measurement ingress as measuredWidth()). Cached. |
static new(string $content = ''): self | |
withContent(string $content): self | |
withRatio(int $ratio): self | |
withBasis(int $basis): self | |
withStyle(string $ansiStyle): self | |
withWidth(int $width): self | Alias of withBasis(): the fixed MAIN-AXIS reservation. The name is row-flavoured — in a column box this same value is the item's HEIGHT in cells, not its width — which makes it an orthographic trap (finding-065: direction-flipping names lie in half the modes). |
Justify enum
Main-axis distribution of leftover cells in a FlexBox.
Cases: Start · End · Center · SpaceBetween · SpaceAround · SpaceEvenly
PHP also provides cases().
Wrap enum
Whether a row-direction FlexBox breaks its items onto further lines.
Cases: NoWrap · Wrap
PHP also provides cases().
SugarCraft\Flexbox\Support
CellPad final class
Combined fit-then-pad for the render loops (finding-040).
| Method | Summary |
|---|---|
static fit(string $line, int $cells): array | The line, truncated to at most $cells display cells, plus its EXACT cell width — the one measurement callers should ever make. |
static pad(string $line, int $knownWidth, int $cells, string $side): string | Pad a line of KNOWN width to exactly $cells on $side without re-measuring. Distribution matches core's padCenter to the space: an odd gap sends the surplus to the right. |
Sgr final class
Shared validation + canonicalization door for SGR parameter strings.
| Method | Summary |
|---|---|
static normalize(?string $value, string $property): ?string | Validate an SGR parameter string and return its canonical (semicolon grammar) form. |
SugarCraft\Flexbox\Table
Column final class
Column definition for a Table.
| Method | Summary |
|---|---|
static new(string $title, int $width): self | |
static make(string $title, int $width): self | |
withAlign(Align|string $align): self | Place cells of this column. The SHARED vocabulary is the Align enum (FBX-25) — the same cases FlexBox::withAlign() takes — and the legacy 'left'/'right'/'center' strings still ride through a coercion at the door; they retire with 2.0.0. Anything outside both spellings throws (they used to fall through to 'left' silently). |
static alignOf(Align|string $align): string | Resolve either alignment vocabulary to the renderer's padding string. Start/Center/End map onto left/center/right; Stretch is FlexBox sizing language with no cell meaning here and refuses. |
withStyle(string $ansiStyle): self | Set the SGR style applied to every data cell of this column at render (the cursor style is painted OVER this one on a cursor row — see Table::buildLines() — so the selected row stays visually dominant). |
withFormatter(callable $fn): self | Attach a cell formatter: fn(string $storedValue, int $rowIndex) answering string or null (null keeps the raw value). The answer is checked at format time and a non-string return refuses with this column's title (FBX-35): an array would have silently became 'Array' under the old cast and a plain object died a stack-trace away from the offending formatter. |
sorted(int $direction = 1, int $priority = 0): self | Author this column as a sort key. The direction is NORMALIZED to the header-arrow contract: > 0 renders as +1 (ascending), < 0 as -1 (descending), 0 clears the marker. |
unsorted(): self | |
format(string $value, int $rowIndex): string | |
padded(string $value, int $rowIndex): string | |
sortDir(): int | |
sortPriority(): int |
Table final class
Sortable, filterable data table renderer.
| Method | Summary |
|---|---|
static new(): self | |
withColumn(Column $col): self | Returns a new Table with $col appended; receiver unchanged. |
addColumn(Column $col): self | |
withRow(array $values): self | Returns a new Table with one more row (values are matched to columns by index). |
addRow(array $values): self | |
withSort(int $colIndex, bool $ascending = true): self | Sort rows by column index. |
sortBy(int $colIndex, bool $ascending = true): self | |
sortByNext(int $colIndex): self | Toggle sort direction on column, or start ascending if different column. |
withFilter(string $text): self | Filter rows by text (Unicode case-folded substring match: 'ärger' finds 'Ärger' and 'strasse' finds 'Straße'; full accent folding too when ext-intl is loaded). |
filter(string $text): self | |
clearFilter(): self | |
withCursor(int $rowIndex): self | Move the cursor to $rowIndex of the materialized view. |
setCursor(int $rowIndex): self | |
withCursorStyle(string $ansiStyle): self | |
withCursorMarker(string $prefix): self | Non-colour focus marker prepended to the cursor row's first cell. |
withHeaderStyle(string $ansiStyle): self | |
withSeparator(string $s): self | Set the cell separator. The string is rendered raw between every pair of cells, so it is sanitized at ingress exactly like data cells: control sequences cannot ride the separator into the terminal (ruler jointing then measures the sanitized display width). |
withRulerChars(string $fill, string $joint): self | Theme the ruler's two runes: the horizontal fill and the column joint (default '─' / '┬', byte-identical to every frame ever rendered). ASCII-themed tables mixed unicode rulers under ASCII separators until the ruler characters rode the same ingress as the separator: sanitized, and STRICTLY one cell — a multi-cell or zero-cell rune would desync the ruler line from the header width arithmetic that FBX-16/FBX-34 welded together, so the door refuses anything but a single-cell grapheme, loudly and by name. |
withEmptyText(?string $text): self | Paint a spanning row when a filter ate every row (FBX-41). |
withVisibleRange(int $from, ?int $to = null): self | |
rowCount(): int | |
colCount(): int | |
totalRowCount(): int | Rows SUPPLIED, before any filter or window: totalRowCount() > 0 with rowCount() === 0 is the 'no match' state; totalRowCount() being 0 is plain 'no data'. The pair is what lets an app paint its own empty-state row with different copy (FBX-41). |
filterText(): string | The active filter text ('' when unfiltered). |
columns(): array | The column roster, index-addressed exactly as the sort keys and header render see it. |
cursor(): ?int | The cursor's index in the materialized view, settling any pending sort/filter first — the same law as rawCurrentRow(). Null means the index addresses no visible row: with FBX-26's refused out-of-range cursors and the follow-its-row re-sort, the only reachable case is an empty view holding the default index 0. |
rawCurrentRow(): ?array | The cursor row of the MATERIALIZED view, RAW: a pending sort or filter is settled first, so this always answers about what render() would show, not about the stale last-settled frame. Null when the view has no rows at all — an out-of-range cursor cannot exist to fall off (withCursor() refuses it, and re-sorts carry the selection with its row), so the empty view is the one honest null source. |
rawCurrentCell(int $colIndex): ?string | One cell under the cursor, RAW like self::rawCurrentRow() — the stored string with no sweep applied — or null when the cursor is off the view or the column index is out of range. |
currentRow(): ?array | |
currentCell(int $colIndex): ?string | |
render(): string | Render the table to a full string (always full frame, never delta). |
buildLines(): array | Build all rendered lines (header, separator, data rows). |
computeTotalWidth(): int | Total display width of a rendered line, in CELLS: column widths plus the separator's display width at every joint. Byte counting the separator (strlen) over-reported any non-ASCII joint — ' │ ' is 5 bytes but 3 cells — and zero columns used to yield a negative total from the (n - 1) joint term. |
TableRenderer final class
Stateful diff renderer for Table.
| Method | Summary |
|---|---|
static new(): self | The house factory shape. The implicit public constructor stays available until 2.0.0, when new() becomes the only door. |
render(Table $table): string | Render the table, emitting a full frame or a delta depending on whether dimensions have changed since the last frame. |
reset(): void | Reset the diff state, forcing the next render to emit a full frame. |
Configuration and options
The library reads no configuration file and no environment variables. Its options are builder calls. Each one returns a new instance.
| Option | Type | Default | Effect |
|---|---|---|---|
FlexBox::withGap() | int, cells | 0 | Space between adjacent items. |
FlexBox::withAlign() | Align | Align::Stretch | Placement of items. In row mode Stretch fills the box height. In column mode it uses the rendered width. |
FlexItem::withRatio() | int, at least 0 | 1 | Share of the leftover main-axis space. 0 never grows. |
FlexItem::withBasis() | int, at least 0 | 0 | Fixed reservation, clamped to the container at render time. |
Column::withAlign() | Align (Start, Center, End) | Start | Horizontal alignment of the column's cells. |
Table::withCursorStyle() | SGR string | empty string | Style for the cursor row. Empty marks nothing on screen. |
Table::withCursorMarker() | string | none | Glyph drawn inside the first column for focus. |
Table::withEmptyText() | ?string | null | Message shown when a filter removes every row. |
Viewport::withStickyHeader() | int, rows | 0 | Rows pinned at the top while the rest scrolls. |
Viewport::withSmoothScroll() | bool | false | Off settles every scroll in one frame. Turn it on to animate scrolls. |
Viewport::withMouseWheelDelta() | int, lines | 3 | Lines moved per wheel notch. |
Viewport::withMouseWheelEnabled() | bool | true | Scroll the viewport on wheel notches, three lines each by default. false ignores the wheel. The terminal reports wheel notches only when the program enables mouse reporting, such as new ProgramOptions(mouseMode: MouseMode::CellMotion). |
Keys and controls
Only Viewport reads keys. It inherits its bindings from sugar-forms, so the keys below work in any program that passes messages to Viewport::update(). Table and FlexBox have no key handling. Your program moves the cursor with withCursor().
| Key | Action |
|---|---|
↑ / k | Scroll up one line. |
↓ / j | Scroll down one line. |
← / h | Scroll left. |
→ / l | Scroll right. |
PageUp / b | Scroll up one page. |
PageDown / f / Space | Scroll down one page. |
| Ctrl+u / Ctrl+d | Scroll up or down half a page. |
Home / g | Jump to the top. |
End / G | Jump to the bottom. |
Mouse-wheel scrolling is on by default, and each wheel notch scrolls three lines. The terminal reports wheel notches only when the program enables mouse reporting, such as new ProgramOptions(mouseMode: MouseMode::CellMotion); with the default options no wheel message reaches Viewport::update(). Pass withMouseWheelEnabled(false) to turn it off, and withMouseWheelDelta() to change the step. examples/viewport-keys.php drives the full key set.
Theme and styling
Styles are SGR parameter strings, not theme objects. Pass them to Column::withStyle(), Table::withCursorStyle() and Table::withHeaderStyle(). The ruler characters come from Table::withRulerChars(), and the column separator from Table::withSeparator(). The cursor style paints over a column style. Validated SGR that you pass in is emitted as given. The library does not read NO_COLOR or TERM, so color policy belongs to your host program.
Examples
examples/flexbox.php: a ratio row and a stacked column with a gap.examples/table.php: a sortable and filterable table with per-column widths and right-aligned numbers.examples/sort-filter.php: sort and cursor movement, with a readout ofrawCurrentRow().examples/viewport-keys.php: a 60-line log in a 6-row viewport, driven entirely by keys.
php examples/flexbox.php
php examples/table.php
php examples/sort-filter.php
php examples/viewport-keys.php
flexbox.php, table.php and sort-filter.php each print a short run of frames (three, four and five) and exit. viewport-keys.php prints its frames as it runs, so pipe it through a pager or read it in a terminal.
Testing
composer install
vendor/bin/phpunit
The suite covers the layout math (FlexboxTest, FlexBoxColumnTest, JustifyTest, WrapTest), the table and its renderer (TableTest, TableRendererTest, ColumnTest), the viewport and scrollbar (StickyViewportTest, ScrollbarTest, ViewportQueryTest), and the SGR and sanitizer doors (SgrDoorTest, UntrustedSanitizerC1Test). ReadmeSnippetsTest and ReadmeTruthPinsTest pin the README's examples and claims to the code.
Trust boundary
Table and Column treat everything they render as untrusted data: cell values and column titles pass through Sanitize::untrusted(), and at render time a line feed or a CRLF pair collapses to a single space, a tab becomes a single space, and a lone carriage return is DELETED (not replaced) — so no escape sequence can ride in through content. FlexBox runs the same sanitizer on each item line, but it splits an item at its line feeds first, so a multi-line item takes one row per line instead of collapsing; its tabs and lone carriage returns are handled as above. One asymmetry to know about: the FlexBox measures an item's raw content before the sweep, and only the tab skews the budget (it measures four cells and prints one space — over-allocation, never a truncation); every other swept byte measures zero cells on both sides. Style strings are gated to legal SGR parameter text (codes 0..255 separated by single ;, colon sub-parameters normalized at the door) or empty for no style; anything else throws InvalidArgumentException naming the refused property. Viewport and Scrollbar are trusted-input by design — the Viewport renders your setContent() / fromContent() lines as given and the Scrollbar emits your runes verbatim — so sanitize user input before feeding them.
Accessibility
Focus is never carried by color alone. The cursor row has no visible cue by default. Set withCursorMarker() to prepend a glyph inside the first column's width without moving frame dimensions, and withCursorStyle() to style the row. A screen reader announces neither color nor shape, so pair the visual cue by reading cursor()/rawCurrentRow() on every change. Sort state is a glyph (▲/▼), not a color; a filtered-to-nothing table can say so with withEmptyText() over totalRowCount()/filterText().
Reduced motion has a real switch (withSmoothScroll(false)), keyboard is the primary path (every scroll verb answers update() with a KeyMsg; see examples/viewport-keys.php), and color policy stays the host's: the library never reads NO_COLOR/TERM — validated SGR you pass in is passed through deliberately.
Troubleshooting and FAQ
- A wide table is cut off, or it spills past the terminal.
Table::render()never wraps. CheckcomputeTotalWidth(), then put the table in aViewportand scroll it with the keys above. - The cursor disappears after a filter. A filter that removes the cursor row moves the selection to row 0. An empty view returns
cursor() === null. Readcursor()after each change rather than caching the index. - The cursor is visible on screen but a screen reader says nothing. Color and reverse video are not spoken. Add
withCursorMarker()and announcecursor()on every move. - An item with a fixed
basisis squeezed in a narrow box. A basis is clamped to the container size at render time, so an oversized basis shrinks rather than overflowing. Give the flexible items a ratio, or widen the box. - Each frame prints the whole table. Call
render()through oneTableRendererinstance. A new renderer, orreset(), starts over with a full frame. - An exception names a surplus value or a bad column.
withRow()throws when a row has more values than there are columns.
Upstream mapping
| Upstream design | SugarFlexbox class | Notes |
|---|---|---|
76creates/stickers FlexBox (PHP) | FlexBox, FlexItem | Named as a design antecedent in the source. The ratio, basis and gap model is native to this library. |
76creates/stickers Table (PHP) | Table, Column, TableRenderer | Named as a design antecedent. Sorting, filtering, the cursor and delta rendering are native. |
CSS justify-content | Justify | Mirrors the values that a cell grid can express. |
| sugar-forms Viewport and Scrollbar | Viewport, Scrollbar | Compositions of the canonical sugar-forms classes, not copies. |
Architecture
Layout is pure. FlexBox::render() and Table::render() take their inputs and return strings, with no terminal writes. TableRenderer is the only class that keeps state between frames, and it holds one previous frame. Viewport is a value that wraps the sugar-forms Viewport and returns a new instance from each update().
Changelog and versioning
The package has no separate changelog file. The version history is in the commit log of sugar-flexbox/. The README records the deprecations, which retire in 2.0.0. The main ones are Column::make() (use Column::new()), Table::addColumn() and addRow() (use withColumn() and withRow()), FlexItem::withWidth() (use withBasis()), and Viewport::setContent() and withScrollbar(). The 2026-10-24 accessor cleanup moved dimension reads to width() and height() and sizing to withSize().
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Design antecedent: 76creates/stickers (PHP). SugarCraft is developed as a native PHP project.
Demos
VHS-recorded GIFs of the flexbox, table and sort-filter examples. viewport-keys.php has no recording. Regenerated automatically on every push that touches the source.
FlexBox row + column
Ratio 1:2:1 row + column with gap=1.
Sort + cursor table
Sort flips on Name and the flag column, then cursor styling, movement and a rawCurrentRow()/rawCurrentCell() readout — no filter call.
Sort + filter table
Age-ascending and Score-descending sorts plus an "e" filter over per-column widths and right-aligned numerics.Related
- SugarTable: the full keyboard-driven data grid with per-cell styles, pagination and frozen columns.
- SugarForms: the canonical Viewport and Scrollbar that this library composes.
- SugarCore: the TEA runtime,
Msgtypes and sanitizer that the components build on.