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

107 lines
2.9 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];
let offset = date.getTimezoneOffset() * 60000;
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;
let date;
if (value && this.iniOptions.enableTime) {
date = new Date(value);
let offset = date.getTimezoneOffset() * 60000;
date.setTime(date.getTime() + offset);
} else
date = value;
this.vp.setDate(date);
this.mdlUpdate();
}
onClear() {
this.model = null;
}
mdlUpdate() {
let mdlField = this.element.firstChild.MaterialTextfield;
if (mdlField)
mdlField.updateClasses_();
}
$onDestroy() {
this.vp.destroy();
this.dateValue = undefined;
}
}
DatePicker.$inject = ['$element', '$scope', '$translate', '$attrs'];
ngModule.component('vnDatePicker', {
template: require('./date-picker.html'),
bindings: {
iniOptions: '<?',
model: '=',
label: '@?',
name: '@?',
disabled: '<?',
rule: '<?',
isLocale: '<?'
},
controller: DatePicker
});