Commit Graph

469 Commits

Author SHA1 Message Date
Maxim Dolgolyov 96b5e46660 revert(textbooks ui): откат компактной сетки — возврат к крупным карточкам с обложками 2026-05-29 21:43:11 +03:00
Maxim Dolgolyov f08a81263d refactor(textbooks ui): компактная сетка каталога — плитки 190px + фильтры по предмету
- Карточка: горизонтальный layout, 74px высоты — цветная маркер-полоса слева (46px) с классом + 4-буквенной аббрев. предмета + watermark, справа название/счётчик параграфов/прогресс-бар (3px)
- В ряд помещается 5-7 карточек на десктопе (вместо 2-3)
- Вся карточка кликабельна (ведёт на 'Продолжить' или 'Открыть')
- Кнопка 'Назначить ДЗ' для учителя — overlay в углу, появляется на hover
- Сверху сетки чипсы-фильтры по предмету с счётчиком; скрыты, если предметов <2
- На hover чуть приподнимается, в углу появляется 'Продолжить →'
- Mobile: 160px минимум, узкие отступы
2026-05-29 21:39:55 +03:00
Maxim Dolgolyov 79992d23c5 fix(bg): rain — drops instead of vertical stripes
Linear-gradients tiled at 3px wide produced striped curtains, not
rain. Switched to two pseudo-element layers of elongated radial
ellipses (1.5px × 12-18px) scattered across 130-180px tiles —
sparse drops at two depths with different fall speeds.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:38:25 +03:00
Maxim Dolgolyov f6fbe922a9 feat(shop): 9 premium animated backgrounds
Doubles the bg catalogue from 10 to 19 with richer multi-layer
animations. Every keyframe pack is CSS-only and respects the existing
prefers-reduced-motion fallback.

  sunset       550   slow hue cycle through warm palette
  rain         650   2-layer vertical streaks at different speeds
  snow         700   3-layer drifting flakes pattern
  clouds       750   drifting white blobs on day sky (only LIGHT one)
  fireflies    800   pulsing glowing dots, opposing drift
  cyber-grid   850   neon grid scrolling down with vignette
  kaleidoscope 1000  two huge conic-gradients in opposite rotation
  ocean        1100  layered blobs drift like undulating waves
  aurora-dance 1500  multi-band aurora — new premium top-tier

Tonal classification mirrored in api.js DARK_BG_SLUGS so the veil
picks the right contrast: clouds is light, the other 8 join the dark
set (alongside dark, stars, aurora, nebula, grid).

Each background also gains a matching .bg-preview.bg-<slug> rule that
reuses the same animation at the shop's 90px swatch — WYSIWYG.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:35:59 +03:00
Maxim Dolgolyov d838c94df4 fix(bg): visible button-groups and tracks on dark backgrounds
The pill containers (.p-tabs, .shop-filters) used a 6% black fill that
disappeared on the dark veil, so the rounded button group lost its
outline and the inactive tabs looked like floating text. Same for the
xp / progress tracks (.ach-xp-progress, .ep-bar, .po-bar) that used
7% black.

Dark-tone overrides:
  • Containers get a 6% white wash + 10% white border so the pill
    shape stays readable
  • Inactive p-tab gets the same color/hover treatment that .shop-filter
    already had (was an oversight in the previous fix)
  • Active pills gain a darker shadow halo so they don't look detached
  • Progress tracks switch to a 10% white track instead of 7% black

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:31:53 +03:00
Maxim Dolgolyov 23075dddb1 fix(bg): light text on dark-tone backgrounds
The dark veil was right (deep navy at 78%), but every page chrome
element below it inherited light-theme text colors and faded to
invisible — 'Магазин наград' header, shop filter buttons, achievement
group titles, balance counter etc.

Targeted overrides for body[data-bg-tone='dark']: only the elements
that sit directly on the veil get a light text color. White cards
(.shop-item, .ach-item, .ep-card) keep their dark text intact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:29:54 +03:00
Maxim Dolgolyov d2ca0d61cc fix(bg): add translucent veil so animated bgs don't bleed UI
The single bg-fx layer was painting at full vibrancy behind the entire
app. Most UI elements use rgba() fills — chips, sub-panels, the
achievements .ach-item, the goal-tier bar — so saturated colors bled
right through, hurting readability on the Достижения / dashboard /
mocks tabs.

Layered fix:
  • bg-fx drops to z-index:-2 (the animated layer)
  • new #ls-bg-veil sits on z-index:-1 with rgba(245,247,251,.78)
    (light) or rgba(15,23,42,.55) when body[data-bg-tone='dark']
  • applyCosmetics injects both elements and tags the body with
    bg-tone based on the slug (dark/stars/aurora/nebula/grid go dark,
    everything else light)
  • clearing the bg removes both layers + the tone attribute

Result: animations stay perceptible (~22% of the chosen palette comes
through the veil), but the page chrome reads at normal contrast.

Shop swatches keep full vibrancy — the .bg-preview is meant to show
the raw palette so users can compare.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:27:35 +03:00
Maxim Dolgolyov 1b04384770 fix(shop): opaque cards on owned/active so backgrounds don't bleed
The shop item card .owned/.active states used semi-transparent fills
(rgba(34,197,94,0.03) / rgba(6,214,224,0.04)) for a subtle color hint.
Phase 6 made the free background presets auto-owned, so every
'Применить'-able card got the translucent overlay — and with an
animated background active, the page-wide gradient bled straight
through the content (see screenshot).

Switch to fully opaque #fff fills, keep the color cue in the border
plus a thin inner-shadow halo. Same visual signal, no bleed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:23:44 +03:00
Maxim Dolgolyov 98ec1ed478 feat(shop): animated backgrounds — system-wide cosmetic + picker
A new cosmetic family: a fixed-position overlay painted behind every
page of the app, switchable from the profile shop. 4 free presets + 6
paid (250-1200 coins) so the new economy has another sink. Every
animation respects prefers-reduced-motion and falls back to its static
gradient.

Catalogue (migration 035):
  free:   none, gradient-soft, dots, dark
  paid:   gradient-flow, grid, bubbles, stars (mid)
          aurora, nebula                       (premium)

Backend:
  • migration 035 adds users.active_background + rebuilds shop_items
    CHECK to include 'background' (standard SQLite 'new + copy + swap')
    and seeds 10 items
  • shopController.getMyActive returns { background: { slug } } and
    activateItem handles type='background' (stores bare slug in
    active_background) + skips the user_purchases check for price=0
    so free presets work for everyone without per-user rows
  • routes/shop validate schema lets 'background' through

Frontend:
  • api.js applyCosmetics injects <div id='ls-bg-fx'> at body start
    and toggles class to bg-<slug>. Cleared backgrounds remove the
    element so dark→light transitions don't leave artifacts.
  • ls.css gains a self-contained 'ANIMATED BACKGROUNDS' block:
    keyframes per animated slug (ls-bg-flow, ls-bg-grid-scan,
    ls-bg-bubble-rise, ls-bg-stars-twinkle, ls-bg-aurora-spin,
    ls-bg-nebula-pan) wrapped in a prefers-reduced-motion kill-switch.
    Same .bg-<slug> classes are reused for the .bg-preview swatches.
  • profile.html shop:
    - new 'Фоны' filter button between Рамки and Титулы
    - _renderItemPreview type='background' draws a real 56-aspect swatch
      (same CSS as the page bg — what you see is what you apply)
    - _isItemActive matches by slug for background type
    - free items (price===0) treated as auto-owned in render so users
      can apply them without a fake 'purchase' step

Verified: getMyActive returns { background: { slug: 'nebula' } } after
flipping users.active_background; activate path updates the row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 21:13:53 +03:00
Maxim Dolgolyov 41ca41d69c feat(gamification): hide locked achievements of disabled modules
When a teacher / admin turns off a module (per-class, per-role, or
globally), the matching achievements no longer clutter the user's
'Достижения' tab — but only the ones the user hasn't earned yet.
Already-unlocked achievements stay visible forever. We never take a
reward away after the fact.

Backend:
  • migration 034 adds achievements.required_feature + backfills 42
    rows (9 exam9, 8 red_book, 6 lab, 5 classroom, 4 textbooks, 3 each
    of biochem/flashcards, 2 live_quiz, 2 pet). 32 core rows stay
    NULL = always visible.
  • middleware/features.js gains computeFeaturesForUser(userId, role)
    + isFeatureEnabledForUser — extracted from server.js#/api/features
    so multiple consumers (gam achievements, future shop filter, etc.)
    apply the same global+class+free_student merge.
  • service.seedAchievements derives required_feature from track/group
    when ACHIEVEMENT_DEFS doesn't spell one out, and UPDATE-syncs it on
    every boot — keeps catalogue consistent across upgrades.
  • _shared.getAllAchs SELECT now returns required_feature.
  • gamification/api.getAchievements filters: drop locked rows whose
    required_feature is === false for this user. Missing flag = ON
    (opt-in disable model).

Verified: with exam9 + pet disabled, 12 locked achievements vanish from
the response while unlocked ones in those tracks remain.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:40:16 +03:00
Maxim Dolgolyov dbeee44fc7 feat(shop): Phase 5 — 22 new shop items (frames + titles + theme)
Triples the catalogue from 10 to 32 active items so coins finally have
somewhere to land. Migration 033 seeds:

  • 12 new frames at 200-1200 coin tiers (морская, лесная, закат,
    минимал, винтаж, пиксельный, молния, космос, изумруд, призрак,
    кибер, золотой ободок) — each with curated CSS that renders
    correctly in the shop preview added in Phase 4

  • 9 new titles at 150-2000 coin tiers (стажёр, аналитик, геометр,
    алгебраист, физик, олимпиец, боссфайтер, магистр, профессор)
    — colored pills that pair with the new title preview UI

  • 1 new theme (тёплая бумага) using the existing active_theme slot

Effects are intentionally not extended in this migration — js/api.js
_applyEffect() only knows pulse/sparkle/snow today, and adding new
effect kinds belongs in a follow-up that updates the renderer in
tandem with the catalogue entries.

Re-runnable: each row is gated by WHERE NOT EXISTS (name, type) so
re-applying the migration on a partially-seeded environment is safe.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:32:08 +03:00
Maxim Dolgolyov 268ea31bb8 feat(gamification): Phase 4 — standalone coin events + coin_log
Coins were always 1:10 of XP. Now they have their own event log + a
helper that dedups by reason within a configurable window.

Backend:
  • migration 032 creates coin_log (user_id, amount, reason, created_at)
    with indices for the 'fired today?' check
  • awardCoins now records into coin_log on every call (reason defaults
    to 'xp_bonus' for the legacy XP-proportional path)
  • awardCoinsOnce(userId, amount, reason, window) — fires the bonus
    only if no row matches in the window:
      'day'     → DATE(created_at) = today
      'week'    → ISO week match
      'forever' → never twice

Wired events (Phase 4 subset of the plan):
  • Daily login — 10 coins, once/day. Hooked in updateStreak so the
    bonus rides on the existing 'daily_activity' XP trigger.
  • Daily goal completion — 15/25/40 coins (easy/medium/hard), once/day.
    Sits next to the existing tier XP bonus in updateDailyGoal.
  • Variant clear — 30 coins, once per (user, variant) forever. Fires
    from the exam-prep attempts endpoint when the user's final correct
    answer fills out a math9 variant.

Deferred (need invasive trigger hooks): weekly goal, paragraph close,
boss defeated, referral.

Verified end-to-end: awardCoinsOnce returns true→false on repeated
calls, coin_log records the first, coins balance moves once.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:30:14 +03:00
Maxim Dolgolyov b005226e2c feat(gamification): Phase 3 — 38 new achievements + triggers + 'exam' group
Adds achievement coverage for every feature shipped since the original
seed: exam-prep (math9), textbooks, classroom/board, biochemistry,
live-quiz, flashcards, hangman/crossword, pet, plus a new 'social' group
for class & leaderboard wins and 'consistency' extensions (streak_100,
goal_30, early_bird, night_owl).

74 achievements now (was 36), grouped into 7 sections:
  onboarding (3) → volume (8) → mastery (16) → consistency (7) →
  exam (9) → exploration (21) → social (10)

A new top-level group 'exam' slots between consistency and exploration
in the profile UI.

What's wired in service.checkPhase3Achievements (called from
checkAchievements):
  • streak_100 — extends the existing streak track
  • goal_30 — 30 days with daily_goals fully met (SUM check)
  • early_bird / night_owl — strftime('%H', xp_log.created_at)
  • exam_first / 25 / 100 — exam_attempts where is_correct=1
  • exam_variant_clear / 5_variants — perfect mock-variant sessions
  • exam_topic_master — ≥10 attempts at ≥90% on a single subtopic
  • exam_mock_done / pass / perfect — exam_mock_sessions.score
  • tb_first_para — textbook_progress
  • fc_first_deck / 100_cards / 1000_cards — flashcard_reviews
  • bc_first_molecule / 5_challenges / 20_challenges — bio_user_*
  • game_win_5 / 25 — xp_log reason IN (hangman_win, crossword_win)
  • pet_streak_7 / 30 — users.pet_petting_streak
  • lq_first / 3_quizzes — live_answers grouped by session
  • cr_first_join / 5 / 25_lessons — classroom_attendance
  • class_5_members / 25 — teacher's biggest class
  • parent_link — parent_links presence
  • lb_top10 / lb_top1 — weekly XP rank among students

What's deferred (catalog entry only, no trigger yet):
  • tb_chapter_done / tb_book_done / tb_3_books — need to parse
    textbook_progress.paragraphs_read JSON against textbook structure

Every block is wrapped in its own try/catch so a missing table on a
legacy install can't take down the whole achievement sweep.

Verified end-to-end: admin user picked up 7 new unlocks on first
checkAchievements call after seed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:26:59 +03:00
Maxim Dolgolyov 90c8464356 feat(gamification): Phase 2 — taxonomy + grouped UI for achievements
Achievements gain four new columns: group_slug, track, tier, sort_order.
Existing 36 are backfilled into 5 groups (onboarding/volume/mastery/
consistency/exploration) by migration 030; 'social' stays empty until
Phase 3 adds class/leaderboard/live-quiz tracks.

Tracks bundle escalating thresholds into one progression (tests_10/50/
100 → track='tests', tiers 1-3), so the UI can show '★★★' on the top
tier and the user understands the relationship. sort_order is reserved
in blocks of 10 inside groups of 100, leaving room for inserts without
renumbering.

Backend:
  • migration 030 adds the columns + index + backfill UPDATEs
  • _shared.ACHIEVEMENT_DEFS gains group/track/tier/sort_order per row
  • _shared exports new ACHIEVEMENT_GROUPS metadata for the UI
  • service.seedAchievements writes the new fields on insert AND
    backfills them via UPDATE on existing rows (fresh installs +
    pre-migration installs both end up consistent)
  • _shared.stmts.getAllAchs SELECT updated, ORDER BY sort_order
  • gamification/api.getAchievements forwards the new fields

Frontend:
  • profile.html groups achievements by group_slug with a per-section
    header (icon + title + 'unlocked / total' chip) and a tier-star
    badge (★★ etc.) on tier ≥ 2 items
  • Hard-coded ACH_GROUPS mirror of the backend list (small, stable)
  • New CSS for .ach-group / .ach-group-head / .ach-tier

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:19:46 +03:00
Maxim Dolgolyov 660e7e2747 feat(gamification): Phase 1 — full kill-switch + textbook XP wrapping
Until now the 'gamification' feature flag did nothing: it had no row in
app_settings, the admin couldn't toggle it, awardXP/awardCoins ignored
it, and the CSS only hid three dashboard widgets — XP bars in textbooks
stayed visible regardless.

Phase 1 closes every hole.

Backend (source of truth):
  • migration 029 seeds feature_gamification_enabled=1
  • new isGamificationEnabled() helper in gamification/_shared.js with a
    30s cache + invalidateGamificationCache() for instant admin toggles
  • awardXP / awardCoins / updateStreak / unlockAchievement /
    checkAchievements all bail out when the flag is off
  • /api/gamification/* and /api/shop/* (user routes) return 404 when
    disabled; admin routes remain open so the switch itself is reachable
  • adminController.updateFeatures gains 'gamification' in the allow-list
    and invalidates the cache on flip

Frontend:
  • LS.isGamificationEnabled() (synchronous, populated by loadFeatures)
    so xp.js + applyCosmetics can bail without a round-trip
  • xp.js load/add/flush become no-ops when the flag is off
  • applyCosmetics skips the round-trip when off
  • CSS .no-gamification rule expanded to cover .hero-xp-badge, .po-xp,
    .xp-card, .xp-bar, #frames-section, and a universal [data-gamified]
    hook for future blocks

Textbooks (Variant 2 of the plan):
  • backend/scripts/wrap_textbook_xp.py — idempotent script that adds
    data-gamified to 167 XP tags across 63 textbook files (chapters +
    hubs, all subjects/grades). Single CSS rule now hides everything.

Verified end-to-end: with the flag off, awardXP/awardCoins write nothing;
flipping back restores normal behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 19:43:24 +03:00
Maxim Dolgolyov 3e7e6e5b9b feat(phys11 ch8): Waves 13-14 — Глава 8 + ФИНАЛ КУРСА (12 интегральных боссов)
- ch8 — индиго-тема (--pri:#4f46e5), watermark ∞/★
- §45: эволюция картины мира (механика → ЭМ → СТО → ОТО → кванты → Стандартная модель), иерархия материи (от кварков до Вселенной), открытые проблемы (тёмная материя, тёмная энергия, объединение теорий)
- ФИНАЛ КУРСА: 12 интегральных боссов по всем 8 главам
  - Босс I: Колебания (Гл. 1)
  - Босс II: ЭМ-индукция (Гл. 2)
  - Боссы III-IV: Оптика (Гл. 3, §14-§17 и §18-§23)
  - Босс V: СТО (Гл. 4)
  - Босс VI: Фотоны (Гл. 5)
  - Боссы VII-VIII: Атом + Лазеры (Гл. 6)
  - Боссы IX-XI: Ядерная физика (Гл. 7)
  - Босс XII: Элем. частицы + картина мира
- Каждый босс 5 этапов, +80 XP
- При победе всех 12: ачивка phys11_master 'МАГИСТР ФИЗИКИ 11' + 500 XP бонус
- КУРС ФИЗИКИ 11 КЛАССА ЗАВЕРШЁН: 8 глав, 45 параграфов, ~80 боссов, 9 финальных ачивок
2026-05-29 19:30:41 +03:00
Maxim Dolgolyov cef226c53e feat(phys11 ch7): Waves 11-12 — Глава 7 «Ядерная физика» (§35-§44 + Финал)
- phys-fx.js: PHYS.RadioactiveDecay (график N(t)=N₀·2^(-t/T))
- ch7 — розово-красная тема (--pri:#e11d48), 10 параграфов
- §35: протонно-нейтронная модель, нуклоны, изотопы, изобары, ядерные силы
- §36: ядерные реакции, законы сохранения,  = \Delta m c^2$
- §37: дефект массы, {св}$, удельная $\varepsilon$, максимум у Fe
- §38: радиоактивность (Беккерель), α/β/γ, проникающая способность
- §39: закон распада  = N_0 \cdot 2^{-t/T}$, активность (Бк), C-14
- §40: деление U-235, цепные реакции, $, критическая масса
- §41: ядерный реактор (Ферми 1942), замедлитель, стержни, ВВЭР/РБМК
- §42: термояд D+T, Солнце, ИТЭР, токамак
- §43: дозы (Грей, Зиверт), коэф. $, нормы радиационной безопасности
- §44: Стандартная модель — 6 кварков, 6 лептонов, бозоны, Хиггс (2012), 4 взаимодействия
- 20 квизов + 10 боссов + 5 интегральных финальных боссов
- Финал главы: +200 XP, ачивка ch7_master 'Магистр ядра'
2026-05-29 19:26:16 +03:00
Maxim Dolgolyov a6d86f4374 feat(phys11 ch6): Wave 10 — Глава 6 «Физика атома» (§30-§34 + Финал)
- phys-fx.js: PHYS.BohrAtom (атом водорода с орбитами + переходом + фотон), PHYS.EnergyLevels (диаграмма E_n + переход + λ)
- ch6 — зелёная тема (--pri:#16a34a), watermark ⊕/n/ν/ω/L/★
- §30: открытие электрона (Томсон), опыт Резерфорда (1911), состав ядра, изотопы
- §31: 2 постулата Бора (1913), E_n=-13,6/n², Боровский радиус
- §32: спектры (сплошные/линейчатые/полосатые), формула Ридберга, серии Лаймана/Бальмера/Пашена
- §33: спонтанное и индуцированное излучение (Эйнштейн 1916), инверсная населённость
- §34: лазеры (Мейман 1960), резонатор, 4 свойства лазерного излучения, применения
- 10 квизов + 5 боссов (b1-b5) + buildSingleQuizPara helper для компактности
- Финал: 3 интегральных босса (fb1-fb3), +150 XP бонус, ачивка ch6_master
2026-05-29 19:18:04 +03:00
Maxim Dolgolyov b5c224d7f5 feat(phys11 ch5): Wave 9 — Глава 5 «Фотоны. Действия света» (§27-§29 + Финал)
- phys-fx.js: PHYS.PhotoeffectLab (катод+свет+анод+амперметр), PHYS.PlanckLinear (график Eк,max от ν)
- ch5 — розовая тема (--pri:#ec4899), watermark hν/A/λ/★
- §27: кризис АЧТ, гипотеза Планка E=hν (1900), открытие ф/э (Герц, Столетов), 3 закона
- §28: фотон, уравнение Эйнштейна hν=A+Eк, работа выхода, красная граница
- §29: импульс фотона p=hν/c, давление света, опыт Лебедева (1900), КВ-дуализм, де Бройль λ=h/p
- 6 квизов + 3 босса (b1-b3)
- Финал: 3 интегральных босса (fb1-fb3), +150 XP бонус, ачивка ch5_master
2026-05-29 19:10:17 +03:00
Maxim Dolgolyov 9df4fd5e24 feat(phys11 ch4): Wave 8 — Глава 4 «Основы СТО» (§24-§26 + Финал)
- phys-fx.js: PHYS.GammaPlot (график γ(β)), PHYS.TimeDilation (двое часов), PHYS.LengthContraction (стержень в покое и в движении)
- ch4 — синяя тема (--pri:#2563eb), watermark c/γ/E/★
- §24: принцип отн. Галилея, кризис эфира, опыт Майкельсона – Морли
- §25: 2 постулата Эйнштейна, замедление времени Δτ=γΔτ₀, сокращение L=L₀/γ, релятив. сложение скоростей
- §26: релятив. импульс p=γmv, E=γmc², E₀=mc², E²=(pc)²+(mc²)², аннигиляция, ядерная энергия
- 6 квизов + 3 босса (b1-b3)
- Финал: 3 интегральных босса (fb1-fb3), +150 XP бонус, ачивка ch4_master
2026-05-29 18:56:52 +03:00
Maxim Dolgolyov 06db392f6a feat(phys11 ch3): Wave 7 — §21-§23 + Финал главы 3 (ThinLens + TwoLensSystem)
- phys-fx.js: PHYS.ThinLens (собирающая/рассеивающая, 2 канон. луча, формула, мнимое=пунктир), PHYS.TwoLensSystem (телескоп Кеплера + микроскоп)
- §21: тонкая линза, формула 1/d + 1/f = 1/F, оптическая сила D = 1/F (дптр), 3 характерных луча
- §22: фотоаппарат (d > 2F) и проектор (F < d < 2F) на одном интерактиве
- §23: лупа Γ = 25/F, микроскоп Γ ≈ Γ_об·25/F_ок, телескоп Кеплера Γ = F_об/F_ок
- 6 квизов (I8-I10 CALC/TH) + 3 босса (b8-b10)
- Финал главы 3: 5 интегрированных боссов (fb1-fb5), +200 XP бонус, ачивка ch3_master
- checkFinalDone() — авто-проверка победы над всеми 5 боссами
- Глава 3 полностью завершена (10 параграфов + финал)
2026-05-29 18:48:16 +03:00
Maxim Dolgolyov 7a703bd184 feat(phys10 phase7 final): итоговая шпаргалка + 10 боссов + ачивка «Магистр физики 10» (+150 XP) 2026-05-29 18:46:10 +03:00
Maxim Dolgolyov 27a67d0866 feat(phys11 ch3): Wave 6 — §18-§20 + phys-fx SphericalMirror/RefractionLab/PrismSpectrum
- phys-fx.js: PHYS.SphericalMirror (вогнутые/выпуклые с формулой и 3 лучами), PHYS.RefractionLab (закон Снелла + ПВО), PHYS.PrismSpectrum (дисперсия, 7 цветов через модель Коши)
- §18: сферические зеркала, формула 1/d + 1/f = 1/F, увеличение Γ = -f/d, построение
- §19: показатель преломления n=c/v, закон Снелла, полное внутр. отражение
- §20: призма + дисперсия, плоскопараллельная пластинка, оптоволокно
- 6 квизов (I5-I7 CALC/TH) + 3 босса (b5-b7)
- §21-§23 + Final остаются заглушками для W7
2026-05-29 18:41:51 +03:00
Maxim Dolgolyov a5ffc624cf feat(phys10 ch6 wave2 + final): §36 «Газы» + §37 «Полупроводники» + Финал Главы 6 2026-05-29 18:41:39 +03:00
Maxim Dolgolyov e4801dcc2f feat(phys11 ch3): Wave 5 — Глава 3 «Оптика» §14-§17 + phys-fx TwoSlit/DiffractionGrating/FlatMirror
- phys-fx.js: PHYS.TwoSlit (опыт Юнга), PHYS.DiffractionGrating (с радужным спектром), PHYS.FlatMirror
- ch3 §14: Электромагнитная природа света + скорость света
- ch3 §15: Интерференция (опыт Юнга)
- ch3 §16: Дифракция света + дифракционная решётка
- ch3 §17: Отражение света + плоское зеркало
- 8 квизов (I1_CALC/NAT, I2_CALC/TH, I3_CALC/TH, I4_CALC/IMG)
- 4 босса (b1-b4) для §14-§17
- §18-§23 + Final — заглушки для W6/W7
2026-05-29 18:35:08 +03:00
Maxim Dolgolyov bed085ac98 feat(phys10 ch6 wave1): §34 «Ток в металлах» + §35 «Электролиты»
§34 «Электрический ток в металлах. Сверхпроводимость»:
- 3 makeCard: природа тока, R(t) для металлов, сверхпроводимость
- IV1: симуляция дрейфа электронов в решётке (SVG, slider U)
- IV2: график R(t) = R_0(1 + alpha t), переключение материалов + скачок T_c
- IV3: квикфайр на носителей заряда в средах (6 вопросов)
- IV4: тренажёр 5 задач (rho L/S, R при разных T, T_c ртути)

§35 «Электрический ток в электролитах. Электролиз»:
- 3 makeCard: электролиты/ионы, законы Фарадея, применение
- IV1: симуляция электролиза (катионы → катоду, анионы → аноду)
- IV2: калькулятор массы m = MIt/(Fn) для Cu/Ag/Al/Fe/H
- IV3: квикфайр направления ионов (6 вопросов, 2 кнопки)
- IV4: тренажёр 5 задач (расчёт m для Cu/Ag, F = 96500)
2026-05-29 18:32:53 +03:00
Maxim Dolgolyov e192feefcc feat(phys11 W4): Глава 2 §10-§13 + Финал главы 2
§10 Производство и передача электроэнергии:
- ТЭС/ГЭС/АЭС; формула потерь P=I²R
- Идея высоковольтных ЛЭП: чтобы уменьшить потери, повышают U
- Магистральные ЛЭП до 750 кВ → 220 В у потребителя
- 5 расчётов (включая повышение U в k раз → потери /k²)
- Босс §10: 5 этапов, +70 XP

§11 Экологические проблемы:
- ВИЭ: ВЭС, СЭС, ГеоТЭС, приливные, биогаз
- Достоинства (без CO₂) и недостатки (погода, площадь)
- 6+5 квизов на типы и плюсы/минусы
- Босс §11: 5 этапов, +70 XP

§12 ЭМ волны. Шкала ЭМ волн:
- ЭМ волна как поперечная, c = 1/√(ε₀μ₀) = 3·10⁸ м/с
- Inline SVG-шкала: радио/СВЧ/ИК/видимый/УФ/рентген/γ
  с радужным градиентом для видимого света
- 5 расчётов λ↔ν + 5 MC на диапазоны
- Босс §12: 5 этапов, +70 XP

§13 Действие ЭМ на живые организмы:
- Ионизирующее (>10 эВ: УФ-С, рентген, γ) vs неионизирующее
- Полезные применения и опасности
- Защита: экранирование (свинец), расстояние, время
- Босс §13: 5 этапов, +65 XP

Финал главы 2:
- 4 интегральных босса (LC+ток, трансф+ЛЭП, ЭМ волны, сборная)
- Celebration: ачивка phys11_ch2_master + 100 XP бонус

Файл 63 → 91 КБ. JS валидируется.
2026-05-29 18:25:30 +03:00
Maxim Dolgolyov d93d8b782e feat(phys10 ch5 wave4 + final): §33 «Самоиндукция» + Финал Главы 5 (7 боссов) 2026-05-29 18:24:57 +03:00
Maxim Dolgolyov 8c3e7ce7aa feat(phys10 ch5 wave3): §31 «Магнитный поток + ЭМИ» + §32 «Ленц + Фарадей» 2026-05-29 18:18:29 +03:00
Maxim Dolgolyov a09616450f feat(phys11 W3): Глава 2 §7-§9 + расширение phys-fx.js (LCcircuit, ACgen, Transformer)
phys-fx.js (+3 электротехнических компонента):
- PHYS.LCcircuit: колебательный контур со схемой C↔L, провода, стрелка тока,
  заряды на пластинах (меняют знак), энергетические столбцы W_C и W_L,
  формула T=2π√(LC) с актуальным значением
- PHYS.ACgen: генератор переменного тока — слева вращающаяся рамка в B,
  справа график U(t)=U₀sin(ωt) с историей
- PHYS.Transformer: схема трансформатора с сердечником, обмотки N₁, N₂,
  входное U₁, расчётное U₂, коэф. трансформации k, отметка повышающий/понижающий

physics_11_ch2.html (~63 КБ, violet-тема):
- 2-кол layout с col-side, hero violet-градиент
- psel-grid 8 карточек (§7-§13 + Финал); §7-§9 активны
- Watermarks: LC, ∿, ≡, , ⚙, λ, ☣, ★

§7 Колебательный контур. Формула Томсона:
- 3 теор. карточки (контур, формула Томсона, превращения энергии)
- Инт. 1: LCcircuit с ползунками L (1-100 мГн), C (0.1-10 мкФ)
- Инт. 2: расчёт T, ν (5 input)
- Инт. 3: аналогии и свойства (5 MC)
- Босс §7: 5 этапов, +70 XP

§8 Вынужденные ЭМ колеб. Переменный ток:
- 2 теор. карточки (генератор, действ. значения I₀/√2)
- Инт. 1: ACgen (вращ. рамка → синусоида) с ползунком ω
- Инт. 2: расчёт I/I₀, U/U₀ (5 input)
- Инт. 3: теория действующих значений (5 MC)
- Босс §8: 5 этапов, +70 XP

§9 Трансформатор:
- 2 теор. карточки (устройство, коэф. трансформации, I₁U₁=I₂U₂)
- Инт. 1: Transformer с ползунками N₁ (50-1000), N₂ (10-1000), U₁ (12-10000 В)
- Инт. 2: расчёт U₂, I₂, k (5 input)
- Инт. 3: повышающий/понижающий (5 MC)
- Босс §9: 5 этапов, +70 XP

§10-§13, Финал — stub-карточки 'в разработке (W4)'.

LocalStorage: physics11_ch2_*, общий physics11_xp
Server sync: /api/textbooks/physics-11-ch2/progress
2026-05-29 18:15:00 +03:00
Maxim Dolgolyov 7aa681b503 feat(phys10 ch5 wave2): §29 «Сила Ампера» + §30 «Сила Лоренца» + 3D-траектория 2026-05-29 18:11:18 +03:00
Maxim Dolgolyov 6087c814b3 feat(phys10 ch5 wave1): §27 «Магнитное поле тока» + §28 «Индукция» 2026-05-29 18:03:50 +03:00
Maxim Dolgolyov fb01e5aafb feat(phys11 W2): Глава 1 §4-§6 + Финал + ResonanceCurve/TransverseWave/LongitudinalWave
phys-fx.js (+3 компонента):
- PHYS.ResonanceCurve: график A(ω) при разных γ затухания, маркер ω₀ и текущей ω
- PHYS.TransverseWave: бегущая поперечная волна (струна) с красным маркером колеблющейся точки + скобка λ
- PHYS.LongitudinalWave: зоны сжатия/разрежения через 60 точек-молекул

physics_11_ch1.html (63→89 КБ):

§4 Резонанс:
- 2 теор. карточки (свобод./вынужд., резонанс ω≈ω₀, формула A(ω))
- Инт. 1: ResonanceCurve с ползунками γ и ω — видно как пик уменьшается с ростом затухания
- Инт. 2: верно/неверно (5)
- Инт. 3: что произойдёт (5, качели/мост Tacoma/солдатский шаг)
- Босс §4: 5 этапов, +70 XP

§5 Волны:
- 2 теор. карточки (определение, поперечные/продольные, λ=vT)
- Инт. 1: TransverseWave с 3 ползунками (A, λ, v) — красная точка показывает что частица колеблется на месте
- Инт. 2: LongitudinalWave (звук-аналог) с 2 ползунками
- Инт. 3: расчёт λ,v,T (5 input)
- Инт. 4: тип волны и свойства (5 MC)
- Босс §5: 5 этапов, +70 XP

§6 Звук:
- 2 теор. карточки (звук как продол. упруг. волна, диапазоны, громкость/высота/тембр)
- Инт. 1: LongitudinalWave (звуковая) с ползунками A, λ
- Инт. 2: расчёт λ звука в воздухе (5 input)
- Инт. 3: свойства звука (5 MC)
- Босс §6: 5 этапов, +65 XP

Финал главы 1:
- 4 интегральных босса (колебания, маятники+энергия, резонанс, волны+звук)
- Celebration: ачивка phys11_ch1_master + 100 XP бонус
- Сохранение в localStorage.physics11_achievements
2026-05-29 18:02:53 +03:00
Maxim Dolgolyov 2b13976610 feat(phys10 ch4 + final): §25 ЭДС + §26 закон Ома + Финал Главы 4 2026-05-29 17:56:38 +03:00
Maxim Dolgolyov f2a1c6e24d feat(phys11 W1): Глава 1 §1-§3 + расширение phys-fx.js (EnergyView)
phys-fx.js (+EnergyView):
- PHYS.EnergyView — график 3 кривых: W_к (красный), W_п (зелёный), W_мех=const (фиолетовый пунктир)
- Использует кинетическую/потенциальную энергию для гарм. колеб.: cos², sin², сумма = 1
- Легенда в правом верхнем углу

physics_11_ch1.html (~63 КБ):
Архитектура geom_10_r1 (geom11-стиль):
- 2-кол layout с col-side (XP card + cheat sheet + tip)
- Hero cyan-градиент + кнопка 'Начать §1'
- psel-grid: 6 параграфов + Финал; §1-§3 активны, §4-§6 и Финал locked
- sec секции с watermark (∿, маятник, E, ☰, ∿, муз. нота, ★)
- card теории + wg workshops + opt-btn кнопки

§1 Колебательное движение. Гарм. колебания:
- 3 теор. карточки (определение, T/ν/ω, гарм. колеб. x=Acos(ωt+φ₀))
- Инт. 1: Oscillogram с ползунками A, ω, φ (live-анимация)
- Инт. 2: Расчёт T,ν,ω (5 задач input)
- Инт. 3: Свойства колеб. (5 MC)
- Босс §1: 5 этапов, +65 XP

§2 Маятники:
- 2 теор. карточки (пружинный T=2π√(m/k), матем. T=2π√(l/g))
- Инт. 1: SpringMass + Pendulum side-by-side с 4 ползунками (m,k,l,g)
- Инт. 2: Расчёт T (5 input)
- Инт. 3: Как изменится T (5 MC)
- Босс §2: 5 этапов, +70 XP

§3 Превращения энергии:
- 2 теор. карточки (формулы W_к, W_п; закон сохранения W_мех=kA²/2)
- Инт. 1: EnergyView с ползунками A, ω (3 кривые в реал. времени)
- Инт. 2: Расчёт энергии (5 input)
- Инт. 3: Превращения энергии (5 MC)
- Босс §3: 5 этапов, +65 XP

§4-§6 и Финал — stub-карточки 'в разработке (W2)'.

LocalStorage: physics11_ch1_*, physics11_xp (общий со всем курсом)
Server sync: /api/textbooks/physics-11-ch1/progress
2026-05-29 17:52:47 +03:00
Maxim Dolgolyov f999ad550e feat(phys10 ch3 wave5 + final): §24 «Энергия конденсатора» + Финал Главы 3 (7 боссов) 2026-05-29 17:48:13 +03:00
Maxim Dolgolyov 22b95ed072 feat(phys11 W0): инфра — миграция БД, phys-fx.js, hub + 8 stub-глав
Миграция 031_physics_11_hub.sql:
- hub textbook 'physics-11' (cyan, sort 12, para_count 45)
- 8 children по главам: ch1 cyan, ch2 violet, ch3 amber, ch4 blue,
  ch5 pink, ch6 green, ch7 rose, ch8 indigo

frontend/js/phys-fx.js (~360 строк):
- Глобальный requestAnimationFrame-цикл (Ticker) с подписками
- util.subscribe/unsubscribe + IntersectionObserver-пауза невидимых
- util.svgFrame, util.axes, util.slider — общие хелперы
- PHYS.Oscillogram: гарм. колебания с амплитудой/частотой/фазой/затуханием
- PHYS.SpringMass: пружинный маятник (T=2π√(m/k)) с зигзаг-пружиной
- PHYS.Pendulum: математический маятник (T=2π√(l/g)) с дугой

frontend/textbooks/physics_11_hub.html:
- Header cyan-gradient + watermark ФИЗИКА
- 4-кол grid карточек глав (8 шт., responsive)
- Прогресс-бар курса + API /api/textbooks/physics-11/children

frontend/textbooks/physics_11_ch1..ch8.html:
- Stub-страницы по образцу geometry_10_r1..r4 (W0)
- Список параграфов с ключевыми формулами + 'Будет добавлено в волне WN'
- Каждая глава со своей темой (gradient, watermark, цветами)
- phys-fx.js подключён сразу (ready для W1+)

backend/scripts/gen_phys11_stubs.js — генератор для повторных сборок.
2026-05-29 17:42:36 +03:00
Maxim Dolgolyov 774b54afc8 feat(phys10 ch3 wave4): §22 «Напряжение» + §23 «Конденсаторы» 2026-05-29 17:41:19 +03:00
Maxim Dolgolyov a24c334730 docs(plans): убраны лабораторные работы из плана Физика 11
- Удалён physics_11_labs.html из списка файлов
- Удалена секция 'Лабораторный эксперимент' в хабе и wireframe
- Убрана волна W15 'physics_11_labs.html — 9 лабораторных работ' (W16 polish → W15)
- Обновлены счётчики: 10 файлов → 9, ~28 сессий → ~26, 16 волн → 15
- Из итогов убрана строка про 9 лабораторок
2026-05-29 17:35:51 +03:00
Maxim Dolgolyov dfc17ae717 feat(phys10 ch3 wave3): §20 «Линии поля» + §21 «Работа и потенциал» 2026-05-29 17:34:50 +03:00
Maxim Dolgolyov dc7ad11e52 docs(plans): добавлен большой план реализации Физика 11 (Жилко-Маркович-Сокольский 2021)
Самый большой план проекта:
- 8 глав, 45 параграфов
- Новая библиотека phys-fx.js (~1000 строк): осциллограммы, маятники,
  волны, LC-контуры, RayTracer (линзы/зеркала/призмы), фотоэффект,
  атом Бора, спектры, ядро, радиоактивный распад, цепная реакция
- 8 цветовых тем по главам (cyan/violet/amber/sky/yellow/emerald/red/indigo)
- ~92 босса, ~135 квизов, 9 ачивок (включая phys11_master)
- 9 лабораторных работ — отдельная страница
- 16 волн реализации (~28 сессий) — крупнейший курс проекта
- Стиль единый с geom11_ch1 / geom10_r1 (2-кол layout, psel-grid, wg)
- Глобальный RAF-таймер для экономии CPU при 5-10 симуляциях на странице
- IntersectionObserver для паузы невидимых симуляций
2026-05-29 17:32:27 +03:00
Maxim Dolgolyov de1dbea8aa feat(phys10 ch3 wave2): §18 «Поле» + §19 «Напряжённость и суперпозиция» 2026-05-29 17:27:35 +03:00
Maxim Dolgolyov 1611e4b461 feat(phys10 ch3 wave1): §16 «Заряд» + §17 «Закон Кулона» 2026-05-29 17:21:04 +03:00
Maxim Dolgolyov 07adcbd108 feat(phys10 ch2 wave3 + final): §15 «Цикл Карно» + Финал Главы 2 (5 боссов) 2026-05-29 17:13:22 +03:00
Maxim Dolgolyov f2398dd078 feat(phys10 ch2 wave2): §13 «Количество теплоты» + §14 «Первый закон ТД»
Наполнены параграфы §13 и §14 (build_p13, build_p14) — теория, формулы,
4 интерактива каждый.

§13:
- 3 теоретические карточки (Q=cmΔT, фазовые переходы, баланс)
- ИНТ1: универсальный калькулятор Q (4 режима: нагрев/плавл/исп/сгор)
- ИНТ2: SVG-график нагревания льда → воды → пара (4 сегмента)
- ИНТ3: DnD-сортер 6 явлений → 4 типа процессов
- ИНТ4: тренажёр 6 задач

§14:
- 3 теоретические карточки (формулировка, изопроцессы, адиабата)
- ИНТ1: визуализатор первого закона с бар-чартом Q, ΔU, A для 4 процессов
- ИНТ2: калькулятор Q = ΔU + A (3 режима поиска)
- ИНТ3: квикфайр 'что неизменно' (T/V/p/Q)
- ИНТ4: тренажёр 5 задач

Файл: 1537 → 2325 строк. KaTeX-делимитеры, renderMath, secNav, wireReadBtn.
2026-05-29 17:06:13 +03:00
Maxim Dolgolyov e1a694ed90 feat(phys10 ch2 wave1): §11 «Внутренняя энергия» + §12 «Работа в ТД» 2026-05-29 16:58:44 +03:00
Maxim Dolgolyov 5e9bafb20c feat(phys10 ch1 wave5 + final): §9 «Испарение» + §10 «Влажность» + Финал Главы 1 (7 боссов) 2026-05-29 16:51:43 +03:00
Maxim Dolgolyov c3d6af8757 fix(exam-prep): normalize LaTeX in dashboard preview text
Recent-attempts widget on /exam-prep/:examKey was showing raw LaTeX
like '\dfrac{7}{9}' because stripPreview only removed HTML tags.
Now it also converts common LaTeX to readable unicode (fractions →
a/b, \sqrt → √, \cdot → ·, comparisons → ≤≥≠, Greek letters, etc.)
before truncating.

KaTeX rendering would be overkill for a 100-char preview row; this
just makes the existing text legible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 16:45:59 +03:00
Maxim Dolgolyov 4154e0b791 feat(phys10 ch1 wave4): §7 «Твёрдые тела» + §8 «Жидкости» 2026-05-29 16:42:20 +03:00
Maxim Dolgolyov 5356096349 fix(api): auto-stringify object bodies in LS.api (apiFetch)
LS.api was passing raw object bodies straight to fetch(), which coerces
them to '[object Object]' — the server then parsed empty JSON and 400'd
on missing fields. This silently broke every POST that uses LS.api
directly (EP.api.startMock, saveAttempt, mockAnswer, etc.).

LS.post already stringified, so most call sites worked. Now apiFetch
mirrors that behavior for plain objects, while FormData / Blob /
URLSearchParams / ArrayBuffer / strings still pass through unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 16:40:42 +03:00