import Component from '@ember/component'; import { scheduleOnce, bind } from '@ember/runloop'; import moment from 'moment'; function formatDate(date, format) { if (format != undefined) { return moment(date).format(format); } return moment(date).format('YYYY/MM/DD H:mm'); } export default Component.extend({ tagName: 'input', classNames: ['date-time-picker'], valuePath: '', init() { this._super(); if (!this.options) { this.set('options', {}); } this.set('_changeHandlerProxy', bind(this, this._changeHandler)); }, _toDate(value) { let datetimeVal = value.split(" "); let dateVal = null; let timeVal = null; if (datetimeVal.length > 0) { dateVal = datetimeVal[0]; } if (datetimeVal.length > 1) { timeVal = datetimeVal[1]; } let dateVals = dateVal != null ? dateVal.split("/") : null; let dateStr = dateVals != null ? dateVals[1] + "/" + dateVals[0] + "/" + dateVals[2] : ""; if (timeVal != null) { dateStr = dateStr + " " + timeVal; return new Date(dateStr); } return new Date(dateStr); }, _changeHandler(event) { let newValue = event.target.value; let oldValue = this.datetime; let newDatetime, newDatetimeFormat, oldDatetimeFormat; if (this.options.datepicker != undefined) { if (!this.options.datepicker) { newValue = '01/01/1900 ' + newValue; } } if (newValue) { newDatetime = this._toDate(newValue); newDatetimeFormat = formatDate(newDatetime, this.formatoptions.formatDate); } if (oldValue) { oldDatetimeFormat = formatDate(oldValue, this.formatoptions.formatDate); } if (newDatetimeFormat === oldDatetimeFormat) { return; } this.action(newDatetime); }, _hideKeyboard() { if (window.cordova) { window.Keyboard.hide(); } }, _updateValue(shouldForceUpdatePicker) { let value; let { datetime } = this; if (datetime) { value = formatDate(datetime, this.formatoptions.formatDate); } else { value = ''; } let el = this.$(); el.val(value); // is only needed for inline, changing value above didn't change the picker if (shouldForceUpdatePicker) { el.datetimepicker({ value }); } }, _initDatetimepicker() { let { options } = this; this.$() .datetimepicker(options) .on('change', this._changeHandlerProxy) .on('focus', this._hideKeyboard) .on('keyup', this._hideKeyboard) .on('keydown', this._hideKeyboard) .on('blur', this._hideKeyboard); }, didInsertElement() { this._updateValue(); scheduleOnce('afterRender', this, this._initDatetimepicker); }, didUpdateAttrs() { this._updateValue(true); }, willDestroyElement() { this.$() .off('change', this._changeHandlerProxy) .datetimepicker('destroy'); } }).reopenClass({ positionalParams: ['datetime'] });