Files
dev f634d88cae feat(sidebar): метки внимания на пунктах меню
- 개인 метки пользователя в user_settings.sidebar_marks (JSON-массив id страниц)
- normalizeSidebarMarks() в lib/sidebar.js с валидацией (^[A-Za-z0-9_.-]+$, <=64 символов)
- точечные индикаторы .nav-dot на пунктах сайдбара, клик/Enter/пробел toggle
- сохранение через PUT /api/user-settings с очередью (keepalive), кэш в localStorage
- синхронизация между вкладками через событие storage
2026-12-02 21:53:17 +03:00

135 lines
8.7 KiB
JavaScript

const DEFAULT_ITEMS = [
{ page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard', section: 'base', sort_order: 10, tutor_visible: true, enabled: true },
{ page: 'profile', label: 'Профиль', icon: 'user', section: 'base', sort_order: 20, tutor_visible: true, enabled: true },
{ page: 'journal', label: 'Журнал', icon: 'book-open', section: 'base', sort_order: 30, tutor_visible: true, enabled: true },
{ page: 'calendar', label: 'Календарь', icon: 'calendar-days', section: 'base', sort_order: 35, tutor_visible: true, enabled: true },
{ page: 'quizzes', label: 'Тесты и опросы', icon: 'clipboard-list', section: 'base', sort_order: 37, tutor_visible: true, enabled: true },
{ page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen', section: 'base', sort_order: 40, tutor_visible: true, enabled: true },
{ page: 'postlesson', label: 'Задачи после занятия', icon: 'list-checks', section: 'base', sort_order: 50, tutor_visible: true, enabled: true },
{ page: 'students', label: 'Ученики', icon: 'graduation-cap', section: 'base', sort_order: 60, tutor_visible: true, enabled: true },
{ page: 'groups', label: 'Группы', icon: 'users', section: 'base', sort_order: 70, tutor_visible: true, enabled: true },
{ page: 'feedback', label: 'Обратная связь', icon: 'message-square-heart', section: 'base', sort_order: 80, tutor_visible: true, enabled: true },
{ page: 'shorts', label: 'Короткие сообщения', icon: 'zap', section: 'base', sort_order: 90, tutor_visible: true, enabled: true },
{ page: 'digest', label: 'Дайджест', icon: 'newspaper', section: 'base', sort_order: 95, tutor_visible: true, enabled: true },
{ page: 'chat', label: 'Чаты', icon: 'messages-square', section: 'base', sort_order: 100, tutor_visible: true, enabled: true },
{ page: 'notifications', label: 'Уведомления', icon: 'bell', section: 'base', sort_order: 110, tutor_visible: true, enabled: true },
{ page: 'photos', label: 'Фото', icon: 'Image', section: 'base', sort_order: 120, tutor_visible: true, enabled: true },
{ page: 'files', label: 'Файлы', icon: 'folder', section: 'base', sort_order: 130, tutor_visible: true, enabled: true },
{ page: 'links', label: 'Ссылки', icon: 'link', section: 'base', sort_order: 140, tutor_visible: true, enabled: true },
{ page: 'bookmarks', label: 'Закладки', icon: 'bookmark', section: 'base', sort_order: 150, tutor_visible: true, enabled: true },
{ page: 'docs', label: 'Документация', icon: 'book-open-text', section: 'base', sort_order: 160, tutor_visible: true, enabled: true },
{ page: 'trash', label: 'Корзина', icon: 'trash-2', section: 'base', sort_order: 170, tutor_visible: true, enabled: true },
{ page: 'notes', label: 'Заметки', icon: 'sticky-note', section: 'base', sort_order: 180, tutor_visible: true, enabled: true },
{ page: 'settings', label: 'Настройки', icon: 'settings', section: 'admin', sort_order: 10, tutor_visible: false, enabled: true },
{ page: 'modules', label: 'Темы модулей', icon: 'layers', section: 'admin', sort_order: 20, tutor_visible: false, enabled: true },
{ page: 'users', label: 'Пользователи', icon: 'user-cog', section: 'admin', sort_order: 30, tutor_visible: false, enabled: true },
{ page: 'branches', label: 'Филиалы', icon: 'building-2', section: 'admin', sort_order: 40, tutor_visible: false, enabled: true },
{ page: 'audit', label: 'Аудит', icon: 'scroll-text', section: 'admin', sort_order: 50, tutor_visible: false, enabled: true },
{ page: 'worker', label: 'Воркер ИИ', icon: 'bot', section: 'admin', sort_order: 60, tutor_visible: false, enabled: true },
{ page: 'faces', label: 'Сканер лиц', icon: 'scan-face', section: 'admin', sort_order: 70, tutor_visible: false, enabled: true },
{ page: 'apikeys', label: 'API-ключи', icon: 'key-round', section: 'admin', sort_order: 80, tutor_visible: false, enabled: true },
{ page: 'bans', label: 'Блокировки', icon: 'shield-off', section: 'admin', sort_order: 90, tutor_visible: false, enabled: true },
{ page: 'sidebar', label: 'Меню', icon: 'panel-left', section: 'admin', sort_order: 100, tutor_visible: false, enabled: true },
];
async function ensureSidebarItemsTable(pool) {
await pool.query(`CREATE TABLE IF NOT EXISTS sidebar_items (
id SERIAL PRIMARY KEY,
kind TEXT NOT NULL DEFAULT 'item',
page TEXT UNIQUE,
label TEXT NOT NULL DEFAULT '',
icon TEXT NOT NULL DEFAULT 'circle',
section TEXT NOT NULL DEFAULT 'base',
sort_order INT NOT NULL DEFAULT 0,
tutor_visible BOOLEAN NOT NULL DEFAULT true,
enabled BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(),
CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))
)`);
await pool.query(`ALTER TABLE sidebar_items ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'item'`);
await pool.query(`ALTER TABLE sidebar_items ALTER COLUMN page DROP NOT NULL`);
await pool.query(`ALTER TABLE sidebar_items ALTER COLUMN label SET DEFAULT ''`);
await pool.query(`ALTER TABLE sidebar_items DROP CONSTRAINT IF EXISTS sidebar_items_kind_check`);
await pool.query(`ALTER TABLE sidebar_items ADD CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id)`);
for (const it of DEFAULT_ITEMS) {
await pool.query(
`INSERT INTO sidebar_items (kind, page, label, icon, section, sort_order, tutor_visible, enabled)
VALUES ('item',$1,$2,$3,$4,$5,$6,$7) ON CONFLICT (page) DO NOTHING`,
[it.page, it.label, it.icon, it.section, it.sort_order, it.tutor_visible, it.enabled]
);
}
}
async function listSidebarItems(pool) {
const { rows } = await pool.query(
`SELECT id, kind, page, label, icon, section, sort_order, tutor_visible, enabled, updated_at
FROM sidebar_items ORDER BY section ASC, sort_order ASC, id ASC`
);
return rows;
}
function normalizeSidebarPayload(input) {
if (!Array.isArray(input)) throw new Error('items must be array');
const out = [];
const seenPages = new Set();
for (const raw of input) {
if (!raw || typeof raw !== 'object') throw new Error('bad item');
const kind = ['item','divider','group'].includes(raw.kind) ? raw.kind : 'item';
const id = Number.isFinite(Number(raw.id)) ? Math.trunc(Number(raw.id)) : null;
const section = raw.section === 'admin' ? 'admin' : 'base';
const sort_order = Number.isFinite(Number(raw.sort_order)) ? Math.trunc(Number(raw.sort_order)) : 0;
const tutor_visible = raw.tutor_visible === true || raw.tutor_visible === 'true';
const enabled = raw.enabled === undefined ? true : (raw.enabled === true || raw.enabled === 'true');
if (kind === 'item') {
const page = String(raw.page || '').trim();
if (!page || page.length > 64) throw new Error('bad page');
if (seenPages.has(page)) throw new Error('duplicate page');
seenPages.add(page);
const label = String(raw.label || '').trim();
if (!label || label.length > 64) throw new Error('bad label');
const icon = String(raw.icon || '').trim();
if (!icon || icon.length > 64) throw new Error('bad icon');
out.push({ id, kind, page, label, icon, section, sort_order, tutor_visible, enabled });
} else {
const label = String(raw.label || '').trim();
if (kind === 'group' && (!label || label.length > 64)) throw new Error('bad label');
if (label.length > 64) throw new Error('bad label');
const icon = String(raw.icon || 'circle').trim() || 'circle';
if (icon.length > 64) throw new Error('bad icon');
out.push({ id, kind, page: null, label, icon, section, sort_order, tutor_visible, enabled });
}
}
return out;
}
function normalizeSidebarMarks(value) {
let list = value;
if (typeof value === 'string') {
if (!value.trim()) return '';
try { list = JSON.parse(value); } catch { throw new Error('Некорректный список меток'); }
}
if (!Array.isArray(list)) throw new Error('Некорректный список меток');
const out = [];
const seen = new Set();
for (const raw of list) {
const page = String(raw == null ? '' : raw).trim();
if (!page) continue;
if (page.length > 64 || !/^[A-Za-z0-9_.-]+$/.test(page)) throw new Error('Некорректная метка');
if (seen.has(page)) continue;
seen.add(page);
out.push(page);
}
return out.length ? JSON.stringify(out) : '';
}
module.exports = {
DEFAULT_ITEMS,
ensureSidebarItemsTable,
listSidebarItems,
normalizeSidebarPayload,
normalizeSidebarMarks,
};