Files
myep-team/assets/controllers/datepicker_controller.js
T

60 lines
1.8 KiB
JavaScript

import { Controller } from '@hotwired/stimulus'
import flatpickr from 'flatpickr';
import { German } from 'flatpickr/dist/l10n/de';
/* stimulusFetch: 'lazy' */
export default class extends Controller {
static targets = [ 'field' ]
static values = { format: String, minDate: String, maxDate: String, disableWeekends: Boolean, mode: String }
initialize() {
flatpickr.localize(German);
flatpickr.setDefaults({
dateFormat: 'd.m.Y',
allowInput: true
});
}
connect() {
const mode = this.modeValue || 'single'
const dateFormat = this.formatValue || 'd.m.Y'
const minDate = this.minDateValue
const maxDate = this.maxDateValue
const options = {
mode,
dateFormat: 'Y-m-d',
altInput: true,
altFormat: dateFormat,
minDate,
maxDate,
allowInput: true,
onClose(dates, currentdatestring, instance) {
instance.setDate(instance.altInput.value, true, instance.config.altFormat)
this.element.dispatchEvent(new CustomEvent('datepicker:closed'))
},
onChange(dates, currentdatestring, instance) {
this.element.dispatchEvent(new CustomEvent('datepicker:picked', {
detail: {
date: instance.altInput.value
}
}))
},
}
if (true === this.disableWeekendsValue) {
options['disable'] = [
function(date) {
return (date.getDay() === 0 || date.getDay() === 6);
}
]
}
this.picker = flatpickr(this.fieldTarget, options)
}
disconnect() {
this.picker.destroy()
}
}