feat(sidebar): виды пунктов меню (item/divider/group), restore и upsert по id
- схема sidebar_items: колонка kind (item|divider|group), pagenullable, label с дефолтом '', constraint種別 - миграция для существующих БД: ADD COLUMN kind, DROP NOT NULL page, SET DEFAULT label, пересоздание constraint - restore: upsert по id (обновление существующих, вставка новых, удаление отсутствующих вpayload) - normalizeRestoreData: kind валидируется, filter по kind/item требует page+label - фронт: добавление разделителя/группы, удаление по cid, порядок из DOM через _cid, payload с kind/id
This commit is contained in:
@@ -27,6 +27,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.sidebar nav{display:flex;flex-direction:column;gap:10px;padding:0 8px}
|
||||
.nav-group{display:flex;flex-direction:column;gap:2px}
|
||||
.nav-group-title{font-size:.66rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);padding:6px 10px 4px;user-select:none;opacity:.8}
|
||||
.nav-divider{height:1px;background:var(--border);margin:6px 10px;opacity:.7}
|
||||
.nav-items{display:flex;flex-direction:column;gap:1px}
|
||||
|
||||
.sidebar nav a{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;color:var(--muted);text-decoration:none;font-size:.84rem;font-weight:500;line-height:1.3;transition:all .14s ease;position:relative}
|
||||
|
||||
+3
-1
@@ -117,13 +117,15 @@ function buildSidebar(active) {
|
||||
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' });
|
||||
const toNav = (i) => ({ page: i.page, label: i.label, icon: i.icon, kind: i.kind || 'item', 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 => {
|
||||
if (n.kind === 'divider') return `<div class="nav-divider"></div>`;
|
||||
if (n.kind === 'group') return `<div class="nav-group-title">${esc(n.label)}</div>`;
|
||||
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>` : '';
|
||||
|
||||
+112
-26
@@ -1,49 +1,65 @@
|
||||
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 }));
|
||||
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 - b.sort_order);
|
||||
const admin = sidebarItems.filter(x => x.section === 'admin').sort((a, b) => a.sort_order - b.sort_order);
|
||||
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;
|
||||
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 handle = `<span class="sidebar-item-handle" draggable="true" data-drag="${esc(it._cid)}" title="Перетащить"><i data-lucide="grip-vertical"></i></span>`;
|
||||
let iconHtml = '';
|
||||
let labelHtml = '';
|
||||
if (it.kind === 'divider') {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="minus"></i></span>`;
|
||||
labelHtml = `<input class="sidebar-item-label-input" data-label="${esc(it._cid)}" type="text" value="${esc(it.label || '')}" placeholder="Разделитель (подпись необязательна)">`;
|
||||
} else if (it.kind === 'group') {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="folder"></i></span>`;
|
||||
labelHtml = `<input class="sidebar-item-label-input" data-label="${esc(it._cid)}" type="text" value="${esc(it.label || '')}" placeholder="Название группы">`;
|
||||
} else {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="${esc(it.icon)}"></i></span>`;
|
||||
labelHtml = `<div class="sidebar-item-label">${esc(it.label)}<small>${esc(it.page)}</small></div>`;
|
||||
}
|
||||
const tutorToggle = (it.section === 'base' && it.kind === 'item')
|
||||
? `<label class="toggle"><input type="checkbox" data-tutor="${esc(it._cid)}" ${it.tutor_visible ? 'checked' : ''} ${disabled ? 'disabled' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Доступно тьюторам</b></span></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)}">
|
||||
let enabledToggle = '';
|
||||
if (it.kind === 'item' && it.page === 'sidebar') {
|
||||
enabledToggle = `<label class="toggle"><input type="checkbox" data-enabled="${esc(it._cid)}" checked disabled><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Включён</b></span></label>`;
|
||||
} else {
|
||||
enabledToggle = `<label class="toggle"><input type="checkbox" data-enabled="${esc(it._cid)}" ${it.enabled !== false ? 'checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Включён</b></span></label>`;
|
||||
}
|
||||
return `<div class="sidebar-item ${disabled ? 'disabled' : ''}" data-cid="${esc(it._cid)}" data-kind="${esc(it.kind)}" data-section="${esc(it.section)}" data-id="${it.id || ''}">
|
||||
${handle}
|
||||
${icon}
|
||||
<div class="sidebar-item-label">
|
||||
${esc(it.label)}
|
||||
<small>${esc(it.page)}</small>
|
||||
</div>
|
||||
${iconHtml}
|
||||
${labelHtml}
|
||||
<div class="sidebar-item-controls">
|
||||
${tutorToggle}
|
||||
${enabledToggle}
|
||||
<span class="sidebar-status ${statusCls}">${statusText}</span>
|
||||
${it.kind !== 'item' ? `<button type="button" class="icon-btn danger" data-del="${esc(it._cid)}" title="Удалить"><i data-lucide="trash-2"></i></button>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -56,7 +72,7 @@ function bindSidebarDrag() {
|
||||
const handle = item.querySelector('.sidebar-item-handle');
|
||||
if (!handle) return;
|
||||
handle.addEventListener('dragstart', e => {
|
||||
e.dataTransfer.setData('text/plain', item.dataset.page);
|
||||
e.dataTransfer.setData('text/plain', item.dataset.cid);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
item.classList.add('dragging');
|
||||
});
|
||||
@@ -75,19 +91,78 @@ function bindSidebarDrag() {
|
||||
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);
|
||||
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', () => {
|
||||
if (cb.dataset.enabled === 'sidebar') return;
|
||||
const it = sidebarItems.find(x => x.page === cb.dataset.enabled);
|
||||
if (it) it.enabled = cb.checked;
|
||||
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 = `<button type="button" class="btn-secondary" data-add="divider" data-section="${section}">+ Разделитель</button><button type="button" class="btn-secondary" data-add="group" data-section="${section}">+ Группа</button>`;
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -109,13 +184,12 @@ function getDragAfterElement(container, y) {
|
||||
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);
|
||||
const it = sidebarItems.find(x => x._cid === el.dataset.cid);
|
||||
if (it) {
|
||||
it.sort_order = (idx + 1) * 10;
|
||||
ordered.push(it);
|
||||
@@ -124,10 +198,21 @@ async function saveSidebarSettings() {
|
||||
});
|
||||
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: ordered }),
|
||||
body: JSON.stringify({ items: payload }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(() => ({}));
|
||||
@@ -153,5 +238,6 @@ async function saveSidebarSettings() {
|
||||
document.getElementById('sidebarSaveHint').textContent = 'Не удалось загрузить меню';
|
||||
}
|
||||
document.getElementById('sidebarSaveBtn').addEventListener('click', saveSidebarSettings);
|
||||
bindSidebarInserts();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -32,6 +32,18 @@
|
||||
}
|
||||
.sidebar-settings-warn i { flex: none; margin-top: 2px; }
|
||||
.sidebar-items { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sidebar-item .icon-btn.danger { color: #ef4444; }
|
||||
.sidebar-item .icon-btn.danger:hover { color: #dc2626; border-color: #ef4444; }
|
||||
.sidebar-item-label-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-size: .85rem;
|
||||
}
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Reference in New Issue
Block a user