All 48 libraries

SugarPanels

H/V panels with flex/natural sizing, borders, nesting, and stateful delta rendering

inspired by treilik/bubbleboxer layoutboxborderuipaneltui

SugarPanels code coverage

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 a vertical() node.
  • Remove frames from a container. Call withBorder(false) on the container, or wrap the subtree in noBorder() 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 with Sanitize::paintedTitle(), so line feeds are flattened and it paints on one row.
  • Redraw efficiently. Keep one SugarPanels instance and call render() each frame at the same size. Call resetPreviousFrame() 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() or withTitle(). Trusted text can carry escape sequences into the grid, as the Trust boundary section of the README explains.

What's in the box

H/V panelsRow and column composition with weighted sizing.
BordersPreset or custom border styles per panel.
Nested layoutsArbitrarily deep nesting — grids within grids.
Word-wrapText reflows inside the region at render time.
ANSI-awareStyled content is placed by visible columns; a clipped or unbalanced span is auto-reset so color stays inside its box.
Diff renderingSelf-positioning delta frames repaint only the cells that changed — light SSH payloads, no full-screen flicker.
Trust boundaryHostile text is repaired, not rejected: UTF-8 mended, zone sentinels stripped, stray controls normalized at the paint choke.
Flex / growwithFlex/withGrow children fill leftover space — fixed headers and status bars, a content pane that fills.

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

OptionTypeDefaultEffect
Node::withMinWidth() / withMinHeight()int0Floor for the natural size. Negative values clamp to 0. Nothing throws.
Node::withMaxWidth() / withMaxHeight()int0Cap on the painted footprint, including frame, padding and content. 0 means no cap. Margin sits outside the cap.
Node::withPadding()int0Inner padding in cells.
Node::withSpacing()int0Gap between children in cells.
Node::withMargin()int top, right, bottom, left0Outer margin in cells.
Node::withFlex() / withGrow()int00 is a fixed child at its natural size. withGrow() is withFlex(1), and larger weights take a bigger share of leftover space.
Node::withBorder()booltrueShows or hides the box border.
Node::withBorderStyle()?Bordersugar-style defaultBorder character set from sugar-style. Border::catalog() lists the presets.
Node::withStyle()?StylenoneColor and attributes from sugar-style.
Node::withTitle()string''Box title, painted on one row.
Node::withAlignH() / withAlignV()?Align, ?VAlignnoneText alignment. null clears it.
SugarPanels::MAX_VIEWPORT_DIMENSIONint4096Largest viewport side that render() accepts. Larger values throw InvalidArgumentException before anything is allocated.
SugarPanels::MAX_VIEWPORT_CELLSint1000000Largest 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

FileShows
examples/basic.phpTwo single-level splits, a three-column row and a two-pane stack, sized by min* hints.
examples/borders.phpEvery border preset sugar-style ships, side by side with its name.
examples/nested.phpA three-level vertical, horizontal, vertical nest. Every box is bordered.
examples/flex.phpA fixed sidebar sized by its content, next to a growing pane.
examples/diff.phpThe 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 in noBorder().
  • render() throws InvalidArgumentException. 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 boxesSugarPanels::horizontal(), SugarPanels::vertical()
Weighted sizing of leftover spaceNode::withFlex(), Node::withGrow()
Bordered boxesNode::withBorder(), Node::withBorderStyle()
Titled boxesNode::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

Try the quickstart →

API reference

ClassMethodDescription
SugarPanelsnew()Create a panels instance
SugarPanelsleaf(string|Buffer)Leaf node with string content, or a cell Buffer it paints cell for cell
SugarPanelshorizontal(Node ...)Horizontal (row) layout
SugarPanelsvertical(Node ...)Vertical (column) layout
SugarPanelsnoBorder(Node)Suppresses every frame and every divider through the whole subtree — adjacent panels render touching
SugarPanelsrender(Node, int $width, int $height)Paint one frame to an ANSI string; throws InvalidArgumentException on a viewport outside the documented ranges
SugarPanelspaintedLeaves(): intHow 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
SugarPanelsresetPreviousFrame()Drop the frame cache — the next render() repaints full, without erasing
SugarPanelsMAX_VIEWPORT_DIMENSION4096 cells — largest viewport side accepted
SugarPanelsMAX_VIEWPORT_CELLS1 000 000 cells — largest viewport area accepted (printed as 1000000 in the exception message)
Nodeleaf(string|Buffer)Static leaf constructor; a Buffer is placed cell for cell instead of text
Nodehorizontal(Node ...)Static horizontal constructor
Nodevertical(Node ...)Static vertical constructor
NodenoBorder(Node)Static no-border wrapper — suppresses every frame and every divider through the whole subtree
NodetotalWidth() / totalHeight()Footprint the node claims: natural content, floored by min*, capped by max*, plus padding, frame and margin
NodewithMinWidth(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
NodewithMaxWidth(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()
NodewithMinHeight(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
NodewithMaxHeight(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()
NodewithPadding(int)Inner padding (cells)
NodewithBorder(bool)Show/hide box border
NodewithSpacing(int)Gap between children (cells)
NodewithContent(string)Replace leaf content (new node)
NodewithFlex(int)Fill leftover space by weight (0 = fixed, natural size)
NodewithGrow()Shorthand for withFlex(1)
NodewithBorderStyle(?Border)Border char set from sugar-style
NodewithStyle(?Style)Style (color, attributes) from sugar-style
NodewithTitle(string)Box title text
NodewithMargin(int $top, ...)Outer margin (top/right/bottom/left)
NodewithAlignH(?Align)Horizontal text alignment (null clears)
NodewithAlignV(?VAlign)Vertical text alignment (null clears)
NodewithCells(?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
NodewithScrollOffset(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
NodewithFocused(bool = true)Paint the node's frame with the focus border set and pen; layout is unchanged
NodewithFocusBorderStyle(?Border) / withFocusStyle(?Style)Border set (null restores Border::thick()) and pen (null paints unstyled) for the focus frame
Splitterhorizontal(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
SplitterwithBounds(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)
SplitterwithSizes(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)
Splitterupdate(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
SplitterdividerAt(int $col, int $row): ?int / dividerPositions() / isDragging()Divider hit test and screen positions
Splitternode(): NodeThe 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.

MethodSummary
static leaf(string|Buffer $content = ''): selfA 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): selfNo-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(): boolShape 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): selfMark 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(): selfShorthand for withFlex(1): this child fills the leftover space.
withPadding(int $cells): selfInner inset around painted content. Applies to leaf nodes only; a container ignores it — its children fill the box.
withBorder(bool $show): selfToggle 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): selfSet 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): selfSet the canonical style from sugar-style. Passing null CLEARS the style — content renders unstyled.
withTitle(string $t): selfSet 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): selfSet outer margin (top, right, bottom, left). sugar-panels-specific: sugar-style Style does not ship margin as a first-class concept.
withAlignH(?Align $a): selfSet horizontal text alignment (sugar-panels-specific). Passing null CLEARS the alignment — content renders left-aligned.
withAlignV(?VAlign $v): selfSet vertical text alignment (sugar-panels-specific). Passing null CLEARS the alignment — content renders top-aligned.
withContent(string $content): selfPainted 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): selfCells 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): selfSkip 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): selfMark 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): selfBorder set for the focus frame; null restores Border::thick().
withFocusStyle(?Style $style): selfPen for the focus frame glyphs; null paints them unstyled.
totalWidth(): intTotal 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(): intThe node's own horizontal margin (left + right).
marginHeight(): intVertical counterpart of marginWidth(): top + bottom.

Sanitize final class

The paint boundary: what a panel is willing to place into a cell grid.

MethodSummary
static painted(string $text): stringNormalise text destined for the grid into text the grid can paint.
static paintedTitle(string $title): stringNormalise a box title.

Splitter final class

A run of panes split along one axis with draggable dividers.

MethodSummary
static horizontal(Node ...$panes): selfPanes side by side; dividers are vertical and drag by column.
static vertical(Node ...$panes): selfPanes stacked top to bottom; dividers are horizontal and drag by row.
withPanes(Node ...$panes): selfReplace 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): selfWhere 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): selfSet 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): selfSmallest size a drag may leave a pane with (clamped to at least 1).
withDividerDrag(int $position, ?int $divider = null): selfMove a divider so it lands on screen column (row, for a vertical splitter) $position.
dividerAt(int $col, int $row): ?intWhich 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(): arrayScreen column (row) of each divider, in order.
isDragging(): bool
update(Msg $msg): arrayDrive divider drag from mouse messages.
node(): NodeThe 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.

MethodSummary
static new(): selfCreate 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 = ''): NodeA 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): stringRender a layout node tree into a string within the given viewport.
paintedLeaves(): intHow many leaves the last render() painted.
resetPreviousFrame(): voidReset 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

Border styles

Every named Border::catalog() preset, side by side with its name.
Basic compose

Basic compose

Horizontal + vertical panels with weighted sizing.
Nested grids

Nested grids

A grid-of-grids — header / body / footer with sidebars.