1 | const os = require('os');
|
2 | const wrapAnsi = require('wrap-ansi');
|
3 | const chalk = require('chalk');
|
4 |
|
5 | function getTerminalWidth() {
|
6 | return process.stdout.columns;
|
7 | }
|
8 |
|
9 | function wrap(str, width) {
|
10 | return wrapAnsi(str, width, { hard: true, trim: false });
|
11 | }
|
12 |
|
13 | function indentString(string, indentationLeft, indentationRight, screenWidth) {
|
14 | if (indentationLeft === undefined) indentationLeft = ' ';
|
15 |
|
16 | if (indentationRight === undefined) indentationRight = indentationLeft;
|
17 |
|
18 | if (screenWidth === Infinity) return indentationLeft + string + indentationRight;
|
19 |
|
20 | if (!screenWidth) screenWidth = getTerminalWidth();
|
21 |
|
22 | return string
|
23 | .split(os.EOL)
|
24 | .map(line =>
|
25 | wrap(line, screenWidth - indentationLeft.length - indentationRight.length)
|
26 | .split(os.EOL)
|
27 | .map(function(wrappedLine) {
|
28 | return indentationLeft + wrappedLine + indentationRight;
|
29 | })
|
30 | .join(os.EOL)
|
31 | )
|
32 | .join(os.EOL);
|
33 | }
|
34 |
|
35 | function fillString(stringLength, char) {
|
36 | return new Array(stringLength).join(char || ' ');
|
37 | }
|
38 |
|
39 | function padString(string, stringLength, char) {
|
40 | return (
|
41 | string +
|
42 | fillString(Math.max((stringLength || 0) - (string.length || 0) + 1, 0), char || ' ')
|
43 | );
|
44 | }
|
45 |
|
46 | function formatString(string, formatting) {
|
47 | if (!formatting) return string;
|
48 |
|
49 | return formatting.reduce((c, formattingOption) => c[formattingOption], chalk)(string);
|
50 | }
|
51 |
|
52 | function getLeftIndentationString(indentation, indentationLevel) {
|
53 | let str = '';
|
54 | for (let i = 0; i < indentationLevel; ++i) {
|
55 | str += indentation;
|
56 | }
|
57 | return str;
|
58 | }
|
59 |
|
60 | module.exports = {
|
61 | wrap: wrap,
|
62 | formatString: formatString,
|
63 | indentString: indentString,
|
64 | padString: padString,
|
65 | fillString: fillString,
|
66 | getLeftIndentationString: getLeftIndentationString,
|
67 | getTerminalWidth: getTerminalWidth
|
68 | };
|