test/static/js/ol/map/map-timeline.js
zakhy b905f49022 Реализовал поле ввода даты и времени в таймлайне
На главной странице добавлена возможность выбирать дату и время с помощью поля ввода (необходимо кликнуть на подчеркнутую текущую дату)
2025-07-08 15:33:49 +07:00

190 lines
6.8 KiB
JavaScript

class TimeLine {
constructor(options) {
this.mapCore = options.mapCore
this.target = options.target
this.updateFunction = options.updateFunction
this.disposePopover = this.disposePopover.bind(this);
this.timeline = this.initTimeLine()
this.addTimelineEventListeners()
}
initTimeLine() {
const items = new vis.DataSet([]);
moment.locale('ru')
const options = {
locale: "ru",
min: '2025-05-30T12:00:00',
max: moment().add(12, 'hours'),
start: moment(),
zoomMin: 1000 * 60 * 60 * 24,
zoomMax: 1000 * 60 * 60 * 24,
moveable: true,
zoomable: true,
showCurrentTime: true,
selectable: false,
orientation: {axis: "top"},
format: {
minorLabels: {
minute: 'HH:mm', hour: 'HH:mm', second: 'HH:mm:ss'
}, majorLabels: function (date) {
return date.format("DD.MM.YY");
}
}
};
return new vis.Timeline(this.target, items, options);
}
disposePopover(e) {
if (e.target !== this.currentTimeLink &&
!this.currentTimeLink.contains(e.target) &&
!document.querySelector('.popover')?.contains(e.target)) {
this.popover.hide();
}
}
addTimelineEventListeners() {
this.timeline.on('rangechanged', (props) => {
const center = new Date((props.start.getTime() + props.end.getTime()) / 2);
const currentDate = new Date()
const dateDif = currentDate - center
const iso = center.toISOString();
if (dateDif > 5000) {
globalTimeQuery = "?time=" + iso
} else {
globalTimeQuery = ""
}
this.updateCurrentTimeDisplay(center);
this.updateFunction(globalTimeQuery);
});
setInterval(() => {
const newMax = moment().add(12, 'hours').toDate();
this.timeline.setOptions({
max: newMax
});
const window = this.timeline.getWindow();
if (window.end > (newMax - (60000 * 5))) {
const duration = window.end - window.start;
this.timeline.setWindow(new Date(newMax - duration), newMax);
}
}, 3000);
}
updateCurrentTimeDisplay(center) {
const currentTime = document.getElementById("current-time");
// Очистка currentTime
while (currentTime.firstChild) {
currentTime.removeChild(currentTime.firstChild);
}
const currentTimeSpan = document.createElement("span");
currentTimeSpan.textContent = "Время на карте: ";
const currentTimeLink = document.createElement("a");
currentTimeLink.textContent = center.toLocaleDateString() + " " + center.toLocaleTimeString();
currentTimeLink.style.zIndex = "33";
currentTimeLink.style.textDecoration = "underline";
currentTimeLink.style.cursor = "pointer";
currentTimeLink.id = "currentTimeLink"
this.currentTimeLink = currentTimeLink
// Создаем форму для выбора времени
const form = document.createElement('form');
form.id = 'timelineDatetimeSelectForm';
form.className = 'needs-validation';
form.noValidate = true;
const formGroup = document.createElement('div');
formGroup.className = 'mb-3';
const label = document.createElement('label');
label.htmlFor = 'timelineDatetimeInput';
label.className = 'form-label';
label.textContent = 'Выбор даты и времени';
const input = document.createElement('input');
input.type = 'datetime-local';
input.id = 'timelineDatetimeInput';
input.className = 'form-control';
// Устанавливаем текущее значение и максимальную дату
const setInputValues = () => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const maxDateTime = `${year}-${month}-${day}T${hours}:${minutes}`;
input.max = maxDateTime;
};
const inputContainer = document.createElement('div');
inputContainer.id = 'datetimeInputContainer';
inputContainer.appendChild(input);
const resetBtn = document.createElement('button');
resetBtn.type = 'reset';
resetBtn.className = 'btn btn-outline-secondary btn-sm me-2';
resetBtn.textContent = 'Сбросить';
const submitBtn = document.createElement('button');
submitBtn.type = 'submit';
submitBtn.className = 'btn btn-primary btn-sm';
submitBtn.textContent = 'Перейти';
formGroup.appendChild(label);
formGroup.appendChild(inputContainer);
form.appendChild(formGroup);
form.appendChild(resetBtn);
form.appendChild(submitBtn);
form.addEventListener("submit", (e) => {
e.preventDefault();
const selectedDate = new Date(input.value);
if (isNaN(selectedDate.getTime())) return;
// Обновляем таймлайн
const duration = this.timeline.getWindow().end - this.timeline.getWindow().start;
const start = new Date(selectedDate.getTime() - duration / 2);
const end = new Date(selectedDate.getTime() + duration / 2);
this.timeline.setWindow(start, end);
// Обновляем URL
globalTimeQuery = "?time=" + selectedDate.toISOString();
this.updateFunction(globalTimeQuery);
// Закрываем popover
popover.hide();
});
const popover = new bootstrap.Popover(currentTimeLink, {
trigger: 'manual', html: true, content: form, placement: 'top', sanitize: false
});
this.popover = popover
// Обновляем значения поля ввода при каждом показе popover
currentTimeLink.addEventListener('click', (e) => {
e.preventDefault();
setInputValues();
if (currentTimeLink.getAttribute('aria-describedby')) {
popover.hide();
} else {
popover.show();
}
});
document.addEventListener('click', (e) => this.disposePopover(e, currentTimeLink, popover));
currentTime.appendChild(currentTimeSpan);
currentTime.appendChild(currentTimeLink);
}
}