All 48 libraries

SugarFlexbox

FlexBox layout + delta Table + sticky Viewport + Scrollbar

design antecedent 76creates/stickers flexboxtablelayoutgrid

SugarFlexbox code coverage

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

FlexBoxRatio-based row and column layout. 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.
TableSort by column (ascending or descending, with authored tiebreakers through 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.
TableRendererDelta rendering. The first frame and every resized frame are full, and each later frame emits only the rows that changed.
ViewportA scrolling window that composes the canonical sugar-forms Viewport. It supports line, page and half-page moves, mouse wheel, smooth scroll and a scrollbar. Sticky headers and footers pin rows with withStickyHeader() and withStickyFooter(). withLinkedViewport() only marks a partner. Scroll state is not shared.
ScrollbarA vertical or horizontal scrollbar that composes the canonical sugar-forms Scrollbar, with configurable thumb and track characters.
ImmutabilityEvery builder returns a new instance, so a shared table or box can be reused without side effects.

API

CallSignatureDescription
FlexBox::row()row(FlexItem ...$items): selfCreate a horizontal flexbox.
FlexBox::column()column(FlexItem ...$items): selfCreate a vertical flexbox.
FlexBox::withGap()withGap(int $cells): selfSet the gap between items.
FlexBox::withAlign()withAlign(Align $a): selfSet the alignment. It takes the enum, not a string.
FlexBox::withJustify()withJustify(Justify $justify): selfSet main-axis spacing (SpaceBetween, SpaceAround, SpaceEvenly and others).
FlexBox::withWrap()withWrap(Wrap $wrap): selfEnable or disable wrapping onto new lines.
FlexBox::withDirection()withDirection(Direction $d): selfSet the main axis (row or column).
FlexBox::render()render(int $totalWidth, int $totalHeight): stringLay out the items inside the given box and return the frame.
FlexItem::new()new(string $content = ''): selfCreate a flex item.
FlexItem::withRatio()withRatio(int $ratio): selfGrowth weight for the leftover main-axis space. 0 never grows and keeps a 1-cell floor.
FlexItem::withBasis()withBasis(int $basis): selfFixed main-axis reservation, taken before ratios share the rest.
FlexItem::withWidth()withWidth(int $width): selfDeprecated alias of withBasis(). In column mode the reserved axis is the height, so prefer withBasis().
Table::new()new(): selfCreate an empty table.
Table::withColumn()withColumn(Column $col): selfAdd a column. addColumn() is the deprecated spelling.
Table::withRow()withRow(array $values): selfAdd a row. A surplus value throws at the door.
Table::withSort()withSort(int $colIndex, bool $ascending = true): selfSort by a column. The selection follows its row through the re-sort.
Table::sortByNext()sortByNext(int $colIndex): selfToggle ascending and descending on a column.
Table::withFilter()withFilter(string $text): selfKeep 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(): selfRemove the filter.
Table::withCursor()withCursor(int $rowIndex): selfMove the cursor. The door settles the view and refuses an index outside it.
Table::cursor()cursor(): ?intCursor index of the settled view. null only while the view has no rows.
Table::rawCurrentRow()rawCurrentRow(): ?arrayStored values of the cursor row, unrendered.
Table::rawCurrentCell()rawCurrentCell(int $colIndex): ?stringOne stored cell under the cursor, unrendered.
Table::computeTotalWidth()computeTotalWidth(): intThe full width of the grid. Use it to decide whether a Viewport is needed.
Table::withCursorStyle()withCursorStyle(string $ansiStyle): selfSGR string for the cursor row. The default is an empty string, which marks nothing on screen.
Table::withCursorMarker()withCursorMarker(string $prefix): selfA non-color focus glyph drawn inside the first column's width.
Table::withEmptyText()withEmptyText(?string $text): selfRow spanning the grid when a filter drops every row.
Table::withVisibleRange()withVisibleRange(int $from, ?int $to = null): selfLimit the rendered rows to a range.
Table::render()render(): stringThe full frame, pure and stateless. Use TableRenderer for deltas.
TableRenderer::new()new(): selfCreate a renderer that keeps the previous frame.
TableRenderer::render()render(Table $table): stringThe first and resized frames in full, then only the changed rows.
TableRenderer::reset()reset(): voidForget the previous frame so the next render is full.
Column::new()new(string $title, int $width): selfCreate a column. Its width is in cells.
Column::withAlign()withAlign(Align|string $align): selfSet Start, Center or End. Stretch is FlexBox sizing language and is refused here.
Column::withStyle()withStyle(string $ansiStyle): selfSGR string applied to every cell of the column. The cursor style paints over it.
Column::sorted()sorted(int $direction = 1, int $priority = 0): selfMark the column as a sort key, with an optional tiebreak priority.
Viewport::new()new(int $width = 80, int $height = 24): selfCreate an empty viewport.
Viewport::fromContent()fromContent(string $content, int $width = 80, int $height = 24): selfCreate a viewport over a string.
Viewport::withStickyHeader()withStickyHeader(int $rows): selfPin the first rows across scrolling. A negative count throws.
Viewport::withStickyFooter()withStickyFooter(int $rows): selfPin the last rows across scrolling. A negative count throws.
Viewport::withSmoothScroll()withSmoothScroll(bool $enable = true): selfReduced-motion switch. When off, each scroll settles in one frame.
Viewport::withMouseWheelEnabled()withMouseWheelEnabled(bool $on): selfAccept mouse-wheel scroll messages.
Viewport::withMouseWheelDelta()withMouseWheelDelta(int $delta): selfLines the wheel scrolls per notch.
Viewport::showScrollbar()showScrollbar(bool $on = true): selfShow or hide the scrollbar.
Viewport::lineUp()lineUp(int $n = 1): self, lineDown(int $n = 1): selfScroll by lines.
Viewport::pageUp()pageUp(): self, pageDown(): self, halfPageUp(): self, halfPageDown(): selfScroll by a page or half a page.
Viewport::gotoTop()gotoTop(): self, gotoBottom(): selfJump to the first or last line.
Viewport::update()update(Msg $msg): arrayApply a key or mouse message and return the new viewport and any command.
Scrollbar::vertical()vertical(): self, horizontal(): selfCreate a vertical or horizontal scrollbar.
Scrollbar::view()view(ScrollbarState|array $state, int $height): stringRender 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/.

MethodSummary
static vertical(): selfVertical scrollbar with defaults (░ track, █ thumb, ▲▼ arrows).
static horizontal(): selfHorizontal scrollbar with defaults (░ track, █ thumb, no arrows).
withTrackChar(string $char): self
withThumbChar(string $char): self
withArrows(bool $show): self
widgetScrollbar(): FormsScrollbarThe 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): stringRender 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/.

MethodSummary
static new(int $width = 80, int $height = 24): selfConstruct with default dimensions (80×24).
static fromContent(string $content, int $width = 80, int $height = 24): selfConstruct 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): selfPin 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): selfPin 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): selfRecord $other as this viewport's LINKED viewport.
hasLinkedViewport(): boolTrue when a self::withLinkedViewport() partner is attached.
syncWith(Viewport $other): self
isSynced(): bool
init(): ?\ClosureForward to the canonical forms viewport.
update(Msg $msg): array
subscriptions(): ?Subscriptions
view(): string
withContent(string $content): selfReturns a new Viewport; the receiver is unchanged (fluent house law).
setContent(string $content): selfBC forwarder onto the single content spelling.
withSize(int $width, int $height): selfResize — 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): selfBC forwarder onto the single sizing spelling.
setHeight(int $height): selfBC forwarder onto the single sizing spelling.
width(): int
height(): int
getWidth(): intBC forwarder for the pre-rename accessor name.
getHeight(): intBC forwarder for the pre-rename accessor name.
withYOffset(int $offset): selfReturns a new Viewport; the receiver is unchanged (fluent house law).
setYOffset(int $offset): selfBC forwarder onto self::withYOffset().
yOffset(): int
withXOffset(int $offset): selfReturns a new Viewport; the receiver is unchanged (fluent house law).
setXOffset(int $offset): selfBC forwarder onto self::withXOffset().
xOffset(): int
withHorizontalStep(int $step): self
withMouseWheelEnabled(bool $on): self
withMouseWheelDelta(int $delta): self
showScrollbar(bool $on = true): selfToggle the scrollbar column on/off.
withScrollbar(bool $on = true): selfBC forwarder for the pre-rename toggle name.
withScrollbarRunes(string $thumb, string $track): self
withVerticalScrollbar(Scrollbar $scrollbar): selfAttach 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/.

MethodSummary
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): selfDistribute leftover main-axis cells (see Justify). Leftover exists only where no ratio item absorbs it, as in CSS.
withWrap(Wrap $wrap): selfBreak a row-direction box onto further lines when its items overflow the width (see Wrap). Column boxes ignore it.
addItem(FlexItem $item): selfAppend one item.
withItems(FlexItem ...$items): selfBulk 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): stringRender 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/.

MethodSummary
lines(): arrayThe raw content split on newlines, once per instance.
measuredWidth(): intNatural 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(): intNatural 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): selfAlias 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).

MethodSummary
static fit(string $line, int $cells): arrayThe 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): stringPad 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.

MethodSummary
static normalize(?string $value, string $property): ?stringValidate an SGR parameter string and return its canonical (semicolon grammar) form.

SugarCraft\Flexbox\Table

Column final class

Column definition for a Table.

MethodSummary
static new(string $title, int $width): self
static make(string $title, int $width): self
withAlign(Align|string $align): selfPlace 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): stringResolve 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): selfSet 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): selfAttach 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): selfAuthor 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.

MethodSummary
static new(): self
withColumn(Column $col): selfReturns a new Table with $col appended; receiver unchanged.
addColumn(Column $col): self
withRow(array $values): selfReturns a new Table with one more row (values are matched to columns by index).
addRow(array $values): self
withSort(int $colIndex, bool $ascending = true): selfSort rows by column index.
sortBy(int $colIndex, bool $ascending = true): self
sortByNext(int $colIndex): selfToggle sort direction on column, or start ascending if different column.
withFilter(string $text): selfFilter 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): selfMove the cursor to $rowIndex of the materialized view.
setCursor(int $rowIndex): self
withCursorStyle(string $ansiStyle): self
withCursorMarker(string $prefix): selfNon-colour focus marker prepended to the cursor row's first cell.
withHeaderStyle(string $ansiStyle): self
withSeparator(string $s): selfSet 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): selfTheme 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): selfPaint a spanning row when a filter ate every row (FBX-41).
withVisibleRange(int $from, ?int $to = null): self
rowCount(): int
colCount(): int
totalRowCount(): intRows 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(): stringThe active filter text ('' when unfiltered).
columns(): arrayThe column roster, index-addressed exactly as the sort keys and header render see it.
cursor(): ?intThe 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(): ?arrayThe 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): ?stringOne 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(): stringRender the table to a full string (always full frame, never delta).
buildLines(): arrayBuild all rendered lines (header, separator, data rows).
computeTotalWidth(): intTotal 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.

MethodSummary
static new(): selfThe house factory shape. The implicit public constructor stays available until 2.0.0, when new() becomes the only door.
render(Table $table): stringRender the table, emitting a full frame or a delta depending on whether dimensions have changed since the last frame.
reset(): voidReset 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.

OptionTypeDefaultEffect
FlexBox::withGap()int, cells0Space between adjacent items.
FlexBox::withAlign()AlignAlign::StretchPlacement of items. In row mode Stretch fills the box height. In column mode it uses the rendered width.
FlexItem::withRatio()int, at least 01Share of the leftover main-axis space. 0 never grows.
FlexItem::withBasis()int, at least 00Fixed reservation, clamped to the container at render time.
Column::withAlign()Align (Start, Center, End)StartHorizontal alignment of the column's cells.
Table::withCursorStyle()SGR stringempty stringStyle for the cursor row. Empty marks nothing on screen.
Table::withCursorMarker()stringnoneGlyph drawn inside the first column for focus.
Table::withEmptyText()?stringnullMessage shown when a filter removes every row.
Viewport::withStickyHeader()int, rows0Rows pinned at the top while the rest scrolls.
Viewport::withSmoothScroll()boolfalseOff settles every scroll in one frame. Turn it on to animate scrolls.
Viewport::withMouseWheelDelta()int, lines3Lines moved per wheel notch.
Viewport::withMouseWheelEnabled()booltrueScroll 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().

KeyAction
↑ / kScroll up one line.
↓ / jScroll down one line.
← / hScroll left.
→ / lScroll right.
PageUp / bScroll up one page.
PageDown / f / SpaceScroll down one page.
Ctrl+u / Ctrl+dScroll up or down half a page.
Home / gJump to the top.
End / GJump 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

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. Check computeTotalWidth(), then put the table in a Viewport and 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. Read cursor() 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 announce cursor() on every move.
  • An item with a fixed basis is 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 one TableRenderer instance. A new renderer, or reset(), 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 designSugarFlexbox classNotes
76creates/stickers FlexBox (PHP)FlexBox, FlexItemNamed as a design antecedent in the source. The ratio, basis and gap model is native to this library.
76creates/stickers Table (PHP)Table, Column, TableRendererNamed as a design antecedent. Sorting, filtering, the cursor and delta rendering are native.
CSS justify-contentJustifyMirrors the values that a cell grid can express.
sugar-forms Viewport and ScrollbarViewport, ScrollbarCompositions 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

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.

Three panels: a ratio row, a stacked column, a centered row

FlexBox row + column

Ratio 1:2:1 row + column with gap=1.
Table frames with sort arrows, then a highlighted cursor row and a raw readout

Sort + cursor table

Sort flips on Name and the flag column, then cursor styling, movement and a rawCurrentRow()/rawCurrentCell() readout — no filter call.
Table frames sorted by column then narrowed to rows containing the letter e

Sort + filter table

Age-ascending and Score-descending sorts plus an "e" filter over per-column widths and right-aligned numerics.
  • 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, Msg types and sanitizer that the components build on.