feat(sidebar): настройка пунктов меню, порядок и доступность для тьюторов; подсветка admin-only

This commit is contained in:
dev
2026-11-02 22:34:14 +03:00
parent 0de5fd8774
commit b360ca8303
9 changed files with 555 additions and 10 deletions
+10
View File
@@ -1464,3 +1464,13 @@ body.report-card-open .report-fields{display:flex}
.chat-messages{max-height:none}
.msg{max-width:92%}
}
.nav-admin-only { opacity: .72; }
.nav-admin-only::after {
content: '';
display: inline-block;
width: 6px; height: 6px;
border-radius: 50%;
background: #94a3b8;
margin-left: 6px;
vertical-align: middle;
}
+30 -4
View File
@@ -1,6 +1,7 @@
const API = location.origin;
let token = sessionStorage.getItem('authToken');
let currentUser = null;
let sidebarConfig = null;
function hdr() { return { 'X-Auth-Token': token }; }
function hdrJson() { return { 'Content-Type': 'application/json', 'X-Auth-Token': token }; }
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
@@ -37,6 +38,7 @@ async function checkAuth() {
if (!res.ok) { cleanupSession(); return false; }
currentUser = await res.json();
await initDateTime();
await loadSidebarConfig();
return true;
} catch { cleanupSession(); return false; }
}
@@ -50,6 +52,15 @@ function cleanupSession() {
function isAdmin() { return currentUser && currentUser.role === 'admin'; }
async function loadSidebarConfig() {
try {
const res = await fetch(`${API}/api/sidebar`, { headers: hdr() });
if (!res.ok) return;
const data = await res.json();
sidebarConfig = Array.isArray(data.items) ? data.items : null;
} catch { sidebarConfig = null; }
}
async function requireAdminPage() {
if (!(await checkAuth())) return false;
if (!isAdmin()) { location.href = 'journal.html'; return false; }
@@ -65,8 +76,8 @@ async function doLogout() {
function buildSidebar(active) {
const el = document.getElementById('sidebar');
if (!el) return;
const base = [
{ page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard' },
const fallbackBase = [
{ page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard', section: 'base', tutorVisible: true },
{ page: 'profile', label: 'Профиль', icon: 'user' },
{ page: 'journal', label: 'Журнал', icon: 'book-open' },
{ page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen' },
@@ -85,7 +96,7 @@ function buildSidebar(active) {
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' },
];
const adminNav = [
const fallbackAdmin = [
{ page: 'settings', label: 'Настройки', icon: 'settings' },
{ page: 'modules', label: 'Темы модулей', icon: 'layers' },
{ page: 'users', label: 'Пользователи', icon: 'user-cog' },
@@ -95,14 +106,29 @@ function buildSidebar(active) {
{ page: 'faces', label: 'Сканер лиц', icon: 'scan-face' },
{ page: 'apikeys', label: 'API-ключи', icon: 'key-round' },
{ page: 'bans', label: 'Блокировки', icon: 'shield-off' },
{ page: 'sidebar', label: 'Меню', icon: 'panel-left' },
];
fallbackBase.forEach(i => { i.section = 'base'; i.tutorVisible = true; });
fallbackAdmin.forEach(i => { i.section = 'admin'; i.tutorVisible = false; });
let base = fallbackBase;
let adminNav = fallbackAdmin;
if (sidebarConfig) {
const sorted = [...sidebarConfig].sort((a, b) => {
if (a.section !== b.section) return a.section === 'base' ? -1 : 1;
return (a.sort_order || 0) - (b.sort_order || 0);
});
const toNav = (i) => ({ page: i.page, label: i.label, icon: i.icon, badge: i.page === 'notifications', chatBadge: i.page === 'chat' });
base = sorted.filter(i => i.section === 'base' && i.enabled !== false).map(toNav);
adminNav = sorted.filter(i => i.section === 'admin' && i.enabled !== false).map(toNav);
}
const userName = currentUser?.name || currentUser?.username || '';
const roleLabel = isAdmin() ? 'Администратор' : 'Тутор';
const renderItem = n => {
const isAct = n.page === active;
const adminOnly = n.section === 'admin' || n.tutorVisible === false;
const badgeHtml = n.badge ? `<span class="sidebar-badge" id="sidebarNotifyBadge" ${notifyUnread > 0 ? '' : 'hidden'}>${notifyUnread > 99 ? '99+' : notifyUnread}</span>` : '';
const chatBadgeHtml = n.chatBadge ? `<span class="sidebar-badge" id="sidebarChatBadge" ${chatUnread > 0 ? '' : 'hidden'}>${chatUnread > 99 ? '99+' : chatUnread}</span>` : '';
return `<a href="${n.page}.html" data-nav="${n.page}" class="${isAct ? 'active' : ''}" title="${n.label}">
return `<a href="${n.page}.html" data-nav="${n.page}" class="${isAct ? 'active' : ''} ${isAdmin() && adminOnly ? 'nav-admin-only' : ''}" title="${n.label}${isAdmin() && adminOnly ? ' (только администратор)' : ''}">
<i data-lucide="${n.icon}"></i>
<span class="nav-text">${n.label}</span>
${badgeHtml}
+157
View File
@@ -0,0 +1,157 @@
let sidebarItems = [];
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 }));
renderSidebarSettings();
}
function renderSidebarSettings() {
const base = sidebarItems.filter(x => x.section === 'base').sort((a, b) => a.sort_order - b.sort_order);
const admin = sidebarItems.filter(x => x.section === 'admin').sort((a, b) => a.sort_order - b.sort_order);
document.getElementById('sidebarBaseList').innerHTML = base.map(renderSidebarItem).join('');
document.getElementById('sidebarAdminList').innerHTML = admin.map(renderSidebarItem).join('');
renderIcons();
bindSidebarDrag();
}
function renderSidebarItem(it) {
const disabled = it.enabled === false;
const isTutor = it.section === 'base' && it.tutor_visible === true && it.enabled !== false;
const isAdminOnly = it.section === 'admin' || it.tutor_visible === false;
let statusCls = 'status-admin';
let statusText = 'Только админ';
if (disabled) { statusCls = 'status-off'; statusText = 'Отключён'; }
else if (isTutor) { statusCls = 'status-tutor'; statusText = 'Доступно тьюторам'; }
const handle = `<span class="sidebar-item-handle" draggable="true" data-drag="${esc(it.page)}" title="Перетащить"><i data-lucide="grip-vertical"></i></span>`;
const icon = `<span class="sidebar-item-icon"><i data-lucide="${esc(it.icon)}"></i></span>`;
const tutorToggle = it.section === 'base'
? `<label class="sidebar-toggle"><input type="checkbox" data-tutor="${esc(it.page)}" ${it.tutor_visible ? 'checked' : ''} ${disabled ? 'disabled' : ''}> Доступно тьюторам</label>`
: '';
const enabledToggle = it.page === 'sidebar'
? `<label class="sidebar-toggle"><input type="checkbox" data-enabled="${esc(it.page)}" checked disabled> Включён</label>`
: `<label class="sidebar-toggle"><input type="checkbox" data-enabled="${esc(it.page)}" ${it.enabled !== false ? 'checked' : ''}> Включён</label>`;
return `<div class="sidebar-item ${disabled ? 'disabled' : ''}" data-page="${esc(it.page)}" data-section="${esc(it.section)}">
${handle}
${icon}
<div class="sidebar-item-label">
${esc(it.label)}
<small>${esc(it.page)}</small>
</div>
<div class="sidebar-item-controls">
${tutorToggle}
${enabledToggle}
<span class="sidebar-status ${statusCls}">${statusText}</span>
</div>
</div>`;
}
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.page);
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')));
});
});
// sync toggles
document.querySelectorAll('[data-tutor]').forEach(cb => {
cb.addEventListener('change', () => {
const it = sidebarItems.find(x => x.page === cb.dataset.tutor);
if (it) it.tutor_visible = cb.checked;
renderSidebarSettings();
});
});
document.querySelectorAll('[data-enabled]').forEach(cb => {
cb.addEventListener('change', () => {
if (cb.dataset.enabled === 'sidebar') return;
const it = sidebarItems.find(x => x.page === cb.dataset.enabled);
if (it) it.enabled = cb.checked;
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');
// rebuild order from DOM
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.page === el.dataset.page);
if (it) {
it.sort_order = (idx + 1) * 10;
ordered.push(it);
}
});
});
btn.disabled = true;
try {
const res = await fetch(`${API}/api/sidebar`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ items: ordered }),
});
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);
}
})();
+162
View File
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Меню — Админ-панель</title>
<link rel="stylesheet" href="admin.css">
<style>
.sidebar-settings-wrap { display: flex; flex-direction: column; gap: 20px; max-width: 920px; }
.sidebar-settings-card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 12px;
padding: 18px 20px;
display: flex;
flex-direction: column;
gap: 12px;
}
.sidebar-settings-card h3 { margin: 0; font-size: 1.05rem; display: flex; align-items: center; gap: 8px; }
.sidebar-settings-card .hint { font-size: .82rem; color: var(--muted); line-height: 1.5; margin: 0; }
.sidebar-settings-warn {
background: rgba(245,158,11,.10);
border: 1px solid rgba(245,158,11,.35);
color: #b45309;
border-radius: 10px;
padding: 12px 14px;
font-size: .85rem;
line-height: 1.5;
display: flex;
align-items: flex-start;
gap: 10px;
}
.sidebar-settings-warn i { flex: none; margin-top: 2px; }
.sidebar-items { display: flex; flex-direction: column; gap: 6px; }
.sidebar-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 10px;
transition: box-shadow .15s, opacity .15s, transform .15s;
}
.sidebar-item.dragging { opacity: .4; border-style: dashed; }
.sidebar-item.drag-over { box-shadow: 0 0 0 2px var(--accent); }
.sidebar-item.disabled { opacity: .5; }
.sidebar-item-handle {
cursor: grab;
color: var(--muted);
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: 6px;
flex: none;
}
.sidebar-item-handle:hover { color: var(--text); background: rgba(127,127,127,.15); }
.sidebar-item-handle:active { cursor: grabbing; }
.sidebar-item-icon {
width: 32px;
height: 32px;
border-radius: 8px;
display: inline-flex;
align-items: center;
justify-content: center;
background: rgba(127,127,127,.12);
color: var(--text);
flex: none;
}
.sidebar-item-icon svg { width: 16px; height: 16px; }
.sidebar-item-label {
flex: 1;
min-width: 0;
font-weight: 600;
font-size: .9rem;
display: flex;
flex-direction: column;
gap: 2px;
}
.sidebar-item-label small { font-weight: 400; color: var(--muted); font-size: .75rem; }
.sidebar-item-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.sidebar-toggle {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: .8rem;
color: var(--text);
cursor: pointer;
user-select: none;
}
.sidebar-toggle input { width: 16px; height: 16px; accent-color: var(--accent); cursor: pointer; }
.sidebar-status {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 9px;
border-radius: 999px;
font-size: .72rem;
font-weight: 600;
white-space: nowrap;
}
.sidebar-status.status-tutor { background: rgba(34,197,94,.14); color: #15803d; }
.sidebar-status.status-admin { background: rgba(127,127,127,.16); color: var(--muted); }
.sidebar-status.status-off { background: rgba(239,68,68,.12); color: #dc2626; }
.sidebar-settings-foot {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
padding-top: 8px;
border-top: 1px solid var(--border);
}
.sidebar-settings-foot .btn-primary { min-width: 140px; }
.sidebar-settings-foot .save-hint { font-size: .82rem; color: var(--muted); }
@media (max-width: 720px) {
.sidebar-item { flex-wrap: wrap; }
.sidebar-item-controls { width: 100%; justify-content: flex-start; }
}
</style>
</head>
<body data-page="sidebar">
<div class="layout">
<div class="sidebar" id="sidebar"></div>
<div class="main">
<div class="page-head">
<h2>Настройка меню</h2>
<p class="page-sub">Порядок и доступность пунктов бокового меню для пользователей</p>
</div>
<div class="sidebar-settings-wrap">
<div class="sidebar-settings-warn">
<i data-lucide="alert-triangle"></i>
<div>
<strong>Важно:</strong> скрытие пункта не закрывает страницу по прямой ссылке — доступ к URL по-прежнему определяется правами пользователя.
Пункты раздела «Администрирование» всегда видны только администраторам.
</div>
</div>
<div class="sidebar-settings-card">
<h3><i data-lucide="layout-list"></i> Основное меню</h3>
<p class="hint">Перетащите пункты, чтобы изменить порядок. Включите «Доступно тьюторам», чтобы пункт появился у пользователей без прав администратора.</p>
<div class="sidebar-items" id="sidebarBaseList"></div>
</div>
<div class="sidebar-settings-card">
<h3><i data-lucide="shield-check"></i> Администрирование</h3>
<p class="hint">Эти пункты видны только администраторам. Можно отключить отдельные пункты, если они не нужны.</p>
<div class="sidebar-items" id="sidebarAdminList"></div>
</div>
<div class="sidebar-settings-foot">
<button type="button" class="btn-primary" id="sidebarSaveBtn"><i data-lucide="save"></i> Сохранить</button>
<span class="save-hint" id="sidebarSaveHint"></span>
</div>
</div>
</div>
</div>
<script src="vendor/lucide.min.js"></script>
<script src="js/datetime.js"></script>
<script src="admin.js"></script>
<script src="js/sidebar-settings.js"></script>
</body>
</html>