UNPKG

2.39 kBJavaScriptView Raw
1/*
2 * Color supports in terminal
3 * @author: Hsiaoming Yang <lepture@me.com>
4 *
5 * Thanks to: https://github.com/lepture/terminal
6 *
7 */
8
9var tty = require('tty');
10var os = require('os');
11var codes = {};
12
13exports.isatty = false;
14exports.disabled = false;
15
16function isColorSupported() {
17 if (exports.disabled) return false;
18
19 // you can force to tty
20 if (!exports.isatty && !tty.isatty()) return false;
21
22 if ('COLORTERM' in process.env) return true;
23 // windows will support color
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
34function esc(code) {
35 return '\x1b[' + code + 'm';
36}
37
38function 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
49var 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
58for (var name in styles) {
59 var code = styles[name];
60 codes[name] = [esc(code[0]), esc(code[1])];
61}
62
63var colors = [
64 'black', 'red', 'green', 'yellow', 'blue',
65 'magenta', 'cyan', 'white'
66];
67
68for (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
73codes.gray = codes.grey = [esc(90), esc(39)];
74codes.gray_bg = codes.grey_bg = [esc(40), esc(49)];
75
76function Color(obj) {
77 this.string = obj;
78 this.color = obj;
79}
80Color.prototype.valueOf = function() {
81 return this.color;
82};
83
84exports.color = {};
85Object.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});
97Object.defineProperty(Color.prototype, 'style', {
98 get: function() {
99 return this.color;
100 }
101});
102
103exports.paint = function(text) {
104 return new Color(text);
105};
106
107exports.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
115Object.defineProperty(exports, 'isSupported', {
116 get: isColorSupported
117});