UI for Zipcoin Blue

password.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /**
  2. * `password` type prompt
  3. */
  4. var util = require('util');
  5. var chalk = require('chalk');
  6. var Base = require('./base');
  7. var observe = require('../utils/events');
  8. function mask(input, maskChar) {
  9. input = String(input);
  10. maskChar = typeof maskChar === 'string' ? maskChar : '*';
  11. if (input.length === 0) {
  12. return '';
  13. }
  14. return new Array(input.length + 1).join(maskChar);
  15. }
  16. /**
  17. * Module exports
  18. */
  19. module.exports = Prompt;
  20. /**
  21. * Constructor
  22. */
  23. function Prompt() {
  24. return Base.apply(this, arguments);
  25. }
  26. util.inherits(Prompt, Base);
  27. /**
  28. * Start the Inquiry session
  29. * @param {Function} cb Callback when prompt is done
  30. * @return {this}
  31. */
  32. Prompt.prototype._run = function (cb) {
  33. this.done = cb;
  34. var events = observe(this.rl);
  35. // Once user confirm (enter key)
  36. var submit = events.line.map(this.filterInput.bind(this));
  37. var validation = this.handleSubmitEvents(submit);
  38. validation.success.forEach(this.onEnd.bind(this));
  39. validation.error.forEach(this.onError.bind(this));
  40. if (this.opt.mask) {
  41. events.keypress.takeUntil(validation.success).forEach(this.onKeypress.bind(this));
  42. }
  43. // Init
  44. this.render();
  45. return this;
  46. };
  47. /**
  48. * Render the prompt to screen
  49. * @return {Prompt} self
  50. */
  51. Prompt.prototype.render = function (error) {
  52. var message = this.getQuestion();
  53. var bottomContent = '';
  54. if (this.status === 'answered') {
  55. message += this.opt.mask ? chalk.cyan(mask(this.answer, this.opt.mask)) : chalk.italic.dim('[hidden]');
  56. } else if (this.opt.mask) {
  57. message += mask(this.rl.line || '', this.opt.mask);
  58. } else {
  59. message += chalk.italic.dim('[input is hidden] ');
  60. }
  61. if (error) {
  62. bottomContent = '\n' + chalk.red('>> ') + error;
  63. }
  64. this.screen.render(message, bottomContent);
  65. };
  66. /**
  67. * When user press `enter` key
  68. */
  69. Prompt.prototype.filterInput = function (input) {
  70. if (!input) {
  71. return this.opt.default == null ? '' : this.opt.default;
  72. }
  73. return input;
  74. };
  75. Prompt.prototype.onEnd = function (state) {
  76. this.status = 'answered';
  77. this.answer = state.value;
  78. // Re-render prompt
  79. this.render();
  80. this.screen.done();
  81. this.done(state.value);
  82. };
  83. Prompt.prototype.onError = function (state) {
  84. this.render(state.isValid);
  85. };
  86. Prompt.prototype.onKeypress = function () {
  87. this.render();
  88. };