feat: Реализована календарная лента из 9 дней для фильтрации заказов
Основные изменения: **Компонент date_range_filter.html:** - Заменены простые кнопки на горизонтальную ленту из 9 дней - Добавлены стрелки навигации влево/вправо - Скрытые поля дат для работы с django-filter **Стили date_filter.css:** - Дизайн календарной ленты с карточками дней - Выделение сегодняшнего дня синим цветом - Выделение выбранной даты зеленым цветом - Hover-эффекты и анимации - Адаптивность для мобильных устройств - Стили для стрелок навигации **Логика date_filter.js:** - Класс DateCarousel для управления лентой - Генерация 9 дней (±4 от центральной даты) - Определение "Вчера/Сегодня/Завтра" для центральных 3 кнопок - Отображение числа (01-31) и дня недели (ПН-ВС) - Навигация стрелками (сдвиг на 1 день) - Клик по дню устанавливает дату в оба поля фильтра - Визуальная индикация выбранной даты **Формат каждой кнопки:** ┌─────────┐ │ Сегодня │ ← Текст (если вчера/сегодня/завтра) │ 07 │ ← Число месяца │ ЧТ │ ← День недели └─────────┘ **Поведение:** - По умолчанию: сегодня в центре (5-я кнопка) - Сегодняшний день выделен синим - Клик по дню фильтрует заказы за эту конкретную дату - Стрелки сдвигают весь диапазон на 1 день вперед/назад 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,89 +1,144 @@
|
||||
/**
|
||||
* Календарный фильтр для выбора диапазона дат
|
||||
* Поддерживает быстрые фильтры (сегодня, завтра, неделя)
|
||||
*
|
||||
* Использование:
|
||||
* Подключить этот файл в шаблоне после компонента date_range_filter.html
|
||||
* Календарная лента с 9 днями для фильтрации заказов
|
||||
* Сегодня в центре, навигация стрелками
|
||||
*/
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Date filter initialized');
|
||||
console.log('Date carousel initialized');
|
||||
|
||||
const quickDateButtons = document.querySelectorAll('.quick-date-btn');
|
||||
// Инициализация всех календарных лент на странице
|
||||
const carousels = document.querySelectorAll('.date-carousel-container');
|
||||
|
||||
quickDateButtons.forEach(button => {
|
||||
button.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
carousels.forEach(container => {
|
||||
const minInputId = container.getAttribute('data-min-input');
|
||||
const maxInputId = container.getAttribute('data-max-input');
|
||||
|
||||
const period = this.getAttribute('data-period');
|
||||
const minInputId = this.getAttribute('data-min-input');
|
||||
const maxInputId = this.getAttribute('data-max-input');
|
||||
|
||||
const minInput = document.getElementById(minInputId);
|
||||
const maxInput = document.getElementById(maxInputId);
|
||||
|
||||
if (!minInput || !maxInput) {
|
||||
console.error('Date inputs not found:', minInputId, maxInputId);
|
||||
return;
|
||||
}
|
||||
|
||||
const dates = getDateRange(period);
|
||||
|
||||
minInput.value = dates.min;
|
||||
maxInput.value = dates.max;
|
||||
|
||||
// Визуальная обратная связь
|
||||
this.classList.add('clicked');
|
||||
setTimeout(() => this.classList.remove('clicked'), 300);
|
||||
|
||||
console.log(`Set date range: ${dates.min} - ${dates.max}`);
|
||||
});
|
||||
// Инициализация с сегодняшней датой в центре
|
||||
const carousel = new DateCarousel(container, minInputId, maxInputId);
|
||||
carousel.init();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Вычисляет диапазон дат для выбранного периода
|
||||
* @param {string} period - период (today, tomorrow, week)
|
||||
* @returns {Object} объект с min и max датами в формате YYYY-MM-DD
|
||||
*/
|
||||
function getDateRange(period) {
|
||||
const today = new Date();
|
||||
const tomorrow = new Date(today);
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
|
||||
let minDate, maxDate;
|
||||
|
||||
switch(period) {
|
||||
case 'today':
|
||||
minDate = maxDate = formatDate(today);
|
||||
break;
|
||||
case 'tomorrow':
|
||||
minDate = maxDate = formatDate(tomorrow);
|
||||
break;
|
||||
case 'week':
|
||||
minDate = formatDate(today);
|
||||
const weekEnd = new Date(today);
|
||||
weekEnd.setDate(weekEnd.getDate() + 6);
|
||||
maxDate = formatDate(weekEnd);
|
||||
break;
|
||||
case 'month':
|
||||
minDate = formatDate(today);
|
||||
const monthEnd = new Date(today);
|
||||
monthEnd.setMonth(monthEnd.getMonth() + 1);
|
||||
maxDate = formatDate(monthEnd);
|
||||
break;
|
||||
default:
|
||||
minDate = maxDate = '';
|
||||
}
|
||||
|
||||
return { min: minDate, max: maxDate };
|
||||
/**
|
||||
* Класс для управления календарной лентой
|
||||
*/
|
||||
class DateCarousel {
|
||||
constructor(container, minInputId, maxInputId) {
|
||||
this.container = container;
|
||||
this.minInputId = minInputId;
|
||||
this.maxInputId = maxInputId;
|
||||
this.minInput = document.getElementById(minInputId);
|
||||
this.maxInput = document.getElementById(maxInputId);
|
||||
this.centerDate = new Date(); // Центральная дата (по умолчанию сегодня)
|
||||
this.today = new Date();
|
||||
this.today.setHours(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует дату в формат YYYY-MM-DD для input[type="date"]
|
||||
* @param {Date} date - объект даты
|
||||
* @returns {string} дата в формате YYYY-MM-DD
|
||||
* Инициализация календарной ленты
|
||||
*/
|
||||
function formatDate(date) {
|
||||
init() {
|
||||
this.render();
|
||||
this.attachNavHandlers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация и отображение 9 дней
|
||||
*/
|
||||
render() {
|
||||
this.container.innerHTML = '';
|
||||
const days = this.generateDays();
|
||||
|
||||
days.forEach(dayData => {
|
||||
const btn = this.createDayButton(dayData);
|
||||
this.container.appendChild(btn);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация массива из 9 дней (±4 от центральной даты)
|
||||
*/
|
||||
generateDays() {
|
||||
const days = [];
|
||||
|
||||
for (let i = -4; i <= 4; i++) {
|
||||
const date = new Date(this.centerDate);
|
||||
date.setDate(date.getDate() + i);
|
||||
date.setHours(0, 0, 0, 0);
|
||||
|
||||
days.push({
|
||||
date: date,
|
||||
label: this.getDateLabel(date, i),
|
||||
isToday: date.getTime() === this.today.getTime(),
|
||||
isCenter: i === 0
|
||||
});
|
||||
}
|
||||
|
||||
return days;
|
||||
}
|
||||
|
||||
/**
|
||||
* Определение текстовой метки для даты
|
||||
*/
|
||||
getDateLabel(date, offset) {
|
||||
if (offset === -1) return 'Вчера';
|
||||
if (offset === 0 && date.getTime() === this.today.getTime()) return 'Сегодня';
|
||||
if (offset === 1 && date.getTime() === new Date(this.today.getTime() + 86400000).getTime()) return 'Завтра';
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Создание кнопки дня
|
||||
*/
|
||||
createDayButton(dayData) {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'date-btn';
|
||||
|
||||
if (dayData.isToday) {
|
||||
btn.classList.add('today');
|
||||
}
|
||||
|
||||
// Проверка, выбрана ли эта дата
|
||||
if (this.isDateSelected(dayData.date)) {
|
||||
btn.classList.add('selected');
|
||||
}
|
||||
|
||||
// Структура кнопки
|
||||
const label = document.createElement('div');
|
||||
label.className = 'date-btn-label';
|
||||
label.textContent = dayData.label;
|
||||
|
||||
const day = document.createElement('div');
|
||||
day.className = 'date-btn-day';
|
||||
day.textContent = String(dayData.date.getDate()).padStart(2, '0');
|
||||
|
||||
const weekday = document.createElement('div');
|
||||
weekday.className = 'date-btn-weekday';
|
||||
weekday.textContent = this.getWeekdayShort(dayData.date);
|
||||
|
||||
btn.appendChild(label);
|
||||
btn.appendChild(day);
|
||||
btn.appendChild(weekday);
|
||||
|
||||
// Обработчик клика
|
||||
btn.addEventListener('click', () => this.selectDate(dayData.date, btn));
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить короткое название дня недели (ПН, ВТ, СР, ЧТ, ПТ, СБ, ВС)
|
||||
*/
|
||||
getWeekdayShort(date) {
|
||||
const weekdays = ['ВС', 'ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ'];
|
||||
return weekdays[date.getDay()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирование даты в YYYY-MM-DD
|
||||
*/
|
||||
formatDate(date) {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
@@ -91,41 +146,53 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Валидация диапазона дат (начало <= конец)
|
||||
* Проверка, выбрана ли дата
|
||||
*/
|
||||
const dateInputs = document.querySelectorAll('.date-input');
|
||||
dateInputs.forEach(input => {
|
||||
input.addEventListener('change', function() {
|
||||
const container = this.closest('.date-range-filter');
|
||||
if (!container) return;
|
||||
|
||||
const minInput = container.querySelector('.date-input[id$="_after"]');
|
||||
const maxInput = container.querySelector('.date-input[id$="_before"]');
|
||||
|
||||
if (!minInput || !maxInput) return;
|
||||
|
||||
if (minInput.value && maxInput.value) {
|
||||
const minDate = new Date(minInput.value);
|
||||
const maxDate = new Date(maxInput.value);
|
||||
|
||||
if (minDate > maxDate) {
|
||||
alert('Дата начала не может быть позже даты окончания');
|
||||
this.value = '';
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
isDateSelected(date) {
|
||||
const formattedDate = this.formatDate(date);
|
||||
return this.minInput.value === formattedDate && this.maxInput.value === formattedDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сброс дат при клике на кнопку "Сбросить" формы
|
||||
* Выбор даты (установка в оба поля фильтра)
|
||||
*/
|
||||
const resetButtons = document.querySelectorAll('a[href*="order-list"]:not([href*="?"])');
|
||||
resetButtons.forEach(button => {
|
||||
button.addEventListener('click', function() {
|
||||
// Очищаем все date inputs
|
||||
dateInputs.forEach(input => {
|
||||
input.value = '';
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
selectDate(date, btn) {
|
||||
const formattedDate = this.formatDate(date);
|
||||
|
||||
this.minInput.value = formattedDate;
|
||||
this.maxInput.value = formattedDate;
|
||||
|
||||
// Визуальная обратная связь
|
||||
btn.classList.add('clicked');
|
||||
setTimeout(() => btn.classList.remove('clicked'), 300);
|
||||
|
||||
// Обновление визуального состояния
|
||||
this.render();
|
||||
|
||||
console.log(`Selected date: ${formattedDate}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Подключение обработчиков для стрелок навигации
|
||||
*/
|
||||
attachNavHandlers() {
|
||||
const prevBtn = this.container.parentElement.querySelector('.carousel-prev');
|
||||
const nextBtn = this.container.parentElement.querySelector('.carousel-next');
|
||||
|
||||
if (prevBtn) {
|
||||
prevBtn.addEventListener('click', () => this.shiftDays(-1));
|
||||
}
|
||||
|
||||
if (nextBtn) {
|
||||
nextBtn.addEventListener('click', () => this.shiftDays(1));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Сдвиг диапазона дней на N дней
|
||||
*/
|
||||
shiftDays(offset) {
|
||||
this.centerDate.setDate(this.centerDate.getDate() + offset);
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user