Skip to content

Commit

Permalink
complete module logic
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Jul 9, 2018
1 parent a904163 commit 41e4696
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 2 deletions.
32 changes: 32 additions & 0 deletions codes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module.exports = {
// modifiers
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],

// colors
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],

// background colors
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
}
45 changes: 44 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,44 @@
module.exports = {}
const { format } = require('util');
const CODES = require('./codes');

const $ = { enabled:true };
const RGX = /\x1b\[[0-9]+m/ig;
const toANSI = x => `\x1b[${x}m`;

function print() {
let out = format.apply(null, arguments);
if (!$.enabled || out.trim().length == 0) return out;

let i=0, tmp, arr=this.keys, isMulti=!!~out.indexOf('\n');
for (; i < arr.length; i++) {
tmp = CODES[arr[i]]; // [x1, x2, rgx]
if (out.indexOf(tmp[0]) !== 0 || out.slice(-tmp[1].length) !== tmp[1]) {
out = tmp[0] + out.replace(tmp[2], tmp[0]) + tmp[1];
}
isMulti && (out = out.replace(/(\r?\n)/g, `${tmp[1]}$1${tmp[0]}`));
}

return out;
}

function wrap(keys) {
let fn = (...args) => print.apply(fn, args);
Object.setPrototypeOf(fn, $);
fn.keys = keys;
return fn;
}

for (let k in CODES) {
CODES[k] = CODES[k].map(toANSI).concat(new RegExp(`\\x1b\\[${CODES[k][1]}m`, 'g'));
Object.defineProperty($, k, {
get() {
return this.keys !== void 0 ? (this.keys.push(k),this) : wrap([k]);
}
});
}

$.clear = str => {
return str && typeof str === 'string' ? str.replace(RGX, '') : str;
}

module.exports = $;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
"url": "lukeed.com"
},
"engines": {
"node": ">=4"
"node": ">=6"
}
}

0 comments on commit 41e4696

Please sign in to comment.