UNPKG

constyle

Version:

A simple and performant console styling library for Node.js

62 lines (50 loc) 2.04 kB
const colorCodes = { black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90, bgBlack: 40, bgRed: 41, bgGreen: 42, bgYellow: 43, bgBlue: 44, bgMagenta: 45, bgCyan: 46, bgWhite: 47, bgGray: 100, bgGrey: 100, blackBright: 90, redBright: 91, greenBright: 92, yellowBright: 93, blueBright: 94, magentaBright: 95, cyanBright: 96, whiteBright: 97, bgBlackBright: 100, bgRedBright: 101, bgGreenBright: 102, bgYellowBright: 103, bgBlueBright: 104, bgMagentaBright: 105, bgCyanBright: 106, bgWhiteBright: 107, }; const styleCodes = { bold: 1, dim: 2, italic: 3, underline: 4, inverse: 7, hidden: 8, strikethrough: 9, }; class Style { constructor(options = {}) { this.options = options; this.openCodes = []; this.closeCodes = []; for (const key in this.options) { if (colorCodes[key]) { this.openCodes.push(`\x1b[${colorCodes[key]}m`); this.closeCodes.unshift(`\x1b[0m`); // Reset code } else if (styleCodes[key]) { this.openCodes.push(`\x1b[${styleCodes[key]}m`); this.closeCodes.unshift(`\x1b[${styleCodes[key] + 20}m`); // Corresponding close code } } } apply(text) { if (this.openCodes.length === 0) return text; return this.openCodes.join('') + text + this.closeCodes.join(''); } } const style = new Proxy({}, { get: (target, prop) => { if (target[prop]) return target[prop]; if (prop === 'reset') return (text) => `\x1b[0m${text}`; const styleInstance = new Style(); const styleProxy = new Proxy(styleInstance, { get: (targetStyle, styleProp) => { if (styleProp === 'apply') return targetStyle.apply.bind(targetStyle); const newOptions = {...targetStyle.options}; if (colorCodes[prop]) newOptions[prop] = true; else if (styleCodes[styleProp]) newOptions[styleProp] = true; return new Proxy(new Style(newOptions), this); } }); target[prop] = styleProxy; return styleProxy; }, }); module.exports = style;