Debian Codegraph @

cli-color/lib/sgr.js

raw
1 "use strict";
2
3 /* CSI - control sequence introducer */
4 /* SGR - set graphic rendition */
5
6 var assign = require("es5-ext/object/assign")
7 , includes = require("es5-ext/string/#/contains")
8 , forOwn = require("es5-ext/object/for-each")
9 , onlyKey = require("es5-ext/object/first-key")
10 , forEachRight = require("es5-ext/array/#/for-each-right")
11 , uniq = require("es5-ext/array/#/uniq.js");
12
13 var CSI = "\x1b[";
14
15 var sgr = function (code) { return CSI + code + "m"; };
16
17 sgr.CSI = CSI;
18
19 var mods = assign(
20 {
21 // Style
22 bold: { _bold: [1, 22] },
23 italic: { _italic: [3, 23] },
24 underline: { _underline: [4, 24] },
25 blink: { _blink: [5, 25] },
26 inverse: { _inverse: [7, 27] },
27 strike: { _strike: [9, 29] }
28
29 // Color
30 },
31 ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"].reduce(function (
32 obj,
33 color,
34 index
35 ) {
36 // foreground
37 obj[color] = { _fg: [30 + index, 39] };
38 obj[color + "Bright"] = { _fg: [90 + index, 39] };
39
40 // background
41 obj["bg" + color[0].toUpperCase() + color.slice(1)] = { _bg: [40 + index, 49] };
42 obj["bg" + color[0].toUpperCase() + color.slice(1) + "Bright"] = { _bg: [100 + index, 49] };
43
44 return obj;
45 }, {})
46 );
47
48 sgr.mods = mods;
49
50 sgr.openers = {};
51 sgr.closers = {};
52
53 forOwn(mods, function (mod) {
54 var modPair = mod[onlyKey(mod)];
55
56 sgr.openers[modPair[0]] = modPair;
57 sgr.closers[modPair[1]] = modPair;
58 });
59
60 sgr.openStyle = function (openedMods, code) { openedMods.push(sgr.openers[code]); };
61
62 sgr.closeStyle = function (openedMods, code) {
63 forEachRight.call(openedMods, function (modPair, index) {
64 if (modPair[1] === code) {
65 openedMods.splice(index, 1);
66 }
67 });
68 };
69
70 /* prepend openers */
71 sgr.prepend = function (currentMods) {
72 return currentMods.map(function (modPair) { return sgr(modPair[0]); });
73 };
74
75 /* complete non-closed openers with corresponding closers */
76 sgr.complete = function (openedMods, closerCodes) {
77 closerCodes.forEach(function (code) { sgr.closeStyle(openedMods, code); });
78
79 // mods must be closed from the last opened to first opened
80 openedMods = openedMods.reverse();
81
82 openedMods = openedMods.map(function (modPair) { return modPair[1]; });
83
84 // one closer can close many openers (31, 32 -> 39)
85 openedMods = uniq.call(openedMods);
86
87 return openedMods.map(sgr);
88 };
89
90 var hasCSI = function (str) { return includes.call(str, CSI); };
91
92 sgr.hasCSI = hasCSI;
93
94 var extractCode = function (csi) {
95 var code = csi.slice(2, -1);
96 code = Number(code);
97 return code;
98 };
99
100 sgr.extractCode = extractCode;
101
102 module.exports = sgr;