fix [P-304]: адаптация ширины FullCalendar при ресайзе контейнера

This commit is contained in:
Inna committed 2026-06-01 15:36:50 +03:00
1 parent 3c9c244dc7
commit 45922643c0
1 file changed
+320 -413
@@ -72,8 +72,7 @@
</v-col>
</v-row>
</div>
<div class="flex-grow-1 d-flex">
<!-- VCalendar -->
<div class="flex-grow-1 d-flex" ref="calWrap">
<FullCalendar
v-if="currentView !== 'listAllEvents'"
ref="calendarRef"
@@ -87,433 +86,341 @@
</v-card>
</v-col>
</template>
<script>
import { ref, watch, nextTick, computed } from 'vue';
<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import multiMonthPlugin from '@fullcalendar/multimonth';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
import rrulePlugin from '@fullcalendar/rrule';
import { onMounted } from 'vue';
import ruLocale from '@fullcalendar/core/locales/ru';
import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { useAccountStore } from '@/store/AccountStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { useEventListFilters } from '../composables/useEventListFilters';
import EventsListView from './EventsListView.vue';
import EventListFilters from './EventListFilters.vue';
import { useEventListFilters } from '../composables/useEventListFilters';
import { useRoute } from 'vue-router';
export default {
name: 'CustomCalendar',
components: {
EventsListView,
EventListFilters,
defineOptions({ name: 'CustomCalendar' });
const props = defineProps({
forHomePage: { type: Boolean, default: false },
view: { type: String, default: 'dayGridMonth' },
});
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const route = useRoute();
const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { isRecurringEvent, generateRecurringInstances } = useRecurrence();
const filters = useEventListFilters();
const currentView = ref('dayGridMonth');
const currentTitle = ref('Календарь');
const calendarRef = ref(null);
const calWrap = ref(null);
const calendarApi = computed(() => calendarRef.value?.getApi?.() || null);
const unwrappedFilters = computed(() => ({
dateRange: filters.dateRange.value,
sortOrder: filters.sortOrder.value,
}));
const weekdayMap = {
воскресенье: 'воскресенье',
понедельник: 'понедельник',
вторник: 'вторник',
среда: 'среду',
четверг: 'четверг',
пятница: 'пятницу',
суббота: 'субботу',
};
const formatScheduleTitle = (dateValue) => {
const date = new Date(dateValue);
const weekdayRaw = date.toLocaleDateString('ru-RU', { weekday: 'long' });
const weekday = weekdayMap[weekdayRaw] || weekdayRaw;
const rest = date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
return `Расписание на ${weekday}, ${rest}`;
};
const handleDateSelection = (dateStr) => {
document
.querySelectorAll('.fc-day-selected-custom')
.forEach((el) => el.classList.remove('fc-day-selected-custom'));
document
.querySelectorAll(`[data-date="${dateStr}"]`)
.forEach((el) => el.classList.add('fc-day-selected-custom'));
selectedDate.value = dateStr;
};
const updateSelectedDateFromCalendar = () => {
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
calendarStore.setSelectedDateFromCalendar({
dateStr: currentDate.toISOString().split('T')[0],
});
}
};
const handleEventClick = (info) => calendarStore.handleEventClick(info);
const handleCalendarDateClick = (info) => {
calendarStore.setSelectedDateFromCalendar(info);
currentTitle.value = info.view.title;
if (calendarApi.value) {
calendarApi.value.gotoDate(info.date);
calendarApi.value.changeView('listWeek');
currentView.value = 'listWeek';
}
};
const handleToday = () => {
calendarApi.value?.today();
updateSelectedDateFromCalendar();
};
const handlePrev = () => {
calendarApi.value?.prev();
updateSelectedDateFromCalendar();
};
const handleNext = () => {
calendarApi.value?.next();
updateSelectedDateFromCalendar();
};
const applyView = async (newView) => {
if (newView === 'listAllEvents') {
currentTitle.value = 'Все события';
return;
}
if (newView === 'listWeek' && selectedDate.value) {
currentTitle.value = formatScheduleTitle(selectedDate.value);
}
await nextTick();
if (!calendarApi.value) return;
calendarApi.value.changeView(newView);
if (newView !== 'listWeek') currentTitle.value = calendarApi.value.view.title;
};
const handleFiltersUpdate = (newFilters) => {
Object.keys(newFilters).forEach((key) => {
if (filters[key] !== undefined) filters[key].value = newFilters[key];
});
};
// Ресайз контейнера
let ro = null;
let rafId = null;
const updateSize = () => calendarRef.value?.getApi()?.updateSize();
const scheduleUpdate = () => {
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(updateSize);
};
const dayClassNames = (arg) => {
const info = calendarStore.isNonWorkingDay(arg.date);
const classes = [];
if (info.isHoliday) classes.push('non-working-day');
if (info.isWeekendForStyling) classes.push('grey-background');
return classes;
};
const buildEvents = (fetchInfo, successCallback) => {
const events = allEvents.value.flatMap((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
if (isRecurringEvent(event)) {
return generateRecurringInstances(event, 52).map((instance) => ({
id: instance.id,
title: instance.title,
start: instance.start,
end: instance.end,
allDay: instance.allDay,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
extendedProps: {
...instance.extendedProps,
_userHash: accountStore.user?.id || 'anonymous',
},
}));
}
return [
{
id: event.id,
title: event.name,
start: event.date_start,
end: event.date_end,
allDay: event.allday,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
extendedProps: {
originalEventId: event.id,
description: event.description,
participant: event.participant,
calendar: event.calendar,
files: event.files,
_userHash: accountStore.user?.id || 'anonymous',
},
},
];
});
successCallback(events);
};
const calendarViews = {
timeGridDay: {
type: 'timeGrid',
duration: { days: 1 },
slotDuration: '01:00:00',
slotLabelInterval: '01:00:00',
slotLabelFormat: { hour: '2-digit', minute: '2-digit', hour12: false, meridiem: false },
allDaySlot: true,
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
expandRows: true,
dayHeaderFormat: { weekday: 'long', day: 'numeric', month: 'long', omitCommas: true },
},
props: {
forHomePage: { type: Boolean, default: false },
view: { type: String, default: 'dayGridMonth' },
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: 1 },
slotDuration: '01:00:00',
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
allDaySlot: true,
expandRows: true,
dayHeaderFormat: { weekday: 'short', day: 'numeric' },
titleFormat: { day: 'numeric', month: 'long', omitCommas: true },
},
setup(props) {
const currentView = ref('dayGridMonth');
const currentTitle = ref('Календарь');
const calendarRef = ref(null);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { isRecurringEvent, generateRecurringInstances } = useRecurrence();
const route = useRoute();
const calendarApi = computed(() => {
return calendarRef.value?.getApi?.() || null;
});
const filters = useEventListFilters();
// Создаем развернутую версию фильтров для передачи в EventsListView
const unwrappedFilters = computed(() => ({
dateRange: filters.dateRange.value,
sortOrder: filters.sortOrder.value,
}));
const handleEventClick = (info) => {
calendarStore.handleEventClick(info);
};
const calendarOptions = ref({
plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale],
locale: 'ru',
timeZone: 'Europe/Moscow',
firstDay: 1,
headerToolbar: false,
height: '80vh',
aspectRatio: 1.5,
weekNumbers: true,
eventDisplay: 'auto',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
meridiem: false,
},
weekNumberFormat: {
week: 'numeric',
},
weekNumberCalculation: 'ISO', // ISO стандарт (понедельник - первый день)
selectable: true,
unselectAuto: false,
selectMirror: false,
dayCellClassNames: (arg) => {
const dayInfo = calendarStore.isNonWorkingDay(arg.date);
const classes = [];
if (dayInfo.isHoliday) classes.push('non-working-day');
if (dayInfo.isWeekendForStyling) classes.push('grey-background');
return classes;
},
dayHeaderClassNames: (arg) => {
const dayInfo = calendarStore.isNonWorkingDay(arg.date);
const classes = [];
if (dayInfo.isHoliday) classes.push('non-working-day');
if (dayInfo.isWeekendForStyling) classes.push('grey-background');
return classes;
},
views: {
timeGridDay: {
type: 'timeGrid',
duration: { days: 1 },
slotDuration: '01:00:00',
slotLabelInterval: '01:00:00',
slotLabelFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
meridiem: false,
},
allDaySlot: true,
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
expandRows: true,
dayHeaderFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: 1 },
slotDuration: '01:00:00',
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
allDaySlot: true,
expandRows: true,
dayHeaderFormat: { weekday: 'short', day: 'numeric' },
titleFormat: {
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
dayGridMonth: {
type: 'dayGrid',
fixedWeekCount: false,
dayHeaderFormat: { weekday: 'short' },
weekNumbers: true,
weekNumberFormat: { week: 'numeric' },
weekNumberContent: (arg) => {
return arg.num;
},
weekText: 'Нед.',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
omitZeroMinute: false,
},
},
multiMonthYear: {
type: 'multiMonth',
duration: { years: 1 },
multiMonthMaxColumns: 4,
fixedWeekCount: false,
weekNumbers: false,
},
listWeek: {
type: 'list',
duration: { days: 1 },
listDayFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
},
listDaySideFormat: false,
},
},
events: function (fetchInfo, successCallback) {
const events = allEvents.value.flatMap((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
const startDate = new Date(event.date_start);
const endDate = new Date(event.date_end);
const isMultiDay = startDate.toDateString() !== endDate.toDateString();
if (isRecurringEvent(event)) {
return generateRecurringInstances(event, 52).map((instance) => ({
id: instance.id,
title: instance.title,
start: instance.start,
end: instance.end,
allDay: instance.allDay,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
extendedProps: {
...instance.extendedProps,
_userHash: accountStore.user?.id || 'anonymous',
},
}));
} else {
return [
{
id: event.id,
title: event.name,
start: event.date_start,
end: event.date_end,
allDay: event.allday,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
extendedProps: {
originalEventId: event.id,
description: event.description,
participant: event.participant,
calendar: event.calendar,
files: event.files,
_userHash: accountStore.user?.id || 'anonymous',
},
},
];
}
});
successCallback(events);
},
eventClick: handleEventClick,
dateClick: (info) => {
calendarStore.setSelectedDateFromCalendar(info);
handleDateSelection(info.dateStr);
handleCalendarDateClick(info);
calendarApi.value?.unselect();
},
datesSet: (info) => {
if (info.view.type === 'listWeek' && selectedDate.value) {
currentTitle.value = formatScheduleTitle(selectedDate.value);
} else if (info.view.type !== 'listWeek') {
currentTitle.value = info.view.title;
}
if (selectedDate?.value) {
handleDateSelection(selectedDate.value);
}
},
});
const handleCalendarDateClick = (info) => {
calendarStore.setSelectedDateFromCalendar(info);
currentTitle.value = info.view.title;
if (calendarApi.value) {
calendarApi.value.gotoDate(info.date);
calendarApi.value.changeView('listWeek');
currentView.value = 'listWeek';
}
};
const handleToday = () => {
calendarApi.value?.today();
// Получаем текущую дату из календаря и передаем в стор
updateSelectedDateFromCalendar();
};
const handlePrev = () => {
calendarApi.value?.prev();
updateSelectedDateFromCalendar();
};
const handleNext = () => {
calendarApi.value?.next();
updateSelectedDateFromCalendar();
};
const updateSelectedDateFromCalendar = () => {
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
const todayInfo = {
dateStr: currentDate.toISOString().split('T')[0],
};
calendarStore.setSelectedDateFromCalendar(todayInfo);
}
};
// Функция обновления выделения
const handleDateSelection = (dateStr) => {
// Убираем предыдущее выделение
const previousSelected = document.querySelectorAll('.fc-day-selected-custom');
previousSelected.forEach((el) => el.classList.remove('fc-day-selected-custom'));
// Добавляем новое выделение
const dayElements = document.querySelectorAll(`[data-date="${dateStr}"]`);
dayElements.forEach((el) => el.classList.add('fc-day-selected-custom'));
selectedDate.value = dateStr;
};
const weekdayMap = {
воскресенье: 'воскресенье',
понедельник: 'понедельник',
вторник: 'вторник',
среда: 'среду',
четверг: 'четверг',
пятница: 'пятницу',
суббота: 'субботу',
};
const formatScheduleTitle = (dateValue) => {
const date = new Date(dateValue);
const weekdayRaw = date.toLocaleDateString('ru-RU', { weekday: 'long' });
const weekday = weekdayMap[weekdayRaw] || weekdayRaw;
const rest = date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
return `Расписание на ${weekday}, ${rest}`;
};
const applyView = async (newView) => {
if (newView === 'listAllEvents') {
currentTitle.value = 'Все события';
return;
}
if (newView === 'listWeek' && selectedDate.value) {
currentTitle.value = formatScheduleTitle(selectedDate.value);
}
await nextTick();
if (!calendarApi.value) return;
calendarApi.value.changeView(newView);
if (newView !== 'listWeek') {
currentTitle.value = calendarApi.value.view.title;
}
};
onMounted(async () => {
const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(currentYear);
// Ждем следующего тика для гарантии, что календарь инициализирован
await nextTick();
// Принудительно обновляем события после загрузки праздников
if (calendarApi.value && currentView.value !== 'listAllEvents') {
calendarApi.value.refetchEvents();
}
if (selectedDate.value && currentView.value !== 'listAllEvents') {
handleDateSelection(selectedDate.value);
}
});
watch(currentView, (newView) => {
applyView(newView);
});
watch(
[() => calendarStore.calendars, () => calendarStore.hiddenCalendarIds],
() => {
// При изменении событий перезагружаем календарь
if (currentView.value === 'listAllEvents') return;
calendarApi.value?.refetchEvents();
},
{ deep: true },
);
watch(
calendarColorMap,
() => {
if (currentView.value === 'listAllEvents') return;
calendarApi.value?.refetchEvents();
},
{ deep: true },
);
watch(selectedDate, (newDate) => {
if (newDate && calendarApi.value && lastUpdatedBy.value !== 'calendar') {
nextTick(() => {
calendarApi.value.gotoDate(newDate);
handleDateSelection(newDate);
if (route.query.date && currentView.value !== 'timeGridDay') {
currentView.value = 'timeGridDay';
}
});
}
});
const handleFiltersUpdate = (newFilters) => {
Object.keys(newFilters).forEach((key) => {
if (filters[key] !== undefined) {
filters[key].value = newFilters[key];
}
});
};
// Сброс фильтров при выходе из кастомного вида
watch(currentView, (newView, oldView) => {
if (oldView === 'listAllEvents' && newView !== 'listAllEvents') {
filters.resetFilters();
}
});
return {
currentTitle,
calendarRef,
calendarApi,
currentView,
calendarOptions,
handleToday,
handleNext,
handlePrev,
handleCalendarDateClick,
handleDateSelection,
handleEventClick,
calendarStore,
filters,
handleFiltersUpdate,
unwrappedFilters,
};
dayGridMonth: {
type: 'dayGrid',
fixedWeekCount: false,
dayHeaderFormat: { weekday: 'short' },
weekNumbers: true,
weekNumberFormat: { week: 'numeric' },
weekNumberContent: (arg) => arg.num,
weekText: 'Нед.',
eventTimeFormat: { hour: '2-digit', minute: '2-digit', hour12: false, omitZeroMinute: false },
},
multiMonthYear: {
type: 'multiMonth',
duration: { years: 1 },
multiMonthMaxColumns: 4,
fixedWeekCount: false,
weekNumbers: false,
},
listWeek: {
type: 'list',
duration: { days: 1 },
listDayFormat: { weekday: 'long', day: 'numeric', month: 'long' },
listDaySideFormat: false,
},
};
const calendarOptions = ref({
plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale],
locale: 'ru',
timeZone: 'Europe/Moscow',
firstDay: 1,
headerToolbar: false,
height: '80vh',
aspectRatio: 1.5,
weekNumbers: true,
eventDisplay: 'auto',
eventTimeFormat: { hour: '2-digit', minute: '2-digit', hour12: false, meridiem: false },
weekNumberFormat: { week: 'numeric' },
weekNumberCalculation: 'ISO',
selectable: true,
unselectAuto: false,
selectMirror: false,
dayCellClassNames: dayClassNames,
dayHeaderClassNames: dayClassNames,
views: calendarViews,
events: buildEvents,
eventClick: handleEventClick,
dateClick: (info) => {
calendarStore.setSelectedDateFromCalendar(info);
handleDateSelection(info.dateStr);
handleCalendarDateClick(info);
calendarApi.value?.unselect();
},
datesSet: (info) => {
if (info.view.type === 'listWeek' && selectedDate.value) {
currentTitle.value = formatScheduleTitle(selectedDate.value);
} else if (info.view.type !== 'listWeek') {
currentTitle.value = info.view.title;
}
if (selectedDate?.value) handleDateSelection(selectedDate.value);
},
});
/* ──────────── Вотчеры ──────────── */
watch(currentView, (newView, oldView) => {
applyView(newView);
if (oldView === 'listAllEvents' && newView !== 'listAllEvents') filters.resetFilters();
});
watch(
[() => calendarStore.calendars, () => calendarStore.hiddenCalendarIds],
() => {
if (currentView.value !== 'listAllEvents') calendarApi.value?.refetchEvents();
},
{ deep: true },
);
watch(
calendarColorMap,
() => {
if (currentView.value !== 'listAllEvents') calendarApi.value?.refetchEvents();
},
{ deep: true },
);
watch(selectedDate, (newDate) => {
if (newDate && calendarApi.value && lastUpdatedBy.value !== 'calendar') {
nextTick(() => {
calendarApi.value.gotoDate(newDate);
handleDateSelection(newDate);
if (route.query.date && currentView.value !== 'timeGridDay') {
currentView.value = 'timeGridDay';
}
});
}
});
onMounted(async () => {
ro = new ResizeObserver(scheduleUpdate);
if (calWrap.value) ro.observe(calWrap.value);
calendarStore.fetchHolidays(new Date().getFullYear());
await nextTick();
if (currentView.value !== 'listAllEvents') {
if (calendarApi.value) calendarApi.value.refetchEvents();
if (selectedDate.value) handleDateSelection(selectedDate.value);
}
});
onBeforeUnmount(() => {
cancelAnimationFrame(rafId);
ro?.disconnect();
});
</script>
<style scoped>
:deep(.fc-daygrid-day-number) {