index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const $ = { enabled:true };
  2. const CODES = {
  3. // modifiers
  4. reset: fmt(0, 0),
  5. bold: fmt(1, 22),
  6. dim: fmt(2, 22),
  7. italic: fmt(3, 23),
  8. underline: fmt(4, 24),
  9. inverse: fmt(7, 27),
  10. hidden: fmt(8, 28),
  11. strikethrough: fmt(9, 29),
  12. // colors
  13. black: fmt(30, 39),
  14. red: fmt(31, 39),
  15. green: fmt(32, 39),
  16. yellow: fmt(33, 39),
  17. blue: fmt(34, 39),
  18. magenta: fmt(35, 39),
  19. cyan: fmt(36, 39),
  20. white: fmt(37, 39),
  21. gray: fmt(90, 39),
  22. // background colors
  23. bgBlack: fmt(40, 49),
  24. bgRed: fmt(41, 49),
  25. bgGreen: fmt(42, 49),
  26. bgYellow: fmt(43, 49),
  27. bgBlue: fmt(44, 49),
  28. bgMagenta: fmt(45, 49),
  29. bgCyan: fmt(46, 49),
  30. bgWhite: fmt(47, 49)
  31. };
  32. function fmt(x, y) {
  33. return {
  34. open: `\x1b[${x}m`,
  35. close: `\x1b[${y}m`,
  36. rgx: new RegExp(`\\x1b\\[${y}m`, 'g')
  37. }
  38. }
  39. function run(key, str) {
  40. let tmp = CODES[key];
  41. return tmp.open + str.replace(tmp.rgx, tmp.open) + tmp.close;
  42. }
  43. function exec(key, str) {
  44. str += '';
  45. if (!$.enabled) return str;
  46. let arr = this.keys;
  47. while (arr.length > 0) {
  48. str = run(arr.shift(), str);
  49. }
  50. this.keys.push(key);
  51. return str;
  52. }
  53. function attach(key) {
  54. let ctx = { keys:[key] };
  55. let fn = exec.bind(ctx, key);
  56. for (let k in CODES) {
  57. Reflect.defineProperty(fn, k, {
  58. get() {
  59. ctx.keys.push(k);
  60. return fn;
  61. }
  62. });
  63. }
  64. return fn;
  65. }
  66. for (let k in CODES) {
  67. $[k] = attach(k);
  68. }
  69. module.exports = $;