Skip to content

@jsvision/core / encode

Function: encode() ​

encode(color, role, depth): string

Defined in: color/encode.ts:100

Encode ONE color to a standalone ANSI escape sequence for the given depth, downsampling automatically when the depth is lower than truecolor.

By depth: truecolor → 38;2;r;g;b / 48;2;r;g;b; 256 → 38;5;n / 48;5;n (nearest palette entry); 16 → 30–37 / 40–47 / 90–97 / 100–107 (nearest); 'default' and mono → '' (no sequence).

Parameters ​

color ​

Color

The color to encode.

role ​

ColorRole

'fg' for foreground or 'bg' for background (selects the base code).

depth ​

ColorDepth

The target color depth (typically caps.colorDepth).

Returns ​

string

The escape sequence, or '' when nothing needs emitting.

Throws ​

InvalidColorError when color is malformed. Use encodeStyle in a render loop, where malformed colors are swallowed instead.

Example ​

ts
import { encode } from '@jsvision/core';

encode('#ff0000', 'fg', 'truecolor');  // → '\x1b[38;2;255;0;0m'
encode('#ff0000', 'bg', '16');         // → '\x1b[101m'  (nearest bright red bg)
encode('default', 'fg', 'truecolor');  // → ''