This repository has been archived by the owner on Jan 23, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.js
94 lines (77 loc) · 1.97 KB
/
util.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const dateFormat = require('dateformat')
// TODO: This code is copied from cabal
// https://github.com/cabal-club/cabal/blob/master/util.js
// Character-wrap text containing ANSI escape codes.
// String, Int -> [String]
function wrapAnsi (text, width) {
if (!text) return []
var res = []
var line = []
var lineLen = 0
var insideCode = false
for (var i = 0; i < text.length; i++) {
var chr = text.charAt(i)
if (chr === '\u001b') {
insideCode = true
}
line.push(chr)
if (!insideCode) {
lineLen++
if (lineLen >= width - 1) {
res.push(line.join(''))
line = []
lineLen = 0
}
}
if (chr === 'm' && insideCode) {
insideCode = false
}
}
if (line.length > 0) {
res.push(line.join(''))
}
return res
}
// Length of 'str' sans ANSI codes
function strlenAnsi (str) {
var len = 0
var insideCode = false
for (var i = 0; i < str.length; i++) {
var chr = str.charAt(i)
if (chr === '\u001b') insideCode = true
if (!insideCode) len++
if (chr === 'm' && insideCode) insideCode = false
}
return len
}
function centerText (text, width) {
var left = Math.floor((width - strlenAnsi(text)) / 2)
var right = Math.ceil((width - strlenAnsi(text)) / 2)
var lspace = left > 0 ? new Array(left).fill(' ').join('') : ''
var rspace = right > 0 ? new Array(right).fill(' ').join('') : ''
return lspace + text + rspace
}
function rightAlignText (text, width) {
var left = width - strlenAnsi(text)
if (left < 0) return text
var lspace = new Array(left).fill(' ').join('')
return lspace + text
}
function leftAlignText (text, width) {
var right = width - strlenAnsi(text)
if (right < 0) return text
var rspace = new Array(right).fill(' ').join('')
return text + rspace
}
function dateTime (now) {
now = now || Date.now()
return dateFormat(now, 'yy/mm/dd hh:MM')
}
module.exports = {
wrapAnsi,
strlenAnsi,
centerText,
rightAlignText,
leftAlignText,
dateTime
}