SugarColorprofile
Terminal color profile detection and color degradation
Detect the terminal's color capability (TrueColor / Ansi256 / Ansi / Ascii / NoTTY — the five detection-emittable levels) and degrade colors, strings and whole output streams to match it — one-way, TrueColor down, never up; an opt-in perceptual family picks the nearest palette color when a degraded value must land on a fixed set. Detection reads the shared env ladder, honoring NO_COLOR, FORCE_COLOR, TERM=dumb and the reduced-motion request. It ports the concepts of charmbracelet/colorprofile, which detects a terminal's color profile and downgrades output to match.
Install
composer require sugarcraft/sugar-colorprofile
No tagged releases ship yet — Packagist serves the dev-master branch only, so require it as sugarcraft/sugar-colorprofile:dev-master; on a default-stable project a bare sugarcraft/sugar-colorprofile request does not resolve.
Requires PHP 8.3+ and the ext-mbstring extension — the UTF-8 sweep in Env::sanitize and the TERM cap run mb_convert_encoding/mb_strcut unguarded, and until this was declared the dependency was satisfied only transitively via sugar-core while the docs claimed the opposite. The probes' optional posix_* calls remain feature-detected, and an absent or unreadable infocmp child degrades the phase-2 answer instead of failing. Direct dependencies: sugarcraft/sugar-core, react/event-loop, react/child-process, react/promise (the latter three back the async AsyncProbe consult).
Supported targets: POSIX terminals. The phase-2 infocmp consult is POSIX-only by design — it queries the compiled terminfo database. The env ladder's Windows/macOS legs (WT_SESSION, the TERM_PROGRAM=iTerm.app hint, the only macOS terminal name matched, since Apple_Terminal is deliberately excluded) are untested by this repository's CI, whose ladder legs run on Linux only; on Windows the library answers from the env ladder alone. Case matters more there than anywhere else: env keys are matched case-exactly, while the Windows environment block is case-insensitive at the OS layer — an unusual spelling such as No_Color can exist in the shell's view and still miss detection, because the library deliberately does not alias-match env keys (Env::resolve).
Quickstart
use SugarCraft\ColorProfile\{Color, ColorProfile, Palette, ProfileWriter};
$profile = Palette::detect(STDOUT); // ColorProfile::TrueColor | Ansi256 | Ansi | Ascii | NoTTY
echo $profile->label(); // e.g. "No TTY" when piped
// Downsample one color to an explicit profile
$coral = Color::parse('#ff6b6b'); // r 255, g 107, b 107
$c256 = Palette::toProfile($coral, ColorProfile::Ansi256);
echo $c256->toAnsi256Index(); // 203
echo $c256->toAnsi256Foreground(); // "\x1b[38;5;203m"
// Rewrite every color in a string for a given profile
$ansi = (new Palette())->withProfile(ColorProfile::Ansi256)
->degrade("\x1b[38;2;255;107;107mhi\x1b[0m"); // "\x1b[38;5;203mhi\x1b[0m"
// Or wrap a stream and let it degrade (or strip, under NoTTY) on write
ProfileWriter::wrap(STDOUT)->write("\x1b[38;2;107;80;255mFancy\x1b[0m\n");
Concepts
A color profile is the richest color an output stream can carry: TrueColor, Ansi256, Ansi, Ascii or NoTTY. Detection picks one of them from the environment, and degradation only goes down. A TrueColor value is rewritten to the nearest color the chosen profile can show, and nothing is ever raised to a richer profile. Ascii drops the color and keeps decoration such as bold and underline. NoTTY strips every escape, so use it for streams that are not terminals.
What's in the box
CLICOLOR_FORCE=1 / FORCE_COLOR outrank every later leg (a falsy FORCE_COLOR spelling lands on the Ascii floor). Suppressors come next: NO_COLOR (empty = unset), CLICOLOR=0 and TERM=dumb (case-insensitive) turn color off — dumb outranks an advertised COLORTERM, it is a promise of minimal capabilities. Advertised depth follows: COLORTERM (24bit/truecolor, plus the legacy marker yes, which the ladder reads as a 256-color promise, not a 24-bit one), TERM_PROGRAM, WT_SESSION, GOOGLE_CLOUD_SHELL (exactly true grants TrueColor; any other value, false and 1 included, carries no 24-bit promise), the TMUX/STY + screen*/tmux* rung and the TERM depth patterns. Palette adds the stream TTY gate on top; Probe/AsyncProbe/TerminalProbe add the phase-2 infocmp Tc/RGB upgrade (a fixed-path binary, run with a minimal child environment). The detection ladder emits five levels (TrueColor, Ansi256, Ansi, Ascii and NoTTY), and the ColorProfile enum that carries the result has eight.Palette::toProfile() / Color::convert() downsample a color to the 256-color cube and gray ramp or to the 16 ANSI slots.degrade() rewrites the SGR colors in a string for the current profile; under NoTTY it strips every escape — SGR, CSI, OSC and DCS sequences, SS3/APC/PM/SOS strings, the Fe escape pairs and charset selectors — decoration included, so pin the Ascii floor for a color-only strip. ProfileWriter does the same to everything written to a stream.Color values via the non-mutating read API — StandardColors::all(), fromIndex(1), catalog(). (The $red/$brightBlack statics are deprecated process-global mutables; see the README deprecation window.)DeltaE) and an opt-in nearest-palette matcher (NearestColor).Detection phases
The capability probes run in four phases; phase 1 is the shared DetectionChain, so the ladder cannot drift between surfaces:
| Phase | Source | What it can set |
|---|---|---|
| 1 — env ladder | DetectionChain over Env::resolve() | Any of the five detection-emittable levels: TrueColor / Ansi256 / Ansi / Ascii / NoTTY |
| 2 — terminfo | infocmp -1 at a fixed absolute-path roster, never looked up on PATH | Promotes an Ansi/Ansi256 rung to TrueColor on Tc/RGB; Sixel from terminfo capability names |
| 3 — advertised | TERM_PROGRAM capability map (interactive streams only) | Advertised TrueColor (WezTerm/vscode/Ghostty), ITerm2 (iTerm.app), Hyperlinks (Hyper) |
| 4 — floors | Suppression and minimal-capability floors | Holds the Ascii/NoTTY landings and the reserved-capability gates |
The terminfo leg is an exec surface: the infocmp binary is launched from a fixed absolute-path roster (never looked up on PATH), and the child environment is built in one place — the queried TERM plus a fixed PATH only. TERMINFO, TERMINFO_DIRS and HOME each steer infocmp's database lookup and are never inherited. The parser's name-position guard protects the parse from a hostile terminfo entry but cannot vouch for the source: whoever can write the system terminfo directories owns that answer. Treat every detection result as a rendering hint, never as an authorization signal.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by charmbracelet/colorprofile (Go); SugarCraft is developed as a native PHP project.
Tasks
Pin the profile for a test or a CI log. A non-empty $env replaces the ambient environment, so the answer is the same on every host.
use SugarCraft\ColorProfile\Palette;
$profile = Palette::detect(STDOUT, ['FORCE_COLOR' => '2']);
echo $profile->label(); // ANSI 256
Strip the color and keep the decoration. Pin the Ascii floor and run the string through degrade().
use SugarCraft\ColorProfile\{ColorProfile, Palette};
$plain = (new Palette())
->withProfile(ColorProfile::Ascii)
->degrade("\x1b[1;38;2;255;0;0mERROR\x1b[0m");
// "\x1b[1mERROR\x1b[0m": the bold stays and the color goes
Pin one stream to a rung. ProfileWriter::wrap() takes the same environment array, so every write to the stream degrades to that rung.
use SugarCraft\ColorProfile\ProfileWriter;
$writer = ProfileWriter::wrap(STDOUT, ['FORCE_COLOR' => '1']);
$writer->write("\x1b[38;2;255;0;0mdisk low\x1b[0m\n"); // written with the ANSI red, \x1b[91m
API reference
| Class | Method | Description |
|---|---|---|
| Palette | static detect($stream = null, array $env = []): ColorProfile | Detect the color profile for a stream |
| Palette | __construct($stream = null, array $env = []) / profile() / withProfile(ColorProfile) | Detected profile, or an explicit one |
| Palette | convert(Color) / static toProfile(Color, ColorProfile) | Downsample a color |
| Palette | degrade(string) / static stripAnsi(string) | Rewrite or strip the escapes in a string |
| Palette | describe() / comment() | Plain-language capability announcement instead of painting escapes (accessibility-friendly) |
| Color | static parse('#rrggbb') / static fromHex(0xrrggbb) / new Color(r, g, b, a) | Construct a color |
| Color | toHex() / toAnsi256Index() / toAnsi16Index() / toAnsiForeground() / toAnsi256Foreground() / toAnsi16Foreground() | Encode a color |
| Color | toAnsiBackground() / toAnsi16Background() / toAnsi8Index() / static ansi16Sgr(int, bool) / static fromAnsi256Index(int) | Background escapes, the 8-color index, SGR pairing and reverse decoding |
| Color | equals(Color) / perceivedBrightness() / isDark() / convert(ColorProfile) | Compare, measure and downsample a color |
| ColorProfile | TrueColor, Ansi256, Ansi240, Ansi, Ansi8, Fgbg, Ascii, NoTTY / label() / description() / maxColors() / degradedTo() / allowsColor() | Enum of color profiles |
| ProfileWriter | static wrap($stream, array $env = []) / write(string) / printf(format, ...) | Stream that degrades color on write |
| StandardColors | all(), fromIndex(int), catalog() | The 16 ANSI colors (non-mutating read API; the $black…$brightWhite statics are deprecated — see README) |
| DetectionChain | static detect(array $env = []) → level() / source() / term() / allowsColor() / isForced() / toColorProfile(); static userOptedOut(array $env = []): bool | The shared 14-step env ladder every detector agrees on; on the TMUX/STY rung the inner TERM is the base — no re-anchoring happens |
| Probe | static colorProfile() / isNoColor() / isForceColor() / reducedMotion() / resetForTesting() | Static env-probe layer + infocmp upgrade |
| Env | static resolve(array $injected) / value(resolved, key) / sanitize(value) | Env resolution (a non-empty injected map fully replaces the ambient env) + sanitized source strings |
| AsyncProbe | static colorProfile(?LoopInterface $loop = null): PromiseInterface / static report(?LoopInterface $loop = null): PromiseInterface<ProbeReport> / resetForTesting() | The async surfaces: a bounded ReactPHP infocmp child on the loop you pass (queried TERM + fixed PATH only). colorProfile() settles from the detection chain, and its only non-chain answer is the TrueColor promotion read from the child's terminfo output. report() is the full capability report and the async replacement for the deprecated Probe\TerminalProbe. Without a loop both resolve in place through the bounded sync door, and no child is parked on the event-loop singleton |
| Probe\TerminalProbe | run() / runProbe() → ProbeReport | Deprecated (REMOVED-IN: 2.0.0): use AsyncProbe::report(). Its terminfo leg blocks the calling thread for up to the 5 s deadline plus the 1 s grace, so do not call run() on an event-loop thread. Phased capability report (TrueColor/Color256/Color16/NoColor/BasicAscii + Sixel, KittyKeyboard, ITerm2, Hyperlinks; BracketedPaste/FocusEvents reserved) with per-capability sources |
| Probe\ProbeReport | has(Capability) / hasTrueColor() / hasColor256() / hasNoColor() / all() / allWithSource() / colorDescription() / toColorProfile() | Per-capability verdicts with the source that set each one |
| ColorMath | static toLab(int, int, int) / rgbToXyz / srgbToLinear / linearToXyz / xyzToLab | sRGB → CIELAB conversion building blocks |
| ColorDistance | between(Color, Color) / betweenLab(array, array): float | The selected ΔE metric (Euclidean / Cie76 / Cie94 / Cie2000) applied to colors or Lab triples |
| DeltaE | static cie76(array, array) / cie94(array, array) / cie2000(array, array): float | The three perceptual-distance formulas |
| NearestColor | __construct(ColorDistance) / ansi256(Color) / ansi16(Color) / closest(Color, array) / withError(Color, ?&err) / metric() / static palette256() / palette256Lab() / palette16Lab() | Opt-in nearest-palette matcher over the cached Lab palettes |
| PaletteIndex | static fromPalette(array, ColorDistance) / nearest(Color) / metric() / palette() / count() | Precomputed Lab index over any fixed palette |
Only methods declared in sugar-colorprofile/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\ColorProfile
AsyncProbe final class
Asynchronous terminal color profile probe using ReactPHP ChildProcess.
| Method | Summary |
|---|---|
static colorProfile(?LoopInterface $loop = null): PromiseInterface | Detect the terminal color profile asynchronously. |
static report(?LoopInterface $loop = null): PromiseInterface | Full terminal capability report on the same loop contract as colorProfile(): the infocmp leg runs as a child on the loop you pass in, and the promise settles with the ProbeReport the sync pipeline composes, not a second implementation of it. |
static _reset(): void |
Color final class
RGBA color value object.
| Method | Summary |
|---|---|
__construct(int $r, int $g, int $b, int $a = 255) | The constructor is the ONE documented deliberate clamp in this class: quantisers and blend pipelines feed raw RGB runs and must not explode mid-frame (the one out-of-range policy otherwise is fail-loud on DECODER-shaped inputs — see self::ansi16Sgr() and self::fromAnsi256Index(), which throw). |
static fromHex(int $hex, int $a = 255): self | Construct from a 24-bit hex integer (0xRRGGBB). |
static parse(string $hex, int $a = 255): self | Parse from CSS hex string ("#rrggbb" or "#rgb"). |
convert(ColorProfile $profile): self | Convert this color to the closest approximation representable in $profile. |
toAnsi256Index(): int | Convert to 256-color ANSI palette index (0-255). |
toAnsi16Index(): int | Convert to ANSI 16-color palette index (0-15). |
toAnsi8Index(): int | Convert to the ANSI 8-color basic palette index (0-7). |
toTrueColorForeground(): string | Render as a 24-bit truecolor SGR foreground escape: \x1b[38;2;R;G;Bm |
toTrueColorBackground(): string | Render as a 24-bit truecolor SGR background escape: \x1b[48;2;R;G;Bm |
toAnsiForeground(): string | |
toAnsiBackground(): string | |
toAnsi256Foreground(): string | Emit a 256-color ANSI foreground escape. |
toAnsi256Background(): string | Emit a 256-color ANSI background escape. |
toAnsi16Foreground(): string | Emit a 16-color ANSI foreground escape using 4-bit SGR. |
toAnsi16Background(): string | Emit a 16-color ANSI background escape using 4-bit SGR. |
toAnsiFor(ColorProfile $profile, bool $background = false): string | Emit the SGR escape that renders this color on a given profile rung — the value-object sibling of Palette::emitColor() (CP-18). |
static ansi16Sgr(int $idx, bool $background): int | Map an ANSI 16-color index (0-15) to a 4-bit SGR code. |
static fromAnsi256Index(int $idx): self | Decode an ANSI 256-color index back to an RGB color. |
toLab(): array | CIE L*a*b* (D65) coordinates of this color. |
toHex(): string | Return "#rrggbb" hex string. |
perceivedBrightness(): float | Perceived brightness (0-255) — the BT.601-weighted root-mean-square this library uses to pick black/white in self::toAscii() and the classic xterm "is this dark?" heuristic. Public so callers can choose a light or dark text variant of a background themselves instead of re-deriving the formula. |
isDark(): bool | True when the color is darker than the mid-gray point of self::perceivedBrightness() — i.e. white text reads better on it. |
static namedColors(): array | Enumerate the names of the standard named colors. |
static fromName(string $name): self | Resolve a standard color by name (case-insensitive). |
static fromAnsi16Index(int $idx): self | Decode an ANSI 16-color index (0-15) to its reference RGB color. |
static fromAnsi8Index(int $idx): self | Decode an ANSI 8-color index (0-7) to its reference RGB color. |
equals(Color $other): bool |
ColorDistance enum
Distance-metric strategy for nearest-color matching.
Cases: Euclidean · Cie76 · Cie94 · Cie2000
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
between(Color $a, Color $b): float | Distance between two colors under this metric. |
betweenLab(array $labA, array $labB): float | Distance between pre-computed Lab triples — the hot-loop entry point, letting callers amortize the sRGB -> Lab conversion over a memoized palette. EUCLIDEAN is an RGB-space metric with no meaning here: it throws instead of silently substituting Lab-space magnitudes, so mixing the two scales fails loudly. |
ColorMath final class
Perceptual color-space conversion math: sRGB -> linear -> CIE XYZ (D65) -> CIE L*a*b*.
| Method | Summary |
|---|---|
static toLab(int $r, int $g, int $b): array | Convert an sRGB byte triplet to CIE L*a*b* (D65). |
static rgbToXyz(int $r, int $g, int $b): array | Convert an sRGB byte triplet to CIE XYZ (D65), Y normalized to 0-1. |
static srgbToLinear(int $byte): float | Inverse-compatibility (gamma) decode one sRGB byte to linear light 0-1. |
static linearToXyz(float $r, float $g, float $b): array | Apply the IEC 61966-2-1 sRGB -> CIE XYZ (D65) matrix to linear light. |
static xyzToLab(array $xyz): array | Convert CIE XYZ (D65) to CIE L*a*b* (CIE 1976). |
ColorProfile enum
Terminal color capability profile — THE single vocabulary.
Cases: TrueColor · Ansi256 · Ansi240 · Ansi · Ansi8 · Fgbg · Ascii · NoTTY
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static fromColorProfile(self $p): self | |
static fromCore(\SugarCraft\Core\Util\ColorProfile $core): self | Lift a sugar-core Util\ColorProfile onto this vocabulary (CP-22). |
toCore(): \SugarCraft\Core\Util\ColorProfile | Project onto the five-rung Core enum (CP-22). Lossy on purpose: Core has no 240/8/fgbg rungs, so each lands on the nearest rung that never emits a color the profile could not render — Ansi240 to Ansi256, Ansi8 to Ansi, Fgbg to Ascii. |
label(): string | Human-readable label for display. |
description(): string | Short description for display. |
maxColors(): int | Maximum colors this profile supports. |
degradedTo(): ?self | Walk the profile downgrade chain to the next simpler profile. Returns null when already at the simplest (NoTTY). The walk is about emission richness, not provenance: standing on either colorless rung it cannot tell an operator opt-out from absent hardware — DetectionChain::userOptedOut() answers that (CP-20). |
allowsColor(): bool | Whether this profile permits ANSI COLOR rendering. |
DeltaE final class
CIE color-difference (delta-E) metrics computed on CIE L*a*b* (D65) triples.
| Method | Summary |
|---|---|
static cie76(array $labA, array $labB): float | CIE 1976 color difference: Euclidean distance in L*a*b*. |
static cie94(array $labA, array $labB): float | CIE 1994 color difference in the graphic-arts parametrisation. |
static cie2000(array $labA, array $labB): float | CIEDE2000 (ΔE00) color difference. |
static between(Color $a, Color $b, ColorDistance $metric = ColorDistance::Cie76): float | Public Color-level door: convert each Color to Lab exactly once, then dispatch to the array-form trio by metric. |
DetectionChain final class
Shared terminal color detection chain — the single source of truth for environment-based color capability detection.
| Method | Summary |
|---|---|
static detect(array $env = []): self | Run the detection chain on an environment array. |
level(): string | Get the detected level as a string. |
source(): string | Get the source of the detection result. |
term(): string | Get the TERM value used in detection. Values at or below self::TERM_MAX_BYTES come back byte-identical; a longer value is clamped to the ceiling here rather than exported raw — the accessor is where TERM leaves the chain, and detection itself already matched it by equality before any consumer could see it. |
allowsColor(): bool | Whether the ladder answered on a rung that renders color at all. |
isForced(): bool | True when the answer came from an explicit force leg rather than a capability read or a suppression. Callers gating on TTY presence use this to yield: upstream parity is Detect() = isatty() || forced() (CP-07), so an operator who PINNED color through the force machinery keeps that rung even on a piped stream. Suppression legs are NOT force — NO_COLOR/CLICOLOR=0/TERM=dumb ask for less output, never for escape sequences past a pipe, so they keep the gate. |
static userOptedOut(array $env = []): bool | Did the OPERATOR opt out of color, as opposed to the hardware lacking a TTY? True iff a suppression leg (NO_COLOR, CLICOLOR=0, TERM=dumb) actually FIRED the answer. A force leg outranking a suppression reads FALSE here — the rung in force is not a suppression, whoever asked. This is the discriminator the profile enums deliberately do not carry: since CP-05 both stories answer colorless rungs (Ascii for the opt-out, NoTTY for absent hardware) and a name cannot hold two truths, while a CLI repairing its own defaults (--color=always) or drawing a doctor panel needs the WHY (CP-20, sugar-colorprofile-023; the full enum split is reserved for 2.0 — decision candidate #4). |
toProfile(): ColorProfile | Convert the detection level to the profile enum. |
toColorProfile(): ColorProfile | Convert the detection level to a ColorProfile enum. |
Env final class
Single environment-resolution rule shared by every detection surface.
| Method | Summary |
|---|---|
static resolve(array $injected): array | Resolve the effective environment map for one detection run. |
static value(array $resolved, string $key): ?string | Read one variable from a resolved map, normalizing absent/false/null to null. |
static isForceValue(?string $value): bool | The force-value grammar shared by every CLICOLOR_FORCE reader: a value forces when it is SET and is neither the empty string nor the exact falsy spelling '0' — the termenv/chafa rule ("any non-empty != 0"), which the README's chalk-escape-hatch justification invokes while the old literal '1'-only reading silently stripped color for the CLICOLOR_FORCE=true|yes|on|2 spellings real dotfiles and CI images export. Only '0' and unset/empty are falsy; every other non-empty string forces. Env owns this single rule so the three readers — DetectionChain step 1, TerminalProbe's capability mapping and Probe::isForceColor — cannot drift apart (XPLAT-02). |
static sanitize(string $value): string | Make an untrusted environment value safe to interpolate into a source string: strip C0/C1/DEL control bytes (which could forge escape sequences downstream consumers print) and cap the length. |
Lang final class
Per-library translation facade for sugar-colorprofile.
NearestColor final class
True nearest-color matching against fixed (or arbitrary) palettes.
| Method | Summary |
|---|---|
static new(ColorDistance $metric = ColorDistance::DEFAULT_METRIC): self | House front door: a matcher on the default metric seat (CP-49). |
static forMetric(ColorDistance $metric): self | House front door spelling an intentional strategy choice (CP-49). |
metric(): ColorDistance | The distance strategy this matcher was built with. |
withError(Color $color, ?array &$err = null): int | |
ansi256(Color $color): int | Nearest index (0-255) in the ANSI-256 palette. |
ansi16(Color $color): int | Nearest index (0-15) in the standard ANSI-16 palette. |
closest(Color $color, array $palette): int|string | Nearest key in an arbitrary palette map of Colors. |
bestMatchWithError(Color $color, ?array &$err = null): int | Error-compensated nearest lookup against the ANSI-256 palette. |
static palette256(): array | The 256-color palette as Colors — memoized, keyed on the live StandardColors slots (indices 0-15) so a redefinition rebuilds it. |
static palette256Lab(): array | L*a*b* of self::palette256(), memoized behind the same slot fingerprint — the hot-loop guard that makes CIEDE2000 nearest matching affordable while the ANSI-16 slots stay untouched. |
static palette16Lab(): array | L*a*b* of the ANSI-16 palette, memoized behind the slot fingerprint so a StandardColors reassignment lands on the next call. |
Palette final class
Detect and query the terminal color profile.
| Method | Summary |
|---|---|
__construct($stream = null, array $env = []) | Detect the terminal color profile from the environment. |
profile(): ColorProfile | Get the detected profile. |
withProfile(ColorProfile $profile): self | Override the detected profile (e.g. manually downgrade for testing). |
static detect($stream = null, array $env = []): ColorProfile | Shortcut: detect and return the profile enum. |
convert(Color $color): Color | Convert a color to the detected (or manually set) profile. |
static toProfile(Color $color, ColorProfile $profile): Color | Static shortcut for one-off color conversion. |
degrade(string $ansi): string | Convert any TrueColor/ANSI256/ANSI sequence in a string to match the current profile. At the colorless Ascii rung every COLOR segment drops while decoration and all other sequences pass (CP-05); NoTTY strips everything. |
static stripAnsi(string $s): string | Strip all ANSI escape sequences from a string. Used when NoTTY is active. |
comment(): string | Comment on the detected profile in a human-readable way. |
describe(): string | Full descriptive sentence about the terminal's color capabilities. |
PaletteIndex final class
PCA-bucketed accelerator for nearest-color lookup over a fixed palette.
| Method | Summary |
|---|---|
static fromPalette(array $colors, ColorDistance $metric = ColorDistance::Cie76): self | Build (or reuse) an index over $colors under $metric. |
nearest(Color $color): int | Nearest palette index (lowest index on exact ties). |
metric(): ColorDistance | The distance strategy this index was built with. |
palette(): array | The palette this index was built from, in caller order. |
count(): int |
Probe final class
Static probe for terminal color profile and environment-based color detection.
| Method | Summary |
|---|---|
static colorProfile(): ColorProfile | Negotiated color profile after walking every environment variable in the canonical precedence order, then the optional infocmp phase-2 upgrade. |
static isNoColor(): bool | NO_COLOR is set to a non-empty value. An empty string means UNSET per the no-color.org convention the whole ecosystem follows. |
static isForceColor(): bool | CLICOLOR_FORCE carries a force value — set, non-empty, and not exactly '0' (the termenv/chafa grammar owned by Env::isForceValue(), shared with DetectionChain step 1 and TerminalProbe) — forcing TrueColor regardless of other settings. |
static reducedMotion(): bool | Reduced motion preference — checks REDUCE_MOTION then PREFERS_REDUCED_MOTION. Explicit negative spellings (0/false/no/off, case-insensitive) mean "not reduced"; any other non-empty value means reduced. The old polarity treated REDUCE_MOTION=false as TRUE, inverting the operator's declared preference. |
static _reset(): void |
ProfileWriter final class
ProfileWriter — stream wrapper that automatically degrades ANSI color sequences to match the terminal's detected color profile.
| Method | Summary |
|---|---|
static wrap($stream, array $env = []): self | |
__construct($stream, ColorProfile $profile) | Create a new ProfileWriter wrapping $stream. |
contents(): ?string | The bytes written so far, read back — for consumers that wrap a memory stream (php://memory / php://temp) in tests and pipelines and want the accumulated output without the ftell/rewind dance themselves. |
profile(): ColorProfile | Get the current target profile. |
withProfile(ColorProfile $profile): self | Manually change the target profile (e.g. force ASCII mode). |
write(string $data): int|false | Write data to the stream, degrading color codes to match the target profile. |
printf(string $format, ...$args): int|false | Alias of write() for printf-style calls. |
StandardColors final class
Standard 16-color ANSI palette as named Color objects.
| Method | Summary |
|---|---|
static all(): array | All 16 colors as an indexed array. |
static fromIndex(int $index): Color | Get a color by ANSI 16-color index (0-15). |
static catalog(): array | Returns a list of all available standard color names. |
SugarCraft\ColorProfile\Probe
Capability enum
Terminal capability enum discovered via TerminalProbe.
Cases: TrueColor · Color256 · Color16 · NoColor · Sixel · KittyKeyboard · ITerm2 · Hyperlinks · BracketedPaste · FocusEvents · BasicAscii
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
label(): string | Human-readable label for display. |
static key(self $cap): string | The string key a Capability occupies in a raw caps map. |
InfocmpBinary final class
Single source of truth for locating the infocmp terminfo binary.
| Method | Summary |
|---|---|
static path(): ?string | Absolute path to infocmp, or null when no roster candidate is a present AND executable file. The executable leg is what keeps this gate from drifting from sugar-image's ChafaBinary roster gate — see the class docblock's shared-rule note. |
static runBounded(string $term, ?float $timeoutSeconds = null): ?string | The ONE bounded infocmp execution surface, shared by every surface (synchronous Probe, the TerminalProbe phase-2 leg, and future callers). The pre-CP-11 shape carried two unbounded waits: the child was untimed (a wedged infocmp blocked the caller for its whole life) and its output was slurped without limit. Both arms are now bounded, and the answer is memoized per TERM so a per-tick consumer multiplies nothing. |
static childEnvironment(?string $term = null): array | The environment every infocmp child receives, at every exec surface. |
static isSafeTermName(string $term): bool | Is $term shaped like a terminal name rather than an infocmp option? |
ProbeReport final readonly class
Readonly value object holding the result of a terminal capability probe.
| Method | Summary |
|---|---|
__construct(array $capabilities, public \DateTimeImmutable $detectedAt = new \DateTimeImmutable()) | |
has(Capability $cap): bool | Check if a capability was detected. |
source(Capability $cap): ?string | Get the source string for a detected capability. |
all(): array | Return all detected capabilities as a list. |
allWithSource(): array | Return all detected capabilities with their sources. |
__get(string $name): mixed | One-release deprecation shim for the pre-CP-51 public map read ($report->capabilities) — answers the map and raises E_USER_DEPRECATED. Removal target: 2.0. New code must use all() or allWithSource(); writes never answered here (the class is readonly, so $report->capabilities = … throws regardless of this shim). |
hasTrueColor(): bool | Check if the probe detected TrueColor support. |
hasColor256(): bool | Check if the probe detected 256-color support. |
hasNoColor(): bool | Check if colors are disabled. |
toColorProfile(): ColorProfile | Bridge the capability set onto the emission-side profile enum. |
colorDescription(): string | Return a human-readable description of the highest color capability. |
TerminalProbe class
Terminal capability probe — the full capability report (color depth plus Sixel/Kitty/iTerm2/Hyperlinks/keyboard flags).
| Method | Summary |
|---|---|
__construct(array $environment = [], bool $interactive = true) | Create a new probe with an optional complete environment replacement. |
static run(): ProbeReport | Run the full probe pipeline and return a report. |
runProbe(array $overrides = [], ?bool $interactive = null): ProbeReport | Run the full probe pipeline with optional environment overrides. |
TerminfoParser final class
Name-position terminfo capability matcher.
| Method | Summary |
|---|---|
static hasCapName(string $output, array $names): bool | Whether the terminfo dump declares any of $names as a capability name (compared lowercased, name position only). |
Configuration and options
Detection has no config file. The answer comes from the environment, and the host can pin it in code. The table lists the environment variables in ladder order. The first leg that matches wins.
| Env var | Step | Effect |
|---|---|---|
CLICOLOR_FORCE=1 | 1 | Forces TrueColor past every other variable, NO_COLOR included. It also keeps the forced rung on a non-TTY stream. |
FORCE_COLOR | 2 | Sets the level: 3 or more gives TrueColor, and so do true, yes and on. 2 gives Ansi256, 1 gives Ansi. Any other spelling, such as 0 or false, lands on the Ascii floor. |
NO_COLOR | 3 | A non-empty value gives the colorless Ascii rung. Color codes are dropped, and decoration such as bold and underline is kept. |
CLICOLOR=0 | 4 | Suppresses color. |
TERM=dumb | 5 | Suppresses color. It outranks COLORTERM. |
TMUX / STY with screen* | 6 | Caps the level at Ansi256 before COLORTERM is read. |
COLORTERM | 7 | truecolor or 24bit gives TrueColor. yes gives Ansi256. |
TERM_PROGRAM=iTerm.app | 8 | Gives TrueColor. Matching is case-sensitive. |
WT_SESSION | 9 | A non-empty value gives TrueColor (Windows Terminal). |
GOOGLE_CLOUD_SHELL | 10 | Exactly true gives TrueColor. |
TMUX / STY with tmux* | 11 | Caps the level at Ansi256, but only when COLORTERM has not already answered. truecolor or 24bit at step 7 still gives TrueColor under tmux. |
TERM | 12–13 | *-256color, xterm-kitty and xterm-ghostty give Ansi256. xterm*, screen* and tmux* give Ansi. |
REDUCE_MOTION / PREFERS_REDUCED_MOTION | — | Not part of the color ladder. A non-empty value other than 0, false, no or off sets Probe::reducedMotion(). |
A host that needs a fixed answer pins it with (new Palette())->withProfile(ColorProfile::Ansi). A Palette or TerminalProbe built with a non-empty $env array is hermetic: the array replaces the ambient environment, so pass every key the check reads. An empty array is not hermetic, and falls through to the process environment.
Keys and input
The library reads no keystrokes and binds no keys. Detection takes its input from the environment and the stream being written to. The optional probes add the output of a fixed-path infocmp run.
Theming and styling
Degradation is one-way. A TrueColor value can drop to Ansi256, Ansi or Ascii, but never rises. Palette::toProfile() and Color::convert() downsample one color, and degrade() rewrites every SGR color in a string. Under the NoTTY profile, degrade() strips all escape sequences, decoration included, so pin the Ascii floor for a color-only strip. The 16 ANSI colors come from StandardColors::all(), fromIndex() and catalog(). Opt into the perceptual family, NearestColor with DeltaE, when a degraded value must land on a fixed palette.
Examples
examples/detect.phpdetects the profile for STDOUT, and prints the plain-language description fromPalette::comment().examples/convert.phpbuilds colors from an int and a hex string, then converts each one to every profile level.examples/degrade.phpwraps a stream withProfileWriterand forces each of the Ansi256, Ansi and Ascii profiles in turn.examples/standard-colors.phplists the 16 ANSI colors through the non-mutating read API.examples/probe-report.phpprints the phased capability report for a hermetic environment map.examples/async-probe.phpruns the ReactPHPinfocmpprobe on a loop that the example hands in.
php examples/detect.php
php examples/convert.php
php examples/degrade.php
php examples/standard-colors.php
php examples/probe-report.php
php examples/async-probe.php
Testing
composer install
vendor/bin/phpunit
The suite pins the detection ladder against its drift guards (LadderDriftTest, EnvUnificationTest), the palette tables against their parity tests (Ansi256TableParityTest, Ansi16TableParityTest), and the degrade output (DegradeTest, DegradeFidelityTest). ProbeTest, ProbeInfocmpTest and the AsyncProbe* files cover the probes, and LangParityTest checks the catalogs.
Troubleshooting and FAQ
Output is plain when the program is piped
That is the design. A stream with no TTY in front of it gets no color, so piping into a file stays safe to read. To keep color on a non-TTY stream, set CLICOLOR_FORCE=1. The force legs outrank the stream gate.
Color still appears with NO_COLOR set
CLICOLOR_FORCE and FORCE_COLOR outrank NO_COLOR. An exported force variable, from a shell alias or a CI image, can re-enable color for a user who set NO_COLOR. Unset the force variables, and check Probe::isNoColor() before you honor a force override.
A truecolor terminal reports Ansi256
Two legs cap the level. COLORTERM=yes is read as a 256-color promise, and a screen session caps the level at Ansi256. A tmux session does the same unless COLORTERM advertises truecolor. Set COLORTERM=truecolor where the terminal honors it, or let the phase-2 terminfo probe promote the rung when the entry advertises Tc or RGB.
An environment key is ignored
Env keys are matched case-exactly, so No_Color does not count as NO_COLOR. Windows reports its environment case-insensitively at the OS layer, so the same spelling can look set in a shell and still miss detection here. Use the exact spelling from the table.
Detection ignores the variables I did set
A non-empty $env array replaces the whole environment rather than overlaying it. Pass every key the check reads, or leave $env out so the process environment is used.
Upstream mapping
The port follows the concepts of charmbracelet/colorprofile: detect a profile from the environment, convert colors down to it, and wrap a writer so that output is downgraded to match. The mapping is behavioral. SugarCraft is developed as a native PHP project.
| Concept | SugarCraft | Notes |
|---|---|---|
| Profile detection from the environment | Palette::detect(), DetectionChain | One shared ladder, so every surface answers the same way. |
| Color profile levels | ColorProfile enum | Eight levels. The detection ladder emits five of them. |
| Color conversion | Color::convert(), Palette::toProfile() | One-way downsampling only. |
| Writer that downgrades output | ProfileWriter | Applies degrade() to everything written to a stream. |
| Perceptual distance (beyond detection) | DeltaE, NearestColor | Opt-in. Not needed for detection or degradation. |
Architecture
DetectionChain is the one precedence core, and Env resolves and sanitizes the environment for it. Palette is the instance over that chain. It adds the stream TTY gate, and it does the degrading and stripping. The static Probe layer answers the questions that do not need an instance. AsyncProbe runs infocmp on a ReactPHP loop with bounded children, and Probe\TerminalProbe produces the phased report. The color math is ColorMath (sRGB to Lab), with DeltaE for the metrics and NearestColor for the matcher. ProfileWriter wraps a stream for automatic degradation.
Changelog and versioning
The library is pre-1.0, so consume dev-master. The mutable StandardColors statics are deprecated in favor of all(), fromIndex() and catalog(), and the Profile name is a deprecated alias for ColorProfile. The deprecation window is set out in the README.
Related
- sugar-core supplies the
Clamphelper and the I18n catalog base that this library'sColorandLangbuild on.
Demos.
VHS-recorded GIFs of the four examples that have a tape: detect, standard-colors, convert and degrade. The probe-report and async-probe examples have no recording. Regenerated automatically on every push that touches the source.
Profile detection
Forced rungs print[TrueColor] -> "fancy" through [No TTY] -> "naughty!".
Standard colors
all() rows from 0 black #000000 to 15 brightWhite #ffffff, plus fromIndex() lookups.
Conversion
One hex, a different encoder per rung:\e[38;2;107;80;255m → \e[38;5;63m → \e[94m; No TTY strips.
Degrade
Same input written per rung:38;2 → 38;5 → 91; the Ascii row drops the color codes, and the No TTY row prints [Orange] [Teal] [Purple] with no escapes.