chalk/index.js

73 lines
1.7 KiB
JavaScript
Raw Normal View History

2013-08-03 02:16:26 +02:00
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
2014-06-04 01:43:07 +02:00
var ansiStyles = require('ansi-styles');
var stripAnsi = require('strip-ansi');
2014-06-24 21:34:11 +02:00
var hasAnsi = require('has-ansi');
2014-06-14 03:49:42 +02:00
var supportsColor = require('supports-color');
2013-08-03 02:16:26 +02:00
var defineProps = Object.defineProperties;
2013-12-13 19:36:43 +01:00
var chalk = module.exports;
2013-08-29 16:14:18 +02:00
2013-08-03 02:16:26 +02:00
var styles = (function () {
var ret = {};
2014-06-04 01:43:07 +02:00
ansiStyles.grey = ansiStyles.gray;
2013-12-13 19:36:43 +01:00
2014-06-04 01:43:07 +02:00
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
2013-08-03 02:16:26 +02:00
ret[key] = {
get: function () {
2013-08-03 18:47:47 +02:00
this._styles.push(key);
2013-08-03 02:16:26 +02:00
return this;
}
};
});
return ret;
})();
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var str = arguments.length === 1 ? arguments[0] + '' : [].slice.call(arguments).join(' ');
if (!chalk.enabled || !str) {
return str;
}
return applyStyle._styles.reduce(function (str, name) {
var code = ansiStyles[name];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
return code.open + str.replace(code.closeRe, code.open) + code.close;
}, str) ;
}
2013-08-03 02:16:26 +02:00
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
var style = defineProps(applyStyle, styles);
2013-08-03 02:16:26 +02:00
ret[name] = {
get: function () {
style._styles = [];
return style[name];
2013-08-03 02:16:26 +02:00
}
2013-12-16 19:25:01 +01:00
};
2013-08-03 02:16:26 +02:00
});
return ret;
}
2013-12-13 19:36:43 +01:00
defineProps(chalk, init());
2014-06-04 01:43:07 +02:00
chalk.styles = ansiStyles;
2014-06-24 21:34:11 +02:00
chalk.hasColor = hasAnsi;
chalk.stripColor = stripAnsi;
2014-06-14 03:49:42 +02:00
chalk.supportsColor = supportsColor;
2013-08-03 02:16:26 +02:00
// detect mode if not set manually
if (chalk.enabled === undefined) {
chalk.enabled = chalk.supportsColor;
}