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
Requires PHP 8.3 or newer. The package has no runtime dependencies.
Quickstart
A classic two-pane sidebar: a fixed-width rail and a content pane that takes whatever width is left. The runnable walk ships as examples/sidebar.php, which runs this split at widths 100 and 10, then a four-pane mix.
use SugarCraft\Constraints\Constraint\Constraint;
use SugarCraft\Constraints\{Direction, GreedySolver, Region};
$solver = GreedySolver::new();
$rects = $solver->solve(Region::fromSize(100, 20), Direction::Horizontal, [
Constraint::length(24), // 24: sidebar, 24 cells
Constraint::fill(1), // 76: content, the cells left
]);
Constraint tour
One 100-cell row with every constraint type. This block is a tour, not a script: no file under examples/ runs it, and the widths in its comments are what the solver returns for it.
$region = Region::fromSize(100, 20);
$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
]);
solve() returns one positioned Region per constraint, in list order. The x and y offsets are absolute cell coordinates: the input region's origin is already included, so a region at x=5 returns its first box at x=5. Paint each box at its returned x and y without adding the origin again.
How it works
Each solve is a pure function of the region, the direction and the constraint list. The solver keeps no state between calls, so re-solving on every WindowSizeMsg is the intended pattern. The package places boxes in whole terminal cells and never measures text; sizing a string with CJK, emoji or combining marks is the caller's job, and sugar-core's Width::of() answers it.
The walk runs in this order. Percentage and Ratio resolve to absolute sizes, and Length plus those sizes form a fixed reservation. Min floors and Max ceilings are entered. Whatever slack remains goes to the Fill weights and to Max, which is weighted by its cap and then clamped to it. A Min takes slack directly only when the set has neither Fill nor Max; on its own it absorbs the whole span. A Max clamp hands its excess back, and a Min takes that first, ahead of Fill. Demand above supply shrinks regions proportionally. A well-constrained set then tiles the span exactly, so its widths sum to the region's size.
Rounding is lossless for well-constrained sets. Slack residue rides the first Fill, or the first Max when no Fill is present. Min-only slack rides the first Min. With neither Fill nor Max in the set, a Percentage or Ratio shortfall of at most N−1 cells is reclaimed earliest-first; with a Fill or Max, that shortfall rides the first Fill or Max along with the rest of the slack. Over-subscription truncates silently by design, because a terminal resized below its fixed panes is a normal state, not an error.
// Length(10) and Max(5) in a 100-cell span: the Max clamp hands back the rest.
$rects = GreedySolver::new()->solve(Region::fromSize(100, 20), Direction::Horizontal, [
Constraint::length(10),
Constraint::max(5),
]);
// widths: 95, 5
Five carve-outs keep the sum law from holding. Under-constrained fixed-only sets keep their gap, so [percentage(30)] at 100 yields one 30-cell region. Compat mode and withoutOverflowTruncation() run off-grid on overflow. A zero-weight Fill set keeps its slack. A Max-only set keeps the shortfall of its caps, so [max(40), max(40)] at 100 yields 40 and 40; adding any Length, Percentage, Ratio, Fill or Min absorbs it. Extreme-magnitude inputs past int64 ride float arithmetic. The README names all five, and the tests pin the first two.
Choosing a layout strategy
- One content flow that sizes itself, such as paragraphs or form fields: reach for
sugar-flexbox. - Several panes split and re-resolved on every resize: this solver.
- An IDE-style center with vertical side stacks: the
Dock\*surface, described below.
Tasks
Check whether a set fits before you paint
$demand = GreedySolver::new()->demandOf(Region::fromSize(100, 20), Direction::Horizontal, [
Constraint::length(60),
Constraint::length(60),
]);
// 120: above the 100-cell span, so the set cannot be satisfied whole
demandOf() sums fixed sizes exactly, resolves Percentage and Ratio under the instance's rounding policy, sums Min floors, ceilings Max caps, and counts Fill as 0. Use it when collapse must be visible. Clipping on the host side with withoutOverflowTruncation() is the other option.
Keep the default policy, or opt into compat parity
New code should use GreedySolver::new(). GreedySolver::compat() reproduces the sugar-panels distribute() splits: round-split, remainder to the last region, and non-truncating overflow. Use it only to match an existing sugar-panels golden frame.
Solve a Dock frame
use SugarCraft\Constraints\Dock\{DockLayout, Side};
use SugarCraft\Constraints\Region;
$dock = DockLayout::new('chat')
->withSlotAdded(Side::Left, 'files')
->withSlotAdded(Side::Left, 'git')
->withSlotAdded(Side::Right, 'term')
->withStackWeight(Side::Left, 0, 2, 1); // files takes twice the rows of git
$geometry = $dock->resolve(Region::fromSize(100, 30));
$chat = $geometry->regionFor('chat'); // null when the pane is undocked or dropped
foreach ($geometry->dividerColumns() as $divider) {
// the host paints each divider column
}
Solvers
solve() raises E_USER_DEPRECATED on every call and delegates wholly to GreedySolver. Results are identical. It is kept only so existing call-sites keep working.resolve() never throws; below the floors it drops a side instead.Constraint types
fill(0) is accepted and weightless.solve() works on one axis. Same reclaim exception as Length: a Max clamp in a set with neither Min nor Fill can inflate it.Configuration
GreedySolver takes six named constructor arguments. The zero-argument new() keeps these defaults.
| Option | Type | Default | Effect |
|---|---|---|---|
roundSplit | bool | false | Use round() instead of floor() for Percentage and Ratio sizes. withRoundSplit() sets it. |
remainderToLast | bool | false | Rounding remainder goes to the last region instead of the first. withRemainderToLast() sets it. |
truncateOverflow | bool | true | When fixed demand exceeds the span, shrink regions proportionally. false keeps full base sizes, off-grid. withoutOverflowTruncation() and withOverflowTruncation() set it. |
minShare | int | 0 | Cells reserved per unplaced region before the Fill split. 0 leaves the floor off. Negative values throw. |
reserveGap | int | 0 | Cells added per placed region while the min-share floor is engaged, for inter-region spacing. Negative values throw. |
reserveLead | int | 0 | Cells reserved before the first region while the min-share floor is engaged, as a leading margin. Negative values throw. |
The dock defaults come from DockLayout::new(). The center pane id is 'center' unless you pass another. Each side starts at a 1/3 column share, with a 24-column center floor and a 20-column side floor, and the divider is one column. withMinimums() changes the floors, and withColumnShare() changes the shares.
API reference
| 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, and an empty list solves to []. Keyed or sparse arrays and non-Constraint members throw InvalidArgumentException. |
| GreedySolver | new(): self / greedy(): self / compat(): self | new() is the default factory. greedy() is a byte-identical alias of new(). compat() is the sugar-panels parity bundle. |
| GreedySolver | __construct(bool $roundSplit = false, bool $remainderToLast = false, bool $truncateOverflow = true, int $minShare = 0, int $reserveGap = 0, int $reserveLead = 0) | Public constructor, called as new GreedySolver(...). Negative floor or reserve values throw InvalidArgumentException. The six fields are public readonly, so the resolved policy reads back off the instance. |
| GreedySolver | static solveStatic(Region $area, Direction $dir, array $constraints): array | Legacy no-instance entry for the default policy. Its argument order matches solve(). Prefer an instance when you need the compat toggles. |
| GreedySolver | static minShareFloor(int $cells = 1, int $reserveGap = 0, int $reserveLead = 0): self | Builds an instance with the min-share floor engaged and the sugar-panels mode settings (floor split, remainder to the last region, truncation on). |
| GreedySolver | demandOf(Region $area, Direction $dir, array $constraints): int | Demand of the set under the instance's rounding policy. A result above the solved axis means the set cannot be satisfied whole. Shares the list guard with solve(). |
| GreedySolver | withRoundSplit(bool $on = true) / withRemainderToLast(bool $on = true) / withoutOverflowTruncation() / withOverflowTruncation(bool $on = true) | Immutable rounding and overflow toggles. Each returns a new instance. |
| GreedySolver | withMinShare(int $cells = 1, int $reserveGap = 0, int $reserveLead = 0) | Engages the sequential min-share floor. It sets roundSplit to false and remainderToLast to true. While engaged, solve() throws InvalidArgumentException for any set that holds a non-Fill constraint, on either axis. |
| CassowarySolver | new(): self / cassowary(): self | Deprecated shim. solve() raises E_USER_DEPRECATED and delegates to GreedySolver. Use GreedySolver in new code. |
| Constraint | length(int $n) / min(int $n) / max(int $n) / fill(int $weight = 1) / percentage(int $n) / ratio(int $numerator, int $denominator) | Factories on the abstract Constraint class. length(), min() and max() throw on a negative n. percentage() outside 0 to 100 throws, and ratio() with a negative numerator or a zero or negative denominator throws. |
| Direction | Horizontal, Vertical / other(): self | Split axis. other() returns the counterpart axis. |
| Region | __construct(int $x, int $y, int $width, int $height) / fromSize(int $width, int $height) / withOrigin(int $x, int $y) | Input and output box. Negative components throw. withOrigin() moves the region without resizing it. |
| Dock\DockLayout | new(string $centerPaneId = 'center') / withSlotAdded(Side $side, string $paneId, ?int $index = null) / withSlotRemoved(string $paneId) / withSlotMovedTo(string $paneId, Side $side, ?int $index = null) / slots(Side $side) | Immutable dock manifest. Removing an undocked pane is a no-op, while moving one throws. Each slot mutator scans every stack, so batch changes through fromArray(). |
| Dock\DockLayout | withColumnShare(Side $side, int $num, int $denom) / withColumnShareExact(Side $side, int $num, int $denom) / columnShare(Side $side): array | Rational column shares. withColumnShare() clamps to the pair rule and stores the effective share. withColumnShareExact() throws instead of clamping. |
| Dock\DockLayout | withStackWeight(Side $side, int $index, int $num, int $denom) / withStackWeightFor(Side $side, string $paneId, int $num, int $denom) | Slot weights by position, or by pane id. The id form cannot write to the wrong slot after a removal shifts the stack. |
| Dock\DockLayout | withMinimums(int $centerMinCols, int $sideMinCols) / withFixedColumns(Side $side, int $cols) | Sets the floors the degradation ladder reads. withFixedColumns() claims exactly $cols columns for a side before the share pass. Passing 0 returns the side to share-driven planning. |
| Dock\DockLayout | resolve(Region $frame): DockGeometry | Never throws. Below the floors it drops a side, and the divider stays at one column. |
| Dock\DockLayout | toArray(): array / static fromArray(array $data): self | Versioned persistence. A share-only dock emits the version-1 shape. A dock with fixed columns emits version 2 with a fixed map, and fromArray() accepts both. Malformed input throws InvalidArgumentException naming the failed key. |
| Dock\DockGeometry | new(array $regions = [], array $dividerColumns = []): self / regionFor(string $paneId): ?Region / dividerColumns(): array / isEmpty(): bool | Final readonly resolved geometry, with public readonly $regions and $dividerColumns. new() validates untrusted payloads. regionFor() returns null for a pane that is never docked or was dropped, and a 0-width region is not null. |
| Dock\DockSlot | new(string $paneId, int $weightNum = 1, int $weightDenom = 1) / withWeight(int $num, int $denom) | One vertical stack slot with a rational weight. |
| Dock\Side | Left, Right / other(): self | Enum of the two stacks. other() returns the opposite side. |
| Expression | (internal) | Linear-expression value object kept from the retired simplex prototype. It is marked @internal, no solver consumes it, and it is not part of the supported surface. Use LayoutSolver. |
Only methods declared in sugar-constraints/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\Constraints
CassowarySolver final class
DEPRECATED constraint solver — retained for backward compatibility only.
| Method | Summary |
|---|---|
static new(): self | Default factory — matches the LayoutSolver convention. |
static cassowary(): CassowarySolver | |
solve(Region $region, Direction $dir, array $constraints): array | Solve constraints against a region in the given direction. |
Direction enum
Direction of a constraint-based layout split.
Cases: Horizontal · Vertical
PHP also provides cases().
| Method | Summary |
|---|---|
other(): self | The other axis of the split — the Dock vocabulary's Dock\Side::other() shape, so a Direction can answer its own counterpart without callers hard-coding the flip. |
GreedySolver final class
The package's solver: maps a Region plus a list of constraints to a list of sub-regions, ratatui-inspired but greedy rather than linear-programming (the retired simplex prototype never converged — see CassowarySolver).
| Method | Summary |
|---|---|
__construct(public readonly bool $roundSplit = false, public readonly bool $remainderToLast = false, public readonly bool $truncateOverflow = true, public readonly int $minShare = 0, public readonly int $reserveGap = 0, public readonly int $reserveLead = 0) | |
static new(): self | Default factory — matches LayoutSolver convention. |
static greedy(): self | |
static compat(): self | sugar-panels parity mode: round-split + remainder-to-last + non-truncating overflow. Opt-in seam for retiring sugar-panels's duplicated distribute() /distributeFlex() without regressing its goldens. |
withRoundSplit(bool $on = true): self | Round Percentage/Ratio proportional sizes with round() instead of floor(). |
withRemainderToLast(bool $on = true): self | Hand the rounding remainder to the LAST region (or LAST Fill/Max) instead of the first. |
withoutOverflowTruncation(): self | Keep each region at its full base size on overflow (layout runs off-grid) instead of truncating proportionally. |
withOverflowTruncation(bool $on = true): self | Re-enable (or disable) proportional overflow truncation. |
withMinShare(int $cells = 1, int $reserveGap = 0, int $reserveLead = 0): self | Engage the sequential min-share floor: split the region proportionally across its Fill weights while reserving at least $cells cell(s) for every region NOT yet placed, so the trailing region never collapses to 0 in a tight viewport. This is the opt-in seam that lets sugar-panels retire its hand-rolled NON-flex distribute() with byte parity — the fourth quirk compat()'s three flags cannot express. |
static minShareFloor(int $cells = 1, int $reserveGap = 0, int $reserveLead = 0): self | Dedicated construction door for the sequential min-share floor: the compat knobs arrive at the mode's truth (floor split, remainder-to-last; truncateOverflow neutral-true) instead of inheriting a policy the floor path ignores — the loud alternative to withMinShare()'s reset when the instance is being built, not retuned. |
solve(Region $region, Direction $dir, array $constraints): array | Instance solve — satisfies LayoutSolver. |
static solveStatic(Region $area, Direction $dir, array $constraints): array | Static convenience for the default (floor / remainder-first / truncating) behaviour — reachable without holding an instance. |
demandOf(Region $area, Direction $dir, array $constraints): int | The integer APPETITE of a constraint set against the frame's solved axis — the README's documented host-side degradation comparison, mechanized: Length at its exact size, Percentage/Ratio resolved against the span under this instance's rounding policy, Min at its floor, Max at its cap, and Fill at 0 (it claims only slack, so it is never left "unmet"). Demand above the span means the set cannot be satisfied whole: either the proportional truncation fires (fixed + Min floors already exceed the axis) or a slack consumer is served below its appetite. Which pane lost what stays a per-frame question one integer cannot split — see the README Degradation section, which still recommends withoutOverflowTruncation() when collapse must be visible per region. Same boundary refusals as solve(); the walk is pure integer arithmetic (carve-out 4 applies to its products too). |
LayoutSolver interface
Interface for constraint-based layout solvers.
| Method | Summary |
|---|---|
solve(Region $region, Direction $dir, array $constraints): array | Solve constraints against a region in the given direction. |
Region final readonly class
Axis-aligned rectangle within a terminal grid.
| Method | Summary |
|---|---|
__construct(public int $x, public int $y, public int $width, public int $height) | |
static fromSize(int $width, int $height): self | Create a 0,0-origin region of the given dimensions. |
withOrigin(int $x, int $y): self | Translate without resizing — replaces the 4-arg constructor re-spell (sugar-style Solver.php:37 precedent) for callers that only ever move a box. A negative destination is refused loudly by the same boundary guard the constructor carries. |
SugarCraft\Constraints\Constraint
Constraint abstract class
Abstract base class for all constraint types used by LayoutSolver::solve().
| Method | Summary |
|---|---|
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Fill final class
Fills all remaining space with proportional $weight.
| Method | Summary |
|---|---|
__construct(public readonly int $weight = 1) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Length final class
Fixed character-cell count.
| Method | Summary |
|---|---|
__construct(public readonly int $n) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Max final class
Upper-bound size cap; takes slack greedily up to the cap, and its clamp pass can give cells BACK to the other types (Min first, then Fill, then everything else — README Tiling guarantee ladder step 6).
| Method | Summary |
|---|---|
__construct(public readonly int $n) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Min final class
At least $n cells — a soft floor.
| Method | Summary |
|---|---|
__construct(public readonly int $n) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Percentage final class
Proportional size as a percentage of the available area.
| Method | Summary |
|---|---|
__construct(public readonly int $n) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
Ratio final class
Proportional size based on a ratio (numerator / denominator).
| Method | Summary |
|---|---|
__construct(public readonly int $numerator, public readonly int $denominator) | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells — a soft floor. Takes slack directly only when the set has neither Fill nor Max; otherwise grows only from cells a Max clamp hands back, which Min takes before Fill. Does not guarantee $n when demand exceeds the area. |
static fill(int $weight = 1): Fill | Fills all remaining space; $weight controls proportional distribution when multiple Fill constraints compete. |
static percentage(int $n): Percentage | Proportional size as a percentage (0-100) of the available area. |
static ratio(int $numerator, int $denominator): Ratio | Proportional size based on a ratio (numerator / denominator). |
static max(int $n): Max | Upper-bound size cap; takes slack greedily (proportional to its cap among the slack consumers) but never more than $n. The clamp pass can also give cells BACK from this type when the greedy share rode over the cap — the hand-back rides Min first, then Fill, and reaches Length/Percentage/Ratio only in a set with neither. |
SugarCraft\Constraints\Dock
DockGeometry final readonly class
Immutable result of DockLayout::resolve() — concrete grid regions for one frame.
| Method | Summary |
|---|---|
static new(array $regions = [], array $dividerColumns = []): self | The validating public door for untrusted payloads: every element of the shape is checked before construction (the scan used to live in the private constructor, where resolve() paid it once per frame on bytes it had just built itself — finding 028 moved it to this door; the paint path takes solved() instead). |
regionFor(string $paneId): ?Region | The region assigned to a pane, or null when the pane is absent from this geometry. Absent covers three distinct states — the pane was never docked, its side was dropped by the degradation ladder, or the frame was degenerate. A null alone does not say which; hosts that must distinguish a dropped side from an undocked pane compare against the input DockLayout (its slots()/columnShare() still describe intent). Note a 0-width region is NOT null: an active side planned at 0 columns keeps a width-0 region by design (see the DockLayout class notes). |
dividerColumns(): array | |
isEmpty(): bool | True when the frame was degenerate (non-positive width/height) and the layout resolved to nothing. |
DockLayout final class
Immutable dock/pane-layout description: a center surface flanked by two optional vertical stacks of docked panes, resolved into concrete DockGeometry for any Region frame.
| Method | Summary |
|---|---|
static new(string $centerPaneId = 'center'): self | Empty dock: center pane id defaults to the neutral 'center' (2026-11: was 'chat', but the factory should not bake one app's vocabulary — candy-code passes its 'chat' explicitly at every call site), no side slots, both column shares at the 1/3 design default, center minimum 24 cols, side minimum 20 cols, 1-col dividers. |
withSlotAdded(Side $side, string $paneId, ?int $index = null): self | Dock a pane onto a side. Null index appends; index is an insertion position in 0..count. Duplicate pane ids across BOTH sides are refused, and so is the center pane's own id — a pane has exactly one home. |
withSlotRemoved(string $paneId): self | Undock a pane from whichever side holds it. Unknown pane ids are a no-op returning the identical instance — the deliberate counterpart to withSlotMovedTo(), which THROWS on an unknown id: removals run in idempotent teardown paths where "already gone" is success, while a move of a never-docked pane can only be a caller bug. The README's Dock walkthrough names this asymmetry so hosts do not have to read both docblocks to find it. |
withSlotMovedTo(string $paneId, Side $side, ?int $index = null): self | Move a pane across sides or reorder it within its side. Null index moves to the end of the destination stack. Unknown pane ids throw — a move of a pane that was never docked is a caller bug, not a no-op (the idempotent no-op side of this asymmetry is withSlotRemoved()). |
withColumnShare(Side $side, int $num, int $denom): self | Set a side's column share. Invalid rationals throw; the pair rule leftShare + rightShare <= 1/2 is enforced by CLAMPING the requested share (never throwing) — the center is the primary surface and must keep at least half the usable columns once the host starts tightening shares. The creation default (thirds) predates any tightening and is documented on the class. |
withColumnShareExact(Side $side, int $num, int $denom): self | Strict sibling of withColumnShare(): identical validation and the identical pair rule, but a share that WOULD be clamped is refused with \InvalidArgumentException naming the request and the ceiling, never silently tightened — for hosts that treat "asked for what the rule cannot grant" as a caller bug. |
withStackWeight(Side $side, int $index, int $num, int $denom): self | Replace the rational stack weight at $index (a current position in the side's stack, 0..count-1). |
withStackWeightFor(Side $side, string $paneId, int $num, int $denom): self | Id-keyed sibling of withStackWeight(): the slot is found by pane id, so a removal that shifted the stack since the caller last looked can never make a positional index weight the wrong pane. An id that is not docked on $side throws, naming the miss. |
withFixedColumns(Side $side, int $cols): self | Claim EXACTLY $cols columns for a side, bypassing the share pass — "20 columns, always" is what the share-only surface could not express. $cols = 0 returns the side to share-driven planning (the default). The center's floor ladder still applies to the remaining pool: a fixed side that starves the center below centerMinCols is dropped by the same degradation ladder that removes share-driven sides, and — by design — the min-protection RAISE never touches a fixed side, since a raise would undo the exactness the caller declared. |
withMinimums(int $centerMinCols, int $sideMinCols): self | Set the column minimums; both must be >= 1. |
slots(Side $side): array | |
columnShare(Side $side): array | |
resolve(Region $frame): DockGeometry | Lay this dock out inside $frame. |
toArray(): array | Exact versioned manifest shape. |
static fromArray(array $data): self | Parse a manifest produced by toArray(). Strict at the boundary — every failure throws InvalidArgumentException naming the offending key path, including a slot id that collides with the center pane (a pane has exactly one home). Hand-edited data that violates basic ranges is REFUSED here (fail-fast), while the 1/2 pair rule stays a withColumnShare() clamping policy: restored manifests keep their persisted shares untouched (the thirds default included), so round-trip identity holds. |
DockSlot final readonly class
One pane's entry in a dock side's vertical stack, carrying its height share as a rational (weightNum / weightDenom).
| Method | Summary |
|---|---|
__construct(public string $paneId, public int $weightNum, public int $weightDenom) | |
static new(string $paneId, int $weightNum = 1, int $weightDenom = 1): self | |
withWeight(int $num, int $denom): self | New slot carrying this pane id with a replacement rational weight. |
Side enum
Which dock column a pane stack occupies, relative to the center surface.
Cases: Left · Right
PHP also provides cases().
| Method | Summary |
|---|---|
other(): self | The opposite side of the dock. |
Examples
examples/sidebar.php: the horizontal two-pane walk, with a fixed rail, an elastic content pane, a crushed frame at width 10, and a four-pane mix.examples/vertical.php: the same walk onDirection::Vertical, where a cell is one text row.examples/dock.php: theDock\*surface, with a center pane, weighted side stacks, and the small-frame ladder that drops sides instead of throwing.
php examples/sidebar.php
php examples/vertical.php
php examples/dock.php
Testing
cd sugar-constraints
composer install
vendor/bin/phpunit
Every fenced php block in the README runs under tests/ReadmeSnippetsTest.php, so the README snippets cannot drift. tests/SolverEdgeCaseTest.php pins the tiling shapes, and tests/WidthSumInvariantSweepTest.php checks the sum law across a sweep. tests/GreedySolverCompatTest.php holds the sugar-panels parity cases, and tests/ExtremeMagnitudeCarveoutTest.php covers the int64 carve-out.
Troubleshooting
solve()throws "Constraints must be a list". The array is keyed or sparse. Pass a sequential list, for example by callingarray_values()on it.- A static call through the interface name is a fatal error.
LayoutSolverdeclares only the instance methodsolve(), so a static factory such asgreedy()called on the interface name fails withError: Call to undefined method, followed by the interface and method name. Call a concrete class such asGreedySolver::greedy()orGreedySolver::new(). - Sizes sum to less than the span. One of the carve-outs applies. For example,
[percentage(30)]at 100 yields 30, and[max(40), max(40)]at 100 yields 40 and 40. Add afill(1)to absorb the rest, or check the set withdemandOf(). - Sizes sum to more than the span. The set was solved with compat mode or
withoutOverflowTruncation().[length(60), length(60)]at 100 yields 60 and 60 under those settings, and 50 and 50 under the default policy. E_USER_DEPRECATEDon every solve. The call usesCassowarySolver, which delegates toGreedySolver. Switch toGreedySolver::new().- A dock side disappears on a small frame. The frame is below the floors, so
resolve()drops that side. Resize the frame, or lower the floors withwithMinimums(). percentage(150)throws. Percentage takes an integer from 0 to 100. Useratio()for other fractions.
Upstream mapping
The layout model follows ratatui's constraint system. Badros, Borning and Stuckey's Cassowary paper is the historical source of the deprecated shim, but this port implements neither the simplex nor the strength and priority vocabulary. The port mapping is in docs/MATCHUPS.md, where the SugarConstraints row carries its port status.
| ratatui | SugarConstraints |
|---|---|
Constraint::Length | Constraint::length(), class Length |
Constraint::Min | Constraint::min(), class Min |
Constraint::Max | Constraint::max(), class Max |
Constraint::Fill | Constraint::fill(), class Fill |
Constraint::Percentage | Constraint::percentage(), class Percentage |
Constraint::Ratio | Constraint::ratio(), class Ratio |
| layout split | LayoutSolver::solve(), implemented by GreedySolver |
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.
Changelog and versioning
The package has no separate changelog file. History is in git and on the Packagist release list. The README header records the 2026-10 rename: the package was published as sugarcraft/candy-layout, and the namespace moved from SugarCraft\Layout\ to SugarCraft\Constraints\.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Inspired by ratatui/ratatui layout constraint system
- Originally inspired by Badros, Borning & Stuckey, "The Cassowary Linear Arithmetic Constraint Solving Algorithm", ACM TOCHI 8(4), 2001. This package implements neither the simplex nor the strength/priority vocabulary.