-
-
Notifications
You must be signed in to change notification settings - Fork 582
/
colorize.ts
72 lines (54 loc) 路 1.46 KB
/
colorize.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import chalk, {type ForegroundColorName, type BackgroundColorName} from 'chalk';
type ColorType = 'foreground' | 'background';
const rgbRegex = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;
const ansiRegex = /^ansi256\(\s?(\d+)\s?\)$/;
const isNamedColor = (color: string): color is ForegroundColorName => {
return color in chalk;
};
const colorize = (
str: string,
color: string | undefined,
type: ColorType,
): string => {
if (!color) {
return str;
}
if (isNamedColor(color)) {
if (type === 'foreground') {
return chalk[color](str);
}
const methodName = `bg${
color[0]!.toUpperCase() + color.slice(1)
}` as BackgroundColorName;
return chalk[methodName](str);
}
if (color.startsWith('#')) {
return type === 'foreground'
? chalk.hex(color)(str)
: chalk.bgHex(color)(str);
}
if (color.startsWith('ansi256')) {
const matches = ansiRegex.exec(color);
if (!matches) {
return str;
}
const value = Number(matches[1]);
return type === 'foreground'
? chalk.ansi256(value)(str)
: chalk.bgAnsi256(value)(str);
}
if (color.startsWith('rgb')) {
const matches = rgbRegex.exec(color);
if (!matches) {
return str;
}
const firstValue = Number(matches[1]);
const secondValue = Number(matches[2]);
const thirdValue = Number(matches[3]);
return type === 'foreground'
? chalk.rgb(firstValue, secondValue, thirdValue)(str)
: chalk.bgRgb(firstValue, secondValue, thirdValue)(str);
}
return str;
};
export default colorize;