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 3
/
index.js
123 lines (92 loc) · 2.23 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
117
118
119
120
121
122
123
'use strict'
const ui = require('cli-styles')
const esc = require('ansi-escapes')
const chalk = require('chalk')
const wrap = require('prompt-skeleton')
const TextPrompt = {
setValue: function (v) {
this.value = v
this.rendered = this.transform(v)
this.cursor = Math.min(this.rendered.length, this.cursor)
this.emit()
}
, reset: function () {
this.setValue(this.initialValue)
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()
}
, _: function (c) {
this.setValue(this.value + c)
this.cursor = this.rendered.length
this.render()
}
, delete: function () {
if (this.value.length === 0) return this.bell()
this.setValue(this.value.slice(0, -1))
this.render()
}
, first: function () {
this.cursor = 0
this.render()
}
, last: function () {
this.cursor = this.rendered.length
this.render()
}
, left: function () {
if (this.cursor <= 0) return this.bell()
this.cursor--
this.render()
}
, right: function () {
if (this.cursor >= this.rendered.length) return this.bell()
this.cursor++
this.render()
}
, render: function () {
const prompt = [
ui.symbol(this.done, this.aborted)
, chalk.bold(this.msg)
, ui.delimiter(this.done)
, this.rendered
].join(' ')
this.out.write(this.clear + prompt)
this.out.write(esc.cursorMove(-this.rendered.length + this.cursor))
this.clear = ui.clear(prompt)
}
}
const defaults = {
value: ''
, rendered: ''
, transform: ui.render()
, clear: ui.clear('')
, msg: ''
, cursor: 0
, done: false
, aborted: false
}
const textPrompt = (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(TextPrompt), defaults, opt)
p.msg = msg
p.initialValue = p.value
p.rendered = p.transform(p.value)
if (!('cursor' in opt)) p.cursor = p.rendered.length
return wrap(p)
}
module.exports = Object.assign(textPrompt, {TextPrompt})