-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
85 lines (73 loc) · 2.67 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
'use strict';
var ansi = require('ansi');
var util = require('util');
var chalk = require('chalk');
var ReadlineInterface = require('readline').Interface;
exports.createInterface = function (options) { return new Interface(options); };
exports.Interface = Interface;
util.inherits(Interface, ReadlineInterface);
function Interface(options) {
if (!(this instanceof Interface)) {
return new Interface(options);
}
this.suggest = (options && options.suggest) || function () {
return null;
};
this.colorize = (options && options.colorize) || function (str) {
return str;
};
this._ansiCursor = ansi(options && options.output);
ReadlineInterface.call(this, options);
}
Interface.prototype._originalWriteToOutput = ReadlineInterface.prototype._writeToOutput;
Interface.prototype._writeToOutput = function (stringToWrite) {
if (stringToWrite === '\r\n' || stringToWrite === ' ') {
this.output.write(stringToWrite);
return;
}
if (!stringToWrite) return;
var startsWithPrompt = stringToWrite.indexOf(this._prompt) === 0;
if (startsWithPrompt) {
this.output.write(this._prompt);
stringToWrite = stringToWrite.substring(this._prompt.length);
renderCurrentLine(this, stringToWrite, true);
} else {
this._originalWriteToOutput(stringToWrite);
}
};
Interface.prototype._insertString = function(c) {
if (this.cursor < this.line.length) {
var beg = this.line.slice(0, this.cursor);
var end = this.line.slice(this.cursor, this.line.length);
this.line = beg + c + end;
this.cursor += c.length;
this._refreshLine();
} else {
this.line += c;
this.cursor += c.length;
this._refreshLine();
this._moveCursor(0);
}
};
function renderCurrentLine(self, stringToWrite, showSuggestions) {
var suggestionPromise = showSuggestions ? self.suggest(stringToWrite) : null;
if (suggestionPromise && typeof suggestionPromise.then === 'function') {
suggestionPromise.then(afterSuggestion, function (err) {
process.nextTick(function () { throw err; });
});
} else {
afterSuggestion(suggestionPromise);
}
function afterSuggestion(suggestion) {
var promptLength = self._prompt.length;
var cursorPos = self._getCursorPos();
var nX = cursorPos.cols;
if (suggestion && suggestion.indexOf(stringToWrite) === 0) {
self._ansiCursor.horizontalAbsolute(promptLength + 1).eraseLine().write(self.colorize(stringToWrite) + chalk.grey(suggestion.substring(stringToWrite.length)));
self._ansiCursor.horizontalAbsolute(nX + 1);
} else {
self._ansiCursor.horizontalAbsolute(promptLength + 1).eraseLine().write(self.colorize(stringToWrite));
self._ansiCursor.horizontalAbsolute(nX);
}
}
}