Current Dev State

This commit is contained in:
Tim Lorsbach
2025-06-23 20:13:54 +02:00
parent b4f9bb277d
commit ded50edaa2
22617 changed files with 4345095 additions and 174 deletions

View File

@ -0,0 +1,175 @@
/**
* Base prompt implementation
* Should be extended by prompt types.
*/
var rx = require('rx-lite');
var _ = require('lodash');
var chalk = require('chalk');
var ansiRegex = require('ansi-regex');
var runAsync = require('run-async');
var Choices = require('../objects/choices');
var ScreenManager = require('../utils/screen-manager');
var Prompt = module.exports = function (question, rl, answers) {
// Setup instance defaults property
_.assign(this, {
answers: answers,
status : 'pending'
});
// Set defaults prompt options
this.opt = _.defaults(_.clone(question), {
validate: function () { return true; },
filter: function (val) { return val; },
when: function () { return true; }
});
// Check to make sure prompt requirements are there
if (!this.opt.message) {
this.throwParamError('message');
}
if (!this.opt.name) {
this.throwParamError('name');
}
// Normalize choices
if (Array.isArray(this.opt.choices)) {
this.opt.choices = new Choices(this.opt.choices, answers);
}
this.rl = rl;
this.screen = new ScreenManager(this.rl);
};
/**
* Start the Inquiry session and manage output value filtering
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype.run = function( cb ) {
this._run(function (value) {
this.filter(value, cb);
}.bind(this));
};
// default noop (this one should be overwritten in prompts)
Prompt.prototype._run = function (cb) { cb(); };
/**
* Throw an error telling a required parameter is missing
* @param {String} name Name of the missing param
* @return {Throw Error}
*/
Prompt.prototype.throwParamError = function (name) {
throw new Error('You must provide a `' + name + '` parameter');
};
/**
* Validate a given input
* @param {String} value Input string
* @param {Function} callback Pass `true` (if input is valid) or an error message as
* parameter.
* @return {null}
*/
Prompt.prototype.validate = function (input, cb) {
runAsync(this.opt.validate, cb, input);
};
/**
* Run the provided validation method each time a submit event occur.
* @param {Rx.Observable} submit - submit event flow
* @return {Object} Object containing two observables: `success` and `error`
*/
Prompt.prototype.handleSubmitEvents = function (submit) {
var self = this;
var validation = submit.flatMap(function (value) {
return rx.Observable.create(function (observer) {
runAsync(self.opt.validate, function (isValid) {
observer.onNext({ isValid: isValid, value: self.getCurrentValue(value) });
observer.onCompleted();
}, self.getCurrentValue(value), self.answers);
});
}).share();
var success = validation
.filter(function (state) { return state.isValid === true; })
.take(1);
var error = validation
.filter(function (state) { return state.isValid !== true; })
.takeUntil(success);
return {
success: success,
error: error
};
};
Prompt.prototype.getCurrentValue = function (value) {
return value;
};
/**
* Filter a given input before sending back
* @param {String} value Input string
* @param {Function} callback Pass the filtered input as parameter.
* @return {null}
*/
Prompt.prototype.filter = function (input, cb) {
runAsync(this.opt.filter, cb, input);
};
/**
* Return the prompt line prefix
* @param {String} [optionnal] String to concatenate to the prefix
* @return {String} prompt prefix
*/
Prompt.prototype.prefix = function (str) {
str || (str = '');
return chalk.green('?') + ' ' + str;
};
/**
* Return the prompt line suffix
* @param {String} [optionnal] String to concatenate to the suffix
* @return {String} prompt suffix
*/
var reStrEnd = new RegExp('(?:' + ansiRegex().source + ')$|$');
Prompt.prototype.suffix = function (str) {
str || (str = '');
// make sure we get the `:` inside the styles
if (str.length < 1 || /[a-z1-9]$/i.test(chalk.stripColor(str))) {
str = str.replace(reStrEnd, ':$&');
}
return str.trim() + ' ';
};
/**
* Generate the prompt question string
* @return {String} prompt question string
*/
Prompt.prototype.getQuestion = function () {
var message = chalk.green('?') + ' ' + chalk.bold(this.opt.message) + ' ';
// Append the default if available, and if question isn't answered
if ( this.opt.default != null && this.status !== 'answered' ) {
message += chalk.dim('('+ this.opt.default + ') ');
}
return message;
};

View File

@ -0,0 +1,213 @@
/**
* `list` type prompt
*/
var _ = require("lodash");
var util = require("util");
var chalk = require("chalk");
var cliCursor = require("cli-cursor");
var figures = require("figures");
var Base = require("./base");
var observe = require("../utils/events");
var Paginator = require("../utils/paginator");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
Base.apply( this, arguments );
if (!this.opt.choices) {
this.throwParamError("choices");
}
if ( _.isArray(this.opt.default) ) {
this.opt.choices.forEach(function( choice ) {
if ( this.opt.default.indexOf(choice.value) >= 0 ) {
choice.checked = true;
}
}, this);
}
this.firstRender = true;
this.pointer = 0;
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
this.paginator = new Paginator();
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
var events = observe(this.rl);
var validation = this.handleSubmitEvents( events.line );
validation.success.forEach( this.onEnd.bind(this) );
validation.error.forEach( this.onError.bind(this) );
events.normalizedUpKey.takeUntil( validation.success ).forEach( this.onUpKey.bind(this) );
events.normalizedDownKey.takeUntil( validation.success ).forEach( this.onDownKey.bind(this) );
events.numberKey.takeUntil( validation.success ).forEach( this.onNumberKey.bind(this) );
events.spaceKey.takeUntil( validation.success ).forEach( this.onSpaceKey.bind(this) );
// Init the prompt
cliCursor.hide();
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
// Render question
var message = this.getQuestion();
var bottomContent = '';
if ( this.firstRender ) {
message += "(Press <space> to select)";
}
// Render choices or answer depending on the state
if ( this.status === "answered" ) {
message += chalk.cyan( this.selection.join(", ") );
} else {
var choicesStr = renderChoices(this.opt.choices, this.pointer);
var indexPosition = this.opt.choices.indexOf(this.opt.choices.getChoice(this.pointer));
message += "\n" + this.paginator.paginate(choicesStr, indexPosition, this.opt.pageSize);
}
if (error) {
bottomContent = chalk.red('>> ') + error;
}
this.firstRender = false;
this.screen.render(message, bottomContent);
};
/**
* When user press `enter` key
*/
Prompt.prototype.onEnd = function( state ) {
this.status = "answered";
// Rerender prompt (and clean subline error)
this.render();
this.screen.done();
cliCursor.show();
this.done( state.value );
};
Prompt.prototype.onError = function ( state ) {
this.render(state.isValid);
};
Prompt.prototype.getCurrentValue = function () {
var choices = this.opt.choices.filter(function( choice ) {
return !!choice.checked && !choice.disabled;
});
this.selection = _.map(choices, "short");
return _.map(choices, "value");
};
Prompt.prototype.onUpKey = function() {
var len = this.opt.choices.realLength;
this.pointer = (this.pointer > 0) ? this.pointer - 1 : len - 1;
this.render();
};
Prompt.prototype.onDownKey = function() {
var len = this.opt.choices.realLength;
this.pointer = (this.pointer < len - 1) ? this.pointer + 1 : 0;
this.render();
};
Prompt.prototype.onNumberKey = function( input ) {
if ( input <= this.opt.choices.realLength ) {
this.pointer = input - 1;
this.toggleChoice( this.pointer );
}
this.render();
};
Prompt.prototype.onSpaceKey = function( input ) {
this.toggleChoice(this.pointer);
this.render();
};
Prompt.prototype.toggleChoice = function( index ) {
var checked = this.opt.choices.getChoice(index).checked;
this.opt.choices.getChoice(index).checked = !checked;
};
/**
* Function for rendering checkbox choices
* @param {Number} pointer Position of the pointer
* @return {String} Rendered content
*/
function renderChoices(choices, pointer) {
var output = '';
var separatorOffset = 0;
choices.forEach(function (choice, i) {
if (choice.type === 'separator') {
separatorOffset++;
output += ' ' + choice + '\n';
return;
}
if (choice.disabled) {
separatorOffset++;
output += ' - ' + choice.name;
output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
} else {
var isSelected = (i - separatorOffset === pointer);
output += isSelected ? chalk.cyan(figures.pointer) : ' ';
output += getCheckbox(choice.checked) + ' ' + choice.name;
}
output += '\n';
});
return output.replace(/\n$/, '');
}
/**
* Get the checkbox
* @param {Boolean} checked - add a X or not to the checkbox
* @return {String} Composited checkbox string
*/
function getCheckbox(checked) {
return checked ? chalk.green(figures.radioOn) : figures.radioOff;
}

View File

@ -0,0 +1,110 @@
/**
* `confirm` type prompt
*/
var _ = require("lodash");
var util = require("util");
var chalk = require("chalk");
var Base = require("./base");
var observe = require("../utils/events");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
Base.apply( this, arguments );
var rawDefault = true;
_.extend( this.opt, {
filter: function( input ) {
var value = rawDefault;
if ( input != null && input !== "" ) {
value = /^y(es)?/i.test(input);
}
return value;
}.bind(this)
});
if ( _.isBoolean(this.opt.default) ) {
rawDefault = this.opt.default;
}
this.opt.default = rawDefault ? "Y/n" : "y/N";
return this;
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
// Once user confirm (enter key)
var events = observe(this.rl);
events.keypress.takeUntil( events.line ).forEach( this.onKeypress.bind(this) );
events.line.take(1).forEach( this.onEnd.bind(this) );
// Init
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (answer) {
var message = this.getQuestion();
if (typeof answer === "boolean") {
message += chalk.cyan(answer ? "Yes" : "No");
} else {
message += this.rl.line;
}
this.screen.render(message);
return this;
};
/**
* When user press `enter` key
*/
Prompt.prototype.onEnd = function( input ) {
this.status = "answered";
var output = this.opt.filter( input );
this.render( output );
this.screen.done();
this.done( input ); // send "input" because the master class will refilter
};
/**
* When user press a key
*/
Prompt.prototype.onKeypress = function() {
this.render();
};

View File

@ -0,0 +1,255 @@
/**
* `rawlist` type prompt
*/
var _ = require("lodash");
var util = require("util");
var chalk = require("chalk");
var Base = require("./base");
var Separator = require("../objects/separator");
var observe = require("../utils/events");
var Paginator = require("../utils/paginator");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
Base.apply( this, arguments );
if ( !this.opt.choices ) {
this.throwParamError("choices");
}
this.validateChoices( this.opt.choices );
// Add the default `help` (/expand) option
this.opt.choices.push({
key : "h",
name : "Help, list all options",
value : "help"
});
// Setup the default string (capitalize the default key)
this.opt.default = this.generateChoicesString( this.opt.choices, this.opt.default );
this.paginator = new Paginator();
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
// Save user answer and update prompt to show selected option.
var events = observe(this.rl);
this.lineObs = events.line.forEach( this.onSubmit.bind(this) );
this.keypressObs = events.keypress.forEach( this.onKeypress.bind(this) );
// Init the prompt
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error, hint) {
var message = this.getQuestion();
var bottomContent = '';
if ( this.status === "answered" ) {
message += chalk.cyan( this.selected.short || this.selected.name );
} else if ( this.status === "expanded" ) {
var choicesStr = renderChoices(this.opt.choices, this.selectedKey);
message += this.paginator.paginate(choicesStr, this.selectedKey, this.opt.pageSize);
message += "\n Answer: ";
}
message += this.rl.line;
if (error) {
bottomContent = chalk.red('>> ') + error;
}
if (hint) {
bottomContent = chalk.cyan('>> ') + hint;
}
this.screen.render(message, bottomContent);
};
/**
* Generate the prompt choices string
* @return {String} Choices string
*/
Prompt.prototype.getChoices = function() {
var output = "";
this.opt.choices.forEach(function( choice, i ) {
output += "\n ";
if ( choice.type === "separator" ) {
output += " " + choice;
return;
}
var choiceStr = choice.key + ") " + choice.name;
if ( this.selectedKey === choice.key ) {
choiceStr = chalk.cyan( choiceStr );
}
output += choiceStr;
}.bind(this));
return output;
};
/**
* When user press `enter` key
*/
Prompt.prototype.onSubmit = function( input ) {
if ( input == null || input === "" ) {
input = this.rawDefault;
}
var selected = this.opt.choices.where({ key : input.toLowerCase().trim() })[0];
if ( selected != null && selected.key === "h" ) {
this.selectedKey = "";
this.status = "expanded";
this.render();
return;
}
if ( selected != null ) {
this.status = "answered";
this.selected = selected;
// Re-render prompt
this.render();
this.lineObs.dispose();
this.keypressObs.dispose();
this.screen.done();
this.done( this.selected.value );
return;
}
// Input is invalid
this.render("Please enter a valid command");
};
/**
* When user press a key
*/
Prompt.prototype.onKeypress = function( s, key ) {
this.selectedKey = this.rl.line.toLowerCase();
var selected = this.opt.choices.where({ key : this.selectedKey })[0];
if ( this.status === "expanded" ) {
this.render();
} else {
this.render(null, selected ? selected.name : null);
}
};
/**
* Validate the choices
* @param {Array} choices
*/
Prompt.prototype.validateChoices = function( choices ) {
var formatError;
var errors = [];
var keymap = {};
choices.filter(Separator.exclude).map(function( choice ) {
if ( !choice.key || choice.key.length !== 1 ) {
formatError = true;
}
if ( keymap[choice.key] ) {
errors.push(choice.key);
}
keymap[ choice.key ] = true;
choice.key = String( choice.key ).toLowerCase();
});
if ( formatError ) {
throw new Error("Format error: `key` param must be a single letter and is required.");
}
if ( keymap.h ) {
throw new Error("Reserved key error: `key` param cannot be `h` - this value is reserved.");
}
if ( errors.length ) {
throw new Error( "Duplicate key error: `key` param must be unique. Duplicates: " +
_.uniq(errors).join(", ") );
}
};
/**
* Generate a string out of the choices keys
* @param {Array} choices
* @param {Number} defaultIndex - the choice index to capitalize
* @return {String} The rendered choices key string
*/
Prompt.prototype.generateChoicesString = function( choices, defaultIndex ) {
var defIndex = 0;
if ( _.isNumber(defaultIndex) && this.opt.choices.getChoice(defaultIndex) ) {
defIndex = defaultIndex;
}
var defStr = this.opt.choices.pluck("key");
this.rawDefault = defStr[ defIndex ];
defStr[ defIndex ] = String( defStr[defIndex] ).toUpperCase();
return defStr.join("");
};
/**
* Function for rendering checkbox choices
* @param {String} pointer Selected key
* @return {String} Rendered content
*/
function renderChoices (choices, pointer) {
var output = '';
choices.forEach(function (choice, i) {
output += '\n ';
if (choice.type === 'separator') {
output += ' ' + choice;
return;
}
var choiceStr = choice.key + ') ' + choice.name;
if (pointer === choice.key) {
choiceStr = chalk.cyan(choiceStr);
}
output += choiceStr;
});
return output;
}

View File

@ -0,0 +1,111 @@
/**
* `input` type prompt
*/
var util = require("util");
var chalk = require("chalk");
var Base = require("./base");
var observe = require("../utils/events");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
return Base.apply( this, arguments );
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
// Once user confirm (enter key)
var events = observe(this.rl);
var submit = events.line.map( this.filterInput.bind(this) );
var validation = this.handleSubmitEvents( submit );
validation.success.forEach( this.onEnd.bind(this) );
validation.error.forEach( this.onError.bind(this) );
events.keypress.takeUntil( validation.success ).forEach( this.onKeypress.bind(this) );
// Init
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
var bottomContent = '';
var message = this.getQuestion();
if (this.status === 'answered') {
message += chalk.cyan(this.answer);
} else {
message += this.rl.line;
}
if (error) {
bottomContent = chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
};
/**
* When user press `enter` key
*/
Prompt.prototype.filterInput = function( input ) {
if ( !input ) {
return this.opt.default != null ? this.opt.default : "";
}
return input;
};
Prompt.prototype.onEnd = function( state ) {
this.filter( state.value, function( filteredValue ) {
this.answer = filteredValue;
this.status = "answered";
// Re-render prompt
this.render();
this.screen.done();
this.done( state.value );
}.bind(this));
};
Prompt.prototype.onError = function( state ) {
this.render(state.isValid);
};
/**
* When user press a key
*/
Prompt.prototype.onKeypress = function() {
this.render();
};

View File

@ -0,0 +1,172 @@
/**
* `list` type prompt
*/
var _ = require("lodash");
var util = require("util");
var chalk = require("chalk");
var figures = require("figures");
var cliCursor = require("cli-cursor");
var Base = require("./base");
var observe = require("../utils/events");
var Paginator = require("../utils/paginator");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
Base.apply( this, arguments );
if (!this.opt.choices) {
this.throwParamError("choices");
}
this.firstRender = true;
this.selected = 0;
var def = this.opt.default;
// Default being a Number
if ( _.isNumber(def) && def >= 0 && def < this.opt.choices.realLength ) {
this.selected = def;
}
// Default being a String
if ( _.isString(def) ) {
this.selected = this.opt.choices.pluck("value").indexOf( def );
}
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
this.paginator = new Paginator();
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
var events = observe(this.rl);
events.normalizedUpKey.takeUntil( events.line ).forEach( this.onUpKey.bind(this) );
events.normalizedDownKey.takeUntil( events.line ).forEach( this.onDownKey.bind(this) );
events.numberKey.takeUntil( events.line ).forEach( this.onNumberKey.bind(this) );
events.line.take(1).forEach( this.onSubmit.bind(this) );
// Init the prompt
cliCursor.hide();
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function() {
// Render question
var message = this.getQuestion();
if ( this.firstRender ) {
message += chalk.dim( "(Use arrow keys)" );
}
// Render choices or answer depending on the state
if ( this.status === "answered" ) {
message += chalk.cyan( this.opt.choices.getChoice(this.selected).short );
} else {
var choicesStr = listRender(this.opt.choices, this.selected );
var indexPosition = this.opt.choices.indexOf(this.opt.choices.getChoice(this.selected));
message += "\n" + this.paginator.paginate(choicesStr, indexPosition, this.opt.pageSize);
}
this.firstRender = false;
this.screen.render(message);
};
/**
* When user press `enter` key
*/
Prompt.prototype.onSubmit = function() {
var choice = this.opt.choices.getChoice( this.selected );
this.status = "answered";
// Rerender prompt
this.render();
this.screen.done();
cliCursor.show();
this.done( choice.value );
};
/**
* When user press a key
*/
Prompt.prototype.onUpKey = function() {
var len = this.opt.choices.realLength;
this.selected = (this.selected > 0) ? this.selected - 1 : len - 1;
this.render();
};
Prompt.prototype.onDownKey = function() {
var len = this.opt.choices.realLength;
this.selected = (this.selected < len - 1) ? this.selected + 1 : 0;
this.render();
};
Prompt.prototype.onNumberKey = function( input ) {
if ( input <= this.opt.choices.realLength ) {
this.selected = input - 1;
}
this.render();
};
/**
* Function for rendering list choices
* @param {Number} pointer Position of the pointer
* @return {String} Rendered content
*/
function listRender(choices, pointer) {
var output = '';
var separatorOffset = 0;
choices.forEach(function (choice, i) {
if (choice.type === 'separator') {
separatorOffset++;
output += ' ' + choice + '\n';
return;
}
var isSelected = (i - separatorOffset === pointer);
var line = (isSelected ? figures.pointer + ' ' : ' ') + choice.name;
if (isSelected) {
line = chalk.cyan(line);
}
output += line + ' \n';
});
return output.replace(/\n$/, '');
}

View File

@ -0,0 +1,118 @@
/**
* `password` type prompt
*/
var util = require("util");
var chalk = require("chalk");
var Base = require("./base");
var observe = require("../utils/events");
function mask(input) {
input = String(input);
if (input.length === 0) {
return '';
}
return new Array(input.length + 1).join('*');
}
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
return Base.apply( this, arguments );
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
var events = observe(this.rl);
// Once user confirm (enter key)
var submit = events.line.map( this.filterInput.bind(this) );
var validation = this.handleSubmitEvents( submit );
validation.success.forEach( this.onEnd.bind(this) );
validation.error.forEach( this.onError.bind(this) );
events.keypress.takeUntil( validation.success ).forEach( this.onKeypress.bind(this) );
// Init
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
var message = this.getQuestion();
var bottomContent = '';
if (this.status === 'answered') {
message += chalk.cyan(mask(this.answer));
} else {
message += mask(this.rl.line || '');
}
if (error) {
bottomContent = '\n' + chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
};
/**
* When user press `enter` key
*/
Prompt.prototype.filterInput = function( input ) {
if ( !input ) {
return this.opt.default != null ? this.opt.default : "";
}
return input;
};
Prompt.prototype.onEnd = function( state ) {
this.status = "answered";
this.answer = state.value;
// Re-render prompt
this.render();
this.screen.done();
this.done( state.value );
};
Prompt.prototype.onError = function( state ) {
this.render(state.isValid);
this.rl.output.unmute();
};
/**
* When user type
*/
Prompt.prototype.onKeypress = function() {
this.render();
};

View File

@ -0,0 +1,183 @@
/**
* `rawlist` type prompt
*/
var _ = require("lodash");
var util = require("util");
var chalk = require("chalk");
var Base = require("./base");
var Separator = require("../objects/separator");
var observe = require("../utils/events");
var Paginator = require("../utils/paginator");
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
Base.apply( this, arguments );
if (!this.opt.choices) {
this.throwParamError("choices");
}
this.opt.validChoices = this.opt.choices.filter(Separator.exclude);
this.selected = 0;
this.rawDefault = 0;
_.extend(this.opt, {
validate: function( index ) {
return this.opt.choices.getChoice( index ) != null;
}.bind(this)
});
var def = this.opt.default;
if ( _.isNumber(def) && def >= 0 && def < this.opt.choices.realLength ) {
this.selected = this.rawDefault = def;
}
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
this.paginator = new Paginator();
}
util.inherits( Prompt, Base );
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function( cb ) {
this.done = cb;
// Once user confirm (enter key)
var events = observe(this.rl);
var submit = events.line.map( this.filterInput.bind(this) );
var validation = this.handleSubmitEvents( submit );
validation.success.forEach( this.onEnd.bind(this) );
validation.error.forEach( this.onError.bind(this) );
events.keypress.takeUntil( validation.success ).forEach( this.onKeypress.bind(this) );
// Init the prompt
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
// Render question
var message = this.getQuestion();
var bottomContent = '';
if ( this.status === "answered" ) {
message += chalk.cyan(this.opt.choices.getChoice(this.selected).name);
} else {
var choicesStr = renderChoices(this.opt.choices, this.selected);
message += this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize);
message += "\n Answer: ";
}
message += this.rl.line;
if (error) {
bottomContent = '\n' + chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
};
/**
* When user press `enter` key
*/
Prompt.prototype.filterInput = function( input ) {
if ( input == null || input === "" ) {
return this.rawDefault;
} else {
return input - 1;
}
};
Prompt.prototype.onEnd = function( state ) {
this.status = "answered";
this.selected = state.value;
var selectedChoice = this.opt.choices.getChoice( this.selected );
// Re-render prompt
this.render();
this.screen.done();
this.done( selectedChoice.value );
};
Prompt.prototype.onError = function() {
this.render("Please enter a valid index");
};
/**
* When user press a key
*/
Prompt.prototype.onKeypress = function() {
var index = this.rl.line.length ? Number(this.rl.line) - 1 : 0;
if ( this.opt.choices.getChoice(index) ) {
this.selected = index;
} else {
this.selected = undefined;
}
this.render();
};
/**
* Function for rendering list choices
* @param {Number} pointer Position of the pointer
* @return {String} Rendered content
*/
function renderChoices(choices, pointer) {
var output = '';
var separatorOffset = 0;
choices.forEach(function (choice, i) {
output += '\n ';
if (choice.type === 'separator') {
separatorOffset++;
output += ' ' + choice;
return;
}
var index = i - separatorOffset;
var display = (index + 1) + ') ' + choice.name;
if (index === pointer) {
display = chalk.cyan( display );
}
output += display;
});
return output;
}