index.js 5.6 KB

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