date.js 5.5 KB

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