index.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. 'use strict';
  2. const stringWidth = require('string-width');
  3. const stripAnsi = require('strip-ansi');
  4. const ansiStyles = require('ansi-styles');
  5. const ESCAPES = new Set([
  6. '\u001B',
  7. '\u009B'
  8. ]);
  9. const END_CODE = 39;
  10. const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`;
  11. // Calculate the length of words split on ' ', ignoring
  12. // the extra characters added by ansi escape codes
  13. const wordLengths = string => string.split(' ').map(character => stringWidth(character));
  14. // Wrap a long word across multiple rows
  15. // Ansi escape codes do not count towards length
  16. const wrapWord = (rows, word, columns) => {
  17. const characters = [...word];
  18. let isInsideEscape = false;
  19. let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
  20. for (const [index, character] of characters.entries()) {
  21. const characterLength = stringWidth(character);
  22. if (visible + characterLength <= columns) {
  23. rows[rows.length - 1] += character;
  24. } else {
  25. rows.push(character);
  26. visible = 0;
  27. }
  28. if (ESCAPES.has(character)) {
  29. isInsideEscape = true;
  30. } else if (isInsideEscape && character === 'm') {
  31. isInsideEscape = false;
  32. continue;
  33. }
  34. if (isInsideEscape) {
  35. continue;
  36. }
  37. visible += characterLength;
  38. if (visible === columns && index < characters.length - 1) {
  39. rows.push('');
  40. visible = 0;
  41. }
  42. }
  43. // It's possible that the last row we copy over is only
  44. // ansi escape characters, handle this edge-case
  45. if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
  46. rows[rows.length - 2] += rows.pop();
  47. }
  48. };
  49. // Trims spaces from a string ignoring invisible sequences
  50. const stringVisibleTrimSpacesRight = str => {
  51. const words = str.split(' ');
  52. let last = words.length;
  53. while (last > 0) {
  54. if (stringWidth(words[last - 1]) > 0) {
  55. break;
  56. }
  57. last--;
  58. }
  59. if (last === words.length) {
  60. return str;
  61. }
  62. return words.slice(0, last).join(' ') + words.slice(last).join('');
  63. };
  64. // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
  65. //
  66. // 'hard' will never allow a string to take up more than columns characters
  67. //
  68. // 'soft' allows long words to expand past the column length
  69. const exec = (string, columns, options = {}) => {
  70. if (options.trim !== false && string.trim() === '') {
  71. return '';
  72. }
  73. let pre = '';
  74. let ret = '';
  75. let escapeCode;
  76. const lengths = wordLengths(string);
  77. let rows = [''];
  78. for (const [index, word] of string.split(' ').entries()) {
  79. if (options.trim !== false) {
  80. rows[rows.length - 1] = rows[rows.length - 1].trimLeft();
  81. }
  82. let rowLength = stringWidth(rows[rows.length - 1]);
  83. if (index !== 0) {
  84. if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
  85. // If we start with a new word but the current row length equals the length of the columns, add a new row
  86. rows.push('');
  87. rowLength = 0;
  88. }
  89. if (rowLength > 0 || options.trim === false) {
  90. rows[rows.length - 1] += ' ';
  91. rowLength++;
  92. }
  93. }
  94. // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
  95. if (options.hard && lengths[index] > columns) {
  96. const remainingColumns = (columns - rowLength);
  97. const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
  98. const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
  99. if (breaksStartingNextLine < breaksStartingThisLine) {
  100. rows.push('');
  101. }
  102. wrapWord(rows, word, columns);
  103. continue;
  104. }
  105. if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
  106. if (options.wordWrap === false && rowLength < columns) {
  107. wrapWord(rows, word, columns);
  108. continue;
  109. }
  110. rows.push('');
  111. }
  112. if (rowLength + lengths[index] > columns && options.wordWrap === false) {
  113. wrapWord(rows, word, columns);
  114. continue;
  115. }
  116. rows[rows.length - 1] += word;
  117. }
  118. if (options.trim !== false) {
  119. rows = rows.map(stringVisibleTrimSpacesRight);
  120. }
  121. pre = rows.join('\n');
  122. for (const [index, character] of [...pre].entries()) {
  123. ret += character;
  124. if (ESCAPES.has(character)) {
  125. const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4)));
  126. escapeCode = code === END_CODE ? null : code;
  127. }
  128. const code = ansiStyles.codes.get(Number(escapeCode));
  129. if (escapeCode && code) {
  130. if (pre[index + 1] === '\n') {
  131. ret += wrapAnsi(code);
  132. } else if (character === '\n') {
  133. ret += wrapAnsi(escapeCode);
  134. }
  135. }
  136. }
  137. return ret;
  138. };
  139. // For each newline, invoke the method separately
  140. module.exports = (string, columns, options) => {
  141. return String(string)
  142. .normalize()
  143. .replace(/\r\n/g, '\n')
  144. .split('\n')
  145. .map(line => exec(line, columns, options))
  146. .join('\n');
  147. };