-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
99 lines (77 loc) · 1.93 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
/**
* `editor` type prompt
*/
var util = require('util');
var ExternalEditor = require('external-editor');
var Prompt = require('prompt-base');
var red = require('ansi-red');
var dim = require('ansi-dim');
/**
* Constructor
*/
function Editor(/*question, answers, rl*/) {
return Prompt.apply(this, arguments);
}
/**
* Inherit `Prompt`
*/
util.inherits(Editor, Prompt);
/**
* Start the prompt session
* @param {Function} `cb` Callback when prompt is finished
* @return {Object} Returns the `Editor` instance
*/
Editor.prototype.ask = function(cb) {
this.callback = cb;
this.ui.once('line', this.onSubmit.bind(this));
this.ui.on('keypress', this.render.bind(this, null));
this.on('error', this.onError.bind(this));
// Prevents default from being printed on terminal (can look weird with multiple lines)
this.currentText = this.question.default;
this.question.default = null;
this.render();
return this;
};
/**
* Render the prompt to terminal
*/
Editor.prototype.render = function(error) {
var append = '';
var message = this.message;
if (this.status === 'answered') {
message += dim('Received');
} else {
message += dim('Press <enter> to launch your preferred editor.');
}
if (error) {
append = red('>> ') + error;
}
this.ui.render(message, append);
};
/**
* Launch $EDITOR when the user presses `enter`
*/
Editor.prototype.startExternalEditor = function() {
this.currentText = ExternalEditor.edit(this.currentText);
return this.currentText;
};
/**
* When the answer is submitted (user presses `enter` key), re-render
* and pass answer to callback.
* @param {Object} `event`
*/
Editor.prototype.onSubmit = function(event) {
this.answer = this.startExternalEditor(event);
this.submitAnswer();
};
/**
* Handle error events
* @param {Object} `event`
*/
Editor.prototype.onError = function(event) {
this.render(event.isValid);
};
/**
* Module exports
*/
module.exports = Editor;