date.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. 'use strict';
  2. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  3. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  4. const color = require('kleur');
  5. const Prompt = require('./prompt');
  6. const _require = require('../util'),
  7. style = _require.style,
  8. clear = _require.clear,
  9. figures = _require.figures;
  10. const _require2 = require('sisteransi'),
  11. erase = _require2.erase,
  12. cursor = _require2.cursor;
  13. const _require3 = require('../dateparts'),
  14. DatePart = _require3.DatePart,
  15. Meridiem = _require3.Meridiem,
  16. Day = _require3.Day,
  17. Hours = _require3.Hours,
  18. Milliseconds = _require3.Milliseconds,
  19. Minutes = _require3.Minutes,
  20. Month = _require3.Month,
  21. Seconds = _require3.Seconds,
  22. Year = _require3.Year;
  23. const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
  24. const regexGroups = {
  25. 1: ({
  26. token
  27. }) => token.replace(/\\(.)/g, '$1'),
  28. 2: opts => new Day(opts),
  29. // Day // TODO
  30. 3: opts => new Month(opts),
  31. // Month
  32. 4: opts => new Year(opts),
  33. // Year
  34. 5: opts => new Meridiem(opts),
  35. // AM/PM // TODO (special)
  36. 6: opts => new Hours(opts),
  37. // Hours
  38. 7: opts => new Minutes(opts),
  39. // Minutes
  40. 8: opts => new Seconds(opts),
  41. // Seconds
  42. 9: opts => new Milliseconds(opts) // Fractional seconds
  43. };
  44. const dfltLocales = {
  45. months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','),
  46. monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  47. weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  48. weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',')
  49. };
  50. /**
  51. * DatePrompt Base Element
  52. * @param {Object} opts Options
  53. * @param {String} opts.message Message
  54. * @param {Number} [opts.initial] Index of default value
  55. * @param {String} [opts.mask] The format mask
  56. * @param {object} [opts.locales] The date locales
  57. * @param {String} [opts.error] The error message shown on invalid value
  58. * @param {Function} [opts.validate] Function to validate the submitted value
  59. * @param {Stream} [opts.stdin] The Readable stream to listen to
  60. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  61. */
  62. class DatePrompt extends Prompt {
  63. constructor(opts = {}) {
  64. super(opts);
  65. this.msg = opts.message;
  66. this.cursor = 0;
  67. this.typed = '';
  68. this.locales = Object.assign(dfltLocales, opts.locales);
  69. this._date = opts.initial || new Date();
  70. this.errorMsg = opts.error || 'Please Enter A Valid Value';
  71. this.validator = opts.validate || (() => true);
  72. this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss';
  73. this.clear = clear('', this.out.columns);
  74. this.render();
  75. }
  76. get value() {
  77. return this.date;
  78. }
  79. get date() {
  80. return this._date;
  81. }
  82. set date(date) {
  83. if (date) this._date.setTime(date.getTime());
  84. }
  85. set mask(mask) {
  86. let result;
  87. this.parts = [];
  88. while (result = regex.exec(mask)) {
  89. let match = result.shift();
  90. let idx = result.findIndex(gr => gr != null);
  91. this.parts.push(idx in regexGroups ? regexGroups[idx]({
  92. token: result[idx] || match,
  93. date: this.date,
  94. parts: this.parts,
  95. locales: this.locales
  96. }) : result[idx] || match);
  97. }
  98. let parts = this.parts.reduce((arr, i) => {
  99. if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i);
  100. return arr;
  101. }, []);
  102. this.parts.splice(0);
  103. this.parts.push(...parts);
  104. this.reset();
  105. }
  106. moveCursor(n) {
  107. this.typed = '';
  108. this.cursor = n;
  109. this.fire();
  110. }
  111. reset() {
  112. this.moveCursor(this.parts.findIndex(p => p instanceof DatePart));
  113. this.fire();
  114. this.render();
  115. }
  116. exit() {
  117. this.abort();
  118. }
  119. abort() {
  120. this.done = this.aborted = true;
  121. this.error = false;
  122. this.fire();
  123. this.render();
  124. this.out.write('\n');
  125. this.close();
  126. }
  127. validate() {
  128. var _this = this;
  129. return _asyncToGenerator(function* () {
  130. let valid = yield _this.validator(_this.value);
  131. if (typeof valid === 'string') {
  132. _this.errorMsg = valid;
  133. valid = false;
  134. }
  135. _this.error = !valid;
  136. })();
  137. }
  138. submit() {
  139. var _this2 = this;
  140. return _asyncToGenerator(function* () {
  141. yield _this2.validate();
  142. if (_this2.error) {
  143. _this2.color = 'red';
  144. _this2.fire();
  145. _this2.render();
  146. return;
  147. }
  148. _this2.done = true;
  149. _this2.aborted = false;
  150. _this2.fire();
  151. _this2.render();
  152. _this2.out.write('\n');
  153. _this2.close();
  154. })();
  155. }
  156. up() {
  157. this.typed = '';
  158. this.parts[this.cursor].up();
  159. this.render();
  160. }
  161. down() {
  162. this.typed = '';
  163. this.parts[this.cursor].down();
  164. this.render();
  165. }
  166. left() {
  167. let prev = this.parts[this.cursor].prev();
  168. if (prev == null) return this.bell();
  169. this.moveCursor(this.parts.indexOf(prev));
  170. this.render();
  171. }
  172. right() {
  173. let next = this.parts[this.cursor].next();
  174. if (next == null) return this.bell();
  175. this.moveCursor(this.parts.indexOf(next));
  176. this.render();
  177. }
  178. next() {
  179. let next = this.parts[this.cursor].next();
  180. this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart));
  181. this.render();
  182. }
  183. _(c) {
  184. if (/\d/.test(c)) {
  185. this.typed += c;
  186. this.parts[this.cursor].setTo(this.typed);
  187. this.render();
  188. }
  189. }
  190. render() {
  191. if (this.closed) return;
  192. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  193. super.render(); // Print prompt
  194. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error
  195. if (this.error) {
  196. this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  197. }
  198. this.out.write(erase.line + cursor.to(0) + this.outputText);
  199. }
  200. }
  201. module.exports = DatePrompt;