Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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