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.
Install
composer require sugarcraft/sugar-colorprofile
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 iTerm/Apple_Terminal hints) 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");
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 that old color terminals set — read here as 24-bit), TERM_PROGRAM, WT_SESSION, GOOGLE_CLOUD_SHELL (any non-empty value declares the environment — even the string false), 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 result is a ColorProfile: TrueColor, Ansi256, Ansi240, Ansi, Ansi8, Fgbg, Ascii or NoTTY.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.
API
| 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 / resetForTesting() | Bounded ReactPHP infocmp child (queried TERM + fixed PATH only); every fallback settle answers from the detection chain — the only non-chain answer is the TrueColor promotion read from the child's terminfo output |
| Probe\TerminalProbe | run() / runProbe() → ProbeReport | 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 |
Demos.
VHS-recorded GIFs of every example shipped with the library. 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 → 97; the No TTY row prints [Orange] [Teal] [Purple] with no escapes.