salix/front/core/components/date-picker/date-picker.js

104 lines
2.8 KiB
JavaScript

import ngModule from '../../module';
import Component from '../../lib/component';
import {Flatpickr} from '../../vendor';
import './style.scss';
class DatePicker extends Component {
constructor($element, $scope, $translate, $attrs) {
super($element, $scope);
this.input = $element[0].querySelector('input');
this.$translate = $translate;
this.$attrs = $attrs;
this._model = undefined;
this.dateValue = undefined;
this.hasMouseIn = false;
let locale = this.$translate.use();
this.defaultOptions = {
locale: locale,
dateFormat: locale == 'es' ? 'd-m-Y' : 'Y-m-d',
enableTime: false,
onValueUpdate: () => this.onValueUpdate()
};
this.userOptions = {};
this._iniOptions = this.defaultOptions;
componentHandler.upgradeElement($element[0].firstChild);
this.vp = new Flatpickr(this.input, this._iniOptions);
}
onValueUpdate() {
if (this.vp.selectedDates.length) {
let date = this.vp.selectedDates[0];
if (!this.isLocale && !this._iniOptions.enableTime) {
let now = new Date();
let offset = now.getTimezoneOffset() * 60000;
date.setHours(0, 0, 0, 0);
date.setTime(date.getTime() - offset);
}
this._model = date;
} else
this.model = null;
this.$.$apply();
}
set iniOptions(value) {
this.userOptions = value;
let options = Object.assign({}, this.defaultOptions, value);
this._iniOptions = options;
// TODO: When some properties change Flatpickr doesn't refresh the view
// for (let option in options)
// this.vp.set(option, options[option]);
if (this.vp) this.vp.destroy();
this.vp = new Flatpickr(this.input, this._iniOptions);
this.vp.setDate(this.dateValue);
this.mdlUpdate();
}
get iniOptions() {
return this.userOptions;
}
get model() {
return this._model;
}
set model(value) {
this._model = value;
this.dateValue = value ? new Date(value) : null;
this.vp.setDate(this.dateValue);
this.mdlUpdate();
}
onClear() {
this.model = null;
}
mdlUpdate() {
let mdlField = this.element.firstChild.MaterialTextfield;
if (mdlField)
mdlField.updateClasses_();
}
$onDestroy() {
this.vp.destroy();
}
}
DatePicker.$inject = ['$element', '$scope', '$translate', '$attrs'];
ngModule.component('vnDatePicker', {
template: require('./date-picker.html'),
bindings: {
model: '=',
label: '@?',
name: '@?',
disabled: '<?',
rule: '<?',
iniOptions: '<?',
isLocale: '<?'
},
controller: DatePicker
});