chalk-pipe
Version:
Create chalk style schemes with simpler style strings
56 lines (55 loc) • 1.69 kB
JavaScript
import chalk, { modifierNames, colorNames, } from 'chalk';
import { cssKeywords } from './styles.js';
import { normalizeHexColor } from './utils.js';
const isBuiltInStyle = (style) => {
return [...modifierNames, ...colorNames].includes(style);
};
const isBackground = (style) => {
return style.startsWith('bg');
};
const isHexColor = (style) => {
return /^#?[a-f\d]{3,8}$/i.test(style);
};
const isKeyword = (style) => {
return style in cssKeywords;
};
const chalkPipe = (stylePipe, customChalk) => {
// eslint-disable-next-line n/no-unsupported-features/es-syntax
let paint = customChalk ?? chalk;
if (!stylePipe || stylePipe.length === 0) {
return paint;
}
const styles = stylePipe.split('.');
for (let style of styles) {
let isBg = false;
// Built-in styles
if (isBuiltInStyle(style)) {
paint = paint[style];
continue;
}
// Background
if (isBackground(style)) {
style = style.slice(2);
style = style.slice(0, 1).toLowerCase() + style.slice(1);
isBg = true;
}
// Keyword
if (isKeyword(style)) {
paint = isBg
? paint.bgHex(cssKeywords[style])
: paint.hex(cssKeywords[style]);
continue;
}
// Hex
if (isHexColor(style)) {
style = normalizeHexColor(style);
paint = isBg ? paint.bgHex(style) : paint.hex(style);
continue;
}
}
return paint;
};
export { default as chalk } from 'chalk';
export * from 'chalk';
export { keywordNames } from './styles.js';
export default chalkPipe;