feat(quizzes): персональное закрепление тестов (quiz_pins)

Добавлен ключ quiz_pins в пользовательские настройки (user_settings):
JSON-массив id тестов, до 500 штук, нормализация через normalizeQuizPins.
На странице тестов закреплённые карточки сортируются наверх, кнопка pin
на каждой карточке, состояние хранится в user_settings и синхронизируется
с сервером через PUT /api/user-settings. Адаптив сетки карточек
(4/3/2/1 колонки), иконки действий и стили закреплённой карточки.
This commit is contained in:
dev
2026-12-03 09:31:54 +03:00
parent d9b785d36c
commit cb0b0ef6b1
5 changed files with 133 additions and 18 deletions
+72 -10
View File
@@ -14,6 +14,7 @@
const aiHistory = { offset: 0, total: 0, items: [], error: '', loading: false, poll: null };
let liveSource = null;
let liveDebounce = null;
let pins = new Set();
function attr(s) {
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
@@ -41,8 +42,15 @@
}
function visibleItems() {
if (!mineOnly() || !currentUser) return items;
return items.filter(q => Number(q.author_id) === Number(currentUser.id));
const base = (!mineOnly() || !currentUser)
? items
: items.filter(q => Number(q.author_id) === Number(currentUser.id));
if (deletedMode || !pins.size) return base;
return base.slice().sort((a, b) => {
const pa = pins.has(Number(a.id)) ? 1 : 0;
const pb = pins.has(Number(b.id)) ? 1 : 0;
return pb - pa;
});
}
function kindLabel(kind) {
@@ -50,6 +58,7 @@
}
function cardHtml(q) {
const pinned = pins.has(Number(q.id));
const cover = q.cover_path
? `<img src="${attr(thumbSrc(q.cover_path))}" alt="">`
: '<span class="quiz-cover-ic"><i data-lucide="clipboard-list"></i></span>';
@@ -64,17 +73,19 @@
const actions = [];
if (q.deleted_at) {
if (q.can_edit) {
actions.push(`<button type="button" class="btn-link" data-restore="${q.id}">Восстановить</button>`);
actions.push(`<button type="button" class="btn-link danger" data-perm="${q.id}">Удалить навсегда</button>`);
actions.push(`<button type="button" class="btn-link" data-restore="${q.id}" title="Восстановить" aria-label="Восстановить"><i data-lucide="rotate-ccw"></i></button>`);
actions.push(`<button type="button" class="btn-link danger" data-perm="${q.id}" title="Удалить навсегда" aria-label="Удалить навсегда"><i data-lucide="trash-2"></i></button>`);
}
} else {
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}">Пройти</a>`);
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}">Изменить</a>`);
if (q.can_edit && q.allow_anonymous && q.is_published && q.public_token) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.public_token}">Ссылку</button>`);
if (q.stats_available) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}">Статистика</button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}">Удалить</button>`);
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}" title="Пройти" aria-label="Пройти"><i data-lucide="play"></i></a>`);
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}" title="Изменить" aria-label="Изменить"><i data-lucide="pencil"></i></a>`);
if (q.can_edit && q.allow_anonymous && q.is_published && q.public_token) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.public_token}" title="Скопировать ссылку" aria-label="Скопировать ссылку"><i data-lucide="link"></i></button>`);
if (q.stats_available) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}" title="Статистика" aria-label="Статистика"><i data-lucide="bar-chart-3"></i></button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}" title="Удалить" aria-label="Удалить"><i data-lucide="trash-2"></i></button>`);
}
return `<article class="quiz-card" data-open="${q.deleted_at ? '' : q.id}">
const pinBtn = q.deleted_at ? '' : `<button type="button" class="quiz-pin${pinned ? ' on' : ''}" data-pin="${q.id}" aria-pressed="${pinned ? 'true' : 'false'}" title="${pinned ? 'Открепить' : 'Закрепить сверху'}"><i data-lucide="pin"></i></button>`;
return `<article class="quiz-card${pinned ? ' is-pinned' : ''}" data-open="${q.deleted_at ? '' : q.id}">
${pinBtn}
<div class="quiz-cover">${cover}<span class="quiz-kind-badge${q.kind === 'survey' ? ' survey' : ''}">${kindLabel(q.kind)}</span></div>
<div class="quiz-body">
<div class="quiz-title">${esc(q.title || 'Без названия')}</div>
@@ -139,6 +150,54 @@
if (list) list.classList.toggle('quiz-busy', busy);
}
async function loadPins() {
try {
const res = await fetch(API + '/api/user-settings', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) return;
let list = [];
const raw = data.settings && data.settings.quiz_pins;
if (raw) {
try { list = JSON.parse(raw); } catch (e) { list = []; }
}
pins = new Set((Array.isArray(list) ? list : [])
.map(Number)
.filter(id => Number.isInteger(id) && id > 0));
} catch (e) {
pins = new Set();
}
}
async function persistPins() {
const value = pins.size ? JSON.stringify([...pins]) : '';
try {
const res = await fetch(API + '/api/user-settings', {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ settings: { quiz_pins: value } }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось сохранить закрепление');
return true;
} catch (e) {
showToast(e.message, true);
return false;
}
}
async function togglePin(id) {
const key = Number(id);
if (!Number.isInteger(key) || key <= 0) return;
const had = pins.has(key);
if (had) pins.delete(key); else pins.add(key);
render();
const ok = await persistPins();
if (!ok) {
if (had) pins.add(key); else pins.delete(key);
render();
}
}
async function load() {
const seq = ++loadSeq;
const f = filters();
@@ -678,6 +737,8 @@
}
const stats = e.target.closest('[data-stats]');
if (stats) { e.preventDefault(); location.href = 'quiz.html?id=' + stats.dataset.stats + '&tab=stats'; return; }
const pin = e.target.closest('[data-pin]');
if (pin) { e.preventDefault(); e.stopPropagation(); togglePin(pin.dataset.pin); return; }
if (e.target.closest('a')) return;
const card = e.target.closest('[data-open]');
if (card && card.dataset.open) location.href = 'quiz.html?id=' + card.dataset.open;
@@ -733,6 +794,7 @@
bind();
bindVisibility();
renderIcons();
await loadPins();
await load();
connectLive();
await refreshAiJob();
+14 -5
View File
@@ -8,11 +8,17 @@
<link rel="stylesheet" href="/admin-dark.css" disabled id="themeCss">
<script src="js/theme.js"></script>
<style>
.quiz-list { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 16px; align-items: stretch; }
@media (max-width: 1200px) { .quiz-list { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 760px) { .quiz-list { grid-template-columns: 1fr; } }
.quiz-card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); display: flex; flex-direction: column; overflow: hidden; transition: box-shadow .15s, transform .15s; }
.quiz-list { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-top: 16px; align-items: stretch; }
@media (max-width: 1400px) { .quiz-list { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 1000px) { .quiz-list { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 680px) { .quiz-list { grid-template-columns: 1fr; } }
.quiz-card { position: relative; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); display: flex; flex-direction: column; overflow: hidden; transition: box-shadow .15s, transform .15s; }
.quiz-card:hover { box-shadow: 0 8px 22px rgba(0,0,0,.08); }
.quiz-card.is-pinned { border-color: rgba(245,158,11,.55); box-shadow: 0 0 0 1px rgba(245,158,11,.22); }
.quiz-pin { position: absolute; top: 10px; right: 10px; z-index: 2; width: 30px; height: 30px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; border: 1px solid var(--border); background: var(--card); color: var(--muted); cursor: pointer; transition: color .15s, background .15s, border-color .15s; }
.quiz-pin:hover { color: var(--accent); border-color: rgba(37,99,235,.4); }
.quiz-pin svg { width: 16px; height: 16px; }
.quiz-pin.on { color: #d97706; background: rgba(245,158,11,.18); border-color: rgba(245,158,11,.55); }
.quiz-cover { height: 220px; background: linear-gradient(135deg, rgba(37,99,235,.14), rgba(37,99,235,.04)); display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; }
.quiz-cover img { width: 100%; height: 100%; object-fit: cover; }
.quiz-cover .quiz-cover-ic { color: var(--accent); opacity: .7; }
@@ -29,7 +35,10 @@
.quiz-flag.on { color: #15803d; border-color: rgba(21,128,61,.28); background: rgba(21,128,61,.08); }
.quiz-flag.del { color: #b91c1c; border-color: rgba(220,38,38,.25); background: rgba(220,38,38,.08); }
.quiz-foot { border-top: 1px solid var(--border); padding: 10px 12px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.quiz-foot .btn-link { font-size: .78rem; }
.quiz-foot .btn-link { display: inline-flex; align-items: center; justify-content: center; padding: 7px 10px; line-height: 1; font-size: .78rem; }
.quiz-foot .btn-link svg { width: 15px; height: 15px; }
.quiz-foot .btn-link.danger { margin-left: auto; color: #ef4444; border-color: rgba(239,68,68,.35); }
.quiz-foot .btn-link.danger:hover { border-color: #ef4444; opacity: 1; }
.quiz-foot .spacer { flex: 1; }
.quiz-toolbar { display: flex; align-items: flex-end; gap: 14px; flex-wrap: wrap; margin-top: 16px; }
.quiz-toolbar .settings-field { margin: 0; min-width: 140px; }