1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', {
|
4 | value: true
|
5 | });
|
6 | exports.default = wrapAnsiString;
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function wrapAnsiString(string, terminalWidth) {
|
17 | if (terminalWidth === 0) {
|
18 |
|
19 | return string;
|
20 | }
|
21 |
|
22 | const ANSI_REGEXP = /[\u001b\u009b]\[\d{1,2}m/gu;
|
23 | const tokens = [];
|
24 | let lastIndex = 0;
|
25 | let match;
|
26 |
|
27 | while ((match = ANSI_REGEXP.exec(string))) {
|
28 | const ansi = match[0];
|
29 | const index = match['index'];
|
30 |
|
31 | if (index != lastIndex) {
|
32 | tokens.push(['string', string.slice(lastIndex, index)]);
|
33 | }
|
34 |
|
35 | tokens.push(['ansi', ansi]);
|
36 | lastIndex = index + ansi.length;
|
37 | }
|
38 |
|
39 | if (lastIndex != string.length - 1) {
|
40 | tokens.push(['string', string.slice(lastIndex, string.length)]);
|
41 | }
|
42 |
|
43 | let lastLineLength = 0;
|
44 | return tokens
|
45 | .reduce(
|
46 | (lines, [kind, token]) => {
|
47 | if (kind === 'string') {
|
48 | if (lastLineLength + token.length > terminalWidth) {
|
49 | while (token.length) {
|
50 | const chunk = token.slice(0, terminalWidth - lastLineLength);
|
51 | const remaining = token.slice(
|
52 | terminalWidth - lastLineLength,
|
53 | token.length
|
54 | );
|
55 | lines[lines.length - 1] += chunk;
|
56 | lastLineLength += chunk.length;
|
57 | token = remaining;
|
58 |
|
59 | if (token.length) {
|
60 | lines.push('');
|
61 | lastLineLength = 0;
|
62 | }
|
63 | }
|
64 | } else {
|
65 | lines[lines.length - 1] += token;
|
66 | lastLineLength += token.length;
|
67 | }
|
68 | } else {
|
69 | lines[lines.length - 1] += token;
|
70 | }
|
71 |
|
72 | return lines;
|
73 | },
|
74 | ['']
|
75 | )
|
76 | .join('\n');
|
77 | }
|