toColorizer
toColorizer(
input
):Colorizer
Normalize any ColorOrColorizer
into a Colorizer
function.
Behavior:
- If
input
is already a function, return it unchanged. - If
input
is a non-empty string:- Trim and split by whitespace into tokens.
- For each token:
- If it matches a built-in
styles
modifier, use that ANSI wrapper. * - Else if it matches
fgColors
, apply the corresponding foreground ANSI code. - Else if it matches
bgColors
, apply the corresponding background ANSI code. - Else if it starts with “#” (3- or 6-digit hex), convert to RGB and wrap.
- Else if it starts with “bg#”, treat as a background hex code.
- Unknown tokens are ignored.
- If it matches a built-in
- Compose all matched Colorizers in sequence.
- If no valid tokens are found (or string is empty), return an identity function.
- All wrappers no-op if
isColorSupported
is false (e.g. NO_COLOR or dumb terminal).
Parameters
Section titled “Parameters”A color/style specification string or a Colorizer function.
Returns
Section titled “Returns”A Colorizer that applies the requested ANSI styles to its input text. *
Examples
Section titled “Examples”// Simple named colorconst red = toColorizer('red');console.log(red('This text is red'));
// Multiple styles chained: bold, underline, yellow text on blue backgroundconst fancy = toColorizer('bold underline yellow bgBlue');console.log(fancy('Chained styles!'));
// Hex colorsconst tealBg = toColorizer('bg#008080');console.log(tealBg('Teal background'));
// Passing through an existing Colorizerconst green = (str: string) => `\u001b[32m${str}\u001b[39m`;const same = toColorizer(green);console.log(same('Already green'));