terminal-styling
Version:
A npm package to add some styling to terminal output
73 lines (72 loc) • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.color = exports.Colors = void 0;
/**
* Color utility using hex codes for terminal ANSI escape sequences
*
* @export
* @class Colors
* @typedef {Colors}
*/
var Colors = /** @class */ (function () {
function Colors() {
var _this = this;
/**
* Generates a foreground color ANSI escape sequence from hex
*
* @param {string} hex
* @returns {string}
*/
this.foregroundColor = function (hex) {
var _a = _this.hexToRgb(hex), r = _a[0], g = _a[1], b = _a[2];
return "\u001B[38;2;" + r + ";" + g + ";" + b + "m";
};
/**
* Generates a background color ANSI escape sequence from hex
*
* @param {string} hex
* @returns {string}
*/
this.backgroundColor = function (hex) {
var _a = _this.hexToRgb(hex), r = _a[0], g = _a[1], b = _a[2];
return "\u001B[48;2;" + r + ";" + g + ";" + b + "m";
};
/**
* Resets all ANSI styles
*
* @returns {string}
*/
this.reset = function () {
return "\x1b[0m";
};
}
/**
* Converts a hex color string to an RGB tuple
*
* @private
* @param {string} hex
* @returns {[number, number, number]}
*/
Colors.prototype.hexToRgb = function (hex) {
var sanitized = hex.replace(/^#/, '');
if (sanitized.length !== 6)
throw new Error('Invalid hex color');
var r = parseInt(sanitized.slice(0, 2), 16);
var g = parseInt(sanitized.slice(2, 4), 16);
var b = parseInt(sanitized.slice(4, 6), 16);
return [r, g, b];
};
/**
* Checks if the terminal supports true color
*
* @returns {boolean}
*/
Colors.prototype.supportsTrueColor = function () {
var colorTerm = process.env.COLORTERM;
console.log(colorTerm);
return colorTerm === 'truecolor' || colorTerm === '24bit';
};
return Colors;
}());
exports.Colors = Colors;
exports.color = new Colors();