(function () { 'use strict'; const API = location.origin; const CAL_WEEK_START = 1; const HOUR_H = 56; const VIEWS = ['day', 'week', 'month', 'agenda']; const DOW_SHORT = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']; const COLORS = ['blue', 'green', 'orange', 'red', 'purple', 'pink', 'teal', 'brown']; const COLOR_HEX = { blue: '#2563eb', green: '#16a34a', orange: '#ea580c', red: '#dc2626', purple: '#9333ea', pink: '#db2777', teal: '#0d9488', brown: '#78716c', }; const SOURCE_META = { groups: { label: 'Занятия групп', icon: 'users', color: 'green', link: 'groups.html' }, lesson_reports: { label: 'Отчёты о занятиях', icon: 'notebook-pen', color: 'purple', link: 'lessons.html' }, digests: { label: 'Дайджест', icon: 'newspaper', color: 'orange', link: 'digest.html' }, }; const REPEAT_LABELS = { none: 'Не повторять', daily: 'Каждый день', weekly: 'Каждую неделю', monthly: 'Каждый месяц', yearly: 'Каждый год', }; const state = { view: 'week', anchorIso: '', items: [], sources: [], hidden: new Set(), rangeFrom: '', rangeTo: '', grid: null, uidMap: new Map(), editor: null, }; let nowTimer = null; let drag = null; function colorHex(name) { return COLOR_HEX[name] || COLOR_HEX.blue; } async function request(path, options) { const opts = options || {}; const res = await fetch(API + path, { method: opts.method || 'GET', headers: opts.body ? hdrJson() : hdr(), body: opts.body ? JSON.stringify(opts.body) : undefined, }); if (!res.ok) { let payload = null; try { payload = await res.json(); } catch {} throw new Error((payload && payload.error) || `Ошибка запроса (${res.status})`); } return res.json(); } function saveState() { try { localStorage.setItem('calView', state.view); localStorage.setItem('calAnchor', state.anchorIso); localStorage.setItem('calSources', JSON.stringify([...state.hidden])); } catch {} } function loadState() { let view = ''; let anchor = ''; let hidden = []; try { view = localStorage.getItem('calView') || ''; anchor = localStorage.getItem('calAnchor') || ''; hidden = JSON.parse(localStorage.getItem('calSources') || '[]'); } catch {} if (VIEWS.includes(view)) state.view = view; if (dtIsoMatch(anchor)) state.anchorIso = anchor; if (Array.isArray(hidden)) state.hidden = new Set(hidden.filter(x => typeof x === 'string')); if (!state.anchorIso) state.anchorIso = todayIso(); } function weekBounds(iso) { const dow = isoDow(iso); if (dow < 0) return { from: iso, to: iso }; const back = (dow - CAL_WEEK_START + 7) % 7; return { from: isoAddDays(iso, -back), to: isoAddDays(iso, 6 - back) }; } function monthBounds(iso) { const p = dtIsoMatch(iso); if (!p) return { from: iso, to: iso }; const y = Number(p.y); const m = Number(p.m); const ny = m === 12 ? y + 1 : y; const nm = m === 12 ? 1 : m + 1; const nextFirst = `${String(ny).padStart(4, '0')}-${String(nm).padStart(2, '0')}-01`; return { from: `${p.y}-${p.m}-01`, to: isoAddDays(nextFirst, -1) }; } function windowFor(view, anchor) { if (view === 'day') return { from: anchor, to: anchor }; if (view === 'week') return weekBounds(anchor); if (view === 'month') return monthBounds(anchor); return { from: anchor, to: isoAddDays(anchor, 29) }; } function monthAnchor(iso, step) { const p = dtIsoMatch(iso); if (!p) return todayIso(); const d = new Date(Date.UTC(Number(p.y), Number(p.m) - 1 + step, 1)); const y = d.getUTCFullYear(); const m = d.getUTCMonth() + 1; const first = `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-01`; const nextFirst = m === 12 ? `${y + 1}-01-01` : `${y}-${String(m + 1).padStart(2, '0')}-01`; const maxDay = Number(isoAddDays(nextFirst, -1).slice(8, 10)); return isoAddDays(first, Math.min(Number(p.d), maxDay) - 1); } function shiftAnchor(step) { if (state.view === 'day') return isoAddDays(state.anchorIso, step); if (state.view === 'week') return isoAddDays(state.anchorIso, step * 7); if (state.view === 'month') return monthAnchor(state.anchorIso, step); return isoAddDays(state.anchorIso, step * 30); } function queryWindow() { if (state.view !== 'month') return windowFor(state.view, state.anchorIso); const from = weekBounds(monthBounds(state.anchorIso).from).from; return { from, to: isoAddDays(from, 41) }; } function periodLabel() { const w = windowFor(state.view, state.anchorIso); if (state.view === 'day') return fmtDateOnlyLongIso(state.anchorIso); if (state.view === 'week') { const suffix = w.from.slice(0, 4) === w.to.slice(0, 4) ? ` ${w.to.slice(0, 4)}` : ''; return `${fmtDayMonthIso(w.from)} — ${fmtDayMonthIso(w.to)}${suffix}`; } if (state.view === 'month') return fmtMonthYearIso(state.anchorIso); return `${fmtDayMonthIso(w.from)} — ${fmtDayMonthIso(w.to)}`; } function localDateOf(instant) { return dtToLocalInput(instant).slice(0, 10); } function localHmOf(instant) { return dtToLocalInput(instant).slice(11, 16); } function toMinutes(hm) { const p = String(hm || '00:00').split(':').map(Number); return (p[0] || 0) * 60 + (p[1] || 0); } function hmFromMinutes(value) { const n = Math.max(0, Math.min(1440, Math.round(value))); if (n === 1440) return '00:00'; return `${String(Math.floor(n / 60)).padStart(2, '0')}:${String(n % 60).padStart(2, '0')}`; } function normalizedItems() { const out = []; if (!state.hidden.has('personal')) { for (const it of state.items) { const start = Date.parse(it.occurrence_start || it.starts_at); const end = Date.parse(it.occurrence_end || it.ends_at); if (!Number.isFinite(start) || !Number.isFinite(end)) continue; out.push({ uid: `p:${it.id}:${start}`, id: it.id, source: 'personal', title: it.title, start, end, seriesStart: it.starts_at, seriesEnd: it.ends_at, allDay: it.all_day === true, color: it.color, notes: it.notes || '', location: it.location || '', repeat: it.repeat_rule || 'none', repeatUntil: it.repeat_until, reminders: it.reminder_minutes || [], }); } } for (const src of state.sources) { if (state.hidden.has(src.id)) continue; for (const it of src.items) { const start = Date.parse(it.starts_at); const end = Date.parse(it.ends_at); if (!Number.isFinite(start) || !Number.isFinite(end)) continue; out.push({ uid: `s:${src.id}:${it.id}:${start}`, id: it.id, source: src.id, title: it.title, start, end, allDay: it.all_day === true, color: src.color, notes: '', location: '', repeat: 'none', reminders: [], link: it.link || SOURCE_META[src.id]?.link || '', }); } } return out.sort((a, b) => a.start - b.start || a.end - b.end); } function daySegments(iso, all) { const out = []; const dayStartIso = dtInputToIso(`${iso}T00:00`); const nextIso = isoAddDays(iso, 1); const dayStart = Date.parse(dayStartIso); const dayEnd = Date.parse(dtInputToIso(`${nextIso}T00:00`)); if (!Number.isFinite(dayStart) || !Number.isFinite(dayEnd)) return out; for (const item of all) { if (item.allDay) { const sDate = localDateOf(new Date(item.start).toISOString()); const span = Math.max(1, Math.ceil((item.end - item.start) / 86400000)); const eDate = isoAddDays(sDate, span - 1); if (iso >= sDate && iso <= eDate) out.push({ ...item, allDay: true, startMin: 0, endMin: 1440, continued: false }); continue; } const from = Math.max(item.start, dayStart); const to = Math.min(item.end, dayEnd); if (to <= from) continue; const startMin = toMinutes(localHmOf(new Date(from).toISOString())); const endMin = to >= dayEnd ? 1440 : toMinutes(localHmOf(new Date(to).toISOString())); if (endMin <= startMin) continue; out.push({ ...item, startMin, endMin, continued: item.start < dayStart || item.end > dayEnd, }); } return out.sort((a, b) => a.startMin - b.startMin || b.endMin - a.endMin); } function visibleHours(perDay) { let start = 7; let end = 23; for (const segs of perDay) { for (const seg of segs) { if (seg.allDay) continue; start = Math.min(start, Math.floor(seg.startMin / 60)); end = Math.max(end, Math.ceil(seg.endMin / 60)); } } start = Math.max(0, Math.min(23, start)); end = Math.max(start + 1, Math.min(24, end)); return { start, end }; } function layoutLanes(segs) { const sorted = [...segs].sort((a, b) => a.startMin - b.startMin || (b.endMin - b.startMin) - (a.endMin - a.startMin)); const out = []; let cluster = []; let clusterEnd = -1; function flush() { if (!cluster.length) return; const laneEnds = []; for (const seg of cluster) { let lane = laneEnds.findIndex(v => v <= seg.startMin); if (lane < 0) { lane = laneEnds.length; laneEnds.push(seg.endMin); } else { laneEnds[lane] = seg.endMin; } seg.lane = lane; } for (const seg of cluster) seg.lanes = laneEnds.length; out.push(...cluster); cluster = []; clusterEnd = -1; } for (const seg of sorted) { if (cluster.length && seg.startMin >= clusterEnd) flush(); cluster.push(seg); clusterEnd = Math.max(clusterEnd, seg.endMin); } flush(); return out; } function sourceIcon(item) { const meta = SOURCE_META[item.source]; return meta ? `` : ''; } function segmentHtml(seg, hours) { const top = (seg.startMin - hours.start * 60) / 60 * HOUR_H; const height = Math.max(20, (seg.endMin - seg.startMin) / 60 * HOUR_H - 2); const width = 100 / (seg.lanes || 1); const left = (seg.lane || 0) * width; const style = `--ev:${colorHex(seg.color)};top:${Math.round(top)}px;height:${Math.round(height)}px;left:${left.toFixed(3)}%;width:${(width - 0.4).toFixed(3)}%`; const time = height >= 34 ? `${esc(fmtHmStr(hmFromMinutes(seg.startMin)))}` : ''; const mark = seg.continued ? '↔ ' : ''; const title = `${mark}${esc(seg.title)}`; const cls = seg.source === 'personal' ? 'cal-event' : 'cal-event is-source'; return `
${sourceIcon(seg)}${time}${title}
`; } function allDayHtml(seg) { const cls = seg.source === 'personal' ? 'cal-allday-chip' : 'cal-allday-chip is-source'; return `
${esc(seg.title)}
`; } function nowTop(hours) { const min = toMinutes(nowHm()); if (min < hours.start * 60 || min > hours.end * 60) return null; return Math.round((min - hours.start * 60) / 60 * HOUR_H); } function renderGrid(days) { const all = normalizedItems(); const uidMap = new Map(); const perDay = days.map(iso => daySegments(iso, all)); all.forEach(item => uidMap.set(item.uid, item)); perDay.flat().forEach(seg => uidMap.set(seg.uid, seg)); state.uidMap = uidMap; const hours = visibleHours(perDay); const gridH = (hours.end - hours.start) * HOUR_H; const today = todayIso(); const todayIndex = days.indexOf(today); let html = `
`; html += '
'; days.forEach(iso => { const dow = isoDow(iso); html += `
${DOW_SHORT[dow] || ''}
${Number(iso.slice(8, 10))}
`; }); html += '
Весь день
'; perDay.forEach(segs => { html += '
'; segs.filter(s => s.allDay).forEach(seg => { html += allDayHtml(seg); }); html += '
'; }); html += '
'; for (let h = hours.start; h < hours.end; h++) { html += `
${esc(fmtHmStr(`${String(h).padStart(2, '0')}:00`))}
`; } const top = nowTop(hours); if (top !== null) html += `
${esc(fmtHmStr(nowHm()))}
`; html += '
'; days.forEach((iso, i) => { const timed = layoutLanes(perDay[i].filter(s => !s.allDay)); html += `
`; timed.forEach(seg => { html += segmentHtml(seg, hours); }); if (i === todayIndex && top !== null) html += `
`; html += '
'; }); html += '
'; document.getElementById('calBody').innerHTML = html; state.grid = { days, hours, gridH, today }; bindGridDrag(); startNowTick(); renderIcons(); } function renderMonth() { const bounds = monthBounds(state.anchorIso); const first = weekBounds(bounds.from).from; const days = Array.from({ length: 42 }, (_, i) => isoAddDays(first, i)); const all = normalizedItems(); const uidMap = new Map(); all.forEach(item => uidMap.set(item.uid, item)); state.uidMap = uidMap; const today = todayIso(); let html = '
'; for (let i = 0; i < 7; i++) { const dow = (CAL_WEEK_START + i) % 7; html += `
${DOW_SHORT[dow]}
`; } days.forEach(iso => { const outer = iso.slice(0, 7) !== bounds.from.slice(0, 7); const segs = daySegments(iso, all); html += `
`; html += `${iso === bounds.from ? `${Number(iso.slice(8, 10))} ${esc(fmtMonthYearIso(iso).split(' ')[0])}` : Number(iso.slice(8, 10))}`; segs.slice(0, 3).forEach(seg => { const time = seg.allDay ? '' : `${esc(fmtHmStr(hmFromMinutes(seg.startMin)))} `; const cls = seg.source === 'personal' ? 'cal-month-chip' : 'cal-month-chip is-source'; html += `
${time}${esc(seg.title)}
`; }); if (segs.length > 3) html += `
+ ещё ${segs.length - 3}
`; html += '
'; }); html += '
'; document.getElementById('calBody').innerHTML = html; state.grid = { days, hours: { start: 0, end: 24 }, gridH: 0, today }; stopNowTick(); } function renderAgenda() { const w = windowFor('agenda', state.anchorIso); const all = normalizedItems(); const uidMap = new Map(); all.forEach(item => uidMap.set(item.uid, item)); state.uidMap = uidMap; let day = w.from; let html = '
'; let count = 0; for (let i = 0; i < 30; i++) { const segs = daySegments(day, all); if (!segs.length) { day = isoAddDays(day, 1); continue; } count += segs.length; html += `
${esc(fmtDateOnlyLongIso(day))}
`; segs.forEach(seg => { const time = seg.allDay ? 'Весь день' : `${fmtHmStr(hmFromMinutes(seg.startMin))} – ${fmtHmStr(hmFromMinutes(seg.endMin))}`; const meta = [seg.location, seg.notes, seg.source !== 'personal' ? REPEAT_LABELS[seg.repeat] || '' : ''].filter(Boolean).join(' · '); html += `
${esc(time)}
${esc(seg.title)}
${meta ? `
${esc(meta)}
` : ''}
`; }); html += '
'; day = isoAddDays(day, 1); } if (!count) html += '
На этот период событий нет
'; html += '
'; document.getElementById('calBody').innerHTML = html; state.grid = null; stopNowTick(); } function renderBody() { if (state.view === 'week') { const from = weekBounds(state.anchorIso).from; renderGrid([0, 1, 2, 3, 4, 5, 6].map(i => isoAddDays(from, i))); } else if (state.view === 'day') renderGrid([state.anchorIso]); else if (state.view === 'month') renderMonth(); else renderAgenda(); } function renderHead() { document.getElementById('calLabel').textContent = periodLabel(); document.querySelectorAll('.cal-view-btn').forEach(btn => { btn.classList.toggle('on', btn.dataset.view === state.view); }); } function monthStepIso(step) { return monthAnchor(state.anchorIso, step); } function renderMini() { const anchor = state.anchorIso; document.getElementById('calMiniLabel').textContent = fmtMonthYearIso(anchor); document.getElementById('calMiniNav').innerHTML = ''; const bounds = monthBounds(anchor); const first = weekBounds(bounds.from).from; const today = todayIso(); let html = ''; for (let i = 0; i < 7; i++) html += `
${DOW_SHORT[(CAL_WEEK_START + i) % 7]}
`; for (let i = 0; i < 42; i++) { const iso = isoAddDays(first, i); const cls = [ 'cal-mini-day', iso.slice(0, 7) !== bounds.from.slice(0, 7) ? 'outer' : '', iso === today ? 'today' : '', iso === anchor ? 'selected' : '', ].filter(Boolean).join(' '); html += `
${Number(iso.slice(8, 10))}
`; } document.getElementById('calMini').innerHTML = html; } function renderSide() { document.getElementById('calCalendars').innerHTML = ``; document.getElementById('calSources').innerHTML = state.sources.map(src => { const meta = SOURCE_META[src.id] || {}; return ``; }).join('') || '
Нет данных за период
'; } function render() { renderHead(); renderMini(); renderSide(); renderBody(); renderIcons(); } function stopNowTick() { if (nowTimer) { clearInterval(nowTimer); nowTimer = null; } } function updateNowLine() { if (!state.grid || !state.grid.days) return; if (state.grid.today !== todayIso()) { render(); return; } const top = nowTop(state.grid.hours); if (top === null || !document.querySelector('.cal-now-label')) { renderBody(); return; } document.querySelectorAll('.cal-now').forEach(el => { el.style.top = `${top}px`; }); document.querySelectorAll('.cal-now-label').forEach(el => { el.style.top = `${top}px`; el.textContent = fmtHmStr(nowHm()); }); } function startNowTick() { stopNowTick(); nowTimer = setInterval(updateNowLine, 60000); } function snapMinute(y, el) { const rect = el.getBoundingClientRect(); const rel = Math.max(0, Math.min(state.grid.gridH, y - rect.top)); const raw = state.grid.hours.start * 60 + rel / HOUR_H * 60; return Math.max(state.grid.hours.start * 60, Math.min(state.grid.hours.end * 60, Math.round(raw / 30) * 30)); } function removeGhost() { if (drag && drag.ghost) drag.ghost.remove(); } function cancelDrag() { removeGhost(); drag = null; } function bindGridDrag() { document.querySelectorAll('.cal-day').forEach(el => { el.addEventListener('pointerdown', e => { if (e.button !== 0 || e.target.closest('.cal-event') || !state.grid) return; drag = { pointerId: e.pointerId, el, dayIso: el.dataset.day, startY: e.clientY, startMin: snapMinute(e.clientY, el), endMin: snapMinute(e.clientY, el), moved: false, ghost: null, }; try { el.setPointerCapture(e.pointerId); } catch {} e.preventDefault(); }); }); } document.addEventListener('pointermove', e => { if (!drag || e.pointerId !== drag.pointerId) return; drag.endMin = snapMinute(e.clientY, drag.el); if (Math.abs(e.clientY - drag.startY) > 4) drag.moved = true; if (!drag.moved) return; const from = Math.min(drag.startMin, drag.endMin); const to = Math.max(drag.startMin, drag.endMin); if (!drag.ghost) { drag.ghost = document.createElement('div'); drag.ghost.className = 'cal-drag'; drag.el.appendChild(drag.ghost); } const top = (from - state.grid.hours.start * 60) / 60 * HOUR_H; drag.ghost.style.top = `${top}px`; drag.ghost.style.height = `${Math.max(12, (to - from) / 60 * HOUR_H)}px`; }); document.addEventListener('pointerup', e => { if (!drag || e.pointerId !== drag.pointerId) return; const d = drag; let from = Math.min(d.startMin, d.endMin); let to = Math.max(d.startMin, d.endMin); if (!d.moved) { from = d.startMin; to = Math.min(state.grid.hours.end * 60, from + 60); } if (to - from < 30) to = Math.min(state.grid.hours.end * 60, from + 30); cancelDrag(); openEditor({ dateStart: d.dayIso, timeStart: hmFromMinutes(from), dateEnd: to >= 1440 ? isoAddDays(d.dayIso, 1) : d.dayIso, timeEnd: to >= 1440 ? '00:00' : hmFromMinutes(to), }); }); document.addEventListener('pointercancel', e => { if (drag && e.pointerId === drag.pointerId) cancelDrag(); }); function renderColors() { document.getElementById('calColors').innerHTML = COLORS.map(name => `` ).join(''); } function reminderLabel(n) { if (n === 0) return 'в момент события'; if (n === 1440) return 'за 1 день'; if (n === 60) return 'за 1 час'; if (n === 120) return 'за 2 часа'; return `за ${n} мин`; } function renderReminders() { document.getElementById('calReminders').innerHTML = state.editor.reminders.map(n => `${reminderLabel(n)} ×` ).join(''); } function syncAllDay() { const on = document.getElementById('calAllDay').checked; document.querySelectorAll('.cal-time').forEach(el => el.classList.toggle('cal-hidden', on)); document.getElementById('calRepeatUntilRow').classList.toggle('cal-hidden', document.getElementById('calRepeat').value === 'none'); } function openEditor(prefill) { const p = prefill || {}; state.editor = { id: p.id || null, color: COLORS.includes(p.color) ? p.color : 'blue', reminders: Array.isArray(p.reminders) ? [...p.reminders].sort((a, b) => a - b) : [], }; document.getElementById('calModalTitle').textContent = p.id ? 'Событие' : 'Новое событие'; document.getElementById('calTitle').value = p.title || ''; document.getElementById('calStartDate').value = p.dateStart || state.anchorIso; document.getElementById('calStartTime').value = p.timeStart || '10:00'; document.getElementById('calEndDate').value = p.dateEnd || p.dateStart || state.anchorIso; document.getElementById('calEndTime').value = p.timeEnd || '11:00'; document.getElementById('calAllDay').checked = p.allDay === true; document.getElementById('calRepeat').value = REPEAT_LABELS[p.repeat] ? p.repeat : 'none'; document.getElementById('calRepeatUntil').value = p.repeatUntil || ''; document.getElementById('calLocation').value = p.location || ''; document.getElementById('calNotes').value = p.notes || ''; document.getElementById('calDeleteBtn').classList.toggle('cal-hidden', !p.id); renderColors(); renderReminders(); syncAllDay(); document.getElementById('calEventModal').classList.add('open'); renderIcons(); document.getElementById('calTitle').focus(); } function closeEditor() { document.getElementById('calEventModal').classList.remove('open'); state.editor = null; } function openFromUid(uid) { const item = state.uidMap.get(uid); if (!item) return; if (item.source !== 'personal') { if (item.link) location.href = item.link; return; } const seriesStart = item.seriesStart || item.start; const seriesEnd = item.seriesEnd || item.end; const startLocal = item.id && seriesStart ? dtToLocalInput(seriesStart) : dtToLocalInput(new Date(item.start).toISOString()); const endLocal = item.allDay ? `${localDateOf(item.id && seriesEnd ? seriesEnd : new Date(item.end).toISOString())}T23:59` : dtToLocalInput(item.id && seriesEnd ? seriesEnd : new Date(item.end).toISOString()); openEditor({ id: item.id, title: item.title, color: item.color, notes: item.notes, location: item.location, repeat: item.repeat, repeatUntil: item.repeatUntil, reminders: item.reminders, allDay: item.allDay, dateStart: startLocal.slice(0, 10), timeStart: startLocal.slice(11, 16), dateEnd: endLocal.slice(0, 10), timeEnd: endLocal.slice(11, 16), }); } async function saveEditor() { if (!state.editor) return; const title = document.getElementById('calTitle').value.trim(); if (!title) { showToast('Укажите заголовок события', true); return; } const allDay = document.getElementById('calAllDay').checked; const startDate = document.getElementById('calStartDate').value; const endDate = document.getElementById('calEndDate').value; const startTime = allDay ? '00:00' : document.getElementById('calStartTime').value; const endTime = allDay ? '23:59' : document.getElementById('calEndTime').value; if (!startDate || !endDate || !/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate)) { showToast('Укажите даты события', true); return; } const startsAt = dtInputToIso(`${startDate}T${startTime}`); const endsAt = dtInputToIso(`${endDate}T${endTime}`); if (!startsAt || !endsAt) { showToast('Неверные дата или время', true); return; } const duration = Date.parse(endsAt) - Date.parse(startsAt); if (duration <= 0) { showToast('Окончание должно быть позже начала', true); return; } if (duration > 31 * 86400000) { showToast('Событие не может длиться больше 31 дня', true); return; } const repeat = document.getElementById('calRepeat').value; if (repeat !== 'none' && duration > 7 * 86400000) { showToast('Повторяющееся событие не может длиться больше 7 дней', true); return; } if (state.editor.reminders.length > 5) { showToast('Не больше 5 напоминаний', true); return; } const repeatUntil = repeat !== 'none' ? document.getElementById('calRepeatUntil').value : ''; if (repeatUntil && repeatUntil < startDate) { showToast('Повтор должен заканчиваться не раньше начала', true); return; } const body = { title, notes: document.getElementById('calNotes').value, location: document.getElementById('calLocation').value, color: state.editor.color, all_day: allDay, starts_at: startsAt, ends_at: endsAt, repeat_rule: repeat, repeat_until: repeatUntil || null, reminder_minutes: state.editor.reminders, }; const id = state.editor.id; try { await request(id ? `/api/calendar/events/${id}` : '/api/calendar/events', { method: id ? 'PUT' : 'POST', body, }); closeEditor(); showToast('Событие сохранено'); await reload(); } catch (e) { showToast(e.message, true); } } async function removeEditor() { if (!state.editor || !state.editor.id || !confirm('Удалить событие?')) return; try { await request(`/api/calendar/events/${state.editor.id}`, { method: 'DELETE' }); closeEditor(); showToast('Событие удалено'); await reload(); } catch (e) { showToast(e.message, true); } } async function loadRange() { const w = queryWindow(); const data = await request(`/api/calendar/events?from=${encodeURIComponent(w.from)}&to=${encodeURIComponent(w.to)}`); return { from: w.from, to: w.to, data }; } let reloadSeq = 0; async function reload() { const seq = ++reloadSeq; try { const result = await loadRange(); if (seq !== reloadSeq) return; state.rangeFrom = result.from; state.rangeTo = result.to; state.items = Array.isArray(result.data.items) ? result.data.items : []; state.sources = Array.isArray(result.data.sources) ? result.data.sources : []; render(); } catch (e) { if (seq !== reloadSeq) return; console.error('calendar load:', e); showToast(e.message || 'Не удалось загрузить календарь', true); } } function go(step) { state.anchorIso = shiftAnchor(step); saveState(); reload(); } function setView(view) { if (!VIEWS.includes(view) || view === state.view) return; state.view = view; saveState(); reload(); } function bindUi() { document.getElementById('calToday').addEventListener('click', () => { state.anchorIso = todayIso(); saveState(); reload(); }); document.getElementById('calPrev').addEventListener('click', () => go(-1)); document.getElementById('calNext').addEventListener('click', () => go(1)); document.getElementById('calViews').addEventListener('click', e => { const btn = e.target.closest('[data-view]'); if (btn) setView(btn.dataset.view); }); document.getElementById('calNewBtn').addEventListener('click', () => openEditor({ dateStart: state.anchorIso, timeStart: '10:00', dateEnd: state.anchorIso, timeEnd: '11:00', })); document.getElementById('calMiniNav').addEventListener('click', e => { const btn = e.target.closest('[data-mini-step]'); if (!btn) return; state.anchorIso = monthStepIso(Number(btn.dataset.miniStep)); saveState(); reload(); }); document.getElementById('calMini').addEventListener('click', e => { const el = e.target.closest('[data-mini-day]'); if (!el) return; state.anchorIso = el.dataset.miniDay; saveState(); reload(); }); document.getElementById('calCalendars').addEventListener('change', e => { const el = e.target.closest('[data-hidden]'); if (!el) return; if (el.checked) state.hidden.delete(el.dataset.hidden); else state.hidden.add(el.dataset.hidden); saveState(); render(); }); document.getElementById('calSources').addEventListener('change', e => { const el = e.target.closest('[data-hidden]'); if (!el) return; if (el.checked) state.hidden.delete(el.dataset.hidden); else state.hidden.add(el.dataset.hidden); saveState(); render(); }); document.getElementById('calBody').addEventListener('click', e => { const evEl = e.target.closest('[data-ev]'); if (evEl) { openFromUid(evEl.dataset.ev); return; } const dayNum = e.target.closest('[data-open-day]'); if (dayNum) { state.anchorIso = dayNum.dataset.openDay; state.view = 'day'; saveState(); reload(); return; } const cell = e.target.closest('[data-day]'); if (cell && (state.view === 'month' || state.view === 'agenda')) { openEditor({ dateStart: cell.dataset.day, dateEnd: cell.dataset.day, allDay: true, timeStart: '00:00', timeEnd: '23:59' }); } }); document.getElementById('calCloseBtn').addEventListener('click', closeEditor); document.getElementById('calCancelBtn').addEventListener('click', closeEditor); document.getElementById('calSaveBtn').addEventListener('click', saveEditor); document.getElementById('calDeleteBtn').addEventListener('click', removeEditor); document.getElementById('calAllDay').addEventListener('change', syncAllDay); document.getElementById('calRepeat').addEventListener('change', syncAllDay); document.getElementById('calColors').addEventListener('click', e => { const btn = e.target.closest('[data-color]'); if (!btn) return; state.editor.color = btn.dataset.color; renderColors(); }); document.getElementById('calReminders').addEventListener('click', e => { const chip = e.target.closest('[data-rem]'); if (!chip) return; state.editor.reminders = state.editor.reminders.filter(n => n !== Number(chip.dataset.rem)); renderReminders(); }); document.getElementById('calReminderAddBtn').addEventListener('click', () => { const n = Number(document.getElementById('calReminderAdd').value); if (state.editor.reminders.length >= 5) { showToast('Не больше 5 напоминаний', true); return; } if (!state.editor.reminders.includes(n)) state.editor.reminders.push(n); state.editor.reminders.sort((a, b) => a - b); renderReminders(); }); document.getElementById('calEventModal').addEventListener('click', e => { if (e.target.id === 'calEventModal') closeEditor(); }); document.addEventListener('keydown', e => { if (e.key === 'Escape') { if (drag) cancelDrag(); else if (document.getElementById('calEventModal').classList.contains('open')) closeEditor(); return; } if ((e.ctrlKey || e.metaKey) && e.key === 'Enter' && document.getElementById('calEventModal').classList.contains('open')) { e.preventDefault(); saveEditor(); } }); window.addEventListener('resize', () => { if (state.view === 'week' || state.view === 'day') renderGrid(state.grid ? state.grid.days : [state.anchorIso]); }); } async function init() { if (!(await checkAuth())) return; loadState(); buildSidebar(document.body.dataset.page); bindUi(); render(); await reload(); } init(); })();