UNPKG

2.04 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
9//var tty = require('tty')
10var codes = {}
11
12function isColorSupported() {
13 // support for child process
14 // if (!tty.isatty()) return false;
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
23function esc(code) {
24 return '\x1b[' + code + 'm'
25}
26
27function 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
38function createColorFunc(name) {
39 // exports here
40 exports[name] = function(text) {
41 return colorize(name, text)
42 }
43}
44
45var 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
54for (var name in styles) {
55 var code = styles[name]
56 codes[name] = [esc(code[0]), esc(code[1])]
57}
58
59var colors = [
60 'black', 'red', 'green', 'yellow', 'blue',
61 'magenta', 'cyan', 'white'
62]
63
64for (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
69codes['gray'] = codes['grey'] = [esc(90), esc(39)]
70codes['gray_bg'] = codes['grey_bg'] = [esc(40), esc(49)]
71
72for (var name in codes) {
73 // this is exports
74 createColorFunc(name)
75}
76
77exports.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
101Object.defineProperty(exports, 'isSupported', {
102 get: isColorSupported
103})