@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
The color to encode.
role
'fg' for foreground or 'bg' for background (selects the base code).
depth
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'); // → ''