camper/web/static/booking-dates.js

59 lines
2.0 KiB
JavaScript

(function () {
'use strict';
function updateDepartureDate(arrivalDateField) {
const arrivalDate = new Date(arrivalDateField.value);
if (isNaN(arrivalDate.getTime())) {
return;
}
const departureDateField = document.querySelector('[name="departure_date"]');
if (!departureDateField) {
return;
}
function updateDepartureDate(date) {
departureDateField.value = date;
departureDateField.dispatchEvent(new Event('input', {bubbles: true}));
}
const minNights = Math.max(1, parseInt(departureDateField.dataset.minNights, 10) || 0);
arrivalDate.setUTCDate(arrivalDate.getUTCDate() + minNights);
const minDate = formatDate(arrivalDate);
departureDateField.setAttribute('min', minDate);
const departureDate = new Date(departureDateField.value);
const validDepartureDate = !isNaN(departureDate.getTime())
if (!validDepartureDate || departureDate < arrivalDate) {
updateDepartureDate(minDate);
}
const maxNights = parseInt(departureDateField.dataset.maxNights, 10) || 0;
if (maxNights > 0) {
arrivalDate.setUTCDate(arrivalDate.getUTCDate() + maxNights - minNights);
const maxDate = formatDate(arrivalDate);
departureDateField.setAttribute('max', maxDate);
if (validDepartureDate && departureDate >= arrivalDate) {
updateDepartureDate(maxDate);
}
}
}
function formatDate(date) {
return `${date.getFullYear()}-${zeroPad(date.getMonth() + 1)}-${zeroPad(date.getDate())}`;
}
function zeroPad(num) {
return `${num < 10 ? '0' : ''}${num}`
}
const arrivalDateField = document.querySelector('[name="arrival_date"]');
if (!arrivalDateField) {
return;
}
arrivalDateField.addEventListener('change', function (event) {
updateDepartureDate(event.target);
});
updateDepartureDate(arrivalDateField);
})();