This repository has been archived by the owner on Oct 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
116 lines (85 loc) · 2.1 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
'use strict'
const ui = require('cli-styles')
const esc = require('ansi-escapes')
const chalk = require('chalk')
const wrap = require('prompt-skeleton')
const isNumber = /[0-9]/
const NumberPrompt = {
reset: function () {
this.typed = ''
this.value = this.initialValue
this.emit()
this.render()
}
, abort: function () {
this.done = this.aborted = true
this.emit()
this.render()
this.out.write('\n')
this.close()
}
, submit: function () {
this.done = true
this.aborted = false
this.emit()
this.render()
this.out.write('\n')
this.close()
}
, up: function () {
this.typed = ''
if (this.value >= this.max) return this.bell()
this.value++
this.emit()
this.render()
}
, down: function () {
this.typed = ''
if (this.value <= this.min) return this.bell()
this.value--
this.emit()
this.render()
}
, _: function (n) {
if (!isNumber.test(n)) return this.bell()
const now = Date.now()
if ((now - this.lastHit) > 1000) this.typed = '' // 1s elapsed
this.typed += n
this.lastHit = now
this.value = Math.min(parseInt(this.typed), this.max)
if (this.value > this.max) this.value = this.max
if (this.value < this.min) this.value = this.min
this.emit()
this.render()
}
, render: function () {
let value = this.transform(this.value)
if (!this.done) value = chalk.cyan.underline(value)
this.out.write(esc.eraseLine + esc.cursorTo(0) + [
ui.symbol(this.done, this.aborted)
, chalk.bold(this.msg)
, ui.delimiter(this.done)
, value
].join(' '))
}
}
const defaults = {
msg: ''
, transform: ui.render()
, min: -Infinity
, max: Infinity
, value: 0
, typed: ''
, lastHit: 0
, done: false
, aborted: false
}
const numberPrompt = (msg, opt) => {
if ('string' !== typeof msg) throw new Error('Message must be string.')
if (Array.isArray(opt) || 'object' !== typeof opt) opt = {}
let p = Object.assign(Object.create(NumberPrompt), defaults, opt)
p.msg = msg
p.initialValue = p.value
return wrap(p)
}
module.exports = Object.assign(numberPrompt, {NumberPrompt})