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