npm-colors-utils
Version:
Simple color utils for working with colors!
75 lines (62 loc) • 2.22 kB
JavaScript
const check = require("./vcheck");
class c {
constructor(text = "", options = {}) {
this.text = text;
if(options.json != null) this.json = options.json;
}
getText() {
check()
test = this.text
final = []
test.split(" ").forEach(a =>final.push(a.replace("&r", "\x1b[0m").replace("&c", "\x1b[31m").replace("&b","\x1b[30m").replace("&a","\x1b[32m").replace("&m","\x1b[35m").replace("&x", "\x1b[36m").replace("&f","\x1b[37m")))
if(this.json) {
return {text:final.join(" ") + "\x1b[0m"}
}
return final.join(" ") + "\x1b[0m";
}
getRGB(rgb) {
check()
var get = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(rgb);
if(this.json) {
return {
r: parseInt(get[1], 16),
g: parseInt(get[2], 16),
b: parseInt(get[3], 16)
};
}
return `r: ${parseInt(get[1], 16)}, g: ${parseInt(get[2], 16)}, b: ${parseInt(get[3], 16)}`
}
getHEX(red, green ,blue, alpha){
check()
if(!red || !green || !blue) throw new Error("You must define colors .getHex('red, green, blue, (alpha)')")
const isPercent = (red + (alpha || '')).toString().includes('%');
if (typeof red === 'string') {
[red, green, blue, alpha] = red.match(/(0?\.?\d{1,3})%?\b/g).map(Number);
} else if (alpha !== undefined) {
alpha = parseFloat(alpha);
}
if (typeof red !== 'number' ||
typeof green !== 'number' ||
typeof blue !== 'number' ||
red > 255 ||
green > 255 ||
blue > 255
) {
throw new TypeError('Expected three numbers below 256');
}
if (typeof alpha === 'number') {
if (!isPercent && alpha >= 0 && alpha <= 1) {
alpha = Math.round(255 * alpha);
} else if (isPercent && alpha >= 0 && alpha <= 100) {
alpha = Math.round(255 * alpha / 100);
} else {
throw new TypeError(`Expected alpha value (${alpha}) as a fraction or percentage`);
}
alpha = (alpha | 1 << 8).toString(16).slice(1);
} else {
alpha = '';
}
return ((blue | green << 8 | red << 16) | 1 << 24).toString(16).slice(1) + alpha;
}
};
module.exports = c;