SugarStyle
Declarative styling + layout
Style, Border, Table\Table, Listing\ItemList, Tree\Tree, Layout::joinHorizontal/joinVertical, Layout::place, multi-layer Canvas, and Theme — the canonical color palette for all SugarCraft libs. The rendering core is pure — no I/O (an optional Output facade wraps print/printf/fprint) — so you can render frames inside a unit test.
Install
composer require sugarcraft/sugar-style
Quickstart
use SugarCraft\Style\{Style, Border, Layout, Position};
use SugarCraft\Style\Table\Table;
use SugarCraft\Core\Util\Color;
$banner = Style::new()
->bold()
->foreground(Color::hex('#ff5f87'))
->padding(0, 2)
->render('hello, styled world');
$table = Table::new()
->headers('Name', 'Age')
->row('Alice', '30')
->row('Bob', '25')
->border(Border::rounded())
->render();
echo Layout::joinVertical(Position::LEFT, $banner, $table);
What's in the box
fg(), bold(), width()) and each returns a new Style.Border::rounded(), thick(), double(), block(), hidden(), normal(), ascii(), markdownBorder().wrap() callback: every line it returns renders, so a wrapped row spans several physical lines.joinHorizontal, joinVertical, place, plus the ratatui-style constraint solver (Layout\Layout::vertical([...])->split()) and RegionBridge for handing rectangles between sugar-constraints and sugar-cellbuffer.with*() setters return a new Theme. adaptive() reads $COLORFGBG: any numeric slot (0-255) in the last field decides light vs dark by luminance (e.g. 7/15 light, 0/8 dark); unset, non-numeric or out-of-range falls back to dark.Border::withEmbeddedTitle() brackets text in junctions (╭─┐cpu┌────┐12:00┌───────╮) on any of six anchors; Border::seam() picks the ┬ ┴ ├ ┤ ┼ rune where an internal divider meets the frame, preserving the border family.ColorProfile and render() downsamples to it, as charmbracelet/colorprofile's Writer does: TrueColor → 38;2, Ansi256 → 38;5, Ansi → 30..37/90..97, Ascii (what NO_COLOR selects) drops color but keeps bold/italic/underline and OSC 8 links, and NoTty strips every escape — including ones carried in by pre-styled content, a transform() or a border title — while padding, borders and alignment stay. Tier rewrites apply to RGB colors; palette-slot colors (Color::ansi(n)) always emit their 30..37/90..97 form at every tier.4:N form emitted only alongside underline() — terminals that ignore 4:N typically draw no underline at all (no plain SGR 4 companion is sent). SGR 58 has no 4-bit spelling, so at the Ansi tier the underline color is applied through the foreground attribute instead — it recolours the glyphs rather than tinting the rule.Embedded border titles
use SugarCraft\Style\Border;
use SugarCraft\Style\Border\TitleAnchor;
use SugarCraft\Style\Style;
$border = Border::rounded()
->withEmbeddedTitle('cpu')
->withEmbeddedTitle('12:00', TitleAnchor::TopCenter)
->withEmbeddedTitle('mem', TitleAnchor::BottomLeft)
->withEmbeddedTitle('disk', TitleAnchor::BottomLeft);
echo Style::new()->border($border)->width(24)->render('load 0.42');
// ╭─┐cpu┌────┐12:00┌───────╮
// │load 0.42 │
// ╰─┘mem└─┘disk└───────────╯
echo Border::normal()->seam(left: true, right: true, up: false, down: true); // ┬
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by lipgloss (Go); SugarCraft is developed as a native PHP project.
Concepts
Style is an immutable value object. Every setter returns a new Style and leaves the receiver unchanged, so one base style can be reused and specialized without side effects. Border, Table, Tree and Canvas follow the same pattern.
render() does not write escape codes blindly. It downsamples each color to the style's color profile, so a TrueColor value becomes a 256-color, 16-color or plain-text sequence depending on the tier. The same approach as the Writer in charmbracelet/colorprofile.
API reference
| Class | Method | Description |
|---|---|---|
| Theme | dark() / light() / dracula() / tokyoNight() / oneDark() / githubDark() / solarizedDark() / solarizedLight() / ansi() / adaptive() | Named theme factories |
| Theme | withPrimary($c) / withForeground($c) / withBackground($c) / withError($c) / … | 13 color slot setters — all return a new Theme |
| Style | new() | Create a new style |
| Style | foreground(color) | Set foreground color |
| Style | background(color) | Set background color |
| Style | bold(), italic(), underline(), blink(), rapidBlink() | Text effects (blink = SGR 5, rapidBlink = SGR 6) |
| Style | patch($other) | Incremental merge — only props set in $other are applied; a null color/width/border in $other is skipped, not a clear |
| Style | colorProfile(ColorProfile $p) | Force the color tier render() downsamples to (TrueColor / Ansi256 / Ansi / Ascii / NoTty) |
| BorderGradientBlend | fromColors(Color ...$colors) | 1-5 colors → 4 interpolated border-side colors |
| Style | padding(...$sides) | Add padding (1, 2, or 4 values — CSS-style shorthand) |
| Style | render(content) | Render styled content |
| Border | normal(), rounded(), thick(), double(), block(), ascii(), hidden(), markdownBorder() | All eight border style presets |
| Border | withEmbeddedTitle(text, ?anchor, ?open, ?close) | btop-style title cut into the edge (╭─┐cpu┌──╮); left/right inset one rune, center uses btop's clock formula, overflow shrinks with … |
| Border | embedJunctions(bool $bottom = false) | Default [open, close] junction pair from the border's own corners (rounded arcs squared off) |
| Border | seam(left, right, up, down) | Junction rune where a divider meets the frame (┬ ┴ ├ ┤ ┼), in the border's own family |
| Border | titles(): array | Configured border titles (getTitles() remains as a deprecated alias); over-long titles are truncated to the edge |
| Table | new() | Create a table |
| Table | headers(...), row(...) | Add table content |
| Table | wrap(?\Closure(string $cell, int $colWidth): list<string> $fn) | Per-cell wrapping; a wrapped row spans several physical lines |
| Layout | joinVertical(), joinHorizontal() | Join layouts |
| Canvas | new() | Create multi-layer canvas |
| Bar | StatusBar::new()->left()/center()/right(Segment|string ...)->width()/style()->render(); HelpBar::fromMap() | One-line chrome: positioned segment groups + key→label help rows |
Configuration
Color output is controlled per style, or once for the whole process. The defaults are the values the classes ship with.
Style::setDefaultProfile(?ColorProfile): process-wide, default unset, so TrueColor. Sets the color tier that styles created byStyle::new()render to.nullrestores TrueColor.Style::colorProfile(ColorProfile): per style, default no profile set, so the process-wide default applies. Forces the tier this style'srender()downsamples to, overriding the process-wide default.Theme::adaptive(bool $fallbackDark): bool, defaulttrue. Palette used whenCOLORFGBGcannot decide light or dark.Border::withEmbeddedTitle(text, ?TitleAnchor, ?open, ?close): anchor, junction runes. The anchor defaults toTitleAnchor::TopLeft; the junction runes default to the square form of the border's corners (┐/┌top,┘/└bottom), so a rounded border gets square junctions too. Cuts a title into the border edge.Table::wrap(?Closure): closure or null, default no callback set. When set, every line it returns renders, so a wrapped row spans several physical lines. Each line is fitted to the column width and cut when it is wider.
Theming
Theme is the palette shared by the SugarCraft libraries, with 13 color slots. It has ten named factories: dark(), light(), dracula(), tokyoNight(), oneDark(), githubDark(), solarizedDark(), solarizedLight(), ansi() and adaptive(). Each slot setter, such as withPrimary(), returns a new Theme.
use SugarCraft\Core\Util\Color;
use SugarCraft\Style\Theme;
$theme = Theme::dracula()->withPrimary(Color::hex('#50fa7b'));
Examples
Each file in examples/ runs from the library root as php examples/<name>.php.
styled-text.php: The lipgloss "hello world": one styled line of text.style.php: Foreground, background, bold, italic, underline and strikethrough, plus adaptive color.adaptive-colour.php: Storing the color once and collapsing it on both the light and dark axes.border.php: The same content under every built-in border style.table.php: A rounded-border table with custom alignment and astyleFuncthat paints alternate rows.list.php: Lists with the default bullet, a custom enumerator and nested enumerators.tree.php: A project structure rendered under three enumerator styles.dashboard.php: A small dashboard built withLayout::joinHorizontal(),joinVertical()andplace().constraint-dashboard.php: A dashboard whose panes are sized by Length, Min and Percentage constraints.canvas.php: A styled popover layer composited over a base layer.theme-roles.php: The role-to-style registry and the injectable darkness seam.
Testing
cd sugar-style
composer install
vendor/bin/phpunit
The only dev dependency is PHPUnit 10. The suite asserts on the exact bytes render() produces, so a change to the escape sequences fails a test.
Only methods declared in sugar-style/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\Style
AdaptiveColor final class
A pair of colours that resolve to one based on the active terminal background. Mirrors lipgloss v2's AdaptiveColor.
| Method | Summary |
|---|---|
__construct(public readonly Color $light, public readonly Color $dark) | |
pick(bool $isDark): Color | Pick the colour appropriate for the current background. Pass the value of \SugarCraft\Core\Msg\BackgroundColorMsg::isDark() (or any other dark-background detector). |
Align enum
Horizontal alignment of content within a fixed-width Style box.
Cases: Left · Center · Right
PHP also provides cases(), from() and tryFrom().
Border final class
The 13 corner / edge / interior runes that make up a rectangular box border. Outer runes drive Style boxes; the five middle-* runes drive Table separators (column splits, row separators, cross intersections).
| Method | Summary |
|---|---|
__construct(public readonly string $top, public readonly string $bottom, public readonly string $left, public readonly string $right, public readonly string $topLeft, public readonly string $topRight, public readonly string $bottomLeft, public readonly string $bottomRight, public readonly string $middleLeft = ' ', public readonly string $middleRight = ' ', public readonly string $middle = ' ', public readonly string $middleTop = ' ', public readonly string $middleBottom = ' ', private readonly array $titles = []) | |
static normal(): self | |
static rounded(): self | |
static thick(): self | |
static double(): self | |
static block(): self | |
static ascii(): self | |
static hidden(): self | |
static markdownBorder(): self | GitHub-flavored Markdown table border. Mirrors lipgloss's Border::markdownBorder() — pipes for the verticals, dashes for the horizontals, plain | corners. Useful when an already-rendered Table\Table grid (this lib's own Markdown-capable table) needs to round-trip through a Markdown reader without losing its grid. |
static catalog(): array | Enumerate the names of all built-in border factories. |
withTitle(string $text, ?TitleAnchor $anchor = null): self | Attach a title to the border. |
withEmbeddedTitle(string $text, ?TitleAnchor $anchor = null, ?string $open = null, ?string $close = null): self | Attach a title EMBEDDED in the edge: bracketed by junction runes so it reads as cut into the line — ╭─┐cpu┌───╮ on the top edge, ╰─┘mem└───╯ on the bottom. Mirrors btop Draw::createBox (title / title2 args) and Draw::update_clock (btop_draw.cpp, Symbols title_left ┐ / title_right ┌, title_left_down ┘ / title_right_down └). |
embedJunctions(bool $bottom = false): array | The default [open, close] junction pair for an embedded title on the top ($bottom = false) or bottom edge. Taken from the border's own opposite corners so every family stays consistent — ┐┌/┘└ for normal and rounded, ┓┏/┛┗ thick, ╗╔/╝╚ double, ++ ascii — with the rounded arcs squared off, matching btop which always embeds with square junctions even on rounded boxes. |
seam(bool $left, bool $right, bool $up, bool $down): string | The rune for a point where lines leave in the given directions — the junction a seam (an internal divider) makes where it meets a frame or another seam. btop's divider law (Symbols div_left ├, div_right ┤, div_up ┬, div_down ┴): a vertical seam landing on the top edge is seam(left: true, right: true, down: true) → ┬. |
withTitles(array $map): self | Attach multiple titles in bulk, replacing any previously set. |
titles(): array | Attached titles, keyed by TitleAnchor case name, each anchor's list in insertion order. |
getTitles(): array | Alias of titles(), kept so existing callers keep compiling. |
Canvas final class
Multi-layer compositor — port of Bubble Tea v2's lipgloss.Canvas.
| Method | Summary |
|---|---|
static new(): self | |
addLayer(Layer $l): self | |
render(): string | Compose all layers and return the rendered string. |
Cell final readonly class
A single character cell with associated style.
| Method | Summary |
|---|---|
__construct(public string $rune, public Style $style) |
CompleteAdaptiveColor final class
Combines AdaptiveColor (light vs dark background) with CompleteColor (per-tier override) — a designer-supplied matrix of (background × profile) → Color. Mirrors lipgloss v2's CompleteAdaptiveColor.
| Method | Summary |
|---|---|
__construct(public readonly CompleteColor $light, public readonly CompleteColor $dark) | |
pick(bool $isDark, ColorProfile $profile): Color |
CompleteColor final class
Profile-aware colour triple. Lets the designer pick the *exact* colour to use at each capability tier, rather than relying on runtime quantization from a single TrueColor value. Mirrors lipgloss v2's CompleteColor.
| Method | Summary |
|---|---|
__construct(public readonly Color $trueColor, public readonly Color $ansi256, public readonly Color $ansi) | |
pick(ColorProfile $profile): Color |
Hsl final class
Factory for creating Color instances via HSL values.
| Method | Summary |
|---|---|
static color(float $h, float $s, float $l): \SugarCraft\Core\Util\Color | Create a Color from HSL values. |
static parse(string $hsl): ?\SugarCraft\Core\Util\Color | Create a Color from HSL string like "hsl(200, 80%, 50%)". |
Lang final class
Per-library translation facade for sugar-style.
Layer final class
A single positioned layer within a Canvas. Holds the pre-rendered content block plus its (x, y) origin and z-index.
| Method | Summary |
|---|---|
__construct(public readonly string $content, public readonly int $x = 0, public readonly int $y = 0, public readonly int $z = 0) | |
static new(string $content): self | |
withX(int $x): self | |
withY(int $y): self | |
withZ(int $z): self | |
lines(): array | |
width(): int | |
height(): int |
Layout final class
Compositional layout primitives.
| Method | Summary |
|---|---|
static width(string $block): int | Cell width of $block. For multi-line blocks it's the widest line. |
static height(string $block): int | Number of lines in $block. |
static size(string $block): array | Width / height pair. Useful for checking that a child fits inside a fixed-size container before placing. |
static joinHorizontal(float $pos, string ...$blocks): string | Stitch blocks side by side. $pos is a vertical anchor (Top/ Center/Bottom or any 0.0-1.0 float): shorter blocks are padded vertically with blank lines anchored per $pos. Per-line widths are equalised with trailing spaces so the output is rectangular. |
static joinHorizontalWithSpacing(float $pos, ?int $spacing, string ...$blocks): string | Stitch blocks side by side with explicit spacing. |
static joinVertical(float $pos, string ...$blocks): string | Stack blocks top-to-bottom. $pos is a horizontal anchor (Left/Center/Right or any 0.0-1.0 float): narrower blocks get padded horizontally with spaces anchored per $pos. |
static joinVerticalWithSpacing(float $pos, ?int $spacing, string ...$blocks): string | Stack blocks top-to-bottom with explicit spacing. |
static joinHorizontalWithDivider(float $pos, string $divider, string ...$blocks): string | Stitch blocks side by side with a divider column between each adjacent pair. Empty blocks ('', zero width) are dropped together with their divider, so a collapsed pane leaves no orphan rule. A single-line $divider is repeated on every row; a multi-line one is laid out row by row (missing rows blank). An empty $divider degrades to joinHorizontal(). |
static joinVerticalWithDivider(float $pos, string $divider, string ...$blocks): string | Stack blocks top-to-bottom with a rule line between each adjacent pair, the rule tiled (repeated, then cut on a cell boundary) to the widest block. Empty blocks are dropped together with their rule. An empty $divider degrades to joinVertical(). |
static tile(string $unit, int $width): string | Repeat $unit until it covers $width cells, then cut to exactly that. |
static clipHead(string $block, int $rows): string | Keep at most $rows lines from the top of $block. |
static clipTail(string $block, int $rows): string | Keep at most $rows lines from the bottom of $block. |
static clipWidth(string $block, int $cols, string $ellipsis = ''): string | Keep at most $cols visible cells of every line. The cut is ANSI-aware (escapes carry no width, a trailing reset survives) and lands on a grapheme boundary. With $ellipsis set an overlong line keeps $cols - width(ellipsis) cells and gains the ellipsis. |
static place(int $width, int $height, float $hPos, float $vPos, string $block, string $fill = ' '): string | Position $block within a $width × $height rectangle. $hPos and $vPos are 0.0-1.0 anchors (use the Position constants). The fill character defaults to a space; passing a styled blank (e.g. Style::new()->background(...)->render(' ')) lets the surrounding area carry a colour. |
static placeHorizontal(int $width, float $pos, string $block, string $fill = ' '): string | Position horizontally only — pads each line in $block to $width with $fill, anchored per $pos. No vertical change. |
static placeVertical(int $height, float $pos, string $block, string $fill = ' '): string | Position vertically only — pads $block above/below to reach $height rows, anchored per $pos. Each blank row is width($block) cells wide. |
LightDark final class
Tiny convenience for picking one of two colours based on whether the terminal background is dark. Mirrors lipgloss v2's LightDark helper.
| Method | Summary |
|---|---|
static pick(bool $isDark, Color $light, Color $dark): Color | |
static picker(bool $isDark): \Closure | Returns a closure that picks (light, dark) pairs based on a single captured isDark flag. |
Markup final class
Parses Rich-style inline markup into Cell arrays.
| Method | Summary |
|---|---|
static parse(string $input, Style $defaultStyle): array | Parse markup string into a list of Cells. |
Output final class
Top-level (un-styled) output helpers — the equivalents of the package-level lipgloss.Print / Println / Sprint / Fprint / Printf functions. Each method is the un-styled twin of the matching Style method (Output::sprint() vs Style::sprint(), and so on) so callers can reach the same shape without a Style instance.
| Method | Summary |
|---|---|
static sprint(string ...$parts): string | Concatenate arguments with single spaces. No newline, no styling. Un-styled twin of Style::sprint() (same join rule and same Go divergence, both documented in the class docblock). |
static printf(string $format, mixed ...$args): string | sprintf() substitution that RETURNS the formatted string (upstream Printf writes instead). Un-styled twin of Style::printfSprint(). |
static print(string ...$parts): int | Write Output::sprint($parts) to STDOUT (no newline). Un-styled twin of Style::print(). Same fail-fast write accounting: returns the bytes written, throws RuntimeException on an invalid STDOUT or a false/short write. |
static println(string ...$parts): int | Write Output::sprint($parts) . "\n" to STDOUT. Un-styled twin of Style::println(). Same fail-fast write accounting as print(). |
static fprint($stream, string ...$parts): int | Write Output::sprint($parts) to a caller-supplied stream resource (no trailing newline). Un-styled twin of Style::fprint(). |
Palette final class
Named ANSI colour constants and colour helpers — the lipgloss equivalents of lipgloss.Black, lipgloss.Red, …, lipgloss.BrightWhite plus the lipgloss.HasDarkBackground() top-level helper.
| Method | Summary |
|---|---|
static black(): Color | |
static red(): Color | |
static green(): Color | |
static yellow(): Color | |
static blue(): Color | |
static magenta(): Color | |
static cyan(): Color | |
static white(): Color | |
static brightBlack(): Color | |
static brightRed(): Color | |
static brightGreen(): Color | |
static brightYellow(): Color | |
static brightBlue(): Color | |
static brightMagenta(): Color | |
static brightCyan(): Color | |
static brightWhite(): Color | |
static gray(): Color | Alias for brightBlack() — the canonical "muted" palette slot. |
static hasDarkBackground(?Color $background): ?bool | lipgloss-style top-level helper: given a known background Color (typically obtained via a SugarCraft terminal-query response), report whether it's dark enough to want light foregrounds. |
static all(): array | All 16 named ANSI colours in ANSI index order. Useful for theme preview tables and for iteration tests. |
Position final class
Position constants for Layout::place(). Match lipgloss's Top / Bottom / Left / Right / Center floats: 0.0 anchors to the start, 1.0 anchors to the end, 0.5 centres.
Renderer final class
Per-writer rendering context. Mirrors lipgloss's Renderer — a small value object that bundles a ColorProfile and a "dark background" flag so callers can branch on those without threading them through every Style construction.
| Method | Summary |
|---|---|
static new(): self | Default renderer: TrueColor profile, dark background. Convenience for the common case (most modern terminals). |
static fromEnvironment(): self | Auto-detect the color profile from the environment via ColorProfile::detectTerminal(), memoised per process and per distinct environment fingerprint (self::$environmentMemo). The dumb-terminal veto matters here: TERM=dumb answers NoTty, so no SGR reaches a terminal that cannot honour it, as before P1-10a. The dark-background flag stays at its default (true) since that's not detectable without an OSC 11 round trip — toggle it explicitly via withHasDarkBackground() once the program has the answer. |
static resetEnvironmentMemoForTesting(): void | Drop every memoised environment detection. Same seam shape as \SugarCraft\Style\Layout\SolverFactory::resetEnvironmentResolutionForTesting(), separate statics — tests that flip colour variables call this to start from a cold memo. |
withColorProfile(ColorProfile $p): self | Override the color profile (downsamples colours when rendering). |
withHasDarkBackground(bool $isDark): self | Override the dark-background flag. Bubble Tea programs set this from a BackgroundColorMsg::isDark() reply on startup; for non-interactive output, leave at the default. |
newStyle(): Style | Create a fresh Style pre-configured with this renderer's color profile. Equivalent to Style::new()->colorProfile($p). |
lightDark(): \Closure | Bind this renderer's hasDarkBackground to a LightDark picker. Equivalent to LightDark::picker($r->hasDarkBackground). |
resolveAdaptive(AdaptiveColor $color): \SugarCraft\Core\Util\Color | Resolve an AdaptiveColor with this renderer's dark-bg flag. Mirrors lipgloss Renderer.HasDarkBackground + adaptive pick. |
Style final class
Immutable styled-text builder. Each setter returns a new Style.
| Method | Summary |
|---|---|
static setDefaultProfile(?ColorProfile $profile): void | Pin the ambient profile for styles created by new() from now on; null restores TrueColor. |
static defaultProfile(): ?ColorProfile | The ambient profile currently in force, or null when none was negotiated. |
static getDefaultProfile(): ?ColorProfile | Prefix-spelled alias of self::defaultProfile() from the lipgloss-era naming; the bare slot never collided (the static property and a method name are separate namespaces). |
static withDefaultProfile(?ColorProfile $profile, callable $callable): mixed | Scoped gate over the ambient default profile: pins $profile for the duration of $callable, then restores whatever was in force — finally-guarded, so an exception thrown inside still unwinds cleanly. Collapses the per-callsite save/restore ritual (finding 020) into one call; nesting is safe (each gate reinstalls its own predecessor) and null behaves as in setDefaultProfile() (TrueColor minting inside the block). |
static new(): self | |
setString(string $content): self | Bind a default content string to the style. Calling render() with no argument then renders this string. Mirrors lipgloss's SetString(). |
value(): ?string | Bound default content (set via setString() / of()), or null. |
underlineColor(Color|string|null $c): self | Coloured underline, separate from the foreground colour. Mirrors lipgloss's UnderlineColor. Emits SGR 58;... (xterm-256 extension) when underlining is active. Accepts the same input shape as fg() — a Color, a 3- or 6-digit hex string, or null to clear; a bad string refuses with the shared InvalidArgumentException path, not a TypeError. Tier caveat: SGR 58 has no 4-bit form, so at the Ansi profile the colour falls back to the FOREGROUND slot and recolours the glyphs themselves (Color::toUnderline()), rather than tinting the line. |
getUnderlineColor(): ?Color | Underline color (SGR 58), or null when default. |
underlineStyle(UnderlineStyle $style): self | Underline-line shape (single / double / curly / dotted / dashed), emitted as the SGR 4:N sub-parameter. A non-None shape also switches underline() on (an explicit later underline(false) still wins; None leaves the flag alone), so the shape never silently renders nothing. The wire form is unchanged (ruled): only 4:N, no plain SGR 4 companion. Terminals that understand SGR 4:N render the styled underline; terminals that don't typically ignore the extended form and render no underline at all, since no plain SGR 4 companion is emitted. Mirrors lipgloss UnderlineStyle. |
getUnderlineStyle(): UnderlineStyle | Underline shape (single / double / curly / dotted / dashed / none). |
paddingChar(string $char): self | Glyph used to fill padding cells. Default ' '. Single-cell graphemes are recommended; wider clusters render but break lipgloss-style width math. Mirrors lipgloss PaddingChar. |
getPaddingChar(): string | Glyph used to fill padding cells (default ' '). |
marginChar(string $char): self | Glyph used to fill margin cells. Default ' '. Mirrors lipgloss MarginChar. |
getMarginChar(): string | Glyph used to fill margin cells (default ' '). |
foreground(?Color $c): self | Set the foreground color. Pass null to clear (no SGR emitted). |
background(?Color $c): self | Set the background color. Pass null to clear. |
fg(Color|string|null $c): self | Short alias for foreground(). Accepts a Color, hex string (e.g. '#ff5'), or null to clear. |
bg(Color|string|null $c): self | Short alias for background(). Same input shape as fg(). |
on(Color|string|null $c): self | Reads naturally in chains: $s->fg('#ffffff')->on('#0000ff'). Same as bg() (hex string, Color or null) but English-shaped. |
of(string $content): self | Short alias for setString() — bind a default content string. After ->of('hello'), render() with no argument uses that string. |
foregroundAdaptive(Color|string $light, Color|string $dark): self | Store a foreground pair for resolveAdaptive() to collapse: $light for terminals with a light background, $dark for terminals with a dark one. render() never consults the pair — the light-vs-dark answer is ambient knowledge the style does not have — and rendering with the pair still uncollapsed throws a LogicException. Until the ritual runs, an explicit foreground slot wins. |
backgroundAdaptive(Color|string $light, Color|string $dark): self | |
foregroundComplete(Color|string $trueColor, Color|string $ansi256, Color|string $ansi): self | Store a foreground that picks per-tier from the supplied triple based on the live ColorProfile. render() collapses the triple itself (the tier lives on the style, so nothing ambient is needed); resolveProfile() materialises the same pick into the concrete slot. Use this when you want to override the automatic downsampling with designer-chosen values for each terminal capability tier. Mirrors lipgloss v2's CompleteColor; assign a pre-built triple through withCompleteForeground() instead (named arguments there keep the tier semantics attached to each value, which is what makes positional misorder invisible). |
backgroundComplete(Color|string $trueColor, Color|string $ansi256, Color|string $ansi): self | |
withAdaptiveForeground(AdaptiveColor $pair): self | Feed a pre-built AdaptiveColor pair into the adaptive foreground slot — the value-object twin of foregroundAdaptive(), byte-identical downstream (same slot, same set-flags). Upstream lipgloss assigns the pair (its lightdark.Color struct) directly to the style field; this restores that shape after the flattened positional port. The same fail-fast contract applies: render() refuses while the pair is uncollapsed. |
withAdaptiveBackground(AdaptiveColor $pair): self | Value-object twin of backgroundAdaptive(). |
withCompleteForeground(CompleteColor $triple): self | Feed a pre-built CompleteColor triple into the complete foreground slot — the value-object twin of foregroundComplete(), byte-identical downstream. Construct with named arguments to keep each tier bound to its value. |
withCompleteBackground(CompleteColor $triple): self | Value-object twin of backgroundComplete(). |
resolveAdaptive(bool $isDark): self | Collapse any adaptive fg/bg slots into concrete foreground / background based on the supplied dark-background flag (typically the value of \SugarCraft\Core\Msg\BackgroundColorMsg::isDark()). |
resolveProfile(): self | Collapse any complete-colour fg/bg slots into concrete foreground / background based on the style's current colour profile. Explicit concrete colours win, matching lipgloss precedence. render() collapses complete slots on its own, so this is only needed to materialise (or re-materialise after a colorProfile() change) the pick for inspection — the adaptive axis has no automatic path and must come through resolveAdaptive(). |
bold(bool $on = true): self | Toggle bold (SGR 1). |
italic(bool $on = true): self | Toggle italic (SGR 3). |
underline(bool $on = true): self | Toggle underline (SGR 4). See underlineStyle() / underlineColor() for sub-options. |
strikethrough(bool $on = true): self | Toggle strikethrough (SGR 9). |
faint(bool $on = true): self | Toggle faint / dim (SGR 2). |
dim(bool $on = true): self | Alias for faint() (SGR 2). Mirrors lipgloss's Dim. |
blink(bool $on = true): self | Toggle blink (SGR 5) — terminal-dependent; many emulators ignore it. |
rapidBlink(bool $on = true): self | Toggle rapid blink (SGR 6) — distinct from plain blink (SGR 5). |
reverse(bool $on = true): self | Toggle reverse video — swap fg / bg (SGR 7). |
overline(bool $on = true): self | Toggle overline (SGR 53). |
invisible(bool $on = true): self | Toggle invisible / hidden text (SGR 8). |
padding(int ...$sides): self | padding($all) | padding($v, $h) | padding($t, $r, $b, $l) |
paddingTop(int $n): self | |
paddingRight(int $n): self | |
paddingBottom(int $n): self | |
paddingLeft(int $n): self | |
margin(int ...$sides): self | margin($all) | margin($v, $h) | margin($t, $r, $b, $l) |
marginTop(int $n): self | |
marginRight(int $n): self | |
marginBottom(int $n): self | |
marginLeft(int $n): self | |
pad(int ...$sides): self | Short alias for padding(). CSS-style: 1 / 2 / 4 args (all / vert+horiz / top/right/bottom/left). |
mg(int ...$sides): self | Short alias for margin(). CSS-style: 1 / 2 / 4 args. |
width(?int $w): self | |
height(?int $h): self | |
maxWidth(?int $w): self | Cap rendered width to $w cells (truncate longer lines). Unlike width(), doesn't pad shorter content. Mirrors lipgloss's MaxWidth. Pass null to remove the cap. |
maxHeight(?int $h): self | Cap rendered height to $h rows (truncate excess). Unlike height(), doesn't pad shorter content. Mirrors MaxHeight. |
inline(bool $on = true): self | Force the rendered output onto a single line. Newlines in content are replaced with spaces; padding-top/bottom and margin-top/bottom collapse to zero. Mirrors lipgloss's Inline(). |
wordWrap(bool $on = true): self | Word-wrap content to width() instead of truncating it. Opt-in: the default keeps width()'s truncation, which existing consumers and the README rely on. Breaks fall on whitespace where the line allows, a word wider than the budget is broken across lines, and SGR styling carries across each break (Width::wrapAnsi()). Without a width() this is a no-op: there is no budget to wrap to. Under inline() it is also a no-op: inline() promises one line, so width() truncation applies instead. |
marginBackground(?Color $c): self | Set the colour painted into the margin area (outside the border). Defaults to no colour; useful for full-width status bars. |
colorWhitespace(bool $on = true): self | Toggle whether the style's SGR (background, reverse, underline, …) extends over whitespace the style itself adds — padding cells, the alignment fill of a width()/align() box, and height() filler rows. With false only the content is styled. Mirrors lipgloss's ColorWhitespace. Defaults to true. |
hyperlink(string $url, string $id = ''): self | Wrap rendered output in an OSC 8 hyperlink envelope so terminals that support it render the styled text as a clickable link. Mirrors lipgloss v2's Hyperlink() setter. |
getHyperlink(): ?string | Currently-set hyperlink target, or null if unset. |
tabWidth(int $w): self | Width of a \t character when expanded inside content. Defaults to Width::TAB_WIDTH. Pass 0 to keep tabs as literal \t (no expansion). |
static expandTabs(string $content, int $tabWidth = Width::TAB_WIDTH): string | Expand \t characters in $content the way render() does: each tab becomes $tabWidth spaces; 0 (or less) keeps them literal, matching the tabWidth() contract. Closes the split-brain noted there for width-budgeting callers (sugar-table fitting, core fitCell): |
transform(?\Closure $fn): self | Apply $fn at the top of the decoration pipeline, before any width measurement, padding, height fit or border, so the callback sees the caller's text (after tab-expansion and inline-fold) and its result is measured and framed like any other content — case folds and width-changing rewrites (e.g. capitalise, mask sensitive values) cannot corrupt the SGR bytes or desync the frame. Mirrors lipgloss's Transform, likewise applied at the top of its Render(). |
align(Align $h): self | |
verticalAlign(VAlign $v): self | |
border(?Border $b, bool ...$sides): self | Apply a border. Sides (variadic) follow CSS shorthand: border($b) → all four sides border($b, $v, $h) → top/bottom = $v, left/right = $h border($b, $t, $r, $b, $l) → per side |
borderTop(bool $on = true): self | |
borderRight(bool $on = true): self | |
borderBottom(bool $on = true): self | |
borderLeft(bool $on = true): self | |
borderForeground(?Color $c): self | |
borderBackground(?Color $c): self | |
borderForegroundBlend(Color|string $start, Color|string $end): self | Border-foreground gradient — pre-blends $start and $end and sets distinct per-side colours on top, right, bottom, left so the rendered border fades from one colour to the other when traversed clockwise from the top edge. |
borderTopForeground(?Color $c): self | Per-side border foreground colours. Each setter overrides the default borderForeground() for that one side; pass null to clear the override and fall back to the default. |
borderRightForeground(?Color $c): self | |
borderBottomForeground(?Color $c): self | |
borderLeftForeground(?Color $c): self | |
borderTopBackground(?Color $c): self | |
borderRightBackground(?Color $c): self | |
borderBottomBackground(?Color $c): self | |
borderLeftBackground(?Color $c): self | |
colorProfile(ColorProfile $p): self | Set the terminal capability the render targets. Mirrors what charmbracelet/colorprofile's Writer does to lipgloss output: TrueColor/Ansi256/Ansi re-quantise colours to the tier; Ascii drops colour but keeps text attributes (bold, underline, …) and OSC 8 hyperlinks; NoTty emits no escape sequence at all — including any carried in by pre-styled content — keeping only the plain-text layout. |
getForeground(): ?Color | Legal exception (owner ruling 2026-10-24): the bare name foreground() is the fluent setter foreground(?Color $c): self, so this getForeground() read keeps its get* prefix permanently. |
getBackground(): ?Color | Legal exception (owner ruling 2026-10-24): the bare name background() is the fluent setter background(?Color $c): self, so this getBackground() read keeps its get* prefix permanently. |
isBold(): bool | |
isItalic(): bool | |
isUnderline(): bool | |
isStrikethrough(): bool | |
isFaint(): bool | |
isBlink(): bool | |
isRapidBlink(): bool | |
isReverse(): bool | |
isOverline(): bool | |
isInvisible(): bool | |
getWidth(): ?int | Legal exception (owner ruling 2026-10-24): the bare name width() is the fluent setter width(?int $w): self, so this getWidth() read keeps its get* prefix permanently. |
getHeight(): ?int | Legal exception (owner ruling 2026-10-24): the bare name height() is the fluent setter height(?int $h): self, so this getHeight() read keeps its get* prefix permanently. |
getMaxWidth(): ?int | Legal exception (owner ruling 2026-10-24): the bare name maxWidth() is the fluent setter maxWidth(?int $w): self, so this getMaxWidth() read keeps its get* prefix permanently. |
getMaxHeight(): ?int | Legal exception (owner ruling 2026-10-24): the bare name maxHeight() is the fluent setter maxHeight(?int $h): self, so this getMaxHeight() read keeps its get* prefix permanently. |
getAlign(): Align | Legal exception (owner ruling 2026-10-24): the bare name align() is the fluent setter align(Align $h): self, so this getAlign() read keeps its get* prefix permanently. |
getVerticalAlign(): VAlign | Legal exception (owner ruling 2026-10-24): the bare name verticalAlign() is the fluent setter verticalAlign(VAlign $v): self, so this getVerticalAlign() read keeps its get* prefix permanently. |
getBorder(): ?Border | Legal exception (owner ruling 2026-10-24): the bare name border() is the fluent setter border(?Border $b, bool ...$sides): self, so this getBorder() read keeps its get* prefix permanently. |
getBorderForeground(): ?Color | Legal exception (owner ruling 2026-10-24): the bare name borderForeground() is the fluent setter borderForeground(?Color $c): self, so this getBorderForeground() read keeps its get* prefix permanently. |
getBorderBackground(): ?Color | Legal exception (owner ruling 2026-10-24): the bare name borderBackground() is the fluent setter borderBackground(?Color $c): self, so this getBorderBackground() read keeps its get* prefix permanently. |
getColorProfile(): ColorProfile | Legal exception (owner ruling 2026-10-24): the bare name colorProfile() is the fluent setter colorProfile(ColorProfile $p): self, so this getColorProfile() read keeps its get* prefix permanently. |
isInline(): bool | |
getTabWidth(): int | Legal exception (owner ruling 2026-10-24): the bare name tabWidth() is the fluent setter tabWidth(int $w): self, so this getTabWidth() read keeps its get* prefix permanently. |
getMarginBackground(): ?Color | Legal exception (owner ruling 2026-10-24): the bare name marginBackground() is the fluent setter marginBackground(?Color $c): self, so this getMarginBackground() read keeps its get* prefix permanently. |
getPadding(): array | Legal exception (owner ruling 2026-10-24): the bare name padding() is the fluent setter padding(int ...$sides): self, so this getPadding() read keeps its get* prefix permanently. |
getMargin(): array | Legal exception (owner ruling 2026-10-24): the bare name margin() is the fluent setter margin(int ...$sides): self, so this getMargin() read keeps its get* prefix permanently. |
borderSides(): array | |
getBorderSides(): array | |
horizontalPadding(): int | Left plus right padding, in cells. Mirrors charmbracelet/lipgloss.GetHorizontalPadding. |
verticalPadding(): int | Top plus bottom padding, in rows; zero under inline(). Mirrors charmbracelet/lipgloss.GetVerticalPadding. |
horizontalMargin(): int | Left plus right margin, in cells. Mirrors charmbracelet/lipgloss.GetHorizontalMargins. |
verticalMargin(): int | Top plus bottom margin, in rows; zero under inline(). Mirrors charmbracelet/lipgloss.GetVerticalMargins. |
horizontalBorderSize(): int | Border columns: one per enabled left or right side; zero without a border(). Mirrors charmbracelet/lipgloss.GetHorizontalBorderSize. |
verticalBorderSize(): int | Border rows: one per enabled top or bottom side; zero without a border(). Mirrors charmbracelet/lipgloss.GetVerticalBorderSize. |
horizontalFrameSize(): int | Total non-content width: padding, border and margin, left and right. Mirrors charmbracelet/lipgloss.GetHorizontalFrameSize. |
verticalFrameSize(): int | Total non-content height: padding, border and margin, top and bottom. Mirrors charmbracelet/lipgloss.GetVerticalFrameSize. |
isSet(string $prop): bool | |
unsetForeground(): self | |
unsetBackground(): self | |
unsetBold(): self | |
unsetItalic(): self | |
unsetUnderline(): self | |
unsetStrikethrough(): self | |
unsetFaint(): self | |
unsetDim(): self | Alias for unsetFaint(). |
unsetBlink(): self | |
unsetReverse(): self | |
unsetOverline(): self | |
unsetInvisible(): self | |
unsetWidth(): self | |
unsetHeight(): self | |
unsetMaxWidth(): self | |
unsetMaxHeight(): self | |
unsetBorder(): self | Drop the border AND its side toggles: the side flags revert to the all-sides default and leave propsSet, so a later inherit() re-inherits the parent's border sides along with its border. |
unsetTransform(): self | |
unsetHyperlink(): self | Drop the currently-set hyperlink. Mirrors lipgloss's UnsetHyperlink. |
unsetPadding(): self | Drop padding entirely (all four sides → 0). |
unsetMargin(): self | Drop margin entirely (all four sides → 0). |
unsetTabWidth(): self | Reset tab width to the default, Width::TAB_WIDTH. |
unsetAlign(): self | Reset horizontal alignment to Align::Left. |
unsetVerticalAlign(): self | Reset vertical alignment to VAlign::Top. |
unsetInline(): self | Drop inline mode. |
unsetMarginBackground(): self | Drop the margin background colour. |
unsetColorWhitespace(): self | Reset colorWhitespace to the default (true). |
unsetBorderTop(): self | Per-side border-side disablers. Each one flips the matching borderSides slot back to false without touching the other three sides or the border characters themselves. Mirror lipgloss's UnsetBorderTop / UnsetBorderRight / UnsetBorderBottom / UnsetBorderLeft. |
unsetBorderRight(): self | |
unsetBorderBottom(): self | |
unsetBorderLeft(): self | |
copy(): self | Duplicate this style. Returns an identical instance (the explicit propsSet is preserved). Mirrors lipgloss's deprecated Copy() — since Style is immutable, this is mostly a clarity helper. |
builder(): StyleBuilder | Start a chain that edits one draft and builds a single new style. |
inherit(self $parent): self | Merge $parent into this style. Any property the child explicitly set wins; everything else is taken from the parent. |
patch(self $other): self | Incrementally merge $other into this style. |
render(string $content = ''): string | |
__invoke(string $content): string | |
sprint(string ...$content): string | Render the arguments, joined with single spaces between them. |
printfSprint(string $format, mixed ...$args): string | printf-substitution analogue: formats with sprintf(), renders the result styled, and RETURNS the string. Upstream lipgloss v2 Printf is a writer that returns (n, err) — this is the analogue, not a mirror (the writing twin is fprint()). The un-styled twin is Output::printf(). |
println(string ...$content): int | Write the rendered sprint() output to STDOUT followed by a newline — for non-TUI scripts that just want styled console output. The space-join (and its Go divergence) is inherited from sprint(). The un-styled twin is Output::println(). |
print(string ...$content): int | Write the rendered sprint() output to STDOUT (no trailing newline). Join semantics as in sprint(); the un-styled twin is Output::print(). Same fail-fast write accounting and byte-count return as println(). |
fprint($stream, string ...$content): int | Write the rendered sprint() output to a caller-supplied stream resource (no trailing newline). The un-styled twin is Output::fprint(). |
StyleBuilder final class
Chain form of Style's plain-value setters: edit one draft, build one Style.
| Method | Summary |
|---|---|
setForeground(?Color $c): self | Set the foreground color. Pass null to clear. Mirrors Style::foreground(). |
setBackground(?Color $c): self | Set the background color. Pass null to clear. Mirrors Style::background(). |
setFg(Color|string|null $c): self | Hex-string form of setForeground(). Mirrors Style::fg(). |
setBg(Color|string|null $c): self | Hex-string form of setBackground(). Mirrors Style::bg(). |
setUnderlineColor(Color|string|null $c): self | Set the underline color (SGR 58), or clear it with null. Mirrors Style::underlineColor(). |
setBold(bool $on = true): self | |
setItalic(bool $on = true): self | |
setUnderline(bool $on = true): self | |
setStrikethrough(bool $on = true): self | |
setFaint(bool $on = true): self | |
setBlink(bool $on = true): self | |
setRapidBlink(bool $on = true): self | |
setReverse(bool $on = true): self | |
setOverline(bool $on = true): self | |
setInvisible(bool $on = true): self | |
setInline(bool $on = true): self | |
setWordWrap(bool $on = true): self | |
setColorWhitespace(bool $on = true): self | |
setUnderlineStyle(UnderlineStyle $style): self | Underline shape. A non-None shape also switches the underline flag on, as Style::underlineStyle() does; None leaves the flag alone. |
setWidth(?int $w): self | |
setHeight(?int $h): self | |
setMaxWidth(?int $w): self | |
setMaxHeight(?int $h): self | |
setTabWidth(int $w): self | Mirrors Style::tabWidth(): a negative width is refused. |
setAlign(Align $h): self | |
setVerticalAlign(VAlign $v): self | |
setColorProfile(ColorProfile $p): self | |
setString(string $content): self | Bind the default content, as Style::setString() does. |
setPadding(int ...$sides): self | |
setMargin(int ...$sides): self | |
setPaddingChar(string $char): self | Glyph that fills padding cells. Mirrors Style::paddingChar(). |
setMarginChar(string $char): self | Glyph that fills margin cells. Mirrors Style::marginChar(). |
setMarginBackground(?Color $c): self | Color painted into the margin, or cleared with null. Mirrors Style::marginBackground(). |
build(): Style | Build the Style. The builder stays usable: the draft is copied, not consumed. |
StyleParser final class
Parses termui-style inline style strings into Cell arrays.
| Method | Summary |
|---|---|
static parse(string $input, Style $defaultStyle): array | Parse a styled string into a list of Cells. |
Theme final class
Canonical theme palette — the single source of truth for terminal colour schemes across SugarCraft consumer libs.
| Method | Summary |
|---|---|
__construct(public readonly Color $foreground, public readonly Color $background, public readonly Color $primary, public readonly Color $secondary, public readonly Color $accent, public readonly Color $muted, public readonly Color $error, public readonly Color $warning, public readonly Color $success, public readonly Color $info, public readonly Color $border, public readonly Color $separator, public readonly Color $cursor, public readonly array $styles = []) | |
static dark(): self | Mirrors charmbracelet/lipgloss.Theme.dark(). |
static light(): self | Mirrors charmbracelet/lipgloss.Theme.light(). |
static dracula(): self | Mirrors charmbracelet/lipgloss.Theme.dracula(). |
static tokyoNight(): self | Mirrors charmbracelet/lipgloss.Theme.tokyoNight(). |
static oneDark(): self | Mirrors charmbracelet/lipgloss.Theme.oneDark(). |
static githubDark(): self | Mirrors charmbracelet/lipgloss.Theme.githubDark(). |
static solarizedDark(): self | Mirrors charmbracelet/lipgloss.Theme.solarizedDark(). Based on the Solarized colour palette (Ethan Schoonover). |
static solarizedLight(): self | Mirrors charmbracelet/lipgloss.Theme.solarizedLight(). Based on the Solarized colour palette (Ethan Schoonover). |
static ansi(): self | Terminal-default 8-colour ANSI theme. Mirrors charmbracelet/lipgloss.Theme.ansi(). |
static for(bool $isDark): self | Pick the matching member of the built-in dark/light pair from a known polarity. The injectable seam adaptive() cannot accept — callers that already know the background (an OSC-11 probe, a host setting, a stored user preference) resolve the theme without re-reading the environment. |
static adaptive(bool $fallbackDark = true): self | Auto-detect theme from the COLORFGBG environment variable. Falls back to dark when the variable is absent or unparseable. |
static catalog(): array | Enumerate the names of all built-in theme factories. |
style(string $role): ?Style | The Style bound to a semantic role, or null when the theme defines no binding for it. Mirrors charmbracelet/lipgloss's Theme.StyleFunc (whose (Style, bool) tuple collapses to the nullable read here). |
withStyle(string $role, ?Style $style): self | Returns a new Theme with one role binding replaced — or removed when $style is null. The registry rides the private copy door, so no wither can drop it: the lesson of finding 037 applied to the 14th field itself (finding 003). |
withForeground(Color $foreground): self | Returns a new Theme with the foreground colour replaced. |
withBackground(Color $background): self | Returns a new Theme with the background colour replaced. |
withPrimary(Color $primary): self | Returns a new Theme with the primary colour replaced. |
withSecondary(Color $secondary): self | Returns a new Theme with the secondary colour replaced. |
withAccent(Color $accent): self | Returns a new Theme with the accent colour replaced. |
withMuted(Color $muted): self | Returns a new Theme with the muted colour replaced. |
withError(Color $error): self | Returns a new Theme with the error colour replaced. |
withWarning(Color $warning): self | Returns a new Theme with the warning colour replaced. |
withSuccess(Color $success): self | Returns a new Theme with the success colour replaced. |
withInfo(Color $info): self | Returns a new Theme with the info colour replaced. |
withBorder(Color $border): self | Returns a new Theme with the border colour replaced. |
withSeparator(Color $separator): self | Returns a new Theme with the separator colour replaced. |
withCursor(Color $cursor): self | Returns a new Theme with the cursor colour replaced. |
TitlePlacement enum
Horizontal alignment of a border title within its allocated space.
Cases: Left · Center · Right
PHP also provides cases().
UnderlineStyle enum
Underline-line style — drives the SGR 4:N sub-parameter that terminals such as kitty, WezTerm, iTerm2 and recent xterm interpret as a distinct line shape under the text.
Cases: None · Single · Double · Curly · Dotted · Dashed
PHP also provides cases(), from() and tryFrom().
VAlign enum
Vertical alignment of content within a fixed-height Style box. Used by Style::verticalAlign() together with Style::height().
Cases: Top · Middle · Bottom
PHP also provides cases(), from() and tryFrom().
SugarCraft\Style\Bar
HelpBar final class
A themed single-line keyboard-shortcut help bar.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(private readonly array $entries = [], private readonly string $keySeparator = ': ', private readonly string $separator = ' │ ', private readonly ?Style $keyStyle = null, private readonly ?Style $labelStyle = null, private readonly ?int $width = null, private readonly bool $visible = true) | |
static new(): self | Empty, visible help bar with default separators. |
static fromMap(array $bindings): self | Build a help bar from a key → label map. Insertion order is preserved; a repeated key overwrites the earlier label. |
add(string $key, string $label): self | Append a key → label entry. Duplicate keys are kept (ordered list). |
bindings(array $bindings): self | Replace all entries from a key → label map. |
without(string $key): self | Drop the first entry whose key matches. |
keySeparator(string $separator): self | Separator between a key and its label (default ': '). |
separator(string $separator): self | Separator between entries (default ' │ '). |
keyStyle(?Style $style): self | Style applied to each key. Null renders keys raw. |
labelStyle(?Style $style): self | Style applied to each label. Null renders labels raw. |
width(?int $width): self | Cap the rendered line to this width (ANSI-aware truncation). Null = uncapped. |
visible(bool $on = true): self | Toggle visibility — a hidden bar renders to the empty string. |
hidden(): self | Alias for visible(false). |
entries(): array | |
getKeySeparator(): string | Legal exception (owner ruling 2026-10-24): the bare name keySeparator() is the fluent setter keySeparator(string $separator): self, so this getKeySeparator() read keeps its get* prefix permanently. |
getSeparator(): string | Legal exception (owner ruling 2026-10-24): the bare name separator() is the fluent setter separator(string $separator): self, so this getSeparator() read keeps its get* prefix permanently. |
getKeyStyle(): ?Style | Legal exception (owner ruling 2026-10-24): the bare name keyStyle() is the fluent setter keyStyle(?Style $style): self, so this getKeyStyle() read keeps its get* prefix permanently. |
getLabelStyle(): ?Style | Legal exception (owner ruling 2026-10-24): the bare name labelStyle() is the fluent setter labelStyle(?Style $style): self, so this getLabelStyle() read keeps its get* prefix permanently. |
getWidth(): ?int | Legal exception (owner ruling 2026-10-24): the bare name width() is the fluent setter width(?int $width): self, so this getWidth() read keeps its get* prefix permanently. |
isVisible(): bool | |
render(): string | Assemble the help bar into a single line. Returns the empty string when hidden or when there are no entries. |
__toString(): string |
Segment final class
A single themed piece of text inside a StatusBar.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(public readonly string $text = '', public readonly ?Style $style = null) | |
static new(): self | Empty segment (no text, no style). |
static of(string $text, ?Style $style = null): self | Build a segment from a text run and an optional Style. |
withText(string $text): self | Replace the text run. |
withStyle(?Style $style): self | Replace (or clear, with null) the segment style. |
text(): string | Bound text run. |
style(): ?Style | Bound style, or null when the text renders raw. |
width(): int | Visible cell width of the text (the raw text carries no SGR). |
isEmpty(): bool | True when the text run is empty (renders to nothing). |
render(): string | Render the text through its style. Returns the raw text unchanged when no style is bound. |
StatusBar final class
A themed single-line status bar with left / center / right segment groups.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(private readonly array $left = [], private readonly array $center = [], private readonly array $right = [], private readonly string $separator = ' ', private readonly ?int $width = null, private readonly ?Style $style = null, private readonly string $leftCap = '', private readonly string $rightCap = '', private readonly string $fillChar = ' ', private readonly bool $visible = true) | |
static new(): self | Empty, visible, auto-width status bar. |
left(Segment|string ...$segments): self | Replace the left group. Accepts Segments and/or plain strings (wrapped into un-styled segments). |
center(Segment|string ...$segments): self | Replace the center group. Same input shape as left(). |
right(Segment|string ...$segments): self | Replace the right group. Same input shape as left(). |
addLeft(Segment|string ...$segments): self | Append to the left group. |
addCenter(Segment|string ...$segments): self | Append to the center group. |
addRight(Segment|string ...$segments): self | Append to the right group. |
separator(string $separator): self | Separator inserted between segments within a single group. |
width(?int $width): self | Fixed target width in cells. The bar fills (pads) up to the width and caps (truncates) longer content. Pass null for natural (auto) width. |
style(?Style $style): self | Bar-wide base style — colours the fill and any un-styled text. Null clears it. |
caps(string $left, string $right): self | Edge caps (borders) placed outside the segment groups. |
fillChar(string $char): self | Glyph used to fill the gaps between groups (default ' '). |
visible(bool $on = true): self | Toggle visibility — a hidden bar renders to the empty string. |
hidden(): self | Alias for visible(false). |
leftSegments(): array | |
centerSegments(): array | |
rightSegments(): array | |
getSeparator(): string | Legal exception (owner ruling 2026-10-24): the bare name separator() is the fluent setter separator(string $separator): self, so this getSeparator() read keeps its get* prefix permanently. |
getWidth(): ?int | Legal exception (owner ruling 2026-10-24): the bare name width() is the fluent setter width(?int $width): self, so this getWidth() read keeps its get* prefix permanently. |
getStyle(): ?Style | Legal exception (owner ruling 2026-10-24): the bare name style() is the fluent setter style(?Style $style): self, so this getStyle() read keeps its get* prefix permanently. |
getCaps(): array | Legal exception (owner ruling 2026-10-24): the bare name caps() is the fluent setter caps(string $left, string $right): self, so this getCaps() read keeps its get* prefix permanently. |
getFillChar(): string | Legal exception (owner ruling 2026-10-24): the bare name fillChar() is the fluent setter fillChar(string $char): self, so this getFillChar() read keeps its get* prefix permanently. |
isVisible(): bool | |
render(): string | Assemble the bar into a single line. Returns the empty string when the bar is hidden. |
__toString(): string |
ZoneEntry final class
The unit a ZoneRow places or drops whole: an ordered run of ZonePieces (a tab body and its close mark, say) that are kept or collapsed together. Pieces are concatenated with no separator, so any gap inside an entry is a plain unzoned piece.
| Method | Summary |
|---|---|
__construct(array $pieces, public readonly mixed $tag = null) | |
static of(array $pieces, mixed $tag = null): self | |
pieces(): array | |
tag(): mixed | |
width(): int | Total plain cell width of every piece. |
ZonePiece final class
One independently clickable run of a ZoneRow: its PLAIN text (the only thing ever measured), an optional zone id, and an optional paint callback that turns the plain text into styled output.
| Method | Summary |
|---|---|
__construct(public readonly string $plain, public readonly ?string $id = null, ?callable $paint = null) | |
static of(string $plain, ?string $id = null, ?callable $paint = null): self | |
plain(): string | Plain text. |
id(): ?string | Zone id, or null for an unclickable piece. |
width(): int | Cell width of the plain text. |
painted(): string | The painted text (the plain text when no callback is bound). |
ZonePlan final class
What a ZoneRow decided for one width: the entries painted, the entries collapsed, and the overflow entry standing in for them (null when nothing was dropped or no marker fits).
| Method | Summary |
|---|---|
__construct(public readonly array $placed, public readonly array $dropped, public readonly ?ZoneEntry $overflow) | |
placed(): array | |
dropped(): array | |
overflow(): ?ZoneEntry |
ZoneRow final class
A one-row bar of clickable pieces that fits a width budget and answers its own click zones. The shared engine behind a menu-title bar and a window-tab strip.
| Method | Summary |
|---|---|
static new(): self | |
withLead(ZonePiece ...$pieces): self | Pieces that always lead the row and are never dropped (a [+] affordance, a leading gap). |
withEntries(array $entries): self | |
withSeparator(string $separator): self | Plain separator between entries (default one space). |
withSeparatorAfter(bool $after = true): self | Place the separator after each entry instead of before it. |
withOverflow(?callable $overflow): self | Builds the overflow entry for a dropped count; return null for "no marker". Receives the entries it would stand in for. |
withMarker(?callable $marker): self | Wraps a zoned piece's painted text for a marked render, e.g. Mark::zone(...). |
withZoneGate(?callable $gate): self | Predicate deciding whether an id may carry a zone at all. |
width(): int | Plain width of the lead plus every entry and separator, no collapse. |
plan(?int $cols): ?ZonePlan | Decide the row for $cols (null = unbounded). Null when $cols is below the lead's width: nothing can be painted. |
render(?int $cols, bool $marked): string | The painted ($marked false) or zone-wrapped ($marked true) row; '' when nothing fits. |
zones(?int $cols): array | Click spans of the row at $cols, same arithmetic as render(). |
SugarCraft\Style\Border
BorderGradientBlend final class
Interpolates between N colors (1-5) to produce 4 border-side colors for a smooth gradient around the border perimeter (top → right → bottom → left clockwise). Mirrors lipgloss v2's BorderGradientBlend.
| Method | Summary |
|---|---|
__construct(private readonly array $colors, private readonly array $sides) | |
static fromColors(Color ...$colors): self | Build a new blend from 2-5 colors. Colors are distributed proportionally around the border perimeter and interpolated to exactly 4 side colors. |
colors(): array | The N source colors passed to the constructor. |
sides(): array | The 4 interpolated colors — one per border side in clockwise order: [top, right, bottom, left]. |
TitleAnchor enum
Anchor position for a border title.
Cases: TopLeft · TopCenter · TopRight · BottomLeft · BottomCenter · BottomRight
PHP also provides cases().
SugarCraft\Style\Layout
Constraint abstract class
Base for all constraint types used by Layout::split().
| Method | Summary |
|---|---|
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Fill final class
Fills all remaining space with proportional $weight.
| Method | Summary |
|---|---|
__construct(int $weight = 1) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Layout final class
Constraint-based layout split facade.
| Method | Summary |
|---|---|
static horizontal(array $constraints): self | Create a horizontal (left-to-right) layout. |
static vertical(array $constraints): self | Create a vertical (top-to-bottom) layout. |
split(Rect $area): array | Split the given area into Rects according to the constraints. |
Length final class
Fixed character-cell count.
| Method | Summary |
|---|---|
__construct(int $n) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Max final class
Upper-bound size cap; takes less if space is insufficient.
| Method | Summary |
|---|---|
__construct(int $n) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Min final class
At least $n cells; takes more if space is available.
| Method | Summary |
|---|---|
__construct(int $n) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Percentage final class
Proportional size as a percentage of the available area.
| Method | Summary |
|---|---|
__construct(int $n) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
Ratio final class
Proportional size based on a ratio (numerator / denominator).
| Method | Summary |
|---|---|
__construct(int $numerator, int $denominator) | |
__get(string $name): mixed | |
static length(int $n): Length | Fixed character-cell count. |
static min(int $n): Min | At least $n cells; takes more if space is available. |
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 less if space is insufficient. |
ReadsConstraintPayload trait
Shared unknown-property guard for the constraint wrappers.
Rect final readonly class
An 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 rect of the given dimensions. |
RegionBridge final class
Converts between the two deliberately-distinct Region value objects that share a name across packages:
| Method | Summary |
|---|---|
static toBuffer(ConstraintsRegion $r): BufferRegion | sugar-constraints Region → sugar-cellbuffer Region. |
static toConstraints(BufferRegion $r): ConstraintsRegion | sugar-cellbuffer Region → sugar-constraints Region. |
Solver final class
Facade that delegates constraint solving to a LayoutSolver.
| Method | Summary |
|---|---|
static solve(Rect $area, array $constraints, Direction $dir): array | Solve constraints against an area in the given direction. |
SolverFactory final class
Factory for creating a LayoutSolver instance.
| Method | Summary |
|---|---|
static resetEnvironmentResolutionForTesting(): void | Drop the memoized environment decision and the notice latch. Test seam: production code resolves exactly once and never calls this. |
static fromEnvironment(): LayoutSolver | Pick the layout solver the environment asks for. |
static default(): LayoutSolver | Alias of fromEnvironment(), kept so callers written before the rename keep working (external consumers track dev-master). |
SugarCraft\Style\Listing
Enumerator final class
Factory of enumerator closures for ItemList.
| Method | Summary |
|---|---|
static dash(): \Closure | |
static bullet(): \Closure | |
static asterisk(): \Closure | |
static arabic(): \Closure | |
static alphabet(): \Closure | |
static none(): \Closure | |
static roman(): \Closure | Lowercase Roman numerals: i. ii. iii. iv. v. … |
static romanUpper(): \Closure | Uppercase Roman numerals: I. II. III. IV. V. … |
static decimal(): \Closure | Decimal-dotted: 1. 2. … 9. 10. (alias for arabic, kept for parity with lipgloss's Decimal). |
static tree(): \Closure | List-as-tree enumerator — emits the box-drawing branch glyphs ├─ (intermediate) and └─ (last item) so an ItemList renders as a flat tree without nesting. Mirrors lipgloss's list.Tree enumerator. |
ItemList final class
Renders an enumerated list — bullet, dash, numbered, alphabet, etc.
| Method | Summary |
|---|---|
__construct() | |
static new(string|self ...$items): self | Variadic constructor — accepts an arbitrary number of items in one call. Mirrors lipgloss's list.New(items ...) shortcut. |
item(string|self $text): self | |
items(iterable $items): self | |
enumerator(\Closure $fn): self | |
itemStyle(?Style $s): self | Style applied to every rendered item's text. Combine with itemStyleFunc() for per-item overrides — the func wins. |
itemStyleFunc(?\Closure $fn): self | Per-item style callback: $fn($index, $itemText). Applied after the static itemStyle() so a func can override per row. |
enumeratorStyle(?Style $s): self | Style applied to enumerator markers. |
indent(string $s): self | Indent string prepended to every line of a nested sublist. Defaults to two spaces; set to a styled border rune for tree-like indentation. |
render(): string | |
__toString(): string |
SugarCraft\Style\Table
Data interface
Row-reader contract consumed by Table::data(). Any data source — in-memory matrix, lazy iterator, database row-walker — implements rows() / columns() / at() to feed Table.
| Method | Summary |
|---|---|
rows(): int | Total row count (excluding any header). |
columns(): int | Column count. Should be uniform across rows. |
at(int $row, int $col): string | Cell content at ($row, $col). Coordinates are 0-based. Out-of- range coordinates may return an empty string or throw — callers should respect rows() / columns() bounds. |
StringData final class
Default in-memory Data implementation — a 2D string array.
| Method | Summary |
|---|---|
__construct(private readonly array $rows) | |
static fromMatrix(iterable $matrix): self | Build a StringData from a 2D array. Non-string cell values are coerced via (string). Ragged rows are padded with empty strings to the widest row. |
rows(): int | |
columns(): int | |
at(int $row, int $col): string | |
append(string ...$cells): self | Append a row. Returns a new instance (immutable). |
static empty(): self | Empty StringData (zero rows, zero columns). |
Table final class
Tabular data renderer. Builds a string with column-aligned cells, an optional header row, and an optional border (using the middle-* runes from Border).
| Method | Summary |
|---|---|
static new(): self | |
headers(string ...$headers): self | |
row(string ...$cells): self | |
rows(iterable $rows): self | |
clearRows(): self | Drop every body row but keep the headers + every other setting intact. Mirrors lipgloss's ClearRows(). Useful when you want to refill a static-headers table from a streaming data source. |
data(Data $data): self | Bulk-replace body rows from any Data source. Mirrors lipgloss's Data(StringData) setter — pass StringData (or any custom Data implementation) for streaming ingest. |
border(?Border $b): self | |
headerAlign(Align $a): self | |
rowAlign(Align $a): self | |
styleFunc(?\Closure $fn): self | Per-cell style callback. $fn($row, $col) is called for every data cell (including the header — row index === Table::HEADER_ROW for the header). Return a Style; the cell content is wrapped in Style::render() before alignment / border join. |
borderTop(bool $on = true): self | Toggle borders per side. Each is on by default. Mirrors lipgloss's Border() / BorderTop() / BorderRight() / …. |
borderRight(bool $on = true): self | |
borderBottom(bool $on = true): self | |
borderLeft(bool $on = true): self | |
borderHeader(bool $on = true): self | Toggle the header / body separator row. Default on. |
borderRow(bool $on = true): self | Draw a separator row between every body row. Default off. |
borderColumn(bool $on = true): self | Draw vertical separators between columns. Default on. Off → cells join with a single space separator. |
width(?int $cells): self | Cap the rendered table width to $cells columns. When set, columns are shrunk proportionally (lipgloss-style) to fit within the cap, with a minimum of 1 cell content per column. Cell content that still exceeds the shrunken column width is truncated via Width::truncateAnsi (unless a wrap() callback is set, which then receives the shrunken width and may spread the cell over several lines). The cap is best-effort: border runes, the one-space cell padding and the 1-cell column floor are never shrunk, so a cap smaller than that fixed overhead (e.g. on all-empty rows) renders wider than requested. Pass null to remove the cap. |
offset(int $n): self | Skip the first $n body rows when rendering (after header). Useful for pagination. Default 0. |
wrap(?\Closure $fn): self | Cell-overflow wrap callback. Receives the raw cell value and the column's content width (after any width() cap shrink) and returns the cell's lines. When set, the callback is invoked per-cell in place of the default Width::truncateAnsi truncation, and EVERY returned line is rendered: a row whose cells wrap to N lines occupies N physical lines, shorter cells padded with blank lines. A returned line still wider than the column is truncated with Width::truncateAnsi so the grid never misaligns; an empty list renders as one blank line. |
render(): string | |
__toString(): string |
SugarCraft\Style\Tree
Enumerator final class
Connector character set used by Tree. Each preset bundles four runes: branch (intermediate child), lastBranch (terminal child), indent (continuation prefix for an intermediate ancestor), and lastIndent (continuation prefix when the ancestor was the last child).
| Method | Summary |
|---|---|
__construct(public readonly string $branch, public readonly string $lastBranch, public readonly string $indent, public readonly string $lastIndent) | |
static default(): self | The standard box-drawing connector set. Named default() — an accepted exception to the repo's no-::default() rule — because it mirrors charmbracelet/lipgloss/tree.DefaultEnumerator one-to-one. |
static rounded(): self | |
static ascii(): self |
Tree final class
Renders a hierarchical tree using box-drawing connectors.
| Method | Summary |
|---|---|
static new(): self | |
static rootOf(string $label): self | Named-ctor variant of Tree::new()->root($label). Mirrors lipgloss's tree.Root(label) package-level constructor. |
root(string $r): self | |
value(): string | Read-only accessor for the configured root label. |
child(self|string $c): self | |
offset(int $start, int $end): self | Render only children in the half-open [start, end) range. Pass 0 for either bound to mean "no clamp on that end" — i.e. offset(2, 0) skips the first two children and renders the rest; offset(0, 5) renders only the first five. Mirrors lipgloss's Tree::Offset(start, end) / OffsetStart / OffsetEnd. |
offsetStart(int $start): self | Convenience: drop the first $start children. |
offsetEnd(int $end): self | Convenience: keep only the first $end children. |
children(self|string ...$c): self | |
hide(bool $on = true): self | Hide this tree's root in the output. Useful when nesting trees as siblings under a single parent — the inner tree's root is already supplied by the parent. |
enumerator(Enumerator $e): self | Swap the connector character set. Pass Enumerator::default() (├──/└──), Enumerator::rounded() (├──/╰──), or Enumerator::ascii() (|--/`--). |
indenter(?\Closure $fn): self | Replace the continuation indenter. $fn(bool $isLast): string receives whether the current branch is the last child and returns the continuation prefix used for descendant lines. Default: '│ ' for non-last and ' ' for last. |
rootStyle(?Style $s): self | |
itemStyle(?Style $s): self | |
enumeratorStyle(?Style $s): self | |
render(): string | |
__toString(): string |
Troubleshooting
Colors still print under NO_COLOR, or into a pipe
Style::new() renders TrueColor unless a process-wide default has been pinned, and Style::new() never reads the environment itself, although Theme::adaptive() and Renderer::fromEnvironment() do. Negotiate the terminal's tier once at startup and pin it with Style::setDefaultProfile(). Every Style created afterwards downsamples to that tier, and NoTty strips every escape. The detection reads NO_COLOR, CLICOLOR, CLICOLOR_FORCE and TERM=dumb through sugar-colorprofile.
use SugarCraft\Core\Util\ColorProfile;
use SugarCraft\Style\Style;
Style::setDefaultProfile(ColorProfile::detect(null, STDOUT));
Theme::adaptive() picks the dark palette on a light terminal
adaptive() reads only the last field of COLORFGBG. A value in the form fg;bg with a background index from 0 to 255 decides light or dark by that colour's luminance. When the variable is unset, has no ;, or holds a non-numeric or out-of-range background, the result is the fallback, which is dark by default. Many terminals never set COLORFGBG, so on those the fallback decides every time. Pass adaptive(false) to make the fallback light, or choose Theme::light() or Theme::dark() when the host knows its background.
A wrapped table cell stays on one line, or render() throws a TypeError
A Table::wrap() callback must return a list of physical lines, not a single string with embedded newlines. Each element of the returned array becomes one rendered line of the row. Split the wrapped text into an array before returning it, so the row grows to match. A callback that returns a plain string does not stay on one line. render() fails with array_values(): Argument #1 ($array) must be of type array, string given.
use SugarCraft\Core\Util\Width;
use SugarCraft\Style\Table\Table;
$table = Table::new()
->headers('Note')
->row('A long note that should wrap across several lines')
->wrap(fn (string $cell, int $colWidth): array =>
explode("\n", Width::wrapAnsi($cell, $colWidth)))
->render();
An overlay hides the layer beneath it instead of blending
Canvas composites layers in z-order, and an upper cell replaces the lower cell it covers. There is no alpha blending, so every cell inside an overlay's footprint shows the overlay's content. Cells outside that footprint still show the base layer. Size the overlay to the area it needs, and keep the base visible around it.
withEmbeddedTitle() adds nothing to the border
An empty string is treated as no title, so the edge stays identical to an untitled border. The layout also budgets exactly one cell per junction. A title that is too long for its edge shrinks to fit and ends in …, so it is cut rather than wrapped. Widen the Style with width() or shorten the title when the cut text matters.
Upstream mapping
Most classes cite the upstream they mirror in their docblock, written as Mirrors charmbracelet/....
Style, color downsampling: lipglossStyle, colorprofileWriterThemeand its factories: lipglossTheme.dark(),Theme.dracula(),Theme.tokyoNight(), and the restLayout::joinHorizontal(),joinVertical(),place(): lipglossJoinHorizontal,JoinVertical,PlaceTree\Enumerator: the default enumerator of lipgloss/treeCanvas: lipglossCanvas(Bubble Tea v2)
Changelog and versioning
The package has no separate changelog file and no release tag yet, so it publishes only dev-master. Its history is the commit log of the sugar-style/ directory in the monorepo, at github.com/detain/sugarcraft/commits/master/sugar-style. Two deprecated accessors on Style, getDefaultProfile() among them, have a docblock that reads REMOVED-IN: 2.0.0, so they go in 2.0.0. The deprecated Border::getTitles() alias carries no removal version yet, so do not plan its removal for 2.0.0.
Demos.
VHS-recorded GIF demos of the library's headline examples. Regenerated automatically on every push that touches the source. One example ships without a GIF: examples/styled-text.php.
Style
Foreground / background, bold, italic — chained Style builders.
Border
All eight built-in border styles.
Table
Per-cell styleFunc with header highlighting.
List
Bulleted list with custom enumerator.
Tree
Indented tree with branch glyphs.
Dashboard
Multi-panel layout joined horizontally + vertically.
Constraints
Constraint-based layout driving a 3-pane dashboard.