index.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 insideEscape = 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. insideEscape = true;
  30. } else if (insideEscape && character === 'm') {
  31. insideEscape = false;
  32. continue;
  33. }
  34. if (insideEscape) {
  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
  65. // in either 'hard' or 'soft' wrap mode
  66. //
  67. // 'hard' will never allow a string to take up more
  68. // than columns characters
  69. //
  70. // 'soft' allows long words to expand past the column length
  71. const exec = (string, columns, options = {}) => {
  72. if (options.trim !== false && string.trim() === '') {
  73. return '';
  74. }
  75. let pre = '';
  76. let ret = '';
  77. let escapeCode;
  78. const lengths = wordLengths(string);
  79. let rows = [''];
  80. for (const [index, word] of string.split(' ').entries()) {
  81. if (options.trim !== false) {
  82. rows[rows.length - 1] = rows[rows.length - 1].trimLeft();
  83. }
  84. let rowLength = stringWidth(rows[rows.length - 1]);
  85. if (index !== 0) {
  86. if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
  87. // If we start with a new word but the current row length equals the length of the columns, add a new row
  88. rows.push('');
  89. rowLength = 0;
  90. }
  91. if (rowLength > 0 || options.trim === false) {
  92. rows[rows.length - 1] += ' ';
  93. rowLength++;
  94. }
  95. }
  96. // In 'hard' wrap mode, the length of a line is
  97. // never allowed to extend past 'columns'
  98. if (options.hard && lengths[index] > columns) {
  99. const remainingColumns = (columns - rowLength);
  100. const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
  101. const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
  102. if (breaksStartingNextLine < breaksStartingThisLine) {
  103. rows.push('');
  104. }
  105. wrapWord(rows, word, columns);
  106. continue;
  107. }
  108. if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
  109. if (options.wordWrap === false && rowLength < columns) {
  110. wrapWord(rows, word, columns);
  111. continue;
  112. }
  113. rows.push('');
  114. }
  115. if (rowLength + lengths[index] > columns && options.wordWrap === false) {
  116. wrapWord(rows, word, columns);
  117. continue;
  118. }
  119. rows[rows.length - 1] += word;
  120. }
  121. if (options.trim !== false) {
  122. rows = rows.map(stringVisibleTrimSpacesRight);
  123. }
  124. pre = rows.join('\n');
  125. for (const [index, character] of [...pre].entries()) {
  126. ret += character;
  127. if (ESCAPES.has(character)) {
  128. const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4)));
  129. escapeCode = code === END_CODE ? null : code;
  130. }
  131. const code = ansiStyles.codes.get(Number(escapeCode));
  132. if (escapeCode && code) {
  133. if (pre[index + 1] === '\n') {
  134. ret += wrapAnsi(code);
  135. } else if (character === '\n') {
  136. ret += wrapAnsi(escapeCode);
  137. }
  138. }
  139. }
  140. return ret;
  141. };
  142. // For each newline, invoke the method separately
  143. module.exports = (string, columns, options) => {
  144. return String(string)
  145. .normalize()
  146. .split('\n')
  147. .map(line => exec(line, columns, options))
  148. .join('\n');
  149. };