UI for Zipcoin Blue

baseUI.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. var _ = require('lodash');
  3. var MuteStream = require('mute-stream');
  4. var readline = require('readline');
  5. /**
  6. * Base interface class other can inherits from
  7. */
  8. var UI = module.exports = function (opt) {
  9. // Instantiate the Readline interface
  10. // @Note: Don't reassign if already present (allow test to override the Stream)
  11. if (!this.rl) {
  12. this.rl = readline.createInterface(setupReadlineOptions(opt));
  13. }
  14. this.rl.resume();
  15. this.onForceClose = this.onForceClose.bind(this);
  16. // Make sure new prompt start on a newline when closing
  17. process.on('exit', this.onForceClose);
  18. // Terminate process on SIGINT (which will call process.on('exit') in return)
  19. this.rl.on('SIGINT', this.onForceClose);
  20. };
  21. /**
  22. * Handle the ^C exit
  23. * @return {null}
  24. */
  25. UI.prototype.onForceClose = function () {
  26. this.close();
  27. process.kill(process.pid, 'SIGINT');
  28. console.log('');
  29. };
  30. /**
  31. * Close the interface and cleanup listeners
  32. */
  33. UI.prototype.close = function () {
  34. // Remove events listeners
  35. this.rl.removeListener('SIGINT', this.onForceClose);
  36. process.removeListener('exit', this.onForceClose);
  37. this.rl.output.unmute();
  38. if (this.activePrompt && typeof this.activePrompt.close === 'function') {
  39. this.activePrompt.close();
  40. }
  41. // Close the readline
  42. this.rl.output.end();
  43. this.rl.pause();
  44. this.rl.close();
  45. };
  46. function setupReadlineOptions(opt) {
  47. opt = opt || {};
  48. // Default `input` to stdin
  49. var input = opt.input || process.stdin;
  50. // Add mute capabilities to the output
  51. var ms = new MuteStream();
  52. ms.pipe(opt.output || process.stdout);
  53. var output = ms;
  54. return _.extend({
  55. terminal: true,
  56. input: input,
  57. output: output
  58. }, _.omit(opt, ['input', 'output']));
  59. }