Skip to content

toColorizer

toColorizer(input): Colorizer

Normalize any ColorOrColorizer into a Colorizer function.

Behavior:

  1. If input is already a function, return it unchanged.
  2. 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.
    • Compose all matched Colorizers in sequence.
  3. If no valid tokens are found (or string is empty), return an identity function.
  4. All wrappers no-op if isColorSupported is false (e.g. NO_COLOR or dumb terminal).

ColorOrColorizer

A color/style specification string or a Colorizer function.

Colorizer

A Colorizer that applies the requested ANSI styles to its input text. *

// Simple named color
const red = toColorizer('red');
console.log(red('This text is red'));
// Multiple styles chained: bold, underline, yellow text on blue background
const fancy = toColorizer('bold underline yellow bgBlue');
console.log(fancy('Chained styles!'));
// Hex colors
const tealBg = toColorizer('bg#008080');
console.log(tealBg('Teal background'));
// Passing through an existing Colorizer
const green = (str: string) => `\u001b[32m${str}\u001b[39m`;
const same = toColorizer(green);
console.log(same('Already green'));