SugarConstraints
Constraint-based layout solver for terminal grids
A ratatui-style constraint layout solver behind a one-method LayoutSolver interface: GreedySolver (deterministic greedy solver, extracted from sugar-style, which now delegates back through its Layout\Solver bridge) implements every constraint type, and the deprecated CassowarySolver shim delegates to it. Plus DockLayout, a center-plus-side-stacks pane geometry. Consumers: sugar-panels (compat mode), candy-code (the Dock\* surface), candy-sql (dashboard page); sugar-forms requires the package but its withConstraints() knob is dormant, and sugar-widgets does not consume it.
Install
composer require sugarcraft/sugar-constraints
Quickstart
use SugarCraft\Constraints\Constraint\Constraint;
use SugarCraft\Constraints\{Direction, GreedySolver, Region};
$solver = GreedySolver::new();
$region = Region::fromSize(100, 24);
// The widths in the comments are what this 100-cell split returns.
$rects = $solver->solve($region, Direction::Horizontal, [
Constraint::length(20), // 20: exactly 20 cells
Constraint::min(10), // 10: a floor; the Fills below take the slack
Constraint::percentage(25), // 25: 25% of 100
Constraint::ratio(1, 10), // 10: 1/10 of 100
Constraint::fill(1), // 12: a third of the 35 cells left (+1 rounding cell, first Fill)
Constraint::fill(2), // 23: two thirds of them
]);
// Max is a greedy ceiling: it grows into free space up to its cap.
$capped = $solver->solve($region, Direction::Horizontal, [
Constraint::length(20), // 20
Constraint::max(15), // 15: clamped at its ceiling
Constraint::fill(1), // 65: everything Max did not take
]);
Solvers
GreedySolverDeterministic greedy solver. Extracted from sugar-style, which routes its own splits back through this solver. No deps; no strength or priority vocabulary. Small and stateless. Lossless rounding: floored fractions are handed back so for a well-constrained set the regions tile the span (Fill/Max remainder to the first Fill (or the first Max when no Fill is present), Min slack residue to the first Min, a Percentage/Ratio shortfall of at most N−1 cells reclaimed earliest-first). When fixed demand exceeds the span, regions shrink proportionally and still sum to it —
withoutOverflowTruncation() keeps full base sizes instead. Tiling assumes a positive-weight recipient: under-constrained fixed-only sets keep their gap, and a zero-weight-only Fill set leaves slack too — the README names all four carve-outs. Over-subscription truncates silently by design; demandOf() answers the pre-paint comparison under the instance's rounding policy.CassowarySolver (deprecated)The original Big-M simplex prototype never converged, so
solve() raises E_USER_DEPRECATED and delegates wholly to GreedySolver — results are identical. Kept only so existing call-sites keep working.DockLayoutCenter pane plus left/right weighted slot stacks. Stack heights are split in exact integer arithmetic (no float decides a boundary row); a weight set whose scaled sum would overflow is refused with
InvalidArgumentException where it is introduced, and resolve() itself never throws, degrading by dropping a side on small frames. withFixedColumns() claims exact columns for a side before the share pass (the center's floor still outranks exactness); fixed widths ride the version-2 manifest while share-only docks keep emitting the byte-identical version-1 shape.Constraint types
LengthFixed cell count — n cells, except the documented carve-outs (the reclaim ladder inflates it in sets with no Min and no Fill, overflow truncation shrinks it, compat mode runs off-grid); the README walks them.
MinSoft floor — at least n cells while slack survives every Fill and Max; clamps proportionally when demand exceeds the span; the README documents the semantics.
MaxCeiling — greedy, clamped to n cells.
FillProportional remainder — weight controls distribution across multiple Fill constraints.
PercentageFraction of total — n% of the available dimension.
RatioFractional proportion — num/denom of the total span, reserved like a fixed size.
Use it for
- Extracted from sugar-style — sugar-style's
Layout\Solverbridge now delegates back through this package. - Live pane splits —
sugar-panels(compat mode),candy-code'sDock\*surface, and thecandy-sqldashboard;sugar-formsrequires it but its constraint knob is dormant, andsugar-widgetsdoes not consume it. - Swap solver without breaking call-sites —
LayoutSolver(solve()alone; construction lives on the concrete classes) is the only public contract.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Inspired by ratatui/ratatui layout constraint system
- Originally inspired by Badros, Van den Broucke & Borning, "The Cassowary Linear Arithmetic Constraint Solving Algorithm", ACM TOPLAS 23(6), 2001 — this package implements neither the simplex nor the strength/priority vocabulary
API
| Class | Method | Description |
|---|---|---|
| LayoutSolver | solve(Region $region, Direction $dir, array $constraints): array | Solve constraints against a region in the given direction; returns one positioned sub-region per constraint - an empty list solves to [], keyed/sparse arrays and non-Constraint members throw InvalidArgumentException, and one constraint per region is the law: "30% but never under 20" is inexpressible |
| GreedySolver | new(): self / compat(): self | Default factory / sugar-panels parity mode (round-split, remainder-to-last, non-truncating overflow) |
| GreedySolver | static solveStatic(Region $area, Direction $dir, array $constraints): array | Legacy no-instance entry for the pre-immutable default policy; argument order matches solve() (reordered 2026-11 — a repo grep found no external positional callers of the old transposed order); prefer an instance for the compat() toggles |
| GreedySolver | new(roundSplit: false, remainderToLast: false, truncateOverflow: true, minShare: 0, reserveGap: 0, reserveLead: 0) | Public six-named-arg constructor — a supported entry point (the zero-arg call keeps the legacy defaults byte-for-byte); negative floor/reserve values throw InvalidArgumentException, and all six fields are public readonly so the resolved policy reads back off the instance |
| GreedySolver | static minShareFloor(int $cells = 1, int $reserveGap = 0, int $reserveLead = 0) | Dedicated construction door for the sequential min-share floor — the compat knobs arrive at the mode's truth (floor split, remainder to the LAST region, truncation on) rather than being inherited, for instances built engaged rather than retuned |
| GreedySolver | demandOf(Region $area, Direction $dir, array $constraints): int | Demand of the set: fixed sizes exact, Percentage/Ratio resolved under the instance's rounding policy, Min floors summed, Max caps ceilinged, Fill contributes 0; demand above the solved axis says the set cannot be satisfied whole. Shares solve()'s list/sparse guard |
| GreedySolver | withRoundSplit() / withRemainderToLast() / withoutOverflowTruncation() / withOverflowTruncation(bool) / withMinShare(cells, reserveGap, reserveLead) | Immutable rounding and overflow options; withMinShare() runs its own proportional path, resets roundSplit/remainderToLast to the mode's truth on engagement, and refuses any set containing a non-Fill constraint on both axes |
| GreedySolver / CassowarySolver | static greedy() / static cassowary() | Concrete-class factories - construction lives on the classes, not the interface; CassowarySolver::greedy() is a warning-free escape hatch returning a supported GreedySolver |
| CassowarySolver | new(): self | Deprecated shim; solve() raises E_USER_DEPRECATED and delegates to GreedySolver |
| Direction | Horizontal, Vertical / other() | Enum: split direction; other() answers the counterpart axis — the Dock vocabulary's Side::other() shape, so callers never hard-code the flip |
| Region | fromSize(int, int) / withOrigin(int $x, int $y) | Factory: width, height; withOrigin() translates without resizing — a negative destination is refused loudly by the same boundary guard the constructor carries |
| Constraint | length(int $n) | Fixed cell count; length(-1) throws InvalidArgumentException |
| Constraint | min(int $n) | Soft floor - at least n cells; negative n throws InvalidArgumentException |
| Constraint | max(int $n) | Ceiling - at most n cells; negative n throws InvalidArgumentException |
| Constraint | fill(int $weight = 1) | Proportional remainder with weight; fill(0) is accepted and silently weightless |
| Constraint | percentage(int $n) | Percentage of total for 0-100; out of range (e.g. 150 or -5) throws InvalidArgumentException |
| Constraint | ratio(int $numerator, int $denominator) | Fraction of the total span; a negative numerator or a zero/negative denominator throws InvalidArgumentException |
| Dock\DockLayout | new(centerPaneId = 'center') / withSlotAdded(side, paneId, index?) / withSlotRemoved(paneId) / withSlotMovedTo(paneId, side, index?) / slots(side) | Immutable center-plus-stacks dock manifest; an undocked withSlotRemoved() is an idempotent no-op while withSlotMovedTo() throws; every slot mutator scans all stacks, so batch with fromArray() (a single linear pass) |
| Dock\DockLayout | withColumnShare(side, num, denom) / withColumnShareExact(side, num, denom) / columnShare(side) | Rational column shares: malformed rationals throw, requested magnitudes clamp down under the pair rule and the mutator stores the effective share (read columnShare() to observe a clamp); withColumnShareExact() refuses a would-be clamp with InvalidArgumentException naming the ceiling |
| Dock\DockLayout | withStackWeight(side, index, num, denom) / withStackWeightFor(side, paneId, num, denom) | Slot weights by positional index or retargeted by pane id — the id door names the miss, so a removal that shifted the stack can never make an index weight the wrong slot; a weight set whose scaled sum would overflow PHP_INT_MAX is refused where it is introduced |
| Dock\DockLayout | withMinimums(centerMinCols, sideMinCols) / withFixedColumns(side, cols) | 24/20 shipped floors the degradation ladder reads per frame; withFixedColumns() claims EXACTLY that many columns for a side before the share pass (the sideMinCols raise never touches a fixed side, and the center's floor still outranks exactness); 0 returns the side to share-driven planning |
| Dock\DockLayout | toArray() / static fromArray(array) | Versioned lossless persistence: share-only docks emit the byte-identical version-1 shape, a dock with fixed columns emits version 2 plus a 'fixed' map, and fromArray() accepts both (an absent fixed key means [0, 0], so every v1 blob round-trips byte-identically); malformed manifests throw InvalidArgumentException naming the failed key |
| Dock\DockLayout | resolve(Region $frame): DockGeometry | Never throws; below the floors it degrades by dropping sides, and the divider is fixed at one column |
| Dock\DockGeometry | static new(regions, dividerColumns) / regionFor(paneId) / dividerColumns() / isEmpty() · public readonly $regions / $dividerColumns | final readonly resolved absolute regions in insertion order (left stack, center, right stack); new() is the validating public door for untrusted payloads while resolve() builds through an @internal zero-validation seam (the solved() twin — nothing reachable from a geometry can mutate). regionFor() null covers never-docked, ladder-dropped, and degenerate alike; a 0-width region is NOT null |
| Dock\DockSlot / Dock\Side | DockSlot::new(paneId, num, denom) / withWeight(num, denom); Side::other() | One vertical stack slot with a rational weight; opposite-side lookup |