-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (51 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';
var stringLength = require('string-length');
var ansiRegex = require('ansi-regex');
var longestLength = require('longest-length');
var trimLeft = require('trim-left');
var substrAnsi = require('substr-ansi');
module.exports = function (str, opts) {
var recursiveSpaceLeft = 0;
return (function wrap(str, opts) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
opts = opts || {};
var width = opts.width || 34;
var linebreak = '\n';
var ansi = ansiRegex().source;
var regex = new RegExp(ansi + '?|\\S+|\\s?', 'g');
var chunks = str.match(regex);
if (opts.autoWidth) {
var longest = longestLength(str);
if (longest > width) {
width = longest;
}
}
var spaceLeft = width;
var result = chunks.reduce(function (previous, current) {
if (current === '\n') {
spaceLeft = width;
return previous + current;
}
if (stringLength(current) > width) {
var overflowed = wrap(substrAnsi(current, spaceLeft), {width: width});
var partial = previous + substrAnsi(current, 0, spaceLeft) + linebreak + trimLeft(overflowed);
spaceLeft = recursiveSpaceLeft;
return partial;
}
if (stringLength(current) > spaceLeft) {
var trimmed = trimLeft(current);
if (stringLength(trimmed) === 0) {
return previous;
}
spaceLeft = width - stringLength(current);
return previous + linebreak + trimLeft(current);
}
spaceLeft -= stringLength(current);
return previous + current;
}, '');
recursiveSpaceLeft = spaceLeft;
return result;
})(str, opts);
};