checkbox.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * checkbox.js - checkbox 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 Input = require('./input');
  11. /**
  12. * Checkbox
  13. */
  14. function Checkbox(options) {
  15. var self = this;
  16. if (!(this instanceof Node)) {
  17. return new Checkbox(options);
  18. }
  19. options = options || {};
  20. Input.call(this, options);
  21. this.text = options.content || options.text || '';
  22. this.checked = this.value = options.checked || false;
  23. this.on('keypress', function(ch, key) {
  24. if (key.name === 'enter' || key.name === 'space') {
  25. self.toggle();
  26. self.screen.render();
  27. }
  28. });
  29. if (options.mouse) {
  30. this.on('click', function() {
  31. self.toggle();
  32. self.screen.render();
  33. });
  34. }
  35. this.on('focus', function() {
  36. var lpos = self.lpos;
  37. if (!lpos) return;
  38. self.screen.program.lsaveCursor('checkbox');
  39. self.screen.program.cup(lpos.yi, lpos.xi + 1);
  40. self.screen.program.showCursor();
  41. });
  42. this.on('blur', function() {
  43. self.screen.program.lrestoreCursor('checkbox', true);
  44. });
  45. }
  46. Checkbox.prototype.__proto__ = Input.prototype;
  47. Checkbox.prototype.type = 'checkbox';
  48. Checkbox.prototype.render = function() {
  49. this.clearPos(true);
  50. this.setContent('[' + (this.checked ? 'x' : ' ') + '] ' + this.text, true);
  51. return this._render();
  52. };
  53. Checkbox.prototype.check = function() {
  54. if (this.checked) return;
  55. this.checked = this.value = true;
  56. this.emit('check');
  57. };
  58. Checkbox.prototype.uncheck = function() {
  59. if (!this.checked) return;
  60. this.checked = this.value = false;
  61. this.emit('uncheck');
  62. };
  63. Checkbox.prototype.toggle = function() {
  64. return this.checked
  65. ? this.uncheck()
  66. : this.check();
  67. };
  68. /**
  69. * Expose
  70. */
  71. module.exports = Checkbox;