All 42 libraries

SugarTable

Customizable keyboard-driven data table with sorting, pagination, and a programmatic row cursor

inspired by Evertras/bubble-table tabledatagridinteractive

SugarTable code coverage

Column-definition table with sortable columns, frozen columns, per-cell styling, pagination, and a programmatic row cursor. Per-cell styling rides a restricted SGR attribute set canonicalised to 24-bit at render.

Install

composer require sugarcraft/sugar-table

Quickstart

use SugarCraft\Table\{Table, Column, Row, RowData, ColumnWidth, WrapMode};

$table = Table::fromColumns([
        Column::new('name', 'Name', 20)->withAlignLeft()
            ->withColumnWidth(ColumnWidth::Dynamic, 0),
        Column::new('role', 'Role', 15)->withColumnWidth(ColumnWidth::Percent, 25.0),
        Column::new('age',  'Age',   5)->withWrapMode(WrapMode::None),
    ])
    ->withRows([
        Row::new(RowData::from(['name' => 'Alice', 'role' => 'Admin', 'age' => '30'])),
        Row::new(RowData::from(['name' => 'Bob',   'role' => 'Dev',   'age' => '28'])),
    ])
    ->withPageSize(25);

echo $table->view();

What's in the box

Column definitionsWidth, alignment, style, wrap per column; frozen columns and sorting handled at the table level.
StyledCellPer-cell SGR styling — bold, underline and colors from a restricted attribute set.
PaginationPaginate large datasets, navigate between pages.
Frozen columnsPin the leftmost columns with withFrozenCols([0..k]) so they stay put during horizontal scroll.
Row selectionProgrammatic cursor - SelectNext/SelectPrevious/withSelectedIndex; handleScrollKey(key|KeyEvent) scrolls; a checked-row set (toggleChecked, optional checkbox gutter) gives multi-select. No mouse handling: wire input events yourself.
Viewport virtualizationRender only visible rows with withViewportHeight() + withScrollY().
Column width modesColumnWidth enum — Fixed, Percent, Dynamic, Content, Flex.
Borderless + width-exactwithBorderless() + withWidth() — compose inside another box at an exact width, with continuous reverse-video selection.
Cell text wrappingWrapMode enum — None, WordWrap, Character.
Border stylingwithBorder(Border) — 8 border families from \SugarCraft\Style\Border; markdownBorder() is visual style only — its output is not GFM-parseable.
Multi-line rowswithMultilineMode(bool) — rows expand to max cell height.
Empty statesNo visible columns render as the empty string; no rows render a centered translatable No data line (header shown or not, borderless and footer-armed included).

Accessors

Property reads are bare: public readonly state ($column->style, $row->data, $cell->value) or bare methods (Table::Columns(), Table::CurrentRow(), Table::scrollY()). No getFoo()-form accessor ships in this lib — under the get*-era ruling (2026-10-24) there was nothing here to deprecate; RowData::get()/::has() and Table::isExpanded() stay ruled as keyed lookups and predicates, pinned by tests/BareAccessorEraTest.php.

Security & untrusted content

Every cell value, column title and expanded-detail line passes through Sanitize::value() before reaching the buffer: C0/DEL bytes become ·, C1 is replaced, invalid UTF-8 repairs to U+FFFD (raw ANSI in a value paints as visible junk, never honored), sugar-mouse zone sentinels U+E000/U+E001 are stripped so forged click targets cannot ride untrusted data, and bidi overrides / zero-width space render as visible <U+XXXX> markers. Style channels are parse-restricted (SGR strings are parsed into a structured attribute set, canonicalised to 24-bit at render). Casting a StyledCell to string is the one deliberate bypass — it emits its raw value unsanitized; render untrusted content only through View(). See docs/TRUST-BOUNDARY.md.

Accessibility

Selection is pure reverse video (ESC[0;7m) — color-independent — and zebra striping is a fixed black-on-white inversion; both stay readable on any palette, and withSelectable(false) drops the highlight entirely. The empty-state message is translatable. There is no NO_COLOR, non-TTY or plain-text degrade path (SGR is always emitted); for assistive tech prefer Border::ascii() or Border::hidden() with withHeaderStyle(''), since box glyphs and the default TrueColor header add noise and light-theme contrast risk, and no semantic header/column association exists beyond visual alignment.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Tablestatic fromColumns(columns) / withColumns(columns)Create a table from its columns / replace them
TablewithRows(rows)Set table rows
TableaddRow(row) / addRows(rows)Append one row / a batch
TablewithBaseStyle(style) / withHeaderStyle(style)Base cell SGR / header-row SGR (default '1;37')
TablewithShowHeader(bool) / withShowFooter(bool)Toggle the header row / footer row
TablewithZebra(bool) / withZebraStyleEven(style) / withZebraStyleOdd(style)Table-level alternating-row stripe (default 30;47 even); suppressed under the cursor row
TablewithMaxLines(n) / renderedLineCount()Line budget for the data region / lines the frame paints (withViewportHeight counts rows)
TablewithFilterFunc(fn) / withPaginationWrap(bool) / withStaticFooter(text)Search predicate, cycling cursor+pages, fixed footer text
TablewithRowSeparator(bool) / withMaxTotalWidth(n) / withOverflowArrows(bool) / scrollLeft() / scrollRight()Rules between rows, horizontal window with overflow marks and pan helpers
TabletoggleChecked() / checkedRows() / withCheckMarks()Multi-row checked set with optional checkbox gutter
TablewithStrictPercent(bool)Throw instead of normalising Percent sets over 100
ColumnwithSortType(SortType) / withSortFunc(fn) / withFormatString(fmt)Auto/Text/Natural sort, raw-value comparator, sprintf display template
TablewithStyleFunc(callable)Per-cell style callback (row, col, value) → CellBuffer\Style|string
TablewithMissingIndicator(text)Placeholder for cells whose row has no entry (default '--')
TablewithPageSize(size)Set rows per page for pagination
TablewithPage(n)Jump to page n (0-based; PageFooter shows n+1)
TableSelectPage(n) / nextPage() / previousPage()Page navigation (clamped to valid pages; cursor snaps to the page)
TablewithFooterType(FooterType) / rowsFooter()Choose footer content (Page|Rows|Both) / read the rows-count footer string
TablewithViewportHeight(n)Render only n visible rows (viewport virtualization)
TablewithScrollY(n)Set vertical scroll offset (row number)
TablescrollY()Get current scroll offset
TableView()Render the table to string — every value passes the Sanitize::value() ingress (see Security & untrusted content)
TableSortBy(colKey, ascending, primary)Sort rows by a column — numeric-aware when both values are numeric, case-insensitive otherwise; repeating the sole active sort key with the same direction toggles it
TableClearSort()Remove all sorting
TableFilter(key, text) / clearFilter(key) / clearAllFilters()Per-column substring filter (filterable-marked columns only once any is marked)
Tablesearch(text) / clearSearch()OR search across the scanned columns
TablehandleScrollKey(key|KeyEvent)Keyboard scrolling - arrowUp/ArrowUp spellings, PageUp/Down, Home, End; clamps to maxScrollY(); handleKey() is the older alias
TableSelectNext() / selectPrevious()Move the row cursor (follows the viewport)
TablemaxScrollY()Highest valid scrollY for the current page + viewport (public, page-aware)
TablewithFrozenCols(indices)Pin a contiguous prefix [0..k]; anything else throws
TablewithHiddenCols(indices) / withScrollX(cols)Hide columns (must stay disjoint from the frozen prefix) / pan the scrollable region
TablewithExpandedRows(i) / toggleExpanded(i) / isExpanded(i)Row detail expansion tracked by Row object identity (withRows() prunes stale identities)
TablecomputeColumnWidths(total)Compute actual widths from ColumnWidth enum values
TablewithBorder(border)Set border family (Border::normal/rounded/thick/double/block/ascii/hidden/markdownBorder)
TablewithBorderStyle(ansiStyle)Apply ANSI SGR style to default border
TablewithMultilineMode(bool)Enable multi-line rows (expands to max cell height)
Columnnew(key, title, width)Create a column
ColumnwithAlignLeft(bool)Left-align (default is right)
ColumnwithColumnWidth(mode, value)Set ColumnWidth::Fixed|Percent|Dynamic|Content|Flex
ColumnwithWrapMode(mode)Set WrapMode::None|WordWrap|Character
Rownew(rowData)Create a row from RowData
RowDatafrom(array)Create from key-value array
RowDataget(key) / has(key) / all() / with(key, value)Keyed map lookup, presence test, full map, immutable set (ruling-3b keepers — not getFoo()-form accessors)
StyledCellnew(value, style)Create styled cell with ANSI style; casting to string bypasses sanitization — render via Table::View()
ColumnWidthenumFixed | Percent | Dynamic | Content | Flex
WrapModeenumNone | WordWrap | Character
FooterTypeenumPage | Rows | Both (footer renders only when pagination is active)

Demos.

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

Terminal GIF of the features example

Frozen + paginated

Wide host-telemetry table with pagination and a frozen first column.
Terminal GIF of the basic example

Basic + sort + filter

Sort by score, filter name contains a, paginate.