feat(exam-prep F2): порт браузера вариантов + API /variants + POST /attempts + редирект /exam9
This commit is contained in:
@@ -41,6 +41,43 @@ const SQL = {
|
||||
JOIN exam_tasks t ON t.id = a.exam_task_id
|
||||
WHERE a.user_id = ? AND t.exam_key = ?
|
||||
`),
|
||||
|
||||
/* Variants list + per-user counts. One row per variant.
|
||||
- total: tasks in variant
|
||||
- solved: distinct tasks where user has ≥1 correct attempt
|
||||
- viewed_sol: distinct tasks where user opened the solution */
|
||||
listVariants: db.prepare(`
|
||||
SELECT
|
||||
t.variant,
|
||||
COUNT(*) AS total,
|
||||
COUNT(DISTINCT CASE WHEN a.is_correct = 1 THEN t.id END) AS solved,
|
||||
COUNT(DISTINCT CASE WHEN a.solution_viewed = 1 THEN t.id END) AS viewed_sol
|
||||
FROM exam_tasks t
|
||||
LEFT JOIN exam_attempts a
|
||||
ON a.exam_task_id = t.id AND a.user_id = ?
|
||||
WHERE t.exam_key = ?
|
||||
GROUP BY t.variant
|
||||
ORDER BY t.variant
|
||||
`),
|
||||
|
||||
getVariantTasks: db.prepare(`
|
||||
SELECT
|
||||
id, task_idx, task_type, text_html, figure_html, opts_json,
|
||||
answer, solution_html, topic, subtopic
|
||||
FROM exam_tasks
|
||||
WHERE exam_key = ? AND variant = ?
|
||||
ORDER BY task_idx
|
||||
`),
|
||||
|
||||
/* For attempt save: confirm the task belongs to a known track + user */
|
||||
getTaskExamKey: db.prepare(`SELECT exam_key FROM exam_tasks WHERE id = ?`),
|
||||
|
||||
insertAttempt: db.prepare(`
|
||||
INSERT INTO exam_attempts
|
||||
(user_id, exam_task_id, user_answer, is_correct, time_ms,
|
||||
mode, session_id, hint_used, solution_viewed, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
};
|
||||
|
||||
/* ── GET /api/exam-prep/tracks ──
|
||||
@@ -52,6 +89,7 @@ router.get('/tracks', (_req, res) => {
|
||||
|
||||
/* ── GET /api/exam-prep/:examKey/info ──
|
||||
Track metadata + global counts + this user's aggregate progress. */
|
||||
// @public-by-design: router-level authMiddleware (line 6) covers this route
|
||||
router.get('/:examKey/info', (req, res) => {
|
||||
const { examKey } = req.params;
|
||||
const track = SQL.getTrack.get(examKey);
|
||||
@@ -83,4 +121,96 @@ router.get('/:examKey/info', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
/* ── GET /api/exam-prep/:examKey/variants ──
|
||||
List of variants with per-user progress aggregates. */
|
||||
// @public-by-design: router-level authMiddleware (line 6) covers this route
|
||||
router.get('/:examKey/variants', (req, res) => {
|
||||
const { examKey } = req.params;
|
||||
if (!SQL.getTrack.get(examKey)) return res.status(404).json({ error: 'Unknown exam track' });
|
||||
const rows = SQL.listVariants.all(req.user.id, examKey);
|
||||
const variants = rows.map(r => ({
|
||||
n: r.variant,
|
||||
label: `Вариант ${r.variant}`,
|
||||
total: r.total,
|
||||
solved: r.solved,
|
||||
viewed_sol: r.viewed_sol,
|
||||
}));
|
||||
res.json({ variants });
|
||||
});
|
||||
|
||||
/* ── GET /api/exam-prep/:examKey/variants/:n/tasks ──
|
||||
All tasks of a specific variant. Includes answer + solution_html
|
||||
(variants view = same UX as old /exam9: read condition + reveal solution).
|
||||
In F3, the task-card will also use `answer` to auto-check user input. */
|
||||
// @public-by-design: router-level authMiddleware (line 6) covers this route
|
||||
router.get('/:examKey/variants/:n/tasks', (req, res) => {
|
||||
const { examKey } = req.params;
|
||||
const n = parseInt(req.params.n, 10);
|
||||
if (!Number.isFinite(n) || n < 1) return res.status(400).json({ error: 'Bad variant number' });
|
||||
|
||||
const rows = SQL.getVariantTasks.all(examKey, n);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Variant not found or empty' });
|
||||
|
||||
const tasks = rows.map(r => ({
|
||||
id: r.id,
|
||||
idx: r.task_idx,
|
||||
type: r.task_type,
|
||||
text: r.text_html,
|
||||
figure: r.figure_html,
|
||||
opts: r.opts_json ? safeJson(r.opts_json) : null,
|
||||
answer: r.answer,
|
||||
solution: r.solution_html,
|
||||
topic: r.topic,
|
||||
subtopic: r.subtopic,
|
||||
}));
|
||||
res.json({ variant: n, tasks });
|
||||
});
|
||||
|
||||
function safeJson(s) { try { return JSON.parse(s); } catch { return null; } }
|
||||
|
||||
/* ── POST /api/exam-prep/attempts ──
|
||||
Save a single attempt. Used by the variants view (F2) for "solution viewed"
|
||||
markers, and by the practice / mock views (F3+) for actual answer checking.
|
||||
|
||||
Body: {
|
||||
exam_task_id (required, integer)
|
||||
user_answer (string|null) — what the user typed/selected
|
||||
is_correct (0|1|null) — null for solution-viewed-only events
|
||||
time_ms (integer|null)
|
||||
mode ('practice'|'variant'|'topic'|'mock')
|
||||
session_id (integer|null)
|
||||
hint_used (0|1)
|
||||
solution_viewed (0|1)
|
||||
}
|
||||
The server does NOT recompute is_correct from `user_answer` here — that's
|
||||
the client's responsibility (it has the `answer` from /tasks). Server only
|
||||
validates ownership and records the event. */
|
||||
router.post('/attempts', (req, res) => {
|
||||
const b = req.body || {};
|
||||
const taskId = Number(b.exam_task_id);
|
||||
if (!Number.isFinite(taskId)) return res.status(400).json({ error: 'exam_task_id required' });
|
||||
|
||||
const task = SQL.getTaskExamKey.get(taskId);
|
||||
if (!task) return res.status(404).json({ error: 'Task not found' });
|
||||
|
||||
const mode = String(b.mode || '');
|
||||
if (!['practice', 'variant', 'topic', 'mock'].includes(mode)) {
|
||||
return res.status(400).json({ error: 'invalid mode' });
|
||||
}
|
||||
|
||||
const userAnswer = b.user_answer != null ? String(b.user_answer).slice(0, 500) : null;
|
||||
const isCorrect = b.is_correct === 1 || b.is_correct === 0 ? b.is_correct : null;
|
||||
const timeMs = Number.isFinite(b.time_ms) ? Math.max(0, Math.min(b.time_ms, 24 * 60 * 60 * 1000)) : null;
|
||||
const sessionId = Number.isFinite(b.session_id) ? b.session_id : null;
|
||||
const hintUsed = b.hint_used ? 1 : 0;
|
||||
const solutionViewed = b.solution_viewed ? 1 : 0;
|
||||
|
||||
const result = SQL.insertAttempt.run(
|
||||
req.user.id, taskId, userAnswer, isCorrect, timeMs,
|
||||
mode, sessionId, hintUsed, solutionViewed, Date.now()
|
||||
);
|
||||
|
||||
res.json({ id: Number(result.lastInsertRowid) });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -366,9 +366,8 @@ app.get(['/exam-prep/:examKey/:view', '/exam-prep/:examKey/:view/*'], (req, res,
|
||||
sendExamPrep(res, file);
|
||||
});
|
||||
|
||||
// NOTE: /exam9 remains live (served by static middleware as exam9.html) until F2
|
||||
// ports the variant browser into /exam-prep/:examKey/variants. The 301 redirect
|
||||
// will be added at that point.
|
||||
// Legacy /exam9 → new variants browser (F2 port complete)
|
||||
app.get('/exam9', (_req, res) => res.redirect(301, '/exam-prep/math9/variants'));
|
||||
|
||||
// Serve HTML files without extension (/dashboard → dashboard.html)
|
||||
// In dev: disable cache so edits are always picked up immediately
|
||||
|
||||
@@ -162,6 +162,162 @@
|
||||
100% { background-position: -100% 0; }
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
Variants view (`vp-*`) — used by exam-prep-variants.html
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* Picker button in the header row */
|
||||
.vp-picker-btn {
|
||||
display: inline-flex; align-items: center; gap: 8px;
|
||||
padding: 9px 16px;
|
||||
border: 1.5px solid var(--border-h);
|
||||
border-radius: 10px;
|
||||
background: var(--surface); color: var(--text);
|
||||
font-family: 'Manrope', sans-serif; font-size: .88rem; font-weight: 700;
|
||||
cursor: pointer; transition: all .15s; white-space: nowrap;
|
||||
}
|
||||
.vp-picker-btn:hover { border-color: var(--violet); color: var(--violet); }
|
||||
.vp-picker-btn .vp-chev {
|
||||
width: 14px; height: 14px; transition: transform .2s;
|
||||
}
|
||||
.vp-picker-btn.open .vp-chev { transform: rotate(180deg); }
|
||||
|
||||
/* Picker overlay */
|
||||
.vp-overlay {
|
||||
display: none; position: fixed; inset: 0;
|
||||
background: rgba(15,23,42,.55); z-index: 300;
|
||||
align-items: flex-start; justify-content: center; padding-top: 80px;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
.vp-overlay.visible { display: flex; }
|
||||
.vp-panel {
|
||||
background: var(--surface); border: 1.5px solid var(--border);
|
||||
border-radius: 16px; box-shadow: 0 24px 64px rgba(0,0,0,.32);
|
||||
width: min(680px, 94vw); max-height: calc(100vh - 120px);
|
||||
overflow-y: auto; padding: 22px 22px 26px;
|
||||
animation: vp-in .18s ease;
|
||||
}
|
||||
@keyframes vp-in {
|
||||
from { opacity: 0; transform: translateY(-12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.vp-panel-head {
|
||||
display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px;
|
||||
}
|
||||
.vp-panel-head h2 {
|
||||
font-family: 'Unbounded', sans-serif; font-size: 1rem; font-weight: 800;
|
||||
}
|
||||
.vp-panel-close {
|
||||
width: 32px; height: 32px; border: none; background: none;
|
||||
color: var(--text-2); cursor: pointer; border-radius: 8px;
|
||||
display: flex; align-items: center; justify-content: center; transition: background .15s;
|
||||
}
|
||||
.vp-panel-close:hover { background: var(--border); color: var(--text); }
|
||||
.vp-panel-close svg { width: 18px; height: 18px; }
|
||||
|
||||
/* Variants grid in the picker */
|
||||
.vp-grid {
|
||||
display: grid; grid-template-columns: repeat(10, 1fr); gap: 6px;
|
||||
}
|
||||
.vg-btn {
|
||||
aspect-ratio: 1; border: 1.5px solid var(--border-h); border-radius: 8px;
|
||||
background: transparent; color: var(--text-2);
|
||||
font-family: 'Manrope', sans-serif; font-size: .82rem; font-weight: 700;
|
||||
cursor: pointer; transition: all .12s; line-height: 1;
|
||||
}
|
||||
.vg-btn:hover { border-color: var(--violet); color: var(--violet); }
|
||||
.vg-btn.active { background: var(--violet); border-color: var(--violet); color: #fff; }
|
||||
.vg-btn.done { background: rgba(6,214,160,.15); border-color: #06D6A0; color: #06D6A0; }
|
||||
.vg-btn.done:hover { background: rgba(6,214,160,.25); }
|
||||
.vg-btn.done.active { background: #06D6A0; border-color: #06D6A0; color: #fff; }
|
||||
.vg-btn.partial { background: rgba(248,150,30,.13); border-color: #F8961E; color: #F8961E; }
|
||||
.vg-btn.partial:hover { background: rgba(248,150,30,.22); }
|
||||
|
||||
@media (max-width: 540px) {
|
||||
.vp-grid { grid-template-columns: repeat(8, 1fr); }
|
||||
}
|
||||
|
||||
/* Variant title + tasks */
|
||||
.vp-title {
|
||||
font-family: 'Unbounded', sans-serif; font-size: 1.35rem; font-weight: 800;
|
||||
letter-spacing: -.02em; margin-bottom: 18px;
|
||||
}
|
||||
.vp-title small {
|
||||
font-family: 'Manrope', sans-serif; font-size: .82rem; font-weight: 500;
|
||||
color: var(--text-2); margin-left: 10px;
|
||||
}
|
||||
|
||||
.vp-task {
|
||||
background: var(--surface); border: 1.5px solid var(--border);
|
||||
border-radius: 14px; margin-bottom: 14px; overflow: hidden;
|
||||
transition: border-color .15s;
|
||||
}
|
||||
.vp-task:hover { border-color: var(--border-h); }
|
||||
.vp-task-header {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 22px; background: rgba(155,93,229,.04);
|
||||
border-bottom: 1.5px solid var(--border);
|
||||
}
|
||||
.vp-task-num {
|
||||
width: 28px; height: 28px; border-radius: 50%;
|
||||
background: var(--violet); color: #fff;
|
||||
font-family: 'Unbounded', sans-serif; font-size: .82rem; font-weight: 800;
|
||||
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
|
||||
}
|
||||
.vp-task-label {
|
||||
font-family: 'Unbounded', sans-serif; font-size: .82rem; font-weight: 700;
|
||||
color: var(--text-2); letter-spacing: .02em;
|
||||
}
|
||||
.vp-task-body { padding: 18px 24px; font-size: .98rem; line-height: 1.8; }
|
||||
.vp-task-text .katex-display { margin: 12px 0 6px; overflow-x: auto; }
|
||||
.vp-task-figure { margin: 14px 0 4px; }
|
||||
.vp-task-figure svg, .vp-task-figure img { max-width: 100%; height: auto; }
|
||||
|
||||
.vp-opts {
|
||||
display: flex; flex-wrap: wrap; gap: 10px 32px;
|
||||
margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border);
|
||||
align-items: center;
|
||||
}
|
||||
.vp-opts-vertical {
|
||||
display: flex; flex-direction: column; gap: 8px;
|
||||
margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border);
|
||||
}
|
||||
.vp-opt { display: inline-flex; align-items: flex-start; gap: 6px; }
|
||||
.vp-opt-lbl {
|
||||
font-family: 'Unbounded', sans-serif; font-weight: 800;
|
||||
color: var(--violet); font-size: .9rem; white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Solution toggle */
|
||||
.vp-sol-wrap { padding: 0 22px 16px; }
|
||||
.vp-sol-btn {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
padding: 6px 14px; border: 1.5px solid #06D6A0; border-radius: 8px;
|
||||
background: transparent; color: #06D6A0;
|
||||
font-family: 'Manrope', sans-serif; font-size: .85rem; font-weight: 700;
|
||||
cursor: pointer; transition: all .15s;
|
||||
}
|
||||
.vp-sol-btn:hover { background: rgba(6,214,160,.12); }
|
||||
.vp-sol-btn.open { background: #06D6A0; border-color: #06D6A0; color: #fff; }
|
||||
.vp-sol-btn svg { width: 13px; height: 13px; transition: transform .2s; }
|
||||
.vp-sol-btn.open svg { transform: rotate(90deg); }
|
||||
|
||||
.vp-sol-panel {
|
||||
display: none; margin-top: 14px; padding: 16px 20px;
|
||||
background: rgba(6,214,160,.06); border-radius: 10px;
|
||||
border-left: 3px solid #06D6A0;
|
||||
line-height: 1.85; font-size: .94rem;
|
||||
}
|
||||
.vp-sol-panel.visible { display: block; }
|
||||
.vp-sol-panel .katex-display { margin: 10px 0 6px; overflow-x: auto; }
|
||||
.vp-sol-panel ul { margin: 6px 0 6px 22px; }
|
||||
.vp-sol-panel li { margin: 3px 0; }
|
||||
.vp-sol-panel .sol-ans {
|
||||
display: inline-block; margin-top: 12px; padding: 4px 14px;
|
||||
background: rgba(6,214,160,.2); border-radius: 6px;
|
||||
font-family: 'Unbounded', sans-serif; font-weight: 800; color: #06D6A0;
|
||||
}
|
||||
|
||||
/* ── Mobile tweaks ─────────────────────────────────────────────── */
|
||||
@media (max-width: 640px) {
|
||||
.ep-wrap { padding: 20px 16px 60px; }
|
||||
@@ -170,4 +326,7 @@
|
||||
.ep-tab { padding: 9px 12px; font-size: .82rem; }
|
||||
.ep-card { padding: 16px 18px; }
|
||||
.ep-stat { padding: 14px 16px; }
|
||||
.vp-task-body { padding: 14px 18px; }
|
||||
.vp-sol-wrap { padding: 0 18px 14px; }
|
||||
.vp-sol-panel { padding: 14px 16px; }
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@400;700;800&family=Manrope:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="/css/ls.css" />
|
||||
<link rel="stylesheet" href="/css/exam-prep.css" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" />
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" onload="onKatexLoad()"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-layout">
|
||||
@@ -24,19 +27,22 @@
|
||||
<path d="m9 14 2 2 4-4"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div style="flex:1">
|
||||
<div class="ep-title" id="ep-title"><span class="ep-skel" style="width:280px;height:1.2em"> </span></div>
|
||||
<div class="ep-sub" id="ep-sub"><span class="ep-skel" style="width:200px;height:.8em"> </span></div>
|
||||
<div class="ep-sub" id="ep-sub"><span class="ep-skel" style="width:200px;height:.8em"> </span></div>
|
||||
</div>
|
||||
<button class="vp-picker-btn" id="vp-btn" title="Выбрать вариант">
|
||||
<span id="vp-label">Выбрать вариант</span>
|
||||
<svg class="vp-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<nav class="ep-tabs" id="ep-tabs"></nav>
|
||||
|
||||
<main id="ep-main">
|
||||
<div class="ep-empty">
|
||||
<i data-lucide="layout-grid"></i>
|
||||
<h4>Браузер вариантов</h4>
|
||||
<p>В F2 сюда переедет просмотр 80 вариантов с условиями и решениями. До этого пользуйтесь старой страницей: <a href="/exam9" style="color:var(--violet)">/exam9</a></p>
|
||||
<i data-lucide="loader-circle"></i>
|
||||
<h4>Загрузка вариантов…</h4>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -44,6 +50,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="vp-overlay" id="vp-overlay">
|
||||
<div class="vp-panel" onclick="event.stopPropagation()">
|
||||
<div class="vp-panel-head">
|
||||
<h2>Выберите вариант</h2>
|
||||
<button class="vp-panel-close" id="vp-close" title="Закрыть">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="vp-grid" id="vp-grid"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/lucide@0.469.0/dist/umd/lucide.min.js"></script>
|
||||
<script src="/js/api.js"></script>
|
||||
<script src="/js/sidebar.js"></script>
|
||||
@@ -52,6 +70,7 @@
|
||||
<script src="/js/mobile.js"></script>
|
||||
<script src="/js/exam-prep/common.js"></script>
|
||||
<script src="/js/exam-prep/api.js"></script>
|
||||
<script>(async () => { await EP.boot(); if (window.lucide) lucide.createIcons(); })();</script>
|
||||
<script src="/js/exam-prep/katex.js"></script>
|
||||
<script src="/js/exam-prep/variants.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
/* ──────────────────────────────────────────────────────────────────
|
||||
KaTeX bootstrap for the exam-prep module.
|
||||
|
||||
Page must include the KaTeX CSS + JS via CDN tags BEFORE this script.
|
||||
The `onKatexLoad` global is wired up via the KaTeX auto-render onload.
|
||||
────────────────────────────────────────────────────────────────── */
|
||||
|
||||
(function () {
|
||||
let loaded = false;
|
||||
const pending = [];
|
||||
|
||||
// Global called from auto-render.min.js onload handler in the HTML.
|
||||
window.onKatexLoad = function () {
|
||||
loaded = true;
|
||||
while (pending.length) {
|
||||
try { renderMathInElement(pending.shift(), KATEX_OPTS); } catch {}
|
||||
}
|
||||
};
|
||||
|
||||
const KATEX_OPTS = {
|
||||
delimiters: [
|
||||
{ left: '$$', right: '$$', display: true },
|
||||
{ left: '$', right: '$', display: false },
|
||||
],
|
||||
throwOnError: false,
|
||||
};
|
||||
|
||||
function run(el) {
|
||||
if (!el) return;
|
||||
if (!loaded) { pending.push(el); return; }
|
||||
try { renderMathInElement(el, KATEX_OPTS); } catch {}
|
||||
}
|
||||
|
||||
window.EP = window.EP || {};
|
||||
window.EP.katex = { run, isLoaded: () => loaded };
|
||||
})();
|
||||
@@ -0,0 +1,202 @@
|
||||
'use strict';
|
||||
/* ──────────────────────────────────────────────────────────────────
|
||||
Variants view — port of the old /exam9 browser onto API + DB.
|
||||
Same UX as before: pick a variant from a grid overlay, then read
|
||||
conditions + reveal solutions. Progress (which variants have all
|
||||
solutions opened) is per-user via /api/exam-prep/attempts.
|
||||
────────────────────────────────────────────────────────────────── */
|
||||
|
||||
(async function () {
|
||||
await EP.boot();
|
||||
const examKey = EP.examKey;
|
||||
|
||||
// Optional ?v=N in URL: open that variant initially
|
||||
const initialVariantFromQuery = (() => {
|
||||
const m = location.search.match(/[?&]v=(\d+)/);
|
||||
return m ? Number(m[1]) : null;
|
||||
})();
|
||||
|
||||
let variants = []; // [{ n, label, total, solved, viewed_sol }]
|
||||
let currentN = null;
|
||||
let currentTasks = null; // cache: { [variantN]: tasks[] }
|
||||
const tasksCache = new Map();
|
||||
|
||||
/* ── Load variants list ─────────────────────────────────────── */
|
||||
try {
|
||||
const r = await EP.api.listVariants(examKey);
|
||||
variants = r.variants || [];
|
||||
} catch (e) {
|
||||
showError(`Не удалось загрузить варианты: ${e.message || e}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!variants.length) {
|
||||
showError('Варианты не найдены');
|
||||
return;
|
||||
}
|
||||
|
||||
/* ── DOM refs ───────────────────────────────────────────────── */
|
||||
const main = document.getElementById('ep-main');
|
||||
const pickerBtn = document.getElementById('vp-btn');
|
||||
const pickerLabel = document.getElementById('vp-label');
|
||||
const pickerOver = document.getElementById('vp-overlay');
|
||||
const pickerGrid = document.getElementById('vp-grid');
|
||||
|
||||
/* ── Picker overlay ─────────────────────────────────────────── */
|
||||
function buildGrid() {
|
||||
pickerGrid.innerHTML = variants.map(v => {
|
||||
let cls = '';
|
||||
if (v.total > 0 && v.viewed_sol === v.total) cls = ' done';
|
||||
else if (v.viewed_sol > 0) cls = ' partial';
|
||||
const active = v.n === currentN ? ' active' : '';
|
||||
const title = v.viewed_sol === v.total ? `${v.label} (все решения открыты)`
|
||||
: `${v.label} (${v.viewed_sol}/${v.total} решений открыто)`;
|
||||
return `<button class="vg-btn${cls}${active}" data-n="${v.n}" title="${title}">${v.n}</button>`;
|
||||
}).join('');
|
||||
pickerGrid.querySelectorAll('button[data-n]').forEach(b => {
|
||||
b.onclick = () => { selectVariant(Number(b.dataset.n)); closePicker(); };
|
||||
});
|
||||
}
|
||||
function openPicker() {
|
||||
buildGrid();
|
||||
pickerOver.classList.add('visible');
|
||||
pickerBtn.classList.add('open');
|
||||
document.addEventListener('keydown', onEsc);
|
||||
}
|
||||
function closePicker() {
|
||||
pickerOver.classList.remove('visible');
|
||||
pickerBtn.classList.remove('open');
|
||||
document.removeEventListener('keydown', onEsc);
|
||||
}
|
||||
function onEsc(e) { if (e.key === 'Escape') closePicker(); }
|
||||
function onOverlayClick(e) { if (e.target === pickerOver) closePicker(); }
|
||||
|
||||
pickerBtn.onclick = () => {
|
||||
if (pickerOver.classList.contains('visible')) closePicker();
|
||||
else openPicker();
|
||||
};
|
||||
pickerOver.onclick = onOverlayClick;
|
||||
document.getElementById('vp-close').onclick = closePicker;
|
||||
|
||||
/* ── Variant rendering ──────────────────────────────────────── */
|
||||
async function selectVariant(n) {
|
||||
currentN = n;
|
||||
pickerLabel.textContent = `Вариант ${n}`;
|
||||
try { localStorage.setItem(`exam_prep_${examKey}_last_variant`, String(n)); } catch {}
|
||||
|
||||
if (!tasksCache.has(n)) {
|
||||
main.innerHTML = `<div class="ep-empty"><i data-lucide="loader-circle"></i><h4>Загрузка варианта ${n}…</h4></div>`;
|
||||
if (window.lucide) lucide.createIcons();
|
||||
try {
|
||||
const r = await EP.api.getVariant(examKey, n);
|
||||
tasksCache.set(n, r.tasks || []);
|
||||
} catch (e) {
|
||||
showError(`Не удалось загрузить вариант ${n}: ${e.message || e}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
currentTasks = tasksCache.get(n);
|
||||
renderVariant(n, currentTasks);
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
function renderVariant(n, tasks) {
|
||||
main.innerHTML =
|
||||
`<div class="vp-title">Вариант ${n}<small>${tasks.length} заданий</small></div>` +
|
||||
tasks.map((t, i) => `
|
||||
<div class="vp-task" data-task-id="${t.id}">
|
||||
<div class="vp-task-header">
|
||||
<div class="vp-task-num">${t.idx}</div>
|
||||
<div class="vp-task-label">Задание ${t.idx}</div>
|
||||
</div>
|
||||
<div class="vp-task-body">
|
||||
<div class="vp-task-text">${t.text}</div>
|
||||
${t.figure ? `<div class="vp-task-figure">${t.figure}</div>` : ''}
|
||||
${t.opts ? buildOpts(t.opts) : ''}
|
||||
</div>
|
||||
${t.solution ? `
|
||||
<div class="vp-sol-wrap">
|
||||
<button class="vp-sol-btn" data-i="${i}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
|
||||
<span>Показать решение</span>
|
||||
</button>
|
||||
<div class="vp-sol-panel">${t.solution}</div>
|
||||
</div>` : ''}
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
main.querySelectorAll('.vp-sol-btn').forEach(btn => {
|
||||
btn.onclick = () => toggleSol(btn, n, Number(btn.dataset.i));
|
||||
});
|
||||
|
||||
EP.katex.run(main);
|
||||
}
|
||||
|
||||
function buildOpts(opts) {
|
||||
const isLong = opts.some(([, txt]) => txt.length > 40 && !txt.startsWith('$'));
|
||||
const cls = isLong ? 'vp-opts vp-opts-vertical' : 'vp-opts';
|
||||
return `<div class="${cls}">` + opts.map(([l, t]) =>
|
||||
`<span class="vp-opt"><span class="vp-opt-lbl">${l})</span><span>${t}</span></span>`
|
||||
).join('') + '</div>';
|
||||
}
|
||||
|
||||
async function toggleSol(btn, n, i) {
|
||||
const panel = btn.nextElementSibling;
|
||||
const wasOpen = panel.classList.contains('visible');
|
||||
panel.classList.toggle('visible', !wasOpen);
|
||||
btn.classList.toggle('open', !wasOpen);
|
||||
btn.querySelector('span').textContent = wasOpen ? 'Показать решение' : 'Скрыть решение';
|
||||
|
||||
if (!wasOpen) {
|
||||
if (!panel.dataset.k) { EP.katex.run(panel); panel.dataset.k = '1'; }
|
||||
// Persist "solution viewed" exactly once per (user, task)
|
||||
if (!panel.dataset.logged) {
|
||||
panel.dataset.logged = '1';
|
||||
const taskId = currentTasks[i]?.id;
|
||||
if (taskId) {
|
||||
EP.api.saveAttempt({
|
||||
exam_task_id: taskId,
|
||||
user_answer: null,
|
||||
is_correct: null,
|
||||
mode: 'variant',
|
||||
solution_viewed: 1,
|
||||
}).catch(() => {
|
||||
// Silent: progress sync is best-effort
|
||||
panel.dataset.logged = '';
|
||||
});
|
||||
// Local optimistic update of picker grid
|
||||
const v = variants.find(v => v.n === n);
|
||||
if (v && panel.dataset.firstView !== '1') {
|
||||
panel.dataset.firstView = '1';
|
||||
v.viewed_sol = Math.min(v.viewed_sol + 1, v.total);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showError(msg) {
|
||||
document.getElementById('ep-main').innerHTML = `
|
||||
<div class="ep-empty">
|
||||
<i data-lucide="alert-triangle"></i>
|
||||
<h4>${escapeHtml(msg)}</h4>
|
||||
</div>`;
|
||||
if (window.lucide) lucide.createIcons();
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s || '').replace(/[&<>"']/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' }[c]));
|
||||
}
|
||||
|
||||
/* ── Pick the initial variant ───────────────────────────────── */
|
||||
let initial = variants[0].n;
|
||||
if (initialVariantFromQuery && variants.some(v => v.n === initialVariantFromQuery)) {
|
||||
initial = initialVariantFromQuery;
|
||||
} else {
|
||||
try {
|
||||
const last = Number(localStorage.getItem(`exam_prep_${examKey}_last_variant`));
|
||||
if (last && variants.some(v => v.n === last)) initial = last;
|
||||
} catch {}
|
||||
}
|
||||
selectVariant(initial);
|
||||
})();
|
||||
Reference in New Issue
Block a user