SugarPanels
H/V panels with flex/natural sizing, borders, nesting, and stateful delta rendering
Compose terminal layouts with horizontal and vertical panels. Attach borders, hint minimum and maximum sizes, let flex children fill the rest, and nest arbitrarily deep.
Install
composer require sugarcraft/sugar-panels
Quickstart
use SugarCraft\Panels\SugarPanels;
$panels = SugarPanels::new();
$layout = $panels->vertical(
$panels->horizontal(
$panels->leaf("Left panel"),
$panels->leaf("Right panel"),
)->withBorder(false)->withGrow(),
$panels->leaf("Bottom bar")->withBorder(false),
)->withBorder(false);
echo $panels->render($layout, 60, 7);
Every node is bordered by default — a plain nested layout paints a doubled frame at each level. Containers are usually scaffolding, so turn their frames off with withBorder(false) (or wrap a subtree in noBorder(), which suppresses every frame and every divider below it), and give the viewport enough rows to hold what you asked for. That prints (protocol and styling stripped):
╭────────────────────────────╮╭────────────────────────────╮
│Left panel ││Right panel │
│ ││ │
│ ││ │
│ ││ │
╰────────────────────────────╯╰────────────────────────────╯
Bottom bar
The horizontal row carries withGrow(), so it flexes to six of the seven rows while Bottom bar — the fixed child — claims its measured natural single row at the bottom. Every row the renderer emits is padded to the viewport width, Bottom bar's included.
Concepts
A layout is a tree of Node values. A leaf holds text. A horizontal or vertical node splits its region among its children, and noBorder() wraps a subtree to drop every frame and divider inside it. SugarPanels::render() paints the tree into a viewport of a given width and height and returns one ANSI string.
Nodes are immutable. Every with*() call returns a new node, so a chain whose result is discarded has no effect. Sizing comes from hints. withMinWidth(), withMaxWidth() and their height twins bound a node's footprint, and withFlex() or withGrow() lets a child fill the space its fixed siblings leave over. Flex sizing is delegated to the greedy solver in sugar-constraints, running in its parity mode.
Every node draws a border by default. That is right for leaf panels and wrong for scaffolding, which is why the Quickstart turns container frames off. The renderer keeps the previous frame's cell grid, so a second render() at the same size emits only the cells that changed.
Tasks
- Fixed header and status bar around a growing body. Give the header and bar no flex weight, so they claim their natural size, and give the body
withGrow(). Put the three in avertical()node. - Remove frames from a container. Call
withBorder(false)on the container, or wrap the subtree innoBorder()to suppress every frame and divider below it. Adjacent panels then render touching. - Title a panel. Call
withTitle()on the leaf or container. The title is sanitized withSanitize::paintedTitle(), so line feeds are flattened and it paints on one row. - Redraw efficiently. Keep one
SugarPanelsinstance and callrender()each frame at the same size. CallresetPreviousFrame()after anything else has written to the terminal, so the next render repaints in full without erasing. - Show untrusted text. Sanitize it before it reaches
leaf()orwithTitle(). Trusted text can carry escape sequences into the grid, as the Trust boundary section of the README explains.
What's in the box
Styled content stays trusted input — escape sequences ride through by design; see the README's Trust boundary section.
Where it fits
There are no in-repo consumers yet — sugar-panels ships as the ecosystem's pane composer for your application. When a sibling does a similar-looking job: the raw CSS flexbox computation (solve, don't paint) is sugar-flexbox; modal foregrounds over existing content with dimming and zone hit-testing are sugar-overlay; tabular data grids with a row cursor are sugar-table. Nested horizontal/vertical panes with borders, titles and flex weights, painted as plain ANSI strings — that is sugar-panels.
Configuration and options
| Option | Type | Default | Effect |
|---|---|---|---|
Node::withMinWidth() / withMinHeight() | int | 0 | Floor for the natural size. Negative values clamp to 0. Nothing throws. |
Node::withMaxWidth() / withMaxHeight() | int | 0 | Cap on the painted footprint, including frame, padding and content. 0 means no cap. Margin sits outside the cap. |
Node::withPadding() | int | 0 | Inner padding in cells. |
Node::withSpacing() | int | 0 | Gap between children in cells. |
Node::withMargin() | int top, right, bottom, left | 0 | Outer margin in cells. |
Node::withFlex() / withGrow() | int | 0 | 0 is a fixed child at its natural size. withGrow() is withFlex(1), and larger weights take a bigger share of leftover space. |
Node::withBorder() | bool | true | Shows or hides the box border. |
Node::withBorderStyle() | ?Border | sugar-style default | Border character set from sugar-style. Border::catalog() lists the presets. |
Node::withStyle() | ?Style | none | Color and attributes from sugar-style. |
Node::withTitle() | string | '' | Box title, painted on one row. |
Node::withAlignH() / withAlignV() | ?Align, ?VAlign | none | Text alignment. null clears it. |
SugarPanels::MAX_VIEWPORT_DIMENSION | int | 4096 | Largest viewport side that render() accepts. Larger values throw InvalidArgumentException before anything is allocated. |
SugarPanels::MAX_VIEWPORT_CELLS | int | 1000000 | Largest viewport area that render() accepts. |
Keys and input
sugar-panels reads no input and binds no keys. It is an output composer: the host decides what the viewport shows and calls render() when it changes. The inputs that matter are the viewport numbers. Negative sizes, sides above MAX_VIEWPORT_DIMENSION and areas above MAX_VIEWPORT_CELLS throw. A zero width or height is valid, paints nothing and leaves no diff state behind, so a collapsed pane cannot poison the next size.
Theme and styling
Styling goes through sugar-style. withStyle() applies color and attributes to a node's content, and withBorderStyle() picks a border character set. The examples/borders.php demo reads Border::catalog() at runtime, so every preset sugar-style ships appears in it. Styled text stays trusted input, so escape sequences in content pass through unchanged, and a clipped or unbalanced span is reset so its color stays inside its box.
Examples
| File | Shows |
|---|---|
examples/basic.php | Two single-level splits, a three-column row and a two-pane stack, sized by min* hints. |
examples/borders.php | Every border preset sugar-style ships, side by side with its name. |
examples/nested.php | A three-level vertical, horizontal, vertical nest. Every box is bordered. |
examples/flex.php | A fixed sidebar sized by its content, next to a growing pane. |
examples/diff.php | The stateful loop: a full frame, a delta frame that changes one digit, and a frame after a resize. |
Run any of them from the lib root with php examples/basic.php. Every example is executed by the suite through tests/ReadmeSnippetsTest.php.
Testing
Run the suite from the lib root:
composer install && vendor/bin/phpunit
The suites cover framing and separators, flex layout, the solver delegation, the frame protocol, ANSI placement, the sanitize boundary, max-width and margin rules, and the edge cases of tiny viewports. Test your own layouts by rendering to a fixed width and height and comparing against the expected string.
Troubleshooting and FAQ
- Every level of a nested layout draws its own frame. Every node is bordered by default. Use
withBorder(false)on containers, or wrap the subtree innoBorder(). render()throwsInvalidArgumentException. The viewport is outside the documented ranges: a negative side, a side above 4096, or an area above 1000000 cells. Clamp the host's winsize before calling render.- Old text stays on screen after a resize. A full frame that follows a resize erases the screen first.
resetPreviousFrame()forces a full repaint without an erase, so call it only when the screen is already clear. - A
with*()call seems to do nothing. Nodes are immutable, so the result must be kept. Write$node = $node->withGrow();. - Content is cut off or wrapped unexpectedly. Lines wider than the interior word-wrap at cell boundaries. Height overflow is dropped without a trace, because continuations consume the row budget and lines past the interior height are not painted. Give the node more rows, or let it flex.
- A grown child is smaller than its min hint. A grown child gets only its weighted share, so its min is not applied, and
totalWidth()over-claims for grown children. Fixed children honor the min through their base size.
Upstream mapping
The lib is inspired by treilik/bubbleboxer (Go), a library of nested boxes with weighted sizes and borders. The mapping is by concept. It is not a class-for-class port.
| Concept (bubbleboxer) | SugarPanels |
|---|---|
| Nested horizontal and vertical boxes | SugarPanels::horizontal(), SugarPanels::vertical() |
| Weighted sizing of leftover space | Node::withFlex(), Node::withGrow() |
| Bordered boxes | Node::withBorder(), Node::withBorderStyle() |
| Titled boxes | Node::withTitle() |
Architecture
Three classes do the work. SugarPanels is the renderer. It walks the tree, asks the constraint solver for each split, paints cells into a buffer, and diffs the buffer against the previous frame. Node is the immutable tree value, and its with*() setters return new nodes. Sanitize normalizes text before it reaches the grid: painted() repairs UTF-8, collapses carriage returns and tabs, and removes unpaintable control characters, and paintedTitle() also flattens line feeds. Both are idempotent, so a host can pre-sanitize and round-trip content unchanged. Cell storage and the delta encoder come from sugar-cellbuffer. Borders and styles come from sugar-style.
Changelog and versioning
The package ships no CHANGELOG file. The commit history of sugar-panels/ in the monorepo is the record of changes. Pin a version in your own manifest. The monorepo publishes all libraries together.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by treilik/bubbleboxer (Go); SugarCraft is developed as a native PHP project.
API reference
| Class | Method | Description |
|---|---|---|
| SugarPanels | new() | Create a panels instance |
| SugarPanels | leaf(string|Buffer) | Leaf node with string content, or a cell Buffer it paints cell for cell |
| SugarPanels | horizontal(Node ...) | Horizontal (row) layout |
| SugarPanels | vertical(Node ...) | Vertical (column) layout |
| SugarPanels | noBorder(Node) | Suppresses every frame and every divider through the whole subtree — adjacent panels render touching |
| SugarPanels | render(Node, int $width, int $height) | Paint one frame to an ANSI string; throws InvalidArgumentException on a viewport outside the documented ranges |
| SugarPanels | paintedLeaves(): int | How many leaves the last render() painted; a same-size frame with the same layout repaints only the leaves whose text, cells, style, frame, scroll offset or focus changed |
| SugarPanels | resetPreviousFrame() | Drop the frame cache — the next render() repaints full, without erasing |
| SugarPanels | MAX_VIEWPORT_DIMENSION | 4096 cells — largest viewport side accepted |
| SugarPanels | MAX_VIEWPORT_CELLS | 1 000 000 cells — largest viewport area accepted (printed as 1000000 in the exception message) |
| Node | leaf(string|Buffer) | Static leaf constructor; a Buffer is placed cell for cell instead of text |
| Node | horizontal(Node ...) | Static horizontal constructor |
| Node | vertical(Node ...) | Static vertical constructor |
| Node | noBorder(Node) | Static no-border wrapper — suppresses every frame and every divider through the whole subtree |
| Node | totalWidth() / totalHeight() | Footprint the node claims: natural content, floored by min*, capped by max*, plus padding, frame and margin |
| Node | withMinWidth(int) | Floor for the natural width. That floor enters the flex path through fixed children's bases; a grown child gets only its weighted share, its min* is not applied, and totalWidth() over-claims for grown children; in the legacy equal-split fallback, a min* acts as a proportional weight, not a floor |
| Node | withMaxWidth(int) | Cap on the node's painted footprint (frame + padding + content) — what a flex basis claims. 0 means no cap; margin rides outside the cap, matching totalWidth() |
| Node | withMinHeight(int) | Floor for the natural height. That floor enters the flex path through fixed children's bases; a grown child gets only its weighted share, its min* is not applied, and totalHeight() over-claims for grown children; in the legacy equal-split fallback, a min* acts as a proportional weight, not a floor |
| Node | withMaxHeight(int) | Cap on the node's painted footprint (frame + padding + content) — what a flex basis claims. 0 means no cap; margin rides outside the cap, matching totalHeight() |
| Node | withPadding(int) | Inner padding (cells) |
| Node | withBorder(bool) | Show/hide box border |
| Node | withSpacing(int) | Gap between children (cells) |
| Node | withContent(string) | Replace leaf content (new node) |
| Node | withFlex(int) | Fill leftover space by weight (0 = fixed, natural size) |
| Node | withGrow() | Shorthand for withFlex(1) |
| Node | withBorderStyle(?Border) | Border char set from sugar-style |
| Node | withStyle(?Style) | Style (color, attributes) from sugar-style |
| Node | withTitle(string) | Box title text |
| Node | withMargin(int $top, ...) | Outer margin (top/right/bottom/left) |
| Node | withAlignH(?Align) | Horizontal text alignment (null clears) |
| Node | withAlignV(?VAlign) | Vertical text alignment (null clears) |
| Node | withCells(?Buffer) | Cells a leaf paints instead of its text, placed top-left in the padded content box and clipped to it; null returns the leaf to its text |
| Node | withScrollOffset(int $rows) | Skip this many rows of leaf content from the top (text rows after wrap, or cell rows); clamps to 0 and to the last full page |
| Node | withFocused(bool = true) | Paint the node's frame with the focus border set and pen; layout is unchanged |
| Node | withFocusBorderStyle(?Border) / withFocusStyle(?Style) | Border set (null restores Border::thick()) and pen (null paints unstyled) for the focus frame |
| Splitter | horizontal(Node ...) / vertical(Node ...) | A run of panes split along one axis with draggable dividers; divider i sits on the last column (row) of pane i |
| Splitter | withBounds(int $x, int $y, int $width, int $height) | Where the splitter is painted, in screen cells; existing sizes rescale proportionally (equal shares when none were set) |
| Splitter | withSizes(int ...) / withMinPaneSize(int) / withPanes(Node ...) | Explicit pane sizes fitted to the span (kept until withBounds() when called first), the drag floor, and replacement panes (sizes survive an unchanged count) |
| Splitter | update(Msg): [Splitter, null] / withDividerDrag(int $position, ?int $divider = null) | Drag driven by mouse messages: a left press on a divider grabs it, motion moves it, the release lets go; each move trades cells between the two neighbors only |
| Splitter | dividerAt(int $col, int $row): ?int / dividerPositions() / isDragging() | Divider hit test and screen positions |
| Splitter | node(): Node | The frameless, spacing-0 layout tree that gives each pane exactly its size |
Only methods declared in sugar-panels/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\Panels
Node final class
Immutable layout tree node.
| Method | Summary |
|---|---|
static leaf(string|Buffer $content = ''): self | A leaf paints either text or pre-built cells. Text is the historical door: it is sanitized at the paint boundary and word-wrapped into the region. A Buffer is placed cell for cell (each cell keeps its own pen, link and width), so a host that already renders into cells does not have to flatten them into escape strings for the panel to re-parse. |
static horizontal(Node ...$children): self | |
static vertical(Node ...$children): self | |
static noBorder(Node $child): self | No-border wrapper — suppresses every frame and every divider through the whole subtree, so adjacent panels render touching. Contrast with self::withBorder(false), which hides one node's own frame and leaves the rest of the layout's rules in place. The wrapper carries border:false and threads $noFrames on render (see SugarPanels::renderNoBorder; pinned by tests/FramingAndSeparatorsTest.php). |
isLeaf(): bool | Shape predicates. The kind string constants remain the wire form, but comparisons are spelled through these so intent reads and the constants cannot be hand-typo'd at call sites. |
isHorizontal(): bool | |
isVertical(): bool | |
withMinWidth(int $w): self | |
withMaxWidth(int $w): self | |
withMinHeight(int $h): self | |
withMaxHeight(int $h): self | |
withFlex(int $weight): self | Mark this child as flexible: in a horizontal/vertical parent it grows to fill the space left after the fixed (non-flex) siblings take their natural size, sharing that leftover with other flex children in proportion to the weight. A weight of 0 means the child is fixed (non-flex). |
withGrow(): self | Shorthand for withFlex(1): this child fills the leftover space. |
withPadding(int $cells): self | Inner inset around painted content. Applies to leaf nodes only; a container ignores it — its children fill the box. |
withBorder(bool $show): self | Toggle this node's OWN frame. Contrast with self::noBorder(), which flattens a whole subtree's frames and dividers, while this hides only the one box and leaves sibling frames and rules alone. The chosen border style survives a true → false → true round-trip: disabling hides the frame, enabling re-shows the style that was last set. |
withSpacing(int $cells): self | |
withBorderStyle(?Border $b): self | Set the border character set from sugar-style. Passing null CLEARS the style: the frame then falls back to Border::rounded() at draw time. The border bool still controls visibility — clearing the style does not hide the border. |
withStyle(?Style $s): self | Set the canonical style from sugar-style. Passing null CLEARS the style — content renders unstyled. |
withTitle(string $t): self | Set the box title text. Passing '' CLEARS the title — the top edge renders as an unbroken run. |
withMargin(int $top, ?int $right = null, ?int $bottom = null, ?int $left = null): self | Set outer margin (top, right, bottom, left). sugar-panels-specific: sugar-style Style does not ship margin as a first-class concept. |
withAlignH(?Align $a): self | Set horizontal text alignment (sugar-panels-specific). Passing null CLEARS the alignment — content renders left-aligned. |
withAlignV(?VAlign $v): self | Set vertical text alignment (sugar-panels-specific). Passing null CLEARS the alignment — content renders top-aligned. |
withContent(string $content): self | Painted string for a leaf. Containers paint their children, never a content string, so content set on a container is stored but inert. |
withCells(?Buffer $cells): self | Cells for a leaf to paint instead of its text content. While cells are set they win over $content; passing null returns the leaf to its text. Cells are placed top-left in the padded content box and clipped to it; leaf style and alignment apply to text only. |
withScrollOffset(int $rows): self | Skip this many rows of leaf content from the top (text rows after word wrap, or cell rows). Negative values clamp to 0. At render time the offset also clamps to the last full page, so scrolling past the end shows the final rows instead of an empty box. |
withFocused(bool $focused = true): self | Mark this node as focused: its frame paints with the focus border set (withFocusBorderStyle(), default Border::thick()) and the focus pen (withFocusStyle()). A node whose frame is hidden has no focus frame to show. Layout is unchanged: focus never moves a cell. |
withFocusBorderStyle(?Border $border): self | Border set for the focus frame; null restores Border::thick(). |
withFocusStyle(?Style $style): self | Pen for the focus frame glyphs; null paints them unstyled. |
totalWidth(): int | Total width including border, padding, the node's own left+right margin, and — for HORIZONTAL layouts only — the inter-child spacing. Vertical spacing consumes rows, never columns, so it is excluded from the width footprint (mirroring totalHeight()'s treatment of horizontal spacing). |
totalHeight(): int | |
marginWidth(): int | The node's own horizontal margin (left + right). |
marginHeight(): int | Vertical counterpart of marginWidth(): top + bottom. |
Sanitize final class
The paint boundary: what a panel is willing to place into a cell grid.
| Method | Summary |
|---|---|
static painted(string $text): string | Normalise text destined for the grid into text the grid can paint. |
static paintedTitle(string $title): string | Normalise a box title. |
Splitter final class
A run of panes split along one axis with draggable dividers.
| Method | Summary |
|---|---|
static horizontal(Node ...$panes): self | Panes side by side; dividers are vertical and drag by column. |
static vertical(Node ...$panes): self | Panes stacked top to bottom; dividers are horizontal and drag by row. |
withPanes(Node ...$panes): self | Replace the panes. Sizes survive when the pane count is unchanged; otherwise the span is shared out again equally. |
withBounds(int $x, int $y, int $width, int $height): self | Where the splitter is painted, in screen cells. Existing sizes are rescaled proportionally to the new span (equal shares when none were set), so a terminal resize keeps the split's proportions. |
withSizes(int ...$sizes): self | Set the pane sizes explicitly (cells along the axis). The list is fitted to the span: a short or long total is rescaled, and no pane goes below the minimum while the span can hold every pane at the minimum. Called before withBounds() (no span yet), the list is kept and fitted once bounds arrive, so the call order does not matter. |
withMinPaneSize(int $cells): self | Smallest size a drag may leave a pane with (clamped to at least 1). |
withDividerDrag(int $position, ?int $divider = null): self | Move a divider so it lands on screen column (row, for a vertical splitter) $position. |
dividerAt(int $col, int $row): ?int | Which divider sits at screen cell ($col, $row), or null. Divider i is the last column (row) of pane i, across the splitter's full cross extent. |
dividerPositions(): array | Screen column (row) of each divider, in order. |
isDragging(): bool | |
update(Msg $msg): array | Drive divider drag from mouse messages. |
node(): Node | The layout tree for the current sizes: a frameless, spacing-0 container whose panes are weighted by their sizes, so SugarPanels gives each pane exactly its cells when the tree is rendered at the splitter's span. A pane's own flex weight is cleared and its min* along the axis becomes its size (the splitter owns that axis). Before bounds are known the panes are returned unweighted. |
SugarPanels final class
Box-drawing layout renderer.
| Method | Summary |
|---|---|
static new(): self | Create a new SugarPanels instance — the canonical door (mirrors the house ::new() factory convention Node follows). It is sugar over the identical public constructor below; both are documented at self::__construct(). |
__construct() | Create a new SugarPanels instance. |
leaf(string|Buffer $content = ''): Node | A leaf of text, or of pre-built cells (see Node::leaf()). |
horizontal(Node ...$children): Node | |
vertical(Node ...$children): Node | |
noBorder(Node $child): Node | |
render(Node $root, int $width, int $height): string | Render a layout node tree into a string within the given viewport. |
paintedLeaves(): int | How many leaves the last render() painted. |
resetPreviousFrame(): void | Reset the previous-frame buffer, forcing the next render to emit a full frame (used on window resize or cursor-position-lost events). |
Demos.
VHS-recorded GIFs of three of the five examples shipped with the library. Regenerated automatically on every push that touches the source.
Border styles
Every named Border::catalog() preset, side by side with its name.
Basic compose
Horizontal + vertical panels with weighted sizing.
Nested grids
A grid-of-grids — header / body / footer with sidebars.Related
- SugarConstraints: the greedy constraint solver that sizes panel grids.