UNPKG

1.72 kBJavaScriptView Raw
1const os = require('os');
2const wrapAnsi = require('wrap-ansi');
3const chalk = require('chalk');
4
5function getTerminalWidth() {
6 return process.stdout.columns;
7}
8
9function wrap(str, width) {
10 return wrapAnsi(str, width, { hard: true, trim: false });
11}
12
13function 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
35function fillString(stringLength, char) {
36 return new Array(stringLength).join(char || ' ');
37}
38
39function padString(string, stringLength, char) {
40 return (
41 string +
42 fillString(Math.max((stringLength || 0) - (string.length || 0) + 1, 0), char || ' ')
43 );
44}
45
46function formatString(string, formatting) {
47 if (!formatting) return string;
48
49 return formatting.reduce((c, formattingOption) => c[formattingOption], chalk)(string);
50}
51
52function getLeftIndentationString(indentation, indentationLevel) {
53 let str = '';
54 for (let i = 0; i < indentationLevel; ++i) {
55 str += indentation;
56 }
57 return str;
58}
59
60module.exports = {
61 wrap: wrap,
62 formatString: formatString,
63 indentString: indentString,
64 padString: padString,
65 fillString: fillString,
66 getLeftIndentationString: getLeftIndentationString,
67 getTerminalWidth: getTerminalWidth
68};