File size: 1,096 Bytes
7e3630c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import chalk from "chalk";
const rgbRegex = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;
const ansiRegex = /^ansi256\(\s?(\d+)\s?\)$/;
const isNamedColor = (color: string): color is keyof typeof chalk =>
color in chalk;
export default function bgColorize(str: string, color: string): string {
if (isNamedColor(color)) {
const methodName = `bg${color[0].toUpperCase() + color.slice(1)}` as
| keyof typeof chalk
| undefined;
if (methodName && methodName in chalk) {
return (chalk[methodName] as (s: string) => string)(str);
}
return str;
}
if (color.startsWith("#")) {
return chalk.bgHex(color)(str);
}
if (color.startsWith("ansi256")) {
const matches = ansiRegex.exec(color);
if (matches) {
return chalk.bgAnsi256(Number(matches[1]))(str);
}
return str;
}
if (color.startsWith("rgb")) {
const matches = rgbRegex.exec(color);
if (matches) {
return chalk.bgRgb(
Number(matches[1]),
Number(matches[2]),
Number(matches[3]),
)(str);
}
return str;
}
return str;
}
|