SugarCellBuffer
Cell-grid value objects for terminal rendering
Immutable Buffer (2-D cell grid) and Cell (rune, style, link, width) value objects forming the shared data model for terminal rendering across the SugarCraft ecosystem. Wide-char (CJK/emoji) cells declare width=2; the writing API enforces the width-0 continuation pair for you.
Install
composer require sugarcraft/sugar-cellbuffer
Quickstart
withCellAt(5, 1, Cell::new('H'));
// Blit a seeded 2x2 sub-buffer at origin — seeding matters: blitting an
// all-blank sub-buffer over blank cells is a visible no-op.
$sub = Buffer::new(2, 2);
$sub = $sub->withCellAt(0, 0, Cell::new('A'))->withCellAt(1, 0, Cell::new('B'));
$sub = $sub->withCellAt(0, 1, Cell::new('C'))->withCellAt(1, 1, Cell::new('D'));
$buf = $buf->withRegion(Region::new(Position::new(0, 0), 2, 2), $sub);
// Read a cell back.
$cell = $buf->cellAt(5, 1);
echo $cell->rune(); // 'H'
// Access dimensions.
echo $buf->width(); // 20
echo $buf->height(); // 3
What's in the box
BufferImmutable 2-D cell grid: the fluent with*() family plus fill(), copy() and applyDiff() (not named with*, equally immutable — every mutation returns a new instance). Bounds-checked cellAt() throws OutOfRangeException.
CellReadonly value object: rune (string), style (?Style), link (?Hyperlink), width (int). Cell::continuation() for wide-char neighbour cells. No with*() — rebuild via new.
Position2-D coordinate (col, row) with bare accessors. Negative coordinates may be used for relative offsets.
RegionRectangular sub-region defined by Position origin + width/height. contains() helper for hit-testing; zero-area regions no-op in fill()/withRegion().
StylePer-cell pen: foreground/background as RGB 0xRRGGBB or palette-slot identity (0-255), underline color, and an attribute bitmask. The with*() builders keep slot and RGB mutually exclusive per channel; the public fromSgr() parses SGR parameter strings back into styles. The rich styling API (border, padding, transforms) lives in sugar-style.
HyperlinkOSC 8 anchor — url and optional id grouping field, validated at construction and again on unserialization (C0/DEL, lone raw 8-bit C1 bytes and their UTF-8
C2 xx spellings, plus semicolons-in-id refused; valid multibyte IRI payloads pass).Wide char handlingwidth=2 cells (CJK, many emoji) carry a width-0 continuation partner at col+1; larger widths are single run-length spans that carry no continuation cells. The writing API enforces the pair law automatically; Buffer::fromGrid() is the escape hatch that skips it — it validates the dimensions and requires a flat list of exactly width×height cells, but takes the cells as given, so pair maintenance is the caller's duty.
Use it for
- Shared cell-grid foundation — consumed by sugar-overlay, sugar-toast, sugar-panels, sugar-table, sugar-forms, sugar-style, sugar-charts, sugar-image, sugar-dashboard, sugar-testing, sugar-video, sugar-datepicker, sugar-flexbox, candy-minesweeper and candy-tetris. Some renderers keep independent engines by design (sugar-core's line-diff Renderer, sugar-vterm's mutable grid) and candy-code does not consume this library; the package's role is the shared data model and its byte encoders.
- Per-cell dirty tracking —
Buffer::diff()emits move / style / set-cell / repeat-run / erase-run / hyperlink ops for only the changed cells, andapplyDiff()is its round-trip inverse. - Terminal rendering — the data model behind styled-grid output:
toAnsi()full repaints and diff-encoded delta frames, hyperlinks surviving intact.
Security & trust boundaries
- Cell runes ride the wire verbatim.
toAnsi()and the diff encoder never strip control characters from cell contents — callers rendering untrusted text must sanitize first (sugar-coreSanitize::untrusted()).text()does not respect styles either: invisible-styled runes still come out, so invisibility is not a redaction boundary. - Hyperlink fields are hard-gated. url and id refuse C0 controls, DEL and the C1 escape introducers — lone raw 0x80-0x9F bytes that do not continue a well-formed UTF-8 sequence, and their UTF-8
C2 xxspellings — and ids refuse semicolons, at construction and again on unserialization, so no escape introducer can be forged into the OSC 8 frame. Well-formed multibyte payloads (arrows, emoji, Cyrillic: an IRI) pass even though their continuation bytes sit in the C1 window. Buffer::fromString()is test-support, not an emulator. Only SGR sequences are interpreted; every other CSI frame deposits its parameter text into cells as literal runes. Do not feed it untrusted input expecting a parse.
Source
- Source on GitHub
- Full README
- Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project. The Buffer/Cell data model follows the cell/style design of charmbracelet/lipgloss and the terminal cell representation in charmbracelet/x (
x/vt).
API
| Class | Method | Description |
|---|---|---|
| Buffer | new(int, int) | Factory: creates width×height grid of blank cells |
| Buffer | cellAt(int, int) | Bounds-checked cell accessor; throws OutOfRangeException |
| Buffer | withCellAt(int, int, Cell) | Immutable cell setter; enforces the wide-pair law |
| Buffer | withRegion(Region, Buffer) | Blit source Buffer into this Buffer's region, clipped to the intersection; returns new Buffer |
| Buffer | width(), height(), region() | Dimension accessors |
| Buffer | fromGrid(int, int, array) | Wrap a flat cell list (index = row*width + col; count validated, pair law not) |
| Buffer | diff(Buffer $previous): list<DiffOp> / applyDiff(array $ops) | Delta ops that turn $previous into this buffer (dimensions must match) / replay them (negative cursor ops refused) |
| Buffer | fill(Region, Cell) / copy(Region) | Paint a region (clipped to the intersection) / extract an always region-sized Buffer (in-grid cells verbatim, out-of-grid area padded with blanks; capped by MAX_COPY_CELLS, 1,000,000) |
| Buffer | text(?Region) | Plain-text extraction; continuation cells skipped, invisible-styled runes included (rows joined with a bare LF, same contract as toAnsi()) |
| Buffer | toAnsi() / fromString(?string $ansi, int, int) | Render to SGR + OSC 8 bytes (rows joined with a bare LF — raw-mode callers post-process) / lossy test-support parse back. SGR channels above 255 saturate, a negative component is refused as malformed (params must be plain digit-runs), 38;5/48;5 indices map through the xterm-256 palette, and a truncated extended color ends the parse keeping the pen built so far |
| Cell | new(string, ?Style, ?Hyperlink, int) | Factory with rune, style, link, width (0 = continuation, 1 normal, 2 wide lead, larger = run-length span) |
| Cell | rune(), style(), link(), width(), equals(Cell) | Property accessors / value equality |
| Cell | continuation() | Factory: empty rune, null style/link, width=0 |
| Position | new(int, int) | Factory: col, row |
| Region | new(Position, int, int) | Factory: origin, width, height |
| Region | contains(int, int) / right() / bottom() | Hit-test a cell coordinate / inclusive edge coordinates |
| Style | new(?fg, ?bg, int attrs) | Convenience factory: RGB 0xRRGGBB colors and attrs bitmask. The full slot-aware form is the constructor — new Style(fg, bg, attrs, fgSlot, bgSlot, ul, ulSlot) — where slots are palette identities 0-255, validated at construction |
| Style | fromSgr(string $params, ?Style $carry) | Public SGR-parameter parser: reset, base/bright/256/RGB colors (slots recorded with an RGB fallback), underline color, on-codes 1-5, 7-9 and 53, off-codes 22, 23-25, 27-29 (22 clears bold and faint; 6, 26 and 55 have no arm); non-digit-run params throw, a truncated extended-color arm ends the parse keeping the pen built so far (null only when nothing was set) |
| Style | withAttrs(int) / withBold()…withInvisible() / bold() / reverse() / hasX() / equals() / valuesEqual() | Bitmask replace and nine single-bit toggles (bool $on = true); factories and predicates for all nine attributes; equals()/valuesEqual() compare by value (the null-safe form the encoders use) |
| Hyperlink | new(string, string) | Factory: url, id (C0 controls, DEL, lone raw 8-bit C1 bytes and their UTF-8 C2 xx spellings, and semicolons-in-id refused at construction and again on unserialization; valid multibyte IRI payloads pass) |