let sidebarItems = []; let cidCounter = 0; function newCid() { return 'c' + (++cidCounter); } async function loadSidebarSettings() { const res = await fetch(`${API}/api/sidebar`, { headers: hdr() }); if (!res.ok) throw new Error('load failed'); const data = await res.json(); sidebarItems = (data.items || []).map(x => ({ ...x, _cid: newCid() })); renderSidebarSettings(); } function renderSidebarSettings() { const base = sidebarItems.filter(x => x.section === 'base').sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0) || String(a._cid).localeCompare(b._cid)); const admin = sidebarItems.filter(x => x.section === 'admin').sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0) || String(a._cid).localeCompare(b._cid)); document.getElementById('sidebarBaseList').innerHTML = base.map(renderSidebarItem).join(''); document.getElementById('sidebarAdminList').innerHTML = admin.map(renderSidebarItem).join(''); renderIcons(); bindSidebarDrag(); bindSidebarLabels(); bindSidebarDeletes(); ensureInsertButtons(); } function renderSidebarItem(it) { const disabled = it.enabled === false; const isTutor = it.section === 'base' && it.tutor_visible === true && it.enabled !== false; let statusCls = 'status-admin'; let statusText = 'Только админ'; if (disabled) { statusCls = 'status-off'; statusText = 'Отключён'; } else if (isTutor) { statusCls = 'status-tutor'; statusText = 'Доступно тьюторам'; } const handle = ``; let iconHtml = ''; let labelHtml = ''; if (it.kind === 'divider') { iconHtml = ``; labelHtml = ``; } else if (it.kind === 'group') { iconHtml = ``; labelHtml = ``; } else { iconHtml = ``; labelHtml = `
`; } const tutorToggle = (it.section === 'base' && it.kind === 'item') ? `` : ''; let enabledToggle = ''; if (it.kind === 'item' && it.page === 'sidebar') { enabledToggle = ``; } else { enabledToggle = ``; } return ``; } function bindSidebarDrag() { const lists = [document.getElementById('sidebarBaseList'), document.getElementById('sidebarAdminList')]; lists.forEach(list => { if (!list) return; list.querySelectorAll('.sidebar-item').forEach(item => { const handle = item.querySelector('.sidebar-item-handle'); if (!handle) return; handle.addEventListener('dragstart', e => { e.dataTransfer.setData('text/plain', item.dataset.cid); e.dataTransfer.effectAllowed = 'move'; item.classList.add('dragging'); }); handle.addEventListener('dragend', () => item.classList.remove('dragging')); }); list.addEventListener('dragover', e => { e.preventDefault(); const dragging = list.querySelector('.dragging'); if (!dragging) return; const after = getDragAfterElement(list, e.clientY); if (after == null) list.appendChild(dragging); else list.insertBefore(dragging, after); }); list.addEventListener('drop', e => { e.preventDefault(); lists.forEach(l => l.querySelectorAll('.sidebar-item').forEach(i => i.classList.remove('drag-over'))); }); }); document.querySelectorAll('[data-tutor]').forEach(cb => { cb.addEventListener('change', () => { const it = sidebarItems.find(x => x._cid === cb.dataset.tutor); if (it) it.tutor_visible = cb.checked; renderSidebarSettings(); }); }); document.querySelectorAll('[data-enabled]').forEach(cb => { cb.addEventListener('change', () => { const it = sidebarItems.find(x => x._cid === cb.dataset.enabled); if (!it) return; if (it.page === 'sidebar') return; it.enabled = cb.checked; renderSidebarSettings(); }); }); } function bindSidebarLabels() { document.querySelectorAll('[data-label]').forEach(inp => { inp.addEventListener('input', () => { const it = sidebarItems.find(x => x._cid === inp.dataset.label); if (it) it.label = inp.value; }); }); } function ensureInsertButtons() { ['sidebarBaseList', 'sidebarAdminList'].forEach(id => { const list = document.getElementById(id); if (!list) return; const card = list.parentElement; if (card.querySelector('.sidebar-add-row')) return; const section = id === 'sidebarBaseList' ? 'base' : 'admin'; const row = document.createElement('div'); row.className = 'sidebar-add-row'; row.style.cssText = 'display:flex;gap:8px;margin-top:8px;'; row.innerHTML = ``; card.appendChild(row); }); } function bindSidebarInserts() { document.querySelectorAll('[data-add]').forEach(btn => { btn.addEventListener('click', () => { const kind = btn.dataset.add; const section = btn.dataset.section; const siblings = sidebarItems.filter(x => x.section === section); const maxOrder = siblings.reduce((m, x) => Math.max(m, x.sort_order || 0), 0); const item = { id: null, _cid: newCid(), kind, page: null, label: kind === 'group' ? 'Новая группа' : '', icon: kind === 'divider' ? 'minus' : 'folder', section, sort_order: maxOrder + 10, tutor_visible: true, enabled: true, }; sidebarItems.push(item); renderSidebarSettings(); }); }); } function bindSidebarDeletes() { document.querySelectorAll('[data-del]').forEach(btn => { btn.addEventListener('click', () => { const cid = btn.dataset.del; sidebarItems = sidebarItems.filter(x => x._cid !== cid); renderSidebarSettings(); }); }); } function getDragAfterElement(container, y) { const els = [...container.querySelectorAll('.sidebar-item:not(.dragging)')]; let closest = { offset: Number.NEGATIVE_INFINITY, element: null }; for (const el of els) { const box = el.getBoundingClientRect(); const offset = y - box.top - box.height / 2; if (offset < 0 && offset > closest.offset) { closest = { offset, element: el }; } } return closest.element; } async function saveSidebarSettings() { const hint = document.getElementById('sidebarSaveHint'); const btn = document.getElementById('sidebarSaveBtn'); const ordered = []; ['sidebarBaseList', 'sidebarAdminList'].forEach(id => { const list = document.getElementById(id); if (!list) return; list.querySelectorAll('.sidebar-item').forEach((el, idx) => { const it = sidebarItems.find(x => x._cid === el.dataset.cid); if (it) { it.sort_order = (idx + 1) * 10; ordered.push(it); } }); }); btn.disabled = true; try { const payload = ordered.map(it => ({ id: it.id || undefined, kind: it.kind, page: it.page, label: it.label, icon: it.icon, section: it.section, sort_order: it.sort_order, tutor_visible: it.tutor_visible, enabled: it.enabled, })); const res = await fetch(`${API}/api/sidebar`, { method: 'PUT', headers: hdrJson(), body: JSON.stringify({ items: payload }), }); if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || 'save failed'); } hint.textContent = 'Сохранено'; hint.style.color = ''; await loadSidebarSettings(); } catch (e) { hint.textContent = 'Ошибка: ' + (e.message || ''); hint.style.color = '#ef4444'; } finally { btn.disabled = false; } } (async () => { if (await requireAdminPage()) { buildSidebar(document.body.dataset.page); try { await loadSidebarSettings(); } catch (e) { document.getElementById('sidebarSaveHint').textContent = 'Не удалось загрузить меню'; } document.getElementById('sidebarSaveBtn').addEventListener('click', saveSidebarSettings); bindSidebarInserts(); } })();