1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | var tty = require('tty');
|
10 | var os = require('os');
|
11 | var codes = {};
|
12 |
|
13 | exports.isatty = false;
|
14 | exports.disabled = false;
|
15 |
|
16 | function isColorSupported() {
|
17 | if (exports.disabled) return false;
|
18 |
|
19 |
|
20 | if (!exports.isatty && !tty.isatty()) return false;
|
21 |
|
22 | if ('COLORTERM' in process.env) return true;
|
23 |
|
24 | if (os.type() === 'Windows_NT') return true;
|
25 |
|
26 | var term = process.env.TERM;
|
27 | if (!term) return false;
|
28 |
|
29 | term = term.toLowerCase();
|
30 | if (term.indexOf('color') !== -1) return true;
|
31 | return term === 'xterm' || term === 'linux';
|
32 | }
|
33 |
|
34 | function esc(code) {
|
35 | return '\x1b[' + code + 'm';
|
36 | }
|
37 |
|
38 | function colorize(name, text) {
|
39 | if (!isColorSupported()) {
|
40 | return text;
|
41 | }
|
42 | var code = codes[name];
|
43 | if (!code) {
|
44 | return text;
|
45 | }
|
46 | return code[0] + text + code[1];
|
47 | }
|
48 |
|
49 | var styles = {
|
50 | bold: [1, 22],
|
51 | italic: [3, 23],
|
52 | underline: [4, 24],
|
53 | blink: [5, 25],
|
54 | inverse: [7, 27],
|
55 | strike: [9, 29]
|
56 | };
|
57 |
|
58 | for (var name in styles) {
|
59 | var code = styles[name];
|
60 | codes[name] = [esc(code[0]), esc(code[1])];
|
61 | }
|
62 |
|
63 | var colors = [
|
64 | 'black', 'red', 'green', 'yellow', 'blue',
|
65 | 'magenta', 'cyan', 'white'
|
66 | ];
|
67 |
|
68 | for (var i = 0; i < colors.length; i++) {
|
69 | codes[colors[i]] = [esc(i + 30), esc(39)];
|
70 | codes[colors[i] + '_bg'] = [esc(i + 40), esc(49)];
|
71 | }
|
72 |
|
73 | codes.gray = codes.grey = [esc(90), esc(39)];
|
74 | codes.gray_bg = codes.grey_bg = [esc(40), esc(49)];
|
75 |
|
76 | function Color(obj) {
|
77 | this.string = obj;
|
78 | this.color = obj;
|
79 | }
|
80 | Color.prototype.valueOf = function() {
|
81 | return this.color;
|
82 | };
|
83 |
|
84 | exports.color = {};
|
85 | Object.keys(codes).forEach(function(style) {
|
86 | Object.defineProperty(Color.prototype, style, {
|
87 | get: function() {
|
88 | this.color = colorize(style, this.color);
|
89 | return this;
|
90 | }
|
91 | });
|
92 |
|
93 | exports.color[style] = function(text) {
|
94 | return colorize(style, text);
|
95 | };
|
96 | });
|
97 | Object.defineProperty(Color.prototype, 'style', {
|
98 | get: function() {
|
99 | return this.color;
|
100 | }
|
101 | });
|
102 |
|
103 | exports.paint = function(text) {
|
104 | return new Color(text);
|
105 | };
|
106 |
|
107 | exports.colorful = function() {
|
108 | if (String.prototype.to) return;
|
109 |
|
110 | Object.defineProperty(String.prototype, 'to', {
|
111 | get: function() { return new Color(this.valueOf()); }
|
112 | });
|
113 | };
|
114 |
|
115 | Object.defineProperty(exports, 'isSupported', {
|
116 | get: isColorSupported
|
117 | });
|