sugarcraft / sugar-flexbox
Terminal-cell layout utilities: FlexBox (CSS-flexbox-like responsive row/column layout), Table (sortable, filterable grid with cursor, styled columns and a delta-rendering TableRenderer), a scrolling Viewport with sticky regions, and Scrollbar indicators.
Requires
- php: ^8.3
- sugarcraft/sugar-cellbuffer: @dev
- sugarcraft/sugar-core: @dev
- sugarcraft/sugar-forms: @dev
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
- ext-intl: Enables accent-insensitive folding in the Table filter and string sort ("Ä" matches and sorts with "A"); case folding itself needs no extension
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:06 UTC
README
SugarFlexbox
Formerly published as
sugarcraft/sugar-stickers(renamed 2026-10). Namespace changed:SugarCraft\Stickers\→SugarCraft\Flexbox\.
sugar-flexbox — layout building blocks for terminal UIs, for PHP 8.3+. Provides four components: FlexBox (flexbox-like row/column layout), Table (sortable, filterable, styled grids with a cursor), Viewport (scrollable window with sticky regions), and Scrollbar (decorative scroll indicators).
The library carries the house i18n plumbing (src/Lang.php plus locale files under lang/) but nothing in the shipped interface calls it yet: every label and message is English-only today, and the wiring stands ready for the day a string needs translating.
Where it fits
The full data-grid genre belongs to sugar-table — the canonical
keyboard-driven table with per-cell styles, pagination and frozen
columns. sugar-flexbox sits beside it as the layout layer: the flexbox
engine, a lightweight model Table for panes that need sorting,
filtering and a cursor without taking on a grid dependency, the
scrolling Viewport behind long documents, and the decorative
Scrollbar. As of this writing no in-repo package imports
SugarCraft\Flexbox classes (grep-verified): this lib is a published
building block for programs written against it, not a dependency of the
fleet it serves.
State reads follow one rule across all four components: plain
constructor-carried state is a public readonly property (e.g.
Column->title, Column->width, FlexItem->ratio) — it can never lie,
because nothing can write it after construction; anything derived,
settled, or guarded is an accessor (Table::cursor(),
Table::rawCurrentRow(), Column::sortDir(), Viewport::yOffset()) —
the settle-and-refuse logic lives there, so the property face stays
boring and the interesting reads are always method calls you can
intercept.
Features
FlexBox
- CSS flexbox-like responsive grid layout for terminal UIs
- Direction: row (horizontal) or column (vertical)
- Align items with the
Alignenum:Align::Start/Align::Center/Align::End/Align::Stretch, set viawithAlign() - Gap between items
- Ratio-based sizing — items with grow ratios fill available space
- Justify leftover main-axis space with the
Justifyenum (withJustify()):Start,End,Center,SpaceBetween,SpaceAround,SpaceEvenly - Wrap row items onto further lines with the
Wrapenum (withWrap())
Table
- Sortable columns —
withSort($column, $ascending = true)sets an order,sortByNext($column)flips it (mouse wiring belongs to the app); when BOTH cells are numeric they compare as numbers — 2 sorts before 100, and a column mixing '9' and text sorts as text; string comparison is Unicode case-folded, so 'a' precedes 'B' and (with ext-intl loaded) 'Ärger' sorts with the A's. Columns authored withColumn::sorted($dir, $priority)are priority-ordered tiebreakers under the clicked primary (1 = first, 0 = last, each leg with its own direction) — a click never authors or erases them — and their arrows show beside the active one. The sort arrow is prepended before the header is truncated, so a sorted column narrower than arrow plus text shows the arrow alone - Filterable — keeps rows where any cell contains a Unicode case-folded substring ('ärger' finds 'Ärger', 'strasse' finds 'Straße'; ext-intl adds full accent folding — without it, letters still case-fold but accented words keep their code-point neighbourhood); matching runs on the stored raw strings, not the render-time sanitized text
- Configurable columns — title, width (0 = hidden: the column contributes no cell, joint, or ruler cluster), alignment, formatter (
Column::new(),withAlign(),withStyle(),withFormatter()); the render pipeline runs formatter → sanitize → truncate/pad, so a formatter's output is sanitized like any other cell value and cannot smuggle color to the screen — styling belongs towithStyle(); a formatter answers string ornull(null keeps the raw value) — anything else refuses at format time naming the column - Cell styling — per-column ANSI style support
- Empty states — a filter that eats every row leaves a bare frame:
withEmptyText('no match')paints one spanning row across the table width in that state only. The NO-DATA case (nothing was ever added) stays bare on purpose — apps own that canvas, and the pairtotalRowCount()(rows supplied) vsrowCount()(settled view) plusfilterText()is the API for painting custom copy per state - Themeable borders —
withSeparator()themes the column joint;withRulerChars($fill, $joint)themes the ruler's two runes under the same ingress (sanitized, exactly one cell each or the door refuses by name), so an ASCII theme renders a fully ASCII frame. Defaults ('─' / '┬') are byte-identical to every frame ever shipped - Cursor tracking — get current row/cell on selection. Note the cursor
style is empty by default, so
withCursor()alone marks nothing on screen — callwithCursorStyle()to paint the cursor row. The style wraps the whole row, separator joints included, so the focused row renders solid; pair it withwithCursorMarker('> ')for focus a colour-less host can still see — the marker rides inside the first column's allocated width (the first VISIBLE one when width-0 columns hide parts of the frame), so frame dimensions never move. - Delta rendering — the stateful
TableRendereremits only the cells that changed between frames (see Buffer diffing below)
Viewport
- Scrollable viewport — composes the canonical
sugar-formsViewportdirectly (FBX-20: the lib's require and imports name Forms, not the deprecatedsugar-widgetsclass_aliasfaçade) - Keyboard navigation — line-up/down, page-up/down, half-page-up/down (
halfPageUp()/halfPageDown()), goto-top/bottom; every one is also reachable throughupdate()with aKeyMsg, so a key handler and a wheel share one code path (examples/viewport-keys.phpdrives the whole contract headlessly) - Sticky regions —
withStickyHeader($rows)/withStickyFooter($rows)pin lines across scrolling; a row can never appear in both regions (the footer is clamped when the document is shorter than header + footer), and a document that FITS the box — nothing scrolled out — renders the plain streaming frame instead of reserving blank bands for pinned rows - Sync partner —
withLinkedViewport($other)is a decorative association: it marks the viewport as synced and is readable viahasLinkedViewport(), but propagates nothing (scroll state never crosses to the partner) - Mouse wheel —
withMouseWheelEnabled(bool)arms it andwithMouseWheelDelta($lines)sizes the step (default 3); wheel motion reaches the sameupdate()door as keys (MouseWheelMsg) - Horizontal scrolling —
scrollLeft()/scrollRight()shift bywithHorizontalStep($cells)(default 6, minimum 1, or pass an explicit per-step count), andhorizontalScrollPercent()answers the slider position - Argument policy — dimensions THROW on negatives (
Viewport::new(-5, 10)refuses) while zero is legal and degenerate boxes simply render nothing; sticky row counts THROW on negatives too (withStickyHeader(-1)refuses by name) because they are an argument bug, not geometry — 0 disables the region, and the render-time cap to available height stays a geometry clamp; scroll offsets never throw — they CLAMP into range (withYOffset(-2)answers 0); and FlexBox with no items or width ≤ 0 renders''rather than refusing - Smooth scroll and scrollbar toggle (
showScrollbar(); the old booleanwithScrollbar()spelling is a deprecated forwarder); attaching a component withwithVerticalScrollbar()arms the bar and renders the SAME thumb/track in the plain and sticky paths; wide scrollbar runes reserve their true cell width
Scrollbar
- The API —
Scrollbar::vertical()/Scrollbar::horizontal()build a bar;view($state, $rows)renders it into exactly$rowslines, where$stateis aSugarCraft\Forms\Scrollbar\ScrollbarStateor its array shape['total' => n, 'position' => row, 'viewport' => visibleRows]; aViewportcomposes one throughwithVerticalScrollbar()and paints it whenshowScrollbar()is on (see Viewport above) - Theming —
withThumbChar()/withTrackChar()set the runes (sanitized, at most one cell), andwithArrows(bool)toggles the end caps (vertical only — the horizontal bar boots arrowless)
use SugarCraft\Flexbox\Scrollbar; $bar = Scrollbar::vertical()->withArrows(true); echo $bar->view(['total' => 100, 'position' => 30, 'viewport' => 24], 9);
Install
composer require sugarcraft/sugar-flexbox
FlexBox Quick Start
All dimensions (widths, heights, gaps, bases, ratios across FlexBox, Table and Viewport) are terminal cells — columns × rows — not bytes or pixels.
use SugarCraft\Flexbox\Flex\{FlexBox, FlexItem}; $box = FlexBox::row( FlexItem::new('Panel A')->withRatio(1), FlexItem::new('Panel B')->withRatio(2), FlexItem::new('Panel C')->withRatio(1), )->withGap(1); echo $box->render(80, 24);
Build the item set in one go: row()/column()/withItems() take the whole list and
copy it ONCE, while addItem() appends immutably — O(n) list copies per call, O(n²) to
build n items. Measured: chained addItem() costs 2.6 ms at 1k items and 18.1 ms at 3k;
bulk construction stays flat.
How sizing works
Every dimension is in cells, and allocation follows one deterministic model (no
reverse-direction counterparts exist; justify-content and flex-wrap are the
withJustify() and withWrap() setters described below):
FlexItem::new() defaults to grow-ratio 1 — plain items divide the free
space evenly, not proportionally to content; CSS's flex-grow: 0 intuition
requires an explicit withRatio(0), and a ratio-0 item with no basis then
falls to the 1-cell floor (rule 3), never to its content width. The fixed-size
recipe is withBasis(), not withRatio(0).
- Basis first. Each item's
withBasis(cells)reserves a fixed main-axis slice (row: width, column: height), clamped to the container: ANY positive basis is a fixed-size item that never grows — even one that also carries a ratio takes exactly its basis and is excluded from the flex pool.withWidth()is a deprecated alias ofwithBasis()(REMOVED-IN: 2.0.0) — in column mode the reserved axis is the HEIGHT, so the direction-flavoured name lies in half the modes;withBasisnames the axis by role. - Gaps next.
nitems cost(n - 1) x gapcells before any ratio math; the gap is clamped at render time if the budget cannot pay for it. - Ratios split the rest. Remaining cells are shared by grow ratios with an exact-sum guarantee: each flex item's base share is the rounded-down quotient, and the rounding remainder is handed out in item order (80 cells across ratios 1:1:1 yields 27/27/26, always the same way). A base share may therefore be 0 when the container cannot pay every flex sibling a cell (3 ratio-1 items across 2 cells yield 1/1/0, never 1/1/1); the 1-cell floor is the fallback for ratio-0/basis-0 items and for the no-flex-space path, not a per-item minimum. Within the ratio-split regime a width never shrinks as the container grows; the no-flex-space fallback sits outside that monotonicity — there every basis-less item is pinned to the 1-cell floor, so growing into the split can hand one a SMALLER share than the fallback gave it (two ratio-1 items beside one ratio-0 sibling allocate 1/1/1 across one cell but 1/0/1 across two).
- Align (
start/center/end/stretch) is ONE value that drives BOTH axes — there is no separate cross-axis knob (main-axis placement of leftover space iswithJustify(), below), and rows are always placed top-down. In row mode the case selects the box height (stretchfills the declared height, every other case the tallest item) as well as how each item's text sits inside its allocated cell. In column mode each line is placed inside the width the ITEM MEASURES —stretchuses the container width, every other case the item's own measured width — so column-mode alignment discriminates only lines of DIFFERENT lengths within one item: a uniform-width item renders byte-identical understart/center/end(centring a whole item against the container is padding's layer, not alignment's). Content beyond the declared height is clamped, never distributed;render(w, h)output always fits the requested box.
Justify and wrap
withJustify(Justify $j) places leftover main-axis cells: widths in a row box, heights in
a column box. Leftover exists only where no ratio item absorbs it (fixed withBasis()
items, ratio-0 items on their 1-cell floor, or the no-flex fallback), as in CSS.
Justify::Start is the default and leaves the line unpadded, exactly as before the
setter existed. End and Center pack the items to one side or the middle; Center
puts the odd cell on the trailing side. SpaceBetween puts all leftover between items,
and a single item behaves as Start. SpaceAround gives each item equal space on both
sides, with half-size edges. SpaceEvenly gives every gap, edges included, the same
size. A withGap() value is a minimum between items, and the justified share is added
on top of it. Leftover that does not divide evenly goes to the trailing slots first, so
the odd cell lands where Center puts it and each split sums to the leftover exactly.
flex-start and flex-end from sugar-dashboard's JustifyContent map to Start and
End; a cell grid has no writing mode, so the logical and physical edges coincide.
use SugarCraft\Flexbox\Flex\{FlexBox, FlexItem, Justify}; $bar = FlexBox::row( FlexItem::new('Home')->withBasis(6), FlexItem::new('Save')->withBasis(6), )->withJustify(Justify::SpaceBetween); echo $bar->render(30, 1), "\n";
withWrap(Wrap::Wrap) breaks a row box onto further lines when its items overflow the
width. Each item's hypothetical size is its withBasis() or, when unset, its natural
content width; a ratio-0 item with no basis counts as its 1-cell floor, the size it is
drawn at (rule 3). A line closes before the item that would overflow it, counting the gap
that line is drawn with: a withGap() wider than the box is capped as it is for NoWrap,
so a set that fits on one line does not break. Each wrapped line is then laid out across
the full width under the same ratio, justify and align rules.
Wrapped lines stack flush with no row gap; withGap() only spaces items within a line.
The box height is the sum of the line heights, clamped to the height passed to render(),
and Align::Stretch pads it to that height. Wrap applies to row boxes only. A column box
ignores withWrap() and does not reflow into extra columns. There is no wrap-reverse:
sugar-dashboard's FlexWrap::WrapReverse was never honored by its layout, so it is not
carried over.
Two differences from the wrap in sugar-dashboard's FlexLayout (the behavior it replaces):
- Sizing. The dashboard wraps only when natural widths overflow, and otherwise keeps
natural widths. Flexbox items default to ratio 1 and grow, so a set that fits still
fills the width:
FlexItem::new('a')andFlexItem::new('b')at width 10 drawa b, where the dashboard drawsab. Within flexbox, a set of growing items that fits draws the same cells underWrap::WrapandWrap::NoWrap(fixed-basis items differ in padding, below). - Per-line allocation. Each wrapped line runs the ratio allocation again.
aaaa,bbbbbbbb,ccat width 10 drawaaaaand thenbbbbbcc: the second line holdsbbbbbbbbandcctogether, and its eight-cell item is cut to five cells. The dashboard keepsbbbbbbbbccon that line. - Padding. A wrapped line is padded to the full width. A NoWrap line of fixed-basis
items is not:
aaandbbatwithBasis(2)in width 8 drawaabbunder NoWrap andaabbunder Wrap. The box is padded to its full height only underAlign::Stretch; the dashboard always pads.
To build a sidebar plus a fill panel: give the sidebar withBasis(20) and the panel
withRatio(1). There is no center-a-dialog primitive in this lib — pad with fixed-ratio
spacers (withRatio(1) on each side, content withRatio(n)) instead.
The alignment cases come from the shared Align enum: FlexBox::withAlign() takes it,
and Column::withAlign() takes it too (Start/Center/End place the cells;
Stretch is sizing-only and refuses at the column door). Columns additionally still
accept the legacy 'left'/'right'/'center' strings — same placement, coerced at
the door, retiring with 2.0.0.
use SugarCraft\Flexbox\Flex\{Align, FlexBox, FlexItem}; $boxes = FlexBox::row( FlexItem::new('ab'), FlexItem::new('cd'), )->withAlign(Align::Center); echo $boxes->render(20, 1);
Table Quick Start
Table and Column are immutable: every builder returns a NEW instance, so the result must be assigned (or chained) — calling a method for effect discards it.
use SugarCraft\Flexbox\Flex\Align; use SugarCraft\Flexbox\Table\{Table, Column}; $table = Table::new() ->withColumn(Column::new('Name', 20)) ->withColumn(Column::new('Age', 5)->withAlign(Align::End)) ->withColumn(Column::new('City', 15)) ->withRow(['Alice', '30', 'NYC']) ->withRow(['Bob', '25', 'LA']) ->withRow(['Carol', '35', 'Chicago']); $sorted = $table->withSort(0); // sort by Name column → new Table $filtered = $sorted->withFilter('ca'); // case-folded substring in ANY cell → keeps the Carol row (its "Chicago" city matches too) $atCursor = $filtered ->withCursorStyle('1;36') // the default style ('') marks nothing on screen ->withCursor(0); // cursor row of the materialized view echo $atCursor->render(); echo $atCursor->rawCurrentCell(0), "\n";
The cursor is guarded at its door: withCursor() throws unless the index
addresses the settled materialized view (a pending sort or filter is resolved
first). Sorting and filtering carry the selection with the row it stood on —
matched by stored cell values, the first identical row wins — and a selection
whose row a filter drops lands back at row 0. cursor() answers the raw index
(null only while the view holds no rows); rawCurrentRow() and
rawCurrentCell() answer that row's stored values or null.
The rest of the query surface, named once so it is findable:
rowCount() is the settled view's size, totalRowCount() counts every
stored row filter aside, colCount() the columns, filterText()
answers the active filter, clearFilter() is exactly withFilter(''),
and buildLines() returns the individual frame lines that render()
implodes — memo, renderer and suite all read the same source of truth.
A table wider than the terminal is honest about its width and nothing else:
computeTotalWidth() counts the full grid, and render() emits it as
measured — no wrapping, no truncation at the box. A console will
soft-wrap those rows, which breaks the column alignment the frame was
built to express (a name column can silently bleed onto the next row's
cells). Gate before you paint: compare computeTotalWidth() against
your terminal width, or compose the table inside a Viewport, whose
horizontal scroll (scrollLeft()/scrollRight()) moves whole cells
through the over-wide region instead of letting the terminal fold it.
(Shipping an automatic clamp like withMaxWidth() is a parked API
decision; the discipline above is the contract today.)
Viewport Quick Start
Every view() row is exactly width() cells — plain, sticky and
scrollbar faces alike (long rows are clamped, short ones right-padded; a
left scroll drops cells first, then the clamp applies). The row COUNT is
the one deliberate difference: the plain (streaming) face paints
min(height, lines left) rows — a 1-line document in a 10-row frame
paints 1 row — while the sticky face pads its regions so a document with
pinned rows is always exactly height rows tall. Size surrounding chrome
to "at most height" rows, not to height.
use SugarCraft\Flexbox\Viewport; $lines = implode("\n", array_map( static fn (int $i): string => sprintf('Line %02d', $i), range(1, 50), )) . "\n"; $viewport = Viewport::fromContent($lines, 80, 24); $viewport = $viewport->showScrollbar(true); // Viewport implements Core\Model (init/update/view/subscriptions): run it // as a program root, or drive it from your own Model's update() and // render the view it returns. $viewport = $viewport->lineDown(3)->withStickyHeader(1); echo $viewport->view(); // Line 01 stays pinned; the numbered body has scrolled past Line 04
All four demos under examples/ run headless in CI (each is executed
and asserted silent by the snippet suite): flexbox.php for the sizing
rules, table.php for the styled grid, sort-filter.php for sorting,
filtering and the cursor, and viewport-keys.php for the
key/wheel update() contract.
Trust boundary
Table, Column and FlexBox treat everything they render as untrusted data.
Cell values and column titles pass through Sanitize::untrusted(), which
strips every terminal escape sequence (ESC, CSI, and the bare C0 control
bytes NUL/BEL/DEL all vanish), and then the structural characters are swept:
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). No
control byte survives to reach the screen, so hostile content can never
smuggle a terminal escape sequence into a frame.
Style strings (FlexItem::withStyle(), Column::withStyle(),
Table::withHeaderStyle(), Table::withCursorStyle()) pass through one door:
a legal SGR parameter string — codes 0..255 separated by single ; — or the
empty string/null for no style; anything else throws InvalidArgumentException
naming the refused property, so the style knobs cannot be repurposed as an
escape channel.
Viewport and Scrollbar are trusted-input by design: the Viewport splits
your setContent() / fromContent() string on \n and renders the lines as given (the
delegated widget stores content without a sweep), and the Scrollbar emits the
track/thumb runes and labels you passed straight to the terminal. Feed them
program-generated frames, or sanitize user input yourself first.
One asymmetry to know about: the FlexBox measures an item's content — width, height and the ratio split are computed from the raw string — before the render-time sweep runs. Only one byte actually skews the two views: a tab is measured as four cells (the terminal's default tab stop) yet the sweep prints a single space, so a tabbed line reserves four cells and paints one — a small over-allocation, never a truncation. Every other stripped byte (ESC/CSI/NUL/BEL/DEL, and the lone carriage return) measures zero both before and after the sweep, so it cannot shift a layout at all; a line feed simply splits the content into two measured lines rather than consuming a cell.
The cursor reads break the sweep the other way: Table::rawCurrentRow() and
Table::rawCurrentCell() answer with the stored strings as given — the
sanitize pass belongs to render(), not to the accessors — which is exactly
why the raw word sits in their names (they used to be the benign
currentRow()/currentCell(); those remain as pinned deprecated forwarders
until 2.0.0). A value that came from an untrusted row must be cleaned by you
before it is echoed or logged.
Buffer diffing (TableRenderer)
Table::render() is pure — it always returns a full frame. TableRenderer is the stateful
companion that maintains the previous frame as a SugarCraft\CellBuffer\Buffer and emits
deltas instead. On each render() it builds the current Buffer, computes current->diff(previous)
(from sugar-cellbuffer),
and returns only the changed cells' ANSI ops via encode($ops) on a per-render DiffEncoder
instance; the current frame
then replaces the previous one. Style changes are visible to the diff (colors are carried per
cell), and a dimension change resets the state so the next frame is complete again.
use SugarCraft\Flexbox\Table\{Column, Table, TableRenderer}; $renderer = TableRenderer::new(); $table = Table::new() ->withColumn(Column::new('Status', 8)) ->withColumn(Column::new('Job', 20)) ->withRow(['running', 'nightly-backup']); echo $renderer->render($table); // full first frame $changed = Table::new() ->withColumn(Column::new('Status', 8)) ->withColumn(Column::new('Job', 20)) ->withRow(['done', 'nightly-backup']); echo $renderer->render($changed); // only the 'Status' cell is re-painted
Call reset() to force the next render() to emit a full frame (e.g. after the terminal
was cleared externally).
SSH bandwidth + flicker win: a one-character change emits only the ops for
the affected cells instead of a full repaint — on an 80×24 screen the
full-frame ceiling is 1,920 cell ops (one per cell), so a delta that touches a
handful of cells sends orders of magnitude less per-frame data on the wire, and
it avoids the flicker of rewrite-based terminals. A full frame is re-emitted on
the first render after startup or an explicit reset(); when the table's
dimensions change, the next frame diffs against the previous one on a union
canvas so cells the new size no longer paints arrive as erases (a SHRINK does
not ghost) — callers that clear the terminal out-of-band must still call
reset().
Accessibility
The renderer's a11y posture, stated as contract rather than hope:
- Focus is never carried by colour alone. The cursor row's default
cue is its background style — invisible on monochrome terminals, to
colour-blind users, and under
NO_COLORhosts.withCursorMarker()prepends a glyph inside the first column's width (frame dimensions never move); the glyph is a shape change, though, and a screen reader announces neither colour nor shape — pair the visual cue with a spoken one by readingcursor()/currentRow()on every change and announcing it in your app's layer. The sort state IS a glyph (▲/▼ in the header, never colour), and a filtered-to-nothing table can say so withwithEmptyText()(withtotalRowCount()andfilterText()answering why the view is empty). - Reduced motion has a real switch.
withSmoothScroll(false)makes every scroll jump settle in one frame; the mouse wheel never arms an animation (that leg is instant by design, FBX-13), andview()is a pure function of state — repeated calls return identical bytes, so a restatement for a screen reader costs nothing. - Keyboard is the primary path; the mouse is parity. Every scroll
verb exists as a method and as a
KeyMsgthroughupdate();examples/viewport-keys.phpis the executable mapping (PageDown, End, wheel). A keyboard-driven app never needs a mouse event, and a wheel event answers exactly like the key it mirrors. - Colour policy is the host's, not the library's. Nothing here
reads
NO_COLORorTERM— stripping is the terminal's (or the user's wrapper's) decision, and style strings you pass in are validated SGR passed through deliberately, byte for byte. The examples print a fixed1;37style for illustration; your app should honour the same host policy its users set. - Sticky header clamp is a content guarantee, not a layout quirk.
Header rows are capped at
height − footer rows: a pinned header that left zero room for the body would repeat content screen-reader users already heard in the footer band. The row budget is the disclosure;cursor()never lies (FBX-26's door refuses indexes that address nothing).
Accessor deprecation (2026-10-24)
Viewport's dimension accessors follow the house bare-accessor convention:
call width() and height(); sizing itself has ONE spelling,
withSize($width, $height) (setWidth()/setHeight() were the second
vocabulary and now forward to it, carrying the receiver's other
dimension); and Table's mutation-flavoured builders are
now withColumn()/withRow()/withSort()/withFilter()/withCursor() — every one
of them returns a new Table; the receiver is unchanged, so muscle-memory
chaining like $t->addRow($r); inside a loop dropped rows silently. The
scrollbar toggle's old boolean
withScrollbar() reads as a fluent setter and shadows the component-attach
verb withVerticalScrollbar() — its honest name is showScrollbar(). The
legacy spellings still work — they are one-line backward-compatibility
forwarders that return the same values — but each is marked @deprecated
with REMOVED-IN: 2.0.0 in its docblock and they will be deleted in
sugar-flexbox v2.0.0. Migrating is a name swap with no behavior change:
| Namespace | Class | Deprecated | Use instead |
|---|---|---|---|
Flexbox |
Viewport |
getWidth() |
width() |
Flexbox |
Viewport |
getHeight() |
height() |
Flexbox |
Viewport |
withScrollbar() |
showScrollbar() |
Flexbox |
Viewport |
setWidth() |
withSize() |
Flexbox |
Viewport |
setHeight() |
withSize() |
Flexbox |
Viewport |
setContent() |
withContent() |
Flexbox |
Viewport |
setYOffset() |
withYOffset() |
Flexbox |
Viewport |
setXOffset() |
withXOffset() |
Flexbox |
Viewport |
syncWith() |
withLinkedViewport() |
Flexbox |
Viewport |
isSynced() |
hasLinkedViewport() |
Flexbox\Table |
Table |
addColumn() |
withColumn() |
Flexbox\Table |
Table |
addRow() |
withRow() |
Flexbox\Table |
Table |
sortBy() |
withSort() |
Flexbox\Table |
Table |
filter() |
withFilter() |
Flexbox\Table |
Table |
setCursor() |
withCursor() |
Flexbox\Table |
Table |
currentRow() |
rawCurrentRow() |
Flexbox\Table |
Table |
currentCell() |
rawCurrentCell() |
Flexbox\Flex |
FlexItem |
withWidth() |
withBasis() |
Flexbox\Table |
Column |
make() |
new() |
License
MIT
Credits & inspiration
Design antecedent: 76creates/stickers; SugarCraft is developed as a native PHP project.
The badges and CI above live in the SugarCraft monorepo where this library is developed; the package is published standalone as sugarcraft/sugar-flexbox.