All 42 libraries

SugarColorprofile

Terminal color profile detection and color degradation

inspired by charmbracelet/colorprofile colorterminaloutput

SugarColorprofile code coverage

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

Profile detectionOne canonical 14-step ladder every surface shares, override-first: 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.
Color degradationPalette::toProfile() / Color::convert() downsample a color to the 256-color cube and gray ramp or to the 16 ANSI slots.
String rewritingdegrade() 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.
StandardColorsThe 16 ANSI colors as 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.)
Perceptual distanceCIELAB conversion with ΔE*76 / ΔE*94 / CIEDE2000 (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:

PhaseSourceWhat it can set
1 — env ladderDetectionChain over Env::resolve()Any of the five detection-emittable levels: TrueColor / Ansi256 / Ansi / Ascii / NoTTY
2 — terminfoinfocmp -1 at a fixed absolute-path roster, never looked up on PATHPromotes an Ansi/Ansi256 rung to TrueColor on Tc/RGB; Sixel from terminfo capability names
3 — advertisedTERM_PROGRAM capability map (interactive streams only)Advertised TrueColor (WezTerm/vscode/Ghostty), ITerm2 (iTerm.app), Hyperlinks (Hyper)
4 — floorsSuppression and minimal-capability floorsHolds 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

Try the quickstart →

API

ClassMethodDescription
Palettestatic detect($stream = null, array $env = []): ColorProfileDetect the color profile for a stream
Palette__construct($stream = null, array $env = []) / profile() / withProfile(ColorProfile)Detected profile, or an explicit one
Paletteconvert(Color) / static toProfile(Color, ColorProfile)Downsample a color
Palettedegrade(string) / static stripAnsi(string)Rewrite or strip the escapes in a string
Palettedescribe() / comment()Plain-language capability announcement instead of painting escapes (accessibility-friendly)
Colorstatic parse('#rrggbb') / static fromHex(0xrrggbb) / new Color(r, g, b, a)Construct a color
ColortoHex() / toAnsi256Index() / toAnsi16Index() / toAnsiForeground() / toAnsi256Foreground() / toAnsi16Foreground()Encode a color
ColortoAnsiBackground() / toAnsi16Background() / toAnsi8Index() / static ansi16Sgr(int, bool) / static fromAnsi256Index(int)Background escapes, the 8-color index, SGR pairing and reverse decoding
Colorequals(Color) / perceivedBrightness() / isDark() / convert(ColorProfile)Compare, measure and downsample a color
ColorProfileTrueColor, Ansi256, Ansi240, Ansi, Ansi8, Fgbg, Ascii, NoTTY / label() / description() / maxColors() / degradedTo() / allowsColor()Enum of color profiles
ProfileWriterstatic wrap($stream, array $env = []) / write(string) / printf(format, ...)Stream that degrades color on write
StandardColorsall(), fromIndex(int), catalog()The 16 ANSI colors (non-mutating read API; the $black…$brightWhite statics are deprecated — see README)
DetectionChainstatic detect(array $env = []) → level() / source() / term() / allowsColor() / isForced() / toColorProfile(); static userOptedOut(array $env = []): boolThe shared 14-step env ladder every detector agrees on; on the TMUX/STY rung the inner TERM is the base — no re-anchoring happens
Probestatic colorProfile() / isNoColor() / isForceColor() / reducedMotion() / resetForTesting()Static env-probe layer + infocmp upgrade
Envstatic resolve(array $injected) / value(resolved, key) / sanitize(value)Env resolution (a non-empty injected map fully replaces the ambient env) + sanitized source strings
AsyncProbestatic 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\TerminalProberun() / runProbe() → ProbeReportPhased capability report (TrueColor/Color256/Color16/NoColor/BasicAscii + Sixel, KittyKeyboard, ITerm2, Hyperlinks; BracketedPaste/FocusEvents reserved) with per-capability sources
Probe\ProbeReporthas(Capability) / hasTrueColor() / hasColor256() / hasNoColor() / all() / allWithSource() / colorDescription() / toColorProfile()Per-capability verdicts with the source that set each one
ColorMathstatic toLab(int, int, int) / rgbToXyz / srgbToLinear / linearToXyz / xyzToLabsRGB → CIELAB conversion building blocks
ColorDistancebetween(Color, Color) / betweenLab(array, array): floatThe selected ΔE metric (Euclidean / Cie76 / Cie94 / Cie2000) applied to colors or Lab triples
DeltaEstatic cie76(array, array) / cie94(array, array) / cie2000(array, array): floatThe 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
PaletteIndexstatic 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.

Detecting the terminal profile, then the same sentence forced through each profile

Profile detection

Forced rungs print [TrueColor] -> "fancy" through [No TTY] -> "naughty!".
The sixteen-index ANSI color catalog printed with swatches

Standard colors

all() rows from 0 black #000000 to 15 brightWhite #ffffff, plus fromIndex() lookups.
One hex converted for each profile with its per-rung escape shown

Conversion

One hex, a different encoder per rung: \e[38;2;107;80;255m → \e[38;5;63m → \e[94m; No TTY strips.
One TrueColor string written through a ProfileWriter on each rung, escapes shrinking per row

Degrade

Same input written per rung: 38;2 → 38;5 → 91 → 97; the No TTY row prints [Orange] [Teal] [Purple] with no escapes.