paragraphs_gantt-1.0.x-dev/js/field_duration.js
js/field_duration.js
(function ($, Drupal, once) {
Drupal.behaviors.duration = {
attach(context) {
$(once('duration-start', 'input.start-date',context)).change(function () {
let field_duration = $(this).data('field-duration');
let parent = $(this).closest('.field--widget-duration-default');
var startDate = new Date($(this).val());
var endDate = parent.find('input.end-date');
let selectorDuration = `input[name*=${field_duration}]`;
if ($(this).val()) {
if (endDate.val()) {
let diffDays = dayBetween($(this).val(), endDate.val())
$(selectorDuration).val(diffDays);
} else if ($(selectorDuration).val()) {
let end = calculateEndDate(startDate, $(selectorDuration).val());
endDate.val(end);
}
}
// Duration to end date.
$(selectorDuration).change(function () {
let duration = parseInt($(this).val());
let end = calculateEndDate(startDate, duration);
endDate.val(end);
});
});
$(once('duration-end', 'input.end-date', context)).change(function () {
let field_duration = $(this).data('field-duration');
let selectorDuration = `input[name*=${field_duration}]`;
let parent = $(this).closest('.field--widget-duration-default');
let starDate = parent.find('input.start-date');
if ($(this).val() && starDate.val()) {
let diffDays = dayBetween(starDate.val(), $(this).val());
$(selectorDuration).val(diffDays);
}
});
}
};
function dayBetween(start, end) {
start = new Date(start);
end = new Date(end);
let timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.ceil(timeDiff / (1000 * 3600 * 24));
}
function calculateEndDate(start, duration) {
if (isNaN(duration)) {
duration = 0;
}
let end = new Date(start.getTime() + (duration * 24 * 60 * 60 * 1000));
let year = end.getFullYear();
let month = ('0' + (end.getMonth() + 1)).slice(-2);
let day = ('0' + end.getDate()).slice(-2);
return year + '-' + month + '-' + day;
}
}(jQuery, Drupal, once));
