wakitsu
Version:
Hobby project for managing anime watch list on Kitsu through CLI
85 lines • 2.57 kB
JavaScript
import { Config } from '../config.js';
const _consoleColors = {
k: '\u001B[30m',
bk: '\u001B[90m',
bw: '\u001B[97m',
r: '\u001B[31m',
br: '\u001B[91m',
g: '\u001B[32m',
bg: '\u001B[92m',
y: '\u001B[33m',
by: '\u001B[93m',
b: '\u001B[34m',
bb: '\u001B[94m',
m: '\u001B[35m',
bm: '\u001B[95m',
c: '\u001B[36m',
bc: '\u001B[96m',
x: '\u001B[39m',
xbg: '\u001B[49m',
xx: '\u001B[0m',
ul: '\u001B[4m',
};
const _colorCodeMap = (function () {
const map = new Map();
for (const key in _consoleColors) {
const k = key;
map.set(k, _consoleColors[k]);
}
return map;
})();
export class PrinterColor {
static colorText(text) {
return replaceColorCodes(text, Config.get('useColor') ? undefined : '');
}
static stripColorCodes(text) {
return replaceColorCodes(text, '');
}
static addCustomColor(code, color) {
const [r, g, b] = toRGBFromHex(color);
if (code.length > 3) {
throw Error('color code must be between 1 and 3 characters long');
}
if (_colorCodeMap.has(code)) {
throw Error(`color code "${code}" already exists`);
}
_colorCodeMap.set(code, `\u001B[38;2;${r};${g};${b}m`);
}
}
function replaceColorCodes(text, replacement) {
const colorCodes = text.match(/;([a-z]){1,3};/g);
if (!colorCodes)
return text;
const invalidCodes = colorCodes.filter((c) => !_colorCodeMap.has(c.replaceAll(';', '')));
if (invalidCodes.length) {
throw Error(`invalid color code(s) "${invalidCodes}"`);
}
for (const [code, color] of _colorCodeMap) {
const colorCode = `;${code};`;
if (text.includes(colorCode)) {
text = text.replaceAll(colorCode, replacement ?? color);
}
}
return text;
}
function toRGBFromHex(hex) {
const hexMatcher = /^[0-9a-f]{6}|[0-9a-f]{3}$/gi;
if (!hexMatcher.test(hex)) {
throw Error('invalid hex color');
}
const fullHex = hex.length > 3 ? hex : [...hex].map((c) => c + c).join('');
const intFromHex = parseInt(fullHex, 16);
return [(intFromHex >> 16) & 0xff, (intFromHex >> 8) & 0xff, intFromHex & 0xff];
}
export function colorWord(str, word, color, defaultColor) {
return str
.split(' ')
.map((p) => {
if (p.toLowerCase().includes(word.toLowerCase())) {
return `;${color};${p};${defaultColor};`;
}
return p;
})
.join(' ');
}
//# sourceMappingURL=print-colors.js.map