state.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const { define, width } = require('./utils');
  3. class State {
  4. constructor(prompt) {
  5. let options = prompt.options;
  6. define(this, '_prompt', prompt);
  7. this.type = prompt.type;
  8. this.name = prompt.name;
  9. this.message = '';
  10. this.header = '';
  11. this.footer = '';
  12. this.error = '';
  13. this.hint = '';
  14. this.input = '';
  15. this.cursor = 0;
  16. this.index = 0;
  17. this.lines = 0;
  18. this.tick = 0;
  19. this.prompt = '';
  20. this.buffer = '';
  21. this.width = width(options.stdout || process.stdout);
  22. Object.assign(this, options);
  23. this.name = this.name || this.message;
  24. this.message = this.message || this.name;
  25. this.symbols = prompt.symbols;
  26. this.styles = prompt.styles;
  27. this.required = new Set();
  28. this.cancelled = false;
  29. this.submitted = false;
  30. }
  31. clone() {
  32. let state = { ...this };
  33. state.status = this.status;
  34. state.buffer = Buffer.from(state.buffer);
  35. delete state.clone;
  36. return state;
  37. }
  38. set color(val) {
  39. this._color = val;
  40. }
  41. get color() {
  42. let styles = this.prompt.styles;
  43. if (this.cancelled) return styles.cancelled;
  44. if (this.submitted) return styles.submitted;
  45. let color = this._color || styles[this.status];
  46. return typeof color === 'function' ? color : styles.pending;
  47. }
  48. set loading(value) {
  49. this._loading = value;
  50. }
  51. get loading() {
  52. if (typeof this._loading === 'boolean') return this._loading;
  53. if (this.loadingChoices) return 'choices';
  54. return false;
  55. }
  56. get status() {
  57. if (this.cancelled) return 'cancelled';
  58. if (this.submitted) return 'submitted';
  59. return 'pending';
  60. }
  61. }
  62. module.exports = State;