question.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /**
  2. * question.js - question element for blessed
  3. * Copyright (c) 2013-2015, Christopher Jeffrey and contributors (MIT License).
  4. * https://github.com/chjj/blessed
  5. */
  6. /**
  7. * Modules
  8. */
  9. var Node = require('./node');
  10. var Box = require('./box');
  11. var Button = require('./button');
  12. /**
  13. * Question
  14. */
  15. function Question(options) {
  16. if (!(this instanceof Node)) {
  17. return new Question(options);
  18. }
  19. options = options || {};
  20. options.hidden = true;
  21. Box.call(this, options);
  22. this._.okay = new Button({
  23. screen: this.screen,
  24. parent: this,
  25. top: 2,
  26. height: 1,
  27. left: 2,
  28. width: 6,
  29. content: 'Okay',
  30. align: 'center',
  31. bg: 'black',
  32. hoverBg: 'blue',
  33. autoFocus: false,
  34. mouse: true
  35. });
  36. this._.cancel = new Button({
  37. screen: this.screen,
  38. parent: this,
  39. top: 2,
  40. height: 1,
  41. shrink: true,
  42. left: 10,
  43. width: 8,
  44. content: 'Cancel',
  45. align: 'center',
  46. bg: 'black',
  47. hoverBg: 'blue',
  48. autoFocus: false,
  49. mouse: true
  50. });
  51. }
  52. Question.prototype.__proto__ = Box.prototype;
  53. Question.prototype.type = 'question';
  54. Question.prototype.ask = function(text, callback) {
  55. var self = this;
  56. var press, okay, cancel;
  57. // Keep above:
  58. // var parent = this.parent;
  59. // this.detach();
  60. // parent.append(this);
  61. this.show();
  62. this.setContent(' ' + text);
  63. this.onScreenEvent('keypress', press = function(ch, key) {
  64. if (key.name === 'mouse') return;
  65. if (key.name !== 'enter'
  66. && key.name !== 'escape'
  67. && key.name !== 'q'
  68. && key.name !== 'y'
  69. && key.name !== 'n') {
  70. return;
  71. }
  72. done(null, key.name === 'enter' || key.name === 'y');
  73. });
  74. this._.okay.on('press', okay = function() {
  75. done(null, true);
  76. });
  77. this._.cancel.on('press', cancel = function() {
  78. done(null, false);
  79. });
  80. this.screen.saveFocus();
  81. this.focus();
  82. function done(err, data) {
  83. self.hide();
  84. self.screen.restoreFocus();
  85. self.removeScreenEvent('keypress', press);
  86. self._.okay.removeListener('press', okay);
  87. self._.cancel.removeListener('press', cancel);
  88. return callback(err, data);
  89. }
  90. this.screen.render();
  91. };
  92. /**
  93. * Expose
  94. */
  95. module.exports = Question;