All files / src/plugins TempusDominusDatePicker.vue.js

94.23% Statements 49/52
65.62% Branches 21/32
100% Functions 14/14
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196                    1x     1x   1x   1x   1x   1x     1x                             1x                       10x           12x                                       12x                           8x                     2x 2x             12x   12x     12x 12x   12x     12x   12x 2x     12x   12x   12x 1x     12x   12x     12x 12x 12x   12x 12x 12x               20x 20x                     8x 1x   7x 7x 7x 1x                 12x 12x 12x   12x   60x 13x              
// @ts-check
import $ from "jquery";
import moment from "moment";
import { forEach, isNil } from "lodash";
import { genId } from "../utils";
import Vue from "vue";
 
/**
 * @type {Promise<void>}
 */
const initTempusDominus = (async function() {
  // karma loads test files asynchronuously, and we're in an async function,
  // let's be cautious
  Eif (!("jQuery" in window)) {
    // @ts-ignore of course doesn't exist. we are creating it.
    window.jQuery = $;
  }
  Eif (!("moment" in window)) {
    // @ts-ignore of course doesn't exist. we are creating it.
    window.moment = moment;
  }
  await import("tempusdominus-bootstrap");
  // Override Font Awesome icons on the widget
  // @ts-ignore window.jQuery exist now.
  $.extend(true, window.jQuery.fn.datetimepicker.Constructor.Default, {
    icons: {
      time: "fa fa-clock",
      today: "fa fa-calendar-check"
    }
  });
}());
 
/**
 * We are using 'tempusdominus-bootstrap' instead of the original
 * 'tempusdominus-bootstrap-4' because the last one is not maintained
 * since more than 2 years. Instead the fork is maintained and fixed by
 * the community.
 */
 
const component = /** @type {V.Constructor<any, any>} */(Vue).extend({
  name: "TempusDominusDatePicker",
  props: {
    value: {
      default: null,
      type: Number,
      /**
       * At the moment it accepts only unix timestamp.
       * We can improve in order to accept also formatted data strings,
       * Date objects and moment objects
       */
      validator(value) {
        return value === null || typeof value === "number";
      }
    },
    // https://tempusdominus.github.io/bootstrap-4/Options/
    config: {
      type: Object,
      default: () => ({
        format: "YYYY-MM-DD HH:mm:ss ZZ",
        buttons: {
          showToday: true,
          showClear: true,
          showClose: false
        },
        keepInvalid: false,
        useCurrent: false
      })
    }
  },
  /**
   * @returns {{
   *   id: string,
   *   dp: any | null,
   *   elem: JQuery<HTMLElement> | null
   * }}
   */
  data() {
    return {
      id: genId(),
      // Tempus Dominus data control
      dp: null,
      // Jquery element
      elem: null
    };
  },
  watch: {
    /**
     * @brief Listen to change from outside of component and update DOM
     * @param {number | null} newValue
     */
    value(newValue /*: ?number*/) {
      this.updateDateValue(newValue);
    },
    /**
     * @brief Watch for any change in options and set them
     */
    config: {
      deep: true,
      /**
       * @param {any} newConfig
       */
      handler(newConfig /*: {} */) {
        Eif (this.dp) {
          this.dp.options(newConfig);
        }
      }
    }
  },
  async mounted() {
    // Return early if date-picker is already loaded
    Iif (this.dp) { return; }
    // Init deps
    await initTempusDominus;
    // Save element
    // @ts-ignore I assure you window.jQuery exist now.
    this.elem = window.jQuery(this.$el);
    Iif (!this.elem) { return; }
    // This trick helps with keepFocus, otherwise the plugin complains
    this.elem.addClass("datetimepicker-input");
    // Init date-picker
    // @ts-ignore: datetimepicker is added by tempus plugin
    this.elem.datetimepicker(this.config);
    // Set attrs again. Plugin is removing some of them.
    forEach(this.$attrs, (value, key) => {
      Eif (this.elem) { this.elem.attr(key, value); }
    });
    // Store data control
    this.dp = this.elem.data("datetimepicker");
    // Set initial value
    this.updateDateValue(this.value);
    // If the input has the focus, show the widget!
    if (this.$el === document.activeElement) {
      this.dp.show();
    }
    // Watch for changes
    this.elem.on("change.datetimepicker", this.onChange);
    // Register remaining events
    this.registerEvents();
  },
  beforeDestroy() {
    Eif (this.dp) {
      this.dp.destroy();
      this.dp = null;
    }
    Eif (this.elem) {
      this.elem.off("change.datetimepicker");
      this.elem = null;
    }
  },
  methods: {
    /**
     * @param {number?} timestamp
     */
    updateDateValue(timestamp) {
      Eif (this.dp) {
        this.dp.date(isNil(timestamp) ? null : moment.unix(timestamp));
      }
    },
    /**
     * @biref Update v-model upon change triggered by date-picker itself
     * @param {any} event
     */
    onChange(event /*: any */) {
      // In case of invalid date, we have event.date === false.
      // Let's trigger input event in order to allow
      // users doing custom check of the field
      if (event.date === false) {
        this.$emit("input", null);
      }
      else Eif (moment.isMoment(event.date)) {
        const timestamp = /** @type moment.Moment */(event.date).unix();
        if (timestamp !== this.value) {
          this.$emit("input", timestamp);
        }
      }
    },
    /**
     * @brief Emit all available events from Tempus Dominus
     *   https://tempusdominus.github.io/bootstrap-4/Events/
     */
    registerEvents() {
      Iif (!this.elem) { return; }
      const events = [ "hide", "show", "change", "error", "update" ];
      const eventNameSpace = "datetimepicker";
 
      events.forEach((name) => {
        // @ts-ignore: it's not null here
        this.elem.on(`${name}.${eventNameSpace}`, (/** @type any[] */...args) => {
          this.$emit(`${name}`, ...args);
        });
      });
    }
  }
});
export default component;