Files
WhatIDo/public/js/calendar.js
T

1010 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(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,
users: [], ownerFilter: '',
};
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]));
localStorage.setItem('calOwner', state.ownerFilter);
} catch {}
}
function loadState() {
let view = '';
let anchor = '';
let hidden = [];
try {
view = localStorage.getItem('calView') || '';
anchor = localStorage.getItem('calAnchor') || '';
hidden = JSON.parse(localStorage.getItem('calSources') || '[]');
state.ownerFilter = isAdmin() ? (localStorage.getItem('calOwner') || '') : '';
} 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 userLabel(u) {
return u.name || u.username || `#${u.id}`;
}
function userOption(u) {
return `<option value="${u.id}">${esc(userLabel(u))}${u.role === 'admin' ? ' (админ)' : ''}</option>`;
}
async function loadUsers() {
if (!isAdmin()) return;
try {
const data = await request('/api/calendar/users');
state.users = Array.isArray(data.items) ? data.items : [];
} catch (e) {
console.error('calendar users:', e);
state.users = [];
}
}
function renderUserFilter() {
const sel = document.getElementById('calUserFilter');
sel.closest('.cal-user-filter').classList.toggle('cal-hidden', !isAdmin());
if (!isAdmin()) return;
sel.innerHTML = '<option value="">Все пользователи</option>' + state.users.map(userOption).join('');
sel.value = state.ownerFilter;
if (sel.value !== state.ownerFilter) {
state.ownerFilter = sel.value;
saveState();
}
}
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 || [],
ownerId: it.user_id || null, ownerName: it.user_name || '',
isCommon: it.is_common === true,
readOnly: it.is_common === true && !isAdmin(),
assigned: isAdmin() && it.is_common !== true && Number(it.user_id) !== Number(currentUser.id),
});
}
}
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 ? `<i data-lucide="${meta.icon}"></i>` : '';
}
function eventOwnerLabel(seg) {
if (seg.isCommon) return '<span class="cal-owner">Общее: </span>';
return seg.assigned && seg.ownerName ? `<span class="cal-owner">${esc(seg.ownerName)}: </span>` : '';
}
function eventClass(base, seg) {
return `${base}${seg.isCommon ? ' is-common' : ''}${seg.assigned ? ' is-assigned' : ''}`;
}
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 ? `<span class="cal-event-time">${esc(fmtHmStr(hmFromMinutes(seg.startMin)))}</span>` : '';
const mark = seg.continued ? '↔ ' : '';
const owner = eventOwnerLabel(seg);
const title = `${mark}${esc(seg.title)}`;
const cls = seg.source === 'personal' ? eventClass('cal-event', seg) : 'cal-event is-source';
return `<div class="${cls}" style="${style}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${sourceIcon(seg)}${time}${owner}${title}</div>`;
}
function allDayHtml(seg) {
const cls = seg.source === 'personal' ? eventClass('cal-allday-chip', seg) : 'cal-allday-chip is-source';
const owner = eventOwnerLabel(seg);
return `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${owner}${esc(seg.title)}</div>`;
}
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 = `<div class="cal-grid" style="--cal-days:${days.length};--cal-grid-h:${gridH}px">`;
html += '<div class="cal-corner"></div>';
days.forEach(iso => {
const dow = isoDow(iso);
html += `<div class="cal-dayhead${iso === today ? ' is-today' : ''}"><div class="cal-dow">${DOW_SHORT[dow] || ''}</div><div class="cal-datenum">${Number(iso.slice(8, 10))}</div></div>`;
});
html += '<div class="cal-allday-label">Весь день</div>';
perDay.forEach(segs => {
html += '<div class="cal-allday-cell">';
segs.filter(s => s.allDay).forEach(seg => { html += allDayHtml(seg); });
html += '</div>';
});
html += '<div class="cal-gutter">';
for (let h = hours.start; h < hours.end; h++) {
html += `<div class="cal-hour-label" style="top:${(h - hours.start) * HOUR_H}px">${esc(fmtHmStr(`${String(h).padStart(2, '0')}:00`))}</div>`;
}
const top = nowTop(hours);
if (top !== null) html += `<div class="cal-now-label" style="top:${top}px">${esc(fmtHmStr(nowHm()))}</div>`;
html += '</div>';
days.forEach((iso, i) => {
const timed = layoutLanes(perDay[i].filter(s => !s.allDay));
html += `<div class="cal-day${iso === today ? ' is-today' : ''}" data-day="${iso}">`;
timed.forEach(seg => { html += segmentHtml(seg, hours); });
if (i === todayIndex && top !== null) html += `<div class="cal-now" style="top:${top}px"></div>`;
html += '</div>';
});
html += '</div>';
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 = '<div class="cal-month-grid">';
for (let i = 0; i < 7; i++) {
const dow = (CAL_WEEK_START + i) % 7;
html += `<div class="cal-month-dow${dow === 0 || dow === 6 ? ' weekend' : ''}">${DOW_SHORT[dow]}</div>`;
}
days.forEach(iso => {
const outer = iso.slice(0, 7) !== bounds.from.slice(0, 7);
const segs = daySegments(iso, all);
html += `<div class="cal-month-cell${outer ? ' outer' : ''}${iso === today ? ' is-today' : ''}" data-day="${iso}">`;
html += `<span class="cal-month-num" data-open-day="${iso}">${iso === bounds.from ? `${Number(iso.slice(8, 10))} ${esc(fmtMonthYearIso(iso).split(' ')[0])}` : Number(iso.slice(8, 10))}</span>`;
segs.slice(0, 3).forEach(seg => {
const time = seg.allDay ? '' : `${esc(fmtHmStr(hmFromMinutes(seg.startMin)))} `;
const cls = seg.source === 'personal' ? eventClass('cal-month-chip', seg) : 'cal-month-chip is-source';
const owner = eventOwnerLabel(seg);
html += `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${time}${owner}${esc(seg.title)}</div>`;
});
if (segs.length > 3) html += `<div class="cal-more">+ ещё ${segs.length - 3}</div>`;
html += '</div>';
});
html += '</div>';
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 = '<div class="cal-agenda">';
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 += `<div class="cal-agenda-day"><div class="cal-agenda-date">${esc(fmtDateOnlyLongIso(day))}</div>`;
segs.forEach(seg => {
const time = seg.allDay ? 'Весь день' : `${fmtHmStr(hmFromMinutes(seg.startMin))} – ${fmtHmStr(hmFromMinutes(seg.endMin))}`;
const meta = [seg.isCommon ? 'Общее событие' : (seg.assigned ? seg.ownerName : ''), seg.location, seg.notes, seg.source !== 'personal' ? REPEAT_LABELS[seg.repeat] || '' : ''].filter(Boolean).join(' · ');
html += `<div class="cal-agenda-row" data-ev="${attrEsc(seg.uid)}"><span class="cal-agenda-time">${esc(time)}</span><span class="cal-dot" style="--ev:${colorHex(seg.color)}"></span><div class="cal-agenda-body"><div class="cal-agenda-title">${esc(seg.title)}</div>${meta ? `<div class="cal-agenda-meta">${esc(meta)}</div>` : ''}</div></div>`;
});
html += '</div>';
day = isoAddDays(day, 1);
}
if (!count) html += '<div class="cal-empty">На этот период событий нет</div>';
html += '</div>';
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 = '<button class="cal-nav-btn" type="button" data-mini-step="-1" aria-label="Предыдущий месяц">‹</button><button class="cal-nav-btn" type="button" data-mini-step="1" aria-label="Следующий месяц">›</button>';
const bounds = monthBounds(anchor);
const first = weekBounds(bounds.from).from;
const today = todayIso();
let html = '';
for (let i = 0; i < 7; i++) html += `<div class="cal-mini-dow">${DOW_SHORT[(CAL_WEEK_START + i) % 7]}</div>`;
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 += `<div class="${cls}" data-mini-day="${iso}">${Number(iso.slice(8, 10))}</div>`;
}
document.getElementById('calMini').innerHTML = html;
}
function renderSide() {
const personalLabel = isAdmin() && !state.ownerFilter ? 'Все события' : 'Личный';
document.getElementById('calCalendars').innerHTML =
`<label class="cal-personal-row" style="--ev:${COLOR_HEX.blue}"><input type="checkbox" data-hidden="personal" ${state.hidden.has('personal') ? '' : 'checked'}><span class="cal-dot"></span><span class="cal-source-label">${personalLabel}</span></label>`;
document.getElementById('calSources').innerHTML = state.sources.map(src => {
const meta = SOURCE_META[src.id] || {};
return `<label class="cal-source-row" style="--ev:${colorHex(src.color)}"><input type="checkbox" data-hidden="${attrEsc(src.id)}" ${state.hidden.has(src.id) ? '' : 'checked'}><span class="cal-dot"></span>${meta.icon ? `<i data-lucide="${meta.icon}"></i>` : ''}<span class="cal-source-label">${esc(meta.label || src.label || src.id)}</span><span class="cal-source-count">${(src.items || []).length}</span></label>`;
}).join('') || '<div class="cal-source-count">Нет данных за период</div>';
}
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 =>
`<button class="cal-color${name === state.editor.color ? ' on' : ''}" type="button" data-color="${name}" style="--ev:${COLOR_HEX[name]}" aria-label="${name}"${state.editor.readOnly ? ' disabled' : ''}></button>`
).join('');
}
function updateAssigneeHint() {
if (!state.editor || !isAdmin()) return;
const hint = document.getElementById('calAssigneeHint');
if (state.editor.isCommon) hint.textContent = 'Видно всем пользователям, включая новых';
else if (state.editor.id) hint.textContent = 'При редактировании можно выбрать одного пользователя';
else {
const count = state.editor.selectedUserIds.length;
hint.textContent = count ? `Выбрано пользователей: ${count}` : 'Выберите хотя бы одного пользователя';
}
}
function renderAssignee() {
const row = document.getElementById('calAssigneeRow');
row.classList.toggle('cal-hidden', !isAdmin());
if (!isAdmin() || !state.editor) return;
const editor = state.editor;
const selected = new Set(editor.selectedUserIds.map(Number));
const known = new Set(state.users.map(u => Number(u.id)));
document.getElementById('calAssigneeCommon').checked = editor.isCommon;
document.getElementById('calAssigneeBox').classList.toggle('is-common', editor.isCommon);
document.getElementById('calAssigneeList').innerHTML =
state.users.map(u => {
const id = Number(u.id);
return `<label><input type="checkbox" data-user="${id}"${selected.has(id) ? ' checked' : ''}><span>${esc(userLabel(u))}${u.role === 'admin' ? ' (админ)' : ''}</span></label>`;
}).join('') +
[...selected].filter(id => !known.has(id)).map(id =>
`<label title="Пользователь недоступен"><input type="checkbox" checked disabled><span>#${id} (недоступен)</span></label>`
).join('');
updateAssigneeHint();
}
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 =>
`<span class="cal-rem-chip" data-rem="${n}" role="button" tabindex="0">${reminderLabel(n)}${state.editor.readOnly ? '' : ' ×'}</span>`
).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 setEditorReadOnly(readOnly) {
const ids = ['calTitle', 'calStartDate', 'calStartTime', 'calEndDate', 'calEndTime', 'calAllDay',
'calRepeat', 'calRepeatUntil', 'calLocation', 'calNotes', 'calReminderAdd', 'calReminderAddBtn'];
ids.forEach(id => {
const el = document.getElementById(id);
if (el) el.disabled = readOnly;
});
document.getElementById('calSaveBtn').classList.toggle('cal-hidden', readOnly);
document.getElementById('calDeleteBtn').classList.add('cal-hidden');
if (!readOnly) document.getElementById('calDeleteBtn').classList.toggle('cal-hidden', !state.editor || !state.editor.id);
}
function openEditor(prefill) {
const p = prefill || {};
const admin = isAdmin();
const ownerId = p.ownerId ? Number(p.ownerId) : (currentUser ? Number(currentUser.id) : null);
const selectedUserIds = Array.isArray(p.selectedUserIds)
? [...new Set(p.selectedUserIds.map(Number))]
: (admin && ownerId ? [ownerId] : []);
state.editor = {
id: p.id || null,
ownerId,
isCommon: p.isCommon === true,
readOnly: p.readOnly === true,
selectedUserIds,
originalUserIds: [...selectedUserIds],
color: COLORS.includes(p.color) ? p.color : 'blue',
reminders: Array.isArray(p.reminders) ? [...p.reminders].sort((a, b) => a - b) : [],
};
const title = state.editor.isCommon || state.editor.readOnly
? 'Общее событие'
: (p.id ? 'Событие' : 'Новое событие');
document.getElementById('calModalTitle').textContent = title;
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 || '';
setEditorReadOnly(state.editor.readOnly);
renderAssignee();
renderColors();
renderReminders();
syncAllDay();
document.getElementById('calEventModal').classList.add('open');
renderIcons();
(state.editor.readOnly ? document.getElementById('calCancelBtn') : 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,
ownerId: item.ownerId, isCommon: item.isCommon, readOnly: item.readOnly,
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 || state.editor.readOnly) return;
const editor = state.editor;
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 (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: editor.color, all_day: allDay, starts_at: startsAt, ends_at: endsAt,
repeat_rule: repeat, repeat_until: repeatUntil || null,
reminder_minutes: editor.reminders,
};
if (isAdmin()) {
if (editor.isCommon) {
body.is_common = true;
} else {
const selected = [...new Set(editor.selectedUserIds.map(Number))].filter(n => Number.isInteger(n) && n > 0);
if (!selected.length) { showToast('Выберите пользователя', true); return; }
const unavailable = selected.filter(id => !state.users.some(u => Number(u.id) === id));
const unchanged = editor.id && selected.length === editor.originalUserIds.length &&
selected.every(id => editor.originalUserIds.includes(id));
if (unavailable.length) {
if (!(unavailable.length === selected.length && unchanged)) {
showToast('Выбранный пользователь недоступен', true);
return;
}
} else {
body.user_ids = selected;
}
}
}
const id = editor.id;
try {
const result = await request(id ? `/api/calendar/events/${id}` : '/api/calendar/events', {
method: id ? 'PUT' : 'POST', body,
});
const count = id ? 1 : (Array.isArray(result.items) ? result.items.length : 1);
closeEditor();
showToast(count > 1 ? `События сохранены: ${count}` : 'Событие сохранено');
if (!id && !editor.isCommon && state.ownerFilter &&
!editor.selectedUserIds.some(uid => String(uid) === state.ownerFilter)) {
state.ownerFilter = '';
saveState();
renderUserFilter();
}
await reload();
} catch (e) {
showToast(e.message, true);
}
}
async function removeEditor() {
if (!state.editor || state.editor.readOnly || !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();
let path = `/api/calendar/events?from=${encodeURIComponent(w.from)}&to=${encodeURIComponent(w.to)}`;
if (isAdmin() && state.ownerFilter) path += `&user_id=${encodeURIComponent(state.ownerFilter)}`;
const data = await request(path);
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('calUserFilter').addEventListener('change', e => {
state.ownerFilter = e.target.value;
saveState();
reload();
});
document.getElementById('calAssigneeCommon').addEventListener('change', e => {
if (!state.editor) return;
state.editor.isCommon = e.target.checked;
renderAssignee();
});
document.getElementById('calAssigneeAllBtn').addEventListener('click', () => {
if (!state.editor || state.editor.isCommon) return;
state.editor.selectedUserIds = state.users.map(u => Number(u.id));
renderAssignee();
});
document.getElementById('calAssigneeList').addEventListener('change', e => {
const input = e.target.closest('input[data-user]');
if (!input || input.disabled || !state.editor || state.editor.isCommon) return;
const uid = Number(input.dataset.user);
if (state.editor.id) {
state.editor.selectedUserIds = input.checked ? [uid] : [];
} else if (input.checked) {
if (!state.editor.selectedUserIds.includes(uid)) state.editor.selectedUserIds.push(uid);
} else {
state.editor.selectedUserIds = state.editor.selectedUserIds.filter(id => id !== uid);
}
renderAssignee();
});
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 || !state.editor || state.editor.readOnly) return;
state.editor.color = btn.dataset.color;
renderColors();
});
document.getElementById('calReminders').addEventListener('click', e => {
const chip = e.target.closest('[data-rem]');
if (!chip || !state.editor || state.editor.readOnly) return;
state.editor.reminders = state.editor.reminders.filter(n => n !== Number(chip.dataset.rem));
renderReminders();
});
document.getElementById('calReminderAddBtn').addEventListener('click', () => {
if (!state.editor || state.editor.readOnly) return;
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();
await loadUsers();
buildSidebar(document.body.dataset.page);
bindUi();
renderUserFilter();
render();
await reload();
}
init();
})();