datepicker.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. DatePicker = BlazeComponent.extendComponent({
  2. template() {
  3. return 'datepicker';
  4. },
  5. onCreated() {
  6. this.error = new ReactiveVar('');
  7. this.card = this.data();
  8. this.date = new ReactiveVar(moment.invalid());
  9. },
  10. onRendered() {
  11. const $picker = this.$('.js-datepicker')
  12. .datepicker({
  13. todayHighlight: true,
  14. todayBtn: 'linked',
  15. language: TAPi18n.getLanguage(),
  16. })
  17. .on(
  18. 'changeDate',
  19. function(evt) {
  20. this.find('#date').value = moment(evt.date).format('L');
  21. this.error.set('');
  22. const timeInput = this.find('#time');
  23. timeInput.focus();
  24. if (!timeInput.value) {
  25. const currentHour = evt.date.getHours();
  26. const defaultMoment = moment(
  27. currentHour > 0 ? evt.date : '1970-01-01 08:00:00',
  28. ); // default to 8:00 am local time
  29. timeInput.value = defaultMoment.format('LT');
  30. }
  31. }.bind(this),
  32. );
  33. if (this.date.get().isValid()) {
  34. $picker.datepicker('update', this.date.get().toDate());
  35. }
  36. },
  37. showDate() {
  38. if (this.date.get().isValid()) return this.date.get().format('L');
  39. return '';
  40. },
  41. showTime() {
  42. if (this.date.get().isValid()) return this.date.get().format('LT');
  43. return '';
  44. },
  45. dateFormat() {
  46. return moment.localeData().longDateFormat('L');
  47. },
  48. timeFormat() {
  49. return moment.localeData().longDateFormat('LT');
  50. },
  51. events() {
  52. return [
  53. {
  54. 'keyup .js-date-field'() {
  55. // parse for localized date format in strict mode
  56. const dateMoment = moment(this.find('#date').value, 'L', true);
  57. if (dateMoment.isValid()) {
  58. this.error.set('');
  59. this.$('.js-datepicker').datepicker('update', dateMoment.toDate());
  60. }
  61. },
  62. 'keyup .js-time-field'() {
  63. // parse for localized time format in strict mode
  64. const dateMoment = moment(this.find('#time').value, 'LT', true);
  65. if (dateMoment.isValid()) {
  66. this.error.set('');
  67. }
  68. },
  69. 'submit .edit-date'(evt) {
  70. evt.preventDefault();
  71. // if no time was given, init with 12:00
  72. const time =
  73. evt.target.time.value ||
  74. moment(new Date().setHours(12, 0, 0)).format('LT');
  75. const dateString = `${evt.target.date.value} ${time}`;
  76. const newDate = moment(dateString, 'L LT', true);
  77. if (newDate.isValid()) {
  78. this._storeDate(newDate.toDate());
  79. Popup.close();
  80. } else {
  81. this.error.set('invalid-date');
  82. evt.target.date.focus();
  83. }
  84. },
  85. 'click .js-delete-date'(evt) {
  86. evt.preventDefault();
  87. this._deleteDate();
  88. Popup.close();
  89. },
  90. },
  91. ];
  92. },
  93. });