index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict';
  2. var ESCAPES = [
  3. '\u001b',
  4. '\u009b'
  5. ];
  6. var END_CODE = 39;
  7. var ESCAPE_CODES = {
  8. 0: 0,
  9. 1: 22,
  10. 2: 22,
  11. 3: 23,
  12. 4: 24,
  13. 7: 27,
  14. 8: 28,
  15. 9: 29,
  16. 30: 39,
  17. 31: 39,
  18. 32: 39,
  19. 33: 39,
  20. 34: 39,
  21. 35: 39,
  22. 36: 39,
  23. 37: 39,
  24. 90: 39,
  25. 40: 49,
  26. 41: 49,
  27. 42: 49,
  28. 43: 49,
  29. 44: 49,
  30. 45: 49,
  31. 46: 49,
  32. 47: 49
  33. };
  34. function wrapAnsi(code) {
  35. return ESCAPES[0] + '[' + code + 'm';
  36. }
  37. module.exports = function (str, begin, end) {
  38. end = end || str.length;
  39. var insideEscape = false;
  40. var escapeCode;
  41. var visible = 0;
  42. var output = '';
  43. for (var i = 0; i < str.length; i++) {
  44. var leftEscape = false;
  45. var x = str[i];
  46. if (ESCAPES.indexOf(x) !== -1) {
  47. insideEscape = true;
  48. var code = /[0-9][^m]*/.exec(str.slice(i, i + 4));
  49. escapeCode = code === END_CODE ? null : code;
  50. } else if (insideEscape && x === 'm') {
  51. insideEscape = false;
  52. leftEscape = true;
  53. }
  54. if (!insideEscape && !leftEscape) {
  55. ++visible;
  56. }
  57. if (visible > begin && visible <= end) {
  58. output += x;
  59. } else if (visible === begin && escapeCode !== undefined && escapeCode !== END_CODE) {
  60. output += wrapAnsi(escapeCode);
  61. } else if (visible >= end) {
  62. if (escapeCode !== undefined) {
  63. output += wrapAnsi(ESCAPE_CODES[escapeCode] || END_CODE);
  64. }
  65. break;
  66. }
  67. }
  68. return output;
  69. };