UNPKG

1.51 kBJavaScriptView Raw
1"use strict";
2
3const sprintf = require('nyks/string/format');
4const repeat = require('mout/string/repeat');
5const truncate = require('nyks/string/truncate');
6
7const CRLF = "\r\n";
8
9//const STR_PAD_LEFT = "left";
10const STR_PAD_RIGHT = "right";
11const STR_PAD_BOTH = "both";
12
13
14
15var pad = function(str, pad, mode, mask, pad_len) {
16
17 pad_len -= sprintf(mask, str).length;
18 var left = (mode == STR_PAD_BOTH) ? Math.floor(pad_len / 2) : 0;
19
20 return sprintf(mask,
21 repeat(pad, Math.max(left, 0)) + str + repeat(pad, Math.max(pad_len - left, 0)));
22};
23
24
25
26var box = function(/*[title, msg]*/) {
27 var args = [].slice.call(arguments);
28 var resp = "";
29
30 if(!args.length)
31 return resp;
32
33 var pad_len = 76;
34
35 if(typeof args[0] == "object") {
36 let opt = args.shift();
37 if(opt.cols)
38 pad_len = opt.cols;
39 }
40
41 for(let msg, a = 1; a < args.length; a += 2) {
42 msg = args[a];
43 if(typeof msg !== "string")
44 msg = JSON.stringify(msg, null, 2);
45
46 msg = msg.trim().replace(" ", " ").split(/\r?\n/);//use 4 tab indent
47 msg = msg.map(line => truncate(line, pad_len - 2));
48 args[a] = msg;
49 }
50
51
52 for(let a = 0; a < args.length; a += 2) {
53 resp += pad(" " + args[a] + " ", "═", STR_PAD_BOTH, a ? "╠%s╣" : "╔%s╗", pad_len) + CRLF;
54 args[a + 1].forEach(function(line) {
55 resp += pad(line, " ", STR_PAD_RIGHT, "║%s║", pad_len) + CRLF;
56 });
57 }
58 resp += pad('', "═", STR_PAD_BOTH, "╚%s╝", pad_len) + CRLF;
59
60 return resp;
61};
62
63
64module.exports = box;