Commit Graph

130 Commits

Author SHA1 Message Date
Maxim Dolgolyov 085b7322cf chore(plans): mark admin-redesign + lab-split as Complete
Both features merged to master; status updated from In Progress to

Complete with merge-commit refs for traceability.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 11:16:39 +03:00
Maxim Dolgolyov 5d5f51acfe Merge feature/lab-split: modular lab.html (5180L → 3499L)
4 phases shipped, phase 5 (template lazy-mount) deferred:

1. Extract inline <style> → /css/lab.css (-856L)

2. Extract inline glue <script> → /js/labs/lab-glue.js (-825L)

3. Token purification ~106 hardcodes → CSS vars

4. Hash-router #sim/<name> deep-links, 34 sims auto-mapped

Final review: READY TO MERGE (0 blockers, 0 warnings, 3 polish notes).

Tests baseline unchanged (66/63/3), all curl endpoints 200.
2026-05-22 23:21:05 +03:00
Maxim Dolgolyov 5fa2844451 docs(lab-split): mark phases 1-4 done, phase 5 deferred
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 23:03:56 +03:00
Maxim Dolgolyov 0b9685bc5e feat(lab): phase 4 -- hash-router for sim deep-links
URL #sim/<name> deep-links: F5 restores sim, browser back/forward
switches between sims, click on sim-card updates URL.

34 sims mapped via _SIM_HASH_MAP (built dynamically from SIMS array).
Unknown hash -> console.warn fallback.
Recursion guard prevents double-activation on programmatic navigate.
closeSim clears hash via history.pushState (no hashchange loop).
Embed mode excluded from hash updates (?embed=1 workflow unaffected).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:56:18 +03:00
Maxim Dolgolyov 6792a4a5c7 refactor(lab): phase 3 — token purification across lab.html / lab.css / lab-glue.js
Replaced ~100 hardcoded brand colors with var() tokens across 3 files.
Kept: tinted-alpha colors (rgba(155,93,229,.x)), canvas fillStyle (vars
don't resolve there), curated SVG card-preview palettes (P_GRAPH, P_MAGNETIC,
etc.), physics-convention colors (#EF476F for positive charges, #4CC9F0 for
negative), slightly-different decorative shades (#EF476F ≠ #F15BB5).

lab.css: #9B5DE5→var(--violet), #06D6E0→var(--cyan), #F15BB5/nscene→var(--pink),
  #0F172A (filter.active)→var(--text), fn-color defaults, trig btn defaults.
lab.html: stat bars, slider labels, info-fn-dot, toggle-dot, panel badges,
  section-specific color coding (violet=wave1/param1, cyan=wave2/param2).
lab-glue.js: toggleTheory() JS style assignments, template-literal HTML headings.

Before: ~265 hardcodes   After: ~60 (canvas+curated+rgba+physics-convention)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:51:28 +03:00
Maxim Dolgolyov 92b5c39860 refactor(lab): phase 2 — extract inline glue script to /js/labs/lab-glue.js
lab.html 4324L → 3499L (-825L). 824 lines of glue code moved.

Position preserved: lab-glue.js loads after lab-init.js, before

newton.js / forcesandbox.js / etc. — same execution order as inline.

node --check passes. /lab returns 200. /js/labs/lab-glue.js returns 200.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:36:26 +03:00
Maxim Dolgolyov 46e6d82010 refactor(lab): phase 1 — extract inline style block to /css/lab.css
lab.html 5180L → 4324L (-856L). All CSS moved to frontend/css/lab.css

(855L). Added <link> tag after ls.css for proper cascade.

Visual rendering unchanged — pure file move.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:35:07 +03:00
Maxim Dolgolyov 77ebe9e3e4 chore(plan): lab-split 5-phase plan
PLAN.md + 5 subplans + CONTEXT.md

Strategy: Incremental | Mode: Automated | Execution: Direct

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:33:41 +03:00
Maxim Dolgolyov 58cff2285e refactor(dashboard): use ls.css design tokens
Replaced 42 hardcoded brand colors with var() tokens:

CSS rules:
- linear-gradient(135deg,#9B5DE5,#06D6E0) → var(--grad-1) in dh-avatar, lb-avatar, gam-level
- #0F172A → var(--text) in 28 CSS rules (text colors for all major widget labels,
  titles, buttons: dh-greeting, ac-title, qa-btn, grade-subj, act-tab.active,
  hm-footer strong, hm-tip bg, hdp-date/subj, assign-search, sc-month,
  qs-subj-btn, qs-select/input, adm-act, adm-sess-name, cs-name, assign-chip.active,
  ae-btn, ar-title, ar-btn, hist-subj, subj-chart-name, weak-name,
  ms-title, empty-cta-title, btn-join, stats-bar tooltip bg, stats-chip-val,
  tc-title, lb-title, lb-name, lb-class-sel, ch-title, gam-rank, gam-chip-val)
- #3D4F6B → var(--text-2) in hist-score, ae-submit-note
- #9B5DE5 → var(--violet) in lb-xp, ar-sub-chip.s-none, lb-tab.active,
  ch-pct, ch-xp, dash-cfg-title, dash-cfg-fab, dash-cfg-checkbox accent-color
- #06D6E0 / #F15BB5 → var(--cyan) / var(--pink) in stat rings and progress fills

JS-generated HTML/SVG:
- var(--violet)/var(--cyan) in SVG statRingSvg calls, goal ring SVG, barColor
- weak-fill gradient partial replacement (--pink)

Kept: 90deg progress bar gradients, domain palette colors (#E0335E/#059652/#7c3aed
/#05aab3/etc.), Chart.js hex configs (CSS vars unsupported there), canvas fillStyle,
action banner dark gradients, heatmap cell alphas, adm-act-icon domain navcolors.

Before: ~65 hardcodes | After: ~20 hardcodes (Chart.js, canvas, domain/dark theme)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:19:02 +03:00
Maxim Dolgolyov 916e2ddc31 refactor(profile): use ls.css design tokens
Replaced 12 hardcoded brand colors with var() tokens:
- linear-gradient(135deg,#9B5DE5,#06D6E0) → var(--grad-1) in 7 CSS rules
  (avatar ring, badge dot, stat val grad, xp level, frame preview, zoom thumb, send btn, modal dot)
- #9B5DE5 → var(--violet) in 3 rules (avatar edit btn, bm-icon-lesson, frame selected border, av-drop hover)
- #06D6E0 → var(--cyan) in bm-icon-file
- #0F172A → var(--text) in frames-section heading inline style

Kept: dark panel palette (#0d0b28/#1a1248), 90deg horizontal gradients,
domain subject colors (SUBJ_META palette), shop gold/amber gradients,
shop-activate/active brand variants, #06D6A0 bookmark course teal,
#EF476F delete-hover (≠ --pink), tinted rgba values.

Before: ~26 hardcodes | After: ~12 hardcodes (decorative/domain/dark-panel)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:10:10 +03:00
Maxim Dolgolyov 0b06e8facd refactor(classes): use ls.css design tokens
Replaced 13 hardcoded brand colors with var() tokens:
- #0F172A → var(--text) in 5 CSS rules and JS-generated strings
- #3D4F6B → var(--text-2) in 3 CSS rules and 2 inline attrs
- #06D6E0 → var(--cyan) in --wc custom property
- Chart bucket/bar colors → var(--pink/amber/cyan/green)

Kept tinted-alpha colors, 90deg gradient bars, #f4f5f8 split layout bg,
#059652 (dark domain green for grade/review status), #06aab3 (status badge),
#c0306a/#c07c00 (grade letter palette), #EF476F (delete icon),
and JS-toggled display:none (incompatible with .hidden class pattern).

Before: ~22 hardcodes | After: ~9 hardcodes (decorative/domain)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:06:43 +03:00
Maxim Dolgolyov 1fdbb9a445 test(backend): +31 integration tests for permissions/overview/search/sessions/features
Coverage:
- Permissions: role/user toggle + audit + token_version bump, /me, 403 non-admin (10 tests)
- Admin overview: shape, all fields, types, auth guard, empty DB zeros (4 tests)
- Cmd+K search: shape, min-query empty, SQL injection sanity, user lookup (5 tests)
- Session delete: CASCADE, audit entry, 404 missing, 403 non-admin (4 tests)
- Feature gates: disabled flag returns 404, enabled returns 401/200, admin API toggle (5 tests)
- setup.js: add /api/permissions, /api/pet, /api/biochem routes for test coverage

tests 66 (was 35) · pass 63 (was 32) · fail 3 (baseline auth.test.js, unchanged)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 21:58:37 +03:00
Maxim Dolgolyov 696049271f feat(dx): pre-commit hooks for local CI (no remote needed)
Local quality gate that runs on every git commit:
- node --check syntax on staged .js files
- block on new emoji in staged .js/.html/.css (md files allowed)
- block on new console.log/debug/debugger statements
- backend route auth lint (existing npm run lint:routes)
- backend tests (baseline 3 fails, block if grew)

Install: npm run hooks:install (top-level)
Bypass: git commit --no-verify

Skips slow checks when irrelevant files changed (tests/lint only run
if backend touched).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 21:49:58 +03:00
Maxim Dolgolyov 3135402dd7 perf(db): +21 indexes for hot-path queries (audit 2026-05-22)
Adds missing indexes identified by comprehensive audit:

users:        created_at, last_login, role, (is_banned, role)

test_sessions: started_at, finished_at, subject_id, (status, finished_at DESC)

notifications: (user_id, created_at DESC) — previous idx was on is_read, not date

admin_audit_log: target, action, (action, created_at DESC)

classroom_*:  session_id FK indexes — prevents full-table scan on CASCADE

              DELETE (muted, attendance, invites, notes, draw_permissions, hands)

              + chat (session_id, created_at)

submissions:  (student_id, submitted_at DESC) — gradebook timeline

questions:    difficulty — exam builder filter

Skipped users.email — UNIQUE constraint already provides equality lookup.

Expected impact: 30-60% on admin overview / analytics, 10-20% on

notification/session timelines. CASCADE DELETE of classroom_sessions

no longer triggers full-table scans on 6 child tables.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:41:37 +03:00
Maxim Dolgolyov e4ec9f8823 feat(design-system): comprehensive showcase page at /design-system
Standalone discoverable hub of all LearnSpace design tokens, components,
patterns, motion, accessibility primitives, and icons.

Sections:
- Foundations: colors (WCAG ratios), typography, spacing, radii,
  shadows, blur
- Components: buttons, inputs, badges, chips, cards, modal, toast,
  skeleton, empty-states, avatars (all with state variants)
- Patterns: stat-card, data-table, search-bar, sidebar nav, tabs, hero,
  bento, hover-row-actions
- Motion: transitions, shimmer, prefers-reduced-motion toggle
- Accessibility: focus rings, touch targets, live contrast checker
- Icons: top 50 Lucide names with click-to-copy
- Anti-patterns: 4x don't vs do examples

Interactive: click-to-copy on swatches/icons/classes, search filter
across sections, code snippets via <details> blocks per component,
LS.modal/toast live triggers with standalone fallback.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 09:58:23 +03:00
Maxim Dolgolyov dfaa346051 feat(ls): expand design-system tokens + utility classes
Adds to ls.css:
- Spacing scale (--space-1..16, 4px base)
- Radius ladder (--r-xs/sm/md/xl in addition to existing lg/pill)
- Semantic color aliases (--success/warning/danger/info -> existing brand)
- Typography scale (--text-xs..3xl) + font-weight scale (--fw-*)
- Motion tokens (--ease-out, --ease-spring, --duration-*)
- Breakpoint documentation vars
- Utility classes (.hidden, .p-*, .m-*, .gap-*, .flex, .grid, .text-*, .rounded-*)
- Shared .ls-skeleton with shimmer animation

All existing tokens preserved unchanged -- additions only.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 09:40:15 +03:00
Maxim Dolgolyov 703c4b5edf feat(admin): surface classroom feature toggle in tab-games
The feature_classroom_enabled flag was fully wired in backend
(classroom/sessions.js:11-14 returns 403 when '0', initialized in
legacy-migrate.js:870 to '1') but had no UI control — admin could
only flip it via direct SQL.

- adminController.updateFeatures: classroom was ALREADY in allowed list
- admin/sections/games.js: new toggle row with video icon added to GAME_FEATURES
- js/api.js hideDisabledFeatures: classroom path mapping added ('/classroom')

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 20:16:26 +03:00
Maxim Dolgolyov 58e29341d4 feat(biochem): surface 3D toggle button in molecular editor
3D rendering (toggle3D/render3D with VDW radii + sphere gradients) was
implemented but had no visible Esc-key exit and cursor was left in 'grab'
state when leaving 3D mode. Changes:
- Esc key now exits 3D mode (toggle3D) in addition to cancel/close actions
- cursor correctly resets to 'crosshair' on 3D exit and 'grab' on enter
- btn-3d toolbar button confirmed visible with mode-3d-active active state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 19:52:03 +03:00
Maxim Dolgolyov 29ef974e35 feat(biochem): skeleton loaders for async fetches
Replace plain "Загрузка..." placeholders with shimmer-animated skeletons
matching the actual layout shape:
- library: 12 placeholder cards (canvas + 2 lines)
- reactions: 6 row skeletons (stripe + title + 2 text lines)
- properties: 10 sidebar row shimmers (thumb + 2 lines)
- biochem editor: 4-5 row skeletons for saved-molecules and challenges lists

No existing skeleton classes in ls.css; added local .bc-sk-* helpers per page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 19:49:54 +03:00
Maxim Dolgolyov d3b1cd75a0 feat(dashboard): teacher view polish — chips, bars, KPIs, groups, mobile
P0 visual polish:
- adm-actions: grouped layout (teaching/content/admin) with 3-col grid at wide, responsive
- thick 8px colored progress bars (green ≥75 / amber 50-74 / pink <50)
- session % rendered as colored chip (tinted bg + border)
- hover state on .adm-sess-row and .asgn-row in admin-grid
- empty states with Lucide icon + CTA button (inbox/users/clock)
- class-name badge on assignment row (disambiguates duplicates)
- relative timestamp on session rows via relativeAgo()
- search input above assignment list (filterAdminAssignments())
- adm-act-icon bumped 16px → 20px; card hover: scale + shadow

P1 header KPIs + urgency:
- dh-kpi-row: classes / students / active-asgn / pending chips under greeting
- isTeacherUrgent(): assignments within 48h get pink border + срочно badge
- adm-act-badge: count badge on Мои классы and Работы cards
- loadTeacherKPIs() fetches /api/classes + teacherAssignments() in parallel

P2 grouping + mobile + micro:
- chevron-right icons on Все/Все классы section links
- mobile ≤640: single-column groups, KPI chips wrap, sess-rows wrap
- mobile ≤480: adm-act-group single column
- dark mode rules for new elements

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:25:34 +03:00
Maxim Dolgolyov d1d20c4c86 polish(admin-dash): avatar pills, skeleton loader, mobile breakpoints, palette kept
- Avatar circles in top/worst-5 tables: initials from name, hsl color from hash of name
- Structural skeleton on first load: 4 shimmer card boxes + 5 row placeholders (replaces
  LS.state.loading spinner for better layout-anchored feedback)
- @media ≤640px: 2-column main grid, hero card reverts to normal size, quick-grid 2-col
- Palette: existing per-card colors (violet/cyan/green/amber) already form a good muted
  hue family with vivid pink/amber for alert cards — kept as is to avoid regression

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:07:18 +03:00
Maxim Dolgolyov 124236db58 feat(admin-dash): P1 — sparklines, content inventory, subject distribution, worst-5 sessions
- 7d sparkline per 3 main metric cards (inline SVG polyline, renderSparkline helper)
- "Контент проекта" row: questions/tests/courses/classes totals (compact .ov-inv-grid)
- Per-subject stacked bar (24h) with hue-cycle colors and legend below
- "Худшие 5 сегодня" mirrors top-5 table; both side-by-side ≥1100px via .ov-results-grid
- renderSessionRows() shared helper for top/worst table rows

Backend: 5 new prepared statements (worstSessions24h, sparkUsers7d, sparkSessions7d,
sparkActiveUsers7d, inventory, sessionsBySubject24h)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:05:57 +03:00
Maxim Dolgolyov 64112e56ed feat(admin-dash): P0 — honest zeros, refresh+timestamp, hero hierarchy, stuck-sessions alert
- fmtNum: 0 no longer renders as "—" (muted "0" via .ov-zero instead)
- backend: classesTotal (renamed from activeClasses — was already full count, label fixed)
- backend: abandonedSessions24h (was failedSessions24h status!=completed; now only status=abandoned)
- backend: stuckSessions[] — in_progress > 1h with user/subject join, limit 5
- header: timestamp + manual refresh button (.ov-header flex layout), updates every 30s via interval
- newSessions24h card promoted to hero (2.6rem value, 52px icon, 2fr column ≥720px)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:03:30 +03:00
Maxim Dolgolyov 8269f5b145 Merge feature/permissions-hardening: RBAC hardening + B-lite + P0 UX
Phase A (security): permission registry, audit log on perm/feature changes,

token_version bump on permission changes.

B-lite: requireFeature middleware blocks API on disabled global flags.

P0 UX: search, modified-dot, confirm on critical perms, badge wording.

Conflict resolution: admin.js monolith was restructured into

frontend/js/admin/sections/* by feature/admin-redesign merge. P0 UX

edits (originally in monolith) were manually ported to:

- sections/permissions.js — modDot, confirm gate, filterPermissions

- sections/users.js — 'Инд.' → 'Индивидуально' badge in user-perms modal

admin.html search input + dot CSS auto-merged cleanly.
2026-05-17 14:51:05 +03:00
Maxim Dolgolyov 1aa6660f4d Merge feature/admin-redesign: admin SPA redesign (6 phases) + security fixes
Hash-router, 14 per-section modules, dashboard #overview, Cmd+K palette,

per-row quick actions, deep entity pages. admin.js: 3500L → ~700L.

Includes stored-XSS fix in user-name onclick interpolation, and

SVG-as-text rendering fixes in 6 lab simulations.

Squashed phase commits preserved (--no-ff merge).
2026-05-17 14:48:01 +03:00
Maxim Dolgolyov 7eea33a135 feat(perm-ui): P0 usability improvements (search, default-dot, confirm-critical, wording)
- registry.js: добавлен флаг requireConfirmOff для 7 критичных прав (questions.manage, classes.manage, library.upload, courses.manage, sessions.reset, theory.access, simulations.access); byRole() теперь возвращает это поле
- admin.html: subtitle в модале прав — «учителя» → «пользователя»; tooltip на кнопке «Сбросить всё по умолчанию»; поле поиска над сеткой прав; CSS .perm-modified-dot (amber, 8px)
- admin.js: badge «Инд.» → «Индивидуально» (font-size 11px); renderPermissions() рисует .perm-modified-dot когда значение отличается от registry default; togglePermission() показывает LS.confirm перед выключением критичных прав; window.filterPermissions() скрывает карточки и role-блоки по поисковому запросу

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 14:43:49 +03:00
Maxim Dolgolyov 19c16bdfe8 feat(perm): block API endpoints for globally-disabled features (B-lite)
Adds backend/src/middleware/features.js with requireFeature(name)

that returns 404 when app_settings.feature_<name>_enabled='0'.

Wired on 8 routes:

- /api/pet            (pet)

- /api/collection     (collection)

- /api/red-book       (red_book)

- /api/flashcards     (flashcards)

- /api/knowledge-map  (knowledge_map)

- /api/biochem        (biochem)

- /api/games/hangman/*   (hangman, per-route inside games router)

- /api/games/crossword/* (crossword, per-route)

Scope: GLOBAL only. Per-class disable (classes.features JSON) and the

free_student role overlay remain UI-gated. Add user-aware merge later

if needed (extract logic from /api/features endpoint into shared helper).

Not gated (intentional, core teacher tools): board, classroom, live_quiz.

Smoke: pet disabled → 404; enabled → 401 (auth-required passthrough).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 14:35:29 +03:00
Maxim Dolgolyov 3e187a94c0 fix(perm): bump token_version on resetUserPermissions too
Reset can downgrade effective access (override=1 vs role default=0),

so the user's JWT must be invalidated alongside the DELETE.

Wrapped in db.transaction for atomicity.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 14:25:03 +03:00
Maxim Dolgolyov 76883b569c feat(perm): central permission registry + key validation in linter
- backend/src/permissions/registry.js: single source of truth (PERMISSIONS map)
  with all 24 keys (16 teacher + 8 student, student keys also cover free_student).
  Exports isKnown(), listKeys(), byRole(), buildDefaultsMap().
- auth.js: PERM_DEFAULTS now sourced from registry.buildDefaultsMap();
  new perm() helper validates key at registration time (crashes early on typos).
  requirePermission() unchanged — backward compat preserved.
- permissionsController.js: ALL_PERMISSIONS now built from registry.byRole();
  inline 24-entry array removed. API response shape unchanged.
- check-route-auth.js: validates every requirePermission/perm call key against
  registry; lists unknown keys as errors before exit.
  perm() added to GUARDS list so it counts as route protection.

Discrepancy noted: auth.js had free_student with same 8 keys as student;
permissionsController never seeded free_student rows. Registry documents
this via roles:[] array; buildDefaultsMap() correctly covers free_student.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 14:22:18 +03:00
Maxim Dolgolyov 539d33df31 feat(perm): audit log for permission + feature-flag changes
Adds audit entries for:
- permission.set (role-level change)
- permission.user_set (per-user override)
- permission.user_reset (clear user override)
- feature.update (global feature flag toggle, per-key with old->new diff)

Old value captured for feature.update for full diff trail.
permissionsController: added audit import, wired audit() after each write.
adminController.updateFeatures: replaced bulk audit with per-key entries
capturing old value from app_settings before overwrite.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 14:16:45 +03:00
Maxim Dolgolyov dd1adc0c69 fix(perm): bump token_version on permission change (invalidates JWTs)
setPermission / setUserPermission now bump token_version for affected
users so cached JWTs lose access immediately instead of after expiry.
Aligns with role-change pattern in adminController.updateRole.
Both writes wrapped in db.transaction() so token_version is only bumped
if the permission write itself succeeds.
Also cleaned up inline require('../db/db') calls to use top-level db.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 14:15:51 +03:00
Maxim Dolgolyov 6de91f7595 fix(labs): SVG markup rendered as text in 6 simulations
Hardcoded inline <svg class="ic"> markers used as arrow replacements

(left over from emoji removal) were displayed as raw HTML text where

the consumer used textContent or canvas fillText:

- chemsandbox: csbar-v5 (Продукты cell) used textContent → SVG visible.

  Switched to innerHTML for consistency with eq/ionNet cells.

  Quiz question (qEl.textContent) and answer also receiving SVG —

  cleaned via _csClean at source.

- reactions: modeTxt drawn via canvas fillText — replaced SVG with →.

- ionexchange: REACTIONS data + canvas labels — bulk SVG → Unicode arrows.

- newton: action button labels used textContent → switched to innerHTML;

  canvas arrow labels: SVG → Unicode →/↓.

- collision: 'KE сохранена' canvas label — SVG checkmark → ✓.

- projectile: canvas badges + textContent wind label — SVG → Unicode ←/→/↩.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 10:47:50 +03:00
Maxim Dolgolyov bf70c3d7d7 fix(admin-redesign): security — stored XSS via user name in onclick
Security review caught: per-row hover actions (users.js) and async

user picker (shop.js, gam.js) interpolated user-controlled name into

JS string literals inside onclick. LS.esc() escapes & < > " but

NOT backslash; the .replace(/'/g, '\'') fallback was broken.

Attack: any authenticated user could set their name to

  a\'); alert(1); //

via PATCH /api/auth/profile (stripTags doesn't strip \) — admin

viewing the users/shop/gam picker would execute arbitrary JS.

Fix: switch from JS-string interpolation to data-uid/data-name

attributes, read via dataset in handler. esc() correctly escapes

for HTML-attribute context; dataset returns the raw string with

zero parse re-entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:30:34 +03:00
Maxim Dolgolyov ce183ef14d docs(admin-redesign): mark phase 6 done + final-review prep
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:15:07 +03:00
Maxim Dolgolyov 3f89030b6e feat(admin): Phase 6 sub-commit 2 — remove .user-panel overlay
Now that the deep pages (sub-commit 1) work, retire the legacy
.user-panel inline overlay entirely.

* admin.html: removed <div class="user-panel" id="user-panel"> block
  inside #tab-users, removed dead .user-panel* CSS (kept .btn-close
  for any external use).
* users.js: removed openUserPanel / closeUserPanel / reloadUserPanel
  and their closure state (activeTr, activeUserRole). User row onclick
  switched from openUserPanel(...) → AdminRouter.navigate('#users/N').
  clearUserHistory / toggleBanUser / confirmDeleteUser / openEditUserModal
  / openUserPermsModal / doSet/doReset* all refactored to use the
  getActiveUid() helper (reads window.activeUid, set by user-detail.init)
  + reloadDetailAndList() helper (refreshes deep page + list together).
* sessions.js: row click + eye-button switched from toggleDrawer(id)
  → gotoSession(id) → AdminRouter.navigate('#sessions/N'). Removed
  toggleDrawer + renderDrawer functions (~60L) and openDrawerId state.
  Inline drawer markup removed from the row template.

Verified node --check on all touched JS. ast-index confirms zero
remaining usages of openUserPanel / closeUserPanel / reloadUserPanel /
toggleDrawer across the repo.

This completes Phase 6 and the admin-redesign feature.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:08:13 +03:00
Maxim Dolgolyov bd3020067b feat(admin): Phase 6 sub-commit 1 — add deep-page sections (overlay still works)
Add user-detail.js (~370L) and session-detail.js (~180L) section
modules that render full pages for #users/:id and #sessions/:id, plus
admin.js dispatch and HTML tab-panes. The legacy .user-panel overlay
is intentionally still in place — sub-commit 2 will remove it once the
deep pages are verified.

* admin.js: DEEP_ROUTES map + activateDeepPane(); activate(route, params)
  signature; initial dispatch respects hash params (so F5 on #users/123
  goes straight to the deep page).
* admin.html: new tab-panes #tab-user-detail / #tab-session-detail and
  two script tags. Old #user-panel overlay untouched.
* user-detail.js: header (avatar/role/email/meta) + sub-tabs
  (Обзор/Сессии/Классы/Audit) with URL-synced sub-tab routing
  (#users/N/sessions etc). Overview: 4 stat cards + per-subject SVG
  bar chart. Sessions: clickable rows that navigate to #sessions/N.
  Classes: placeholder empty-state (no per-user classes endpoint).
  Audit: client-side filter of /admin/audit-log by uid match. Header
  action buttons (Изменить/Права/История/Бан/Удалить) call existing
  overlay handlers; window.activeUid is set before opening any modal.
* session-detail.js: full header (user/subject/score/stats) + per-
  question correctness layout reusing the drawer renderer. Delete
  button uses LS.adminDeleteSession then navigates to #sessions.
  Clicking the user name opens the user deep page.
* users.js: quickOpenUserSessions now navigates to
  #users/<uid>/sessions instead of the bare #sessions list.

Verified node --check on all new/modified JS. baseline npm test still
shows pre-existing 3 auth failures unrelated to this change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:01:22 +03:00
Maxim Dolgolyov 69113ab35e feat(admin): phase 5 — per-row quick actions for users + sessions
Hover-only action buttons (right-aligned, opacity transition, hidden on mobile).

- users.js: 4 actions (ban/unban, award coins, sessions, delete) — replaces `>` glyph cell, falls back to glyph for non-admin / self

- sessions.js: 2 actions (view, delete)

- DELETE /api/admin/sessions/:id (NEW): transactional (assignment_sessions=NULL, user_answers, session_questions, test_sessions), audit-logged, admin-only

- event.stopPropagation defence-in-depth (each button + parent .row-actions)

- LS.confirm for destructive ops; LS.modal for award-coins amount/reason

- CSS injected once via #row-actions-style id-dedup (same content in both sections)

Existing user-panel overlay + session toggle-drawer flows untouched (Phase 6 removes overlay).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:53:19 +03:00
Maxim Dolgolyov f562fe4a71 feat(admin): phase 4 — Cmd+K command palette
Global search modal: actions + users + tests + classes.

- GET /api/admin/search?q=X (~50L controller): 3 parameterized LIKE queries, admin-only

- frontend/js/admin/palette.js (~366L): custom lightweight modal (not LS.modal — footer-button oriented), Ctrl+K/Cmd+K capture-phase override of generic /js/search.js, debounce 150ms, race-guard via _reqSeq, min-query 2 chars, 8 hardcoded actions, ↑↓ wrap + Enter, click-outside close

- adminGlobalSearch helper: drop ignored 'limit' param (server hardcodes 5/3/3)

window.AdminPalette = { open, close, isOpen } exposed for Phase 5/6 use.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:39:59 +03:00
Maxim Dolgolyov 41acbdd0d0 feat(admin): phase 3 — dashboard #overview landing
GET /api/admin/overview returns 24h digest (~0.08ms/call).

- adminController.getOverview: 7 prepared statements (users 24h, sessions 24h, active users, classes count, failed sessions, banned this week, top-5 sessions)

- new section frontend/js/admin/sections/overview.js (~205L): bento-grid cards, alerts (only when >0), top-5 table, quick-links

- nav-item + tab-pane reordered: #overview is now default; #stats remains routable

Auth: admin-only (inside requireRole('admin') block, sibling of /stats).

Backward compat: all 13 existing routes unchanged.

Known follow-ups (post-merge polish):

- activeClasses counts all (label could be 'Всего классов')

- failedSessions24h includes in_progress (could tighten to abandoned only)

- topSessions24h drops NULL-score completed rows

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:26:59 +03:00
Maxim Dolgolyov fa67ad1294 fix(admin): expose updateCharCounter for Q-modal oninput handler
Phase 2 review caught this: updateCharCounter was defined inside

questions.js IIFE but never exposed via window.X; admin.html:1672

calls it via oninput, would throw ReferenceError on every keypress.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 22:58:59 +03:00
Maxim Dolgolyov 8a815ca3eb docs(admin-redesign): mark phase 2 done + handoff notes for phase 3+ 2026-05-16 22:52:24 +03:00
Maxim Dolgolyov 92030b462c feat(admin): phase 2 — split admin.js into 13 section modules
Replace ~3500L admin.js monolith with thin orchestrator (~700L) +

14 IIFE-wrapped per-section modules under /js/admin/sections/.

Section modules expose AdminSections.<name>.init/reload (lazy init via

switchTab/router) and re-expose onclick handlers via window.X for

backward compat. Shared helpers (MODES/DIFFS, fmtDate, pctClass,

renderMath, qTypeBadge, pagination) live in /js/admin/_shared.js

exposed on window.AdminCtx.

switchTab now dispatches to AdminSections via ROUTE_TO_SECTION map;

non-extracted system tabs (topics/audit/errors/health/classroom/avatars)

remain inline in admin.js. user-panel overlay markup untouched — Phase 6

will remove it.
2026-05-16 22:50:14 +03:00
Maxim Dolgolyov 8a7bed487f feat(admin): phase 1 — hash-router
AdminRouter wraps existing switchTab for deep-linking.

- frontend/js/admin/router.js (new, 102L): parse/navigate/current/on/off, recursion guard via _navigating flag

- admin.html: +1 <script> before admin.js

- admin.js: switchTab(btn, opts) + initAdminRouter IIFE for hashchange dispatch

Backward compat: all 21 onclick=switchTab(this) callsites continue working.

F5 / back / forward / deep-link verified.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 22:22:20 +03:00
Maxim Dolgolyov 76e376ee04 chore(plan): admin-redesign 6-phase plan
PLAN.md + 6 subplans + CONTEXT.md

Strategy: Incremental | Mode: Automated | Execution: Orchestrator

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 21:47:55 +03:00
Maxim Dolgolyov bd7a9dbee2 feat(admin): pagination для users-таблицы (50/стр)
- adminGetUsers возвращает { users, total, page, limit }

- pagination-controls (← 1 … N →) с ellipsis для длинных списков

- shop/gam search callers адаптированы под новый формат ответа

- helper _renderPgnControls переиспользуем для sessions/shop

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:24:18 +03:00
Maxim Dolgolyov bcee5a57e3 ux(admin): Q-modal ergonomic improvements — формулы скрыты, preview по требованию
Полный wizard-refactor Q-modal был отложен как высокорискованный
(сложная форма с многими типами вопросов, риск регрессии). Вместо
этого — безопасные ergonomic-улучшения:

1) FORMULA BAR — collapsed by default
   Раньше: 18 кнопок формул всегда занимали ~50px вертикали в модалке,
   но нужны только при создании math-вопросов.
   Теперь: маленькая кнопка «Вставить формулу» с chevron. Click → bar
   разворачивается. Состояние сохраняется в пределах сессии (DOM-стейт).

2) PREVIEW — показывается только когда есть текст
   Раньше: пустой preview-блок с placeholder «Введите текст вопроса…»
   занимал ~80px независимо от состояния.
   Теперь: .q-preview-wrap.hidden скрывается полностью пока textarea
   пуста. Появляется по input с debounce 150ms (уже было).

Эффект: модал стал ~130px ниже в типичном кейсе (создание non-math
вопроса). На 1080p теперь умещается без скролла для single/multi
с 4 опциями.

Без wizard'а, без риска регрессии — но visible UX-win. Wizard-refactor
по-прежнему доступен как опция, если понадобится дальнейшее снижение
когнитивной нагрузки.
2026-05-16 20:04:08 +03:00
Maxim Dolgolyov 6b7d0355b6 ux(admin): lock-icons на admin-only табах + LS.state helpers
1) LOCK-ICONS на admin-only табах
   Раньше: 7 табов (Магазин, Геймификация, Шаблоны, Симуляции, Игры,
   Доступные тесты, Права доступа) скрывались от учителей через
   display:none. Учитель не знал что они существуют — discoverability 0.

   Теперь:
   - Все табы видны всем, но для не-админа добавлен .locked класс
   - .locked: opacity .42, cursor not-allowed, lock-icon справа
   - title=\"Только для администраторов\" — нативный tooltip
   - switchTab() при клике на .locked показывает toast вместо
     переключения

   Эффект: учитель видит границы своих прав; знает что есть в системе,
   но не доступно ему — может попросить админа дать доступ.

2) LS.state — общий helper для loading/empty/error состояний
   api.js:381 — добавлен LS.state с тремя методами:

   LS.state.loading(el, msg?)           — спиннер + опц. текст
   LS.state.empty(el, msg, icon='inbox') — пустое состояние с иконкой
   LS.state.error(el, err, retryFn?)    — красная иконка + текст
                                          + опц. кнопка «Повторить»

   Все три используют один CSS (.ls-state*) с одним визуальным языком.
   inject стилей лениво (id=ls-state-style).

   Демо-миграция: 3 error-handler'а в admin.js (Stats / Users /
   Sessions) переписаны на LS.state.error с retry-функцией. Юзер
   теперь может нажать «Повторить» вместо перезагрузки страницы.

   Остальные 20+ inline error/empty/spinner'ов в admin.js — для
   постепенной миграции (паттерн установлен).
2026-05-16 19:56:58 +03:00
Maxim Dolgolyov ffd7bac0ac ux(admin): sticky table headers + collapsible nav + унификация лейблов
3 победы из аудита админ-панели за один заход:

1) STICKY TABLE HEADERS
   admin.html:142 — добавлен position:sticky; top:0; z-index:5; на <th>
   Заголовки колонок теперь остаются видны при scroll длинных таблиц
   (Users, Sessions, Shop, Gam — 100+ строк). Background фон поменян
   на opaque #E5EAF7 чтобы строки скроллились чисто за header'ом.
   Стоимость: 1 CSS-правило. Эффект: пользователи не теряют контекст
   столбцов при просмотре длинного списка.

2) COLLAPSIBLE NAV GROUPS
   admin.html:875+ — 4 группы (Аналитика, Контент, Пользователи,
   Система) вместо плоского списка 21 кнопки с просто визуальными
   сепараторами. Каждая группа сворачивается кликом по заголовку.
   Состояние per-группа в localStorage (ls_adm_g_<slug>).
   Группа «Система» (только админ) теперь объединяет shop, gam, sims,
   games, audit, errors, health — раньше они шли вперемешку с
   teacher-видимыми табами (sublog, topics, broadcast). Переместил
   sublog/broadcast в группу «Пользователи», topics в «Контент» —
   логичнее по смыслу.
   Паттерн один-в-один как у sidebar.js (где мы это сделали ранее).

3) УНИФИКАЦИЯ ЛЕЙБЛОВ
   Правило: «+ Добавить» для атомов (вопрос, тема, опция, товар),
              «+ Создать» для составных объектов (тест, задание, курс).
   Изменения:
   - admin.html:1431 — «Создать» → «Добавить» (форма темы — атом)
   - admin.html:1195 — «Новый товар» → «Добавить товар»
   - admin.js:415 — q-modal title «Новый вопрос» → «Добавить вопрос»
   - admin.js:2239 — shop-form-title «Новый товар» → «Добавить товар»
   Теперь кнопка в toolbar и заголовок модалки/формы согласованы.

Остались крупные пункты из аудита (на отдельный заход):
  - Q-modal wizard (split на 2 шага) — 🔴 высокий приоритет
  - Pagination в больших таблицах — 🟡
  - Standardized error/loading states — 🔵
2026-05-16 19:48:31 +03:00
Maxim Dolgolyov 846a3c389d fix: sidebar group headers — контраст под светлую тему
Заголовки групп были rgba(255,255,255,0.45) — белые 45%, что под
тёмный sidebar. Но LearnSpace использует светлую тему (--bg=#EEF2FF),
из-за чего «УЧЕБНЫЙ ПРОЦЕСС» и пр. сливались с фоном.

Теперь:
  color: var(--text-3, #56687A) с opacity .72
  hover: var(--violet) с opacity 1

Visible contrast: было ~1.2:1 (невидимо), стало ~4:1 (WCAG AA для
небольшого uppercase-текста — годится).
2026-05-16 19:39:29 +03:00
Maxim Dolgolyov 5c66105fc2 refactor: ещё 6 модалок → LS.modal (dashboard, theory, course)
dashboard.html: 2 → 0 
  - join-modal — вступить в класс
  - qs-modal — быстрый тест с выбором предмета + режим + кол-во

theory.html: 1 → 0 
  - new-course-modal — создание нового курса учителем

course.html: 4 → 0 
  - add-section-modal — новый раздел курса
  - edit-course-modal — редактирование курса
  - add-lesson-modal — новый урок
  - save-course-tpl-modal — сохранить курс как шаблон

Везде:
  - Inline <div class=\"modal-overlay\">...</div> → удалён
  - openX(): создаёт modal через LS.modal({content, actions})
  - closeX() удалена — _xModal.close()
  - Глобальный selectQsSubject() inline'нут как listener на body модалки
  - Enter-handler на главных inputs сохранён

Не трогаю:
  - biochem.html#lib-modal — кастомная тёмная тема, не подходит под
    светлый LS.modal без редизайна
  - library.html — 3 сложные модалки (folder-access, assign, upload)
    с tabs и dynamic state — отдельный заход
  - classes.html — modal-assign (128 строк, complex) + review-modal
  - flashcards.html — fc-modal (не modal-overlay, своя CSS)

Прогресс миграции: 12 простых модалок → LS.modal за серию (4 ранее
+ 2 ранее + 6 сейчас). 4 страницы полностью очищены от
modal-overlay. Унифицированы:
  - ESC/backdrop/focus поведение
  - z-index (9000)
  - Анимация (scale .22s)
  - Адаптив на мобилке
2026-05-16 19:33:39 +03:00