Prompt.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. var _constants;
  6. function _load_constants() {
  7. return (_constants = require('../constants'));
  8. }
  9. /**
  10. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  11. *
  12. * This source code is licensed under the MIT license found in the
  13. * LICENSE file in the root directory of this source tree.
  14. *
  15. *
  16. */
  17. class Prompt {
  18. constructor() {
  19. this._onResize = this._onResize.bind(this);
  20. }
  21. _onResize() {
  22. this._onChange(this._value);
  23. }
  24. enter(onChange, onSuccess, onCancel) {
  25. this._entering = true;
  26. this._value = '';
  27. this._onSuccess = onSuccess;
  28. this._onCancel = onCancel;
  29. this._selection = null;
  30. this._offset = -1;
  31. this._promptLength = 0;
  32. this._onChange = () =>
  33. onChange(this._value, {
  34. max: 10,
  35. offset: this._offset
  36. });
  37. this._onChange();
  38. process.stdout.on('resize', this._onResize);
  39. }
  40. setPromptLength(length) {
  41. this._promptLength = length;
  42. }
  43. setPromptSelection(selected) {
  44. this._selection = selected;
  45. }
  46. put(key) {
  47. switch (key) {
  48. case (_constants || _load_constants()).KEYS.ENTER:
  49. this._entering = false;
  50. this._onSuccess(this._selection || this._value);
  51. this.abort();
  52. break;
  53. case (_constants || _load_constants()).KEYS.ESCAPE:
  54. this._entering = false;
  55. this._onCancel(this._value);
  56. this.abort();
  57. break;
  58. case (_constants || _load_constants()).KEYS.ARROW_DOWN:
  59. this._offset = Math.min(this._offset + 1, this._promptLength - 1);
  60. this._onChange();
  61. break;
  62. case (_constants || _load_constants()).KEYS.ARROW_UP:
  63. this._offset = Math.max(this._offset - 1, -1);
  64. this._onChange();
  65. break;
  66. case (_constants || _load_constants()).KEYS.ARROW_LEFT:
  67. case (_constants || _load_constants()).KEYS.ARROW_RIGHT:
  68. break;
  69. default:
  70. this._value =
  71. key === (_constants || _load_constants()).KEYS.BACKSPACE
  72. ? this._value.slice(0, -1)
  73. : this._value + key;
  74. this._offset = -1;
  75. this._selection = null;
  76. this._onChange();
  77. break;
  78. }
  79. }
  80. abort() {
  81. this._entering = false;
  82. this._value = '';
  83. process.stdout.removeListener('resize', this._onResize);
  84. }
  85. isEntering() {
  86. return this._entering;
  87. }
  88. }
  89. exports.default = Prompt;