-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
placeholder.js
66 lines (53 loc) · 1.92 KB
/
placeholder.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
/**
* This file is taken almost unchanged from enquirer, because it's not exported from the module
*/
const isPrimitive = val =>
val != null && typeof val !== `object` && typeof val !== `function`
/**
* Render a placeholder value with cursor and styling based on the
* position of the cursor.
*
* @param {Object} `prompt` Prompt instance.
* @param {String} `input` Input string.
* @param {String} `initial` The initial user-provided value.
* @param {Number} `pos` Current cursor position.
* @param {Boolean} `showCursor` Render a simulated cursor using the inverse primary style.
* @return {String} Returns the styled placeholder string.
* @api public
*/
module.exports = (prompt, options = {}) => {
prompt.cursorHide()
let { input = ``, initial = ``, pos, showCursor = true, color } = options
let style = color || prompt.styles.placeholder
let inverse = prompt.styles.primary.inverse
let blinker = str => inverse(str)
let output = input
let char = ` `
let reverse = blinker(char)
if (prompt.blink && prompt.blink.off === true) {
blinker = str => str
reverse = ``
}
if (showCursor && pos === 0 && initial === `` && input === ``) {
return blinker(char)
}
if (showCursor && pos === 0 && (input === initial || input === ``)) {
return blinker(initial[0]) + style(initial.slice(1))
}
initial = isPrimitive(initial) ? `${initial}` : ``
input = isPrimitive(input) ? `${input}` : ``
let placeholder = initial && initial.startsWith(input) && initial !== input
let cursor = placeholder ? blinker(initial[input.length]) : reverse
if (pos !== input.length && showCursor === true) {
output = input.slice(0, pos) + blinker(input[pos]) + input.slice(pos + 1)
cursor = ``
}
if (showCursor === false) {
cursor = ``
}
if (placeholder) {
let raw = prompt.styles.unstyle(output + cursor)
return output + cursor + style(initial.slice(raw.length))
}
return output + cursor
}