From 4a7675bc027f64eeec23615703497a9a2b0b725f Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 16:16:31 +0100 Subject: [PATCH 1/2] home: add missing roadmap cover SVGs CategoriesSection imports covers for the new topics (pandas, ai-coding, low-level-design, behavioral, machine-learning) and a default fallback, but the files were never committed, so vite build failed with 'Could not resolve ../../assets/roadmaps/pandas.svg'. --- frontend/src/assets/roadmaps/ai-coding.svg | 39 ++++++++++++ frontend/src/assets/roadmaps/behavioral.svg | 30 +++++++++ frontend/src/assets/roadmaps/default.svg | 25 ++++++++ .../src/assets/roadmaps/low-level-design.svg | 53 ++++++++++++++++ .../src/assets/roadmaps/machine-learning.svg | 39 ++++++++++++ frontend/src/assets/roadmaps/pandas.svg | 61 +++++++++++++++++++ 6 files changed, 247 insertions(+) create mode 100644 frontend/src/assets/roadmaps/ai-coding.svg create mode 100644 frontend/src/assets/roadmaps/behavioral.svg create mode 100644 frontend/src/assets/roadmaps/default.svg create mode 100644 frontend/src/assets/roadmaps/low-level-design.svg create mode 100644 frontend/src/assets/roadmaps/machine-learning.svg create mode 100644 frontend/src/assets/roadmaps/pandas.svg diff --git a/frontend/src/assets/roadmaps/ai-coding.svg b/frontend/src/assets/roadmaps/ai-coding.svg new file mode 100644 index 0000000..bf9e3bd --- /dev/null +++ b/frontend/src/assets/roadmaps/ai-coding.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/assets/roadmaps/behavioral.svg b/frontend/src/assets/roadmaps/behavioral.svg new file mode 100644 index 0000000..c1853a5 --- /dev/null +++ b/frontend/src/assets/roadmaps/behavioral.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + S + T + A + R + + + + + + + + + + diff --git a/frontend/src/assets/roadmaps/default.svg b/frontend/src/assets/roadmaps/default.svg new file mode 100644 index 0000000..c4ae387 --- /dev/null +++ b/frontend/src/assets/roadmaps/default.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/assets/roadmaps/low-level-design.svg b/frontend/src/assets/roadmaps/low-level-design.svg new file mode 100644 index 0000000..3c19c74 --- /dev/null +++ b/frontend/src/assets/roadmaps/low-level-design.svg @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/assets/roadmaps/machine-learning.svg b/frontend/src/assets/roadmaps/machine-learning.svg new file mode 100644 index 0000000..5b6d98f --- /dev/null +++ b/frontend/src/assets/roadmaps/machine-learning.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/assets/roadmaps/pandas.svg b/frontend/src/assets/roadmaps/pandas.svg new file mode 100644 index 0000000..5b270c7 --- /dev/null +++ b/frontend/src/assets/roadmaps/pandas.svg @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From afa08efd47fab43a52720472acf6954ac8bf0dd5 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 17:02:13 +0100 Subject: [PATCH 2/2] roadmap: own page with a path map, step interviews with Bit, badges and ranks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /roadmap/:slug: hero with progress ring and rank, winding path of steps (done / current / locked), step panel with mastery marks - 'Пройти шаг с Битом': interview mode generalized (InterviewFlow) and run on a roadmap step at /roadmap/:slug/step/:stepId/interview/:n - achievements restored (lost in the 2026-11-30 redesign): per-roadmap milestones and ranks (Питонист → Суперпитонист → Гиперпитонист, ...), general badges, unlock dialog, profile 'Достижения' section - catalog: progress on every card, 'continue' banner, badges counter --- .../achievements/AchievementsPanel.tsx | 88 ++++++ .../components/achievements/BadgeMedal.tsx | 79 +++++ .../src/components/achievements/BadgeTile.tsx | 68 +++++ .../achievements/BadgeUnlockDialog.tsx | 97 +++++++ .../achievements/achievements.test.ts | 76 +++++ .../components/achievements/achievements.ts | 235 +++++++++++++++ .../achievements/useAchievements.ts | 89 ++++++ .../components/interview/InterviewResults.tsx | 6 +- .../components/interview/InterviewSetup.tsx | 11 +- frontend/src/components/ui/PracticeMascot.tsx | 2 +- frontend/src/pages/InterviewModePage.tsx | 78 +++-- .../src/pages/RoadmapsPage/RoadmapCard.tsx | 148 +++++----- .../src/pages/RoadmapsPage/RoadmapCover.tsx | 81 ++++++ .../src/pages/RoadmapsPage/RoadmapDetail.tsx | 141 --------- .../src/pages/RoadmapsPage/RoadmapHero.tsx | 192 +++++++++++++ .../RoadmapsPage/RoadmapInterviewPage.tsx | 40 +++ .../src/pages/RoadmapsPage/RoadmapPage.tsx | 228 +++++++++++++++ .../src/pages/RoadmapsPage/RoadmapPath.tsx | 205 +++++++++++++ frontend/src/pages/RoadmapsPage/StepPanel.tsx | 208 ++++++++++++++ .../src/pages/RoadmapsPage/TimelineStep.tsx | 269 ------------------ frontend/src/pages/RoadmapsPage/index.tsx | 264 +++++++---------- frontend/src/pages/UserProfilePage/index.tsx | 2 + frontend/src/queries/interview.ts | 18 +- frontend/src/router.tsx | 8 + 24 files changed, 1952 insertions(+), 681 deletions(-) create mode 100644 frontend/src/components/achievements/AchievementsPanel.tsx create mode 100644 frontend/src/components/achievements/BadgeMedal.tsx create mode 100644 frontend/src/components/achievements/BadgeTile.tsx create mode 100644 frontend/src/components/achievements/BadgeUnlockDialog.tsx create mode 100644 frontend/src/components/achievements/achievements.test.ts create mode 100644 frontend/src/components/achievements/achievements.ts create mode 100644 frontend/src/components/achievements/useAchievements.ts create mode 100644 frontend/src/pages/RoadmapsPage/RoadmapCover.tsx delete mode 100644 frontend/src/pages/RoadmapsPage/RoadmapDetail.tsx create mode 100644 frontend/src/pages/RoadmapsPage/RoadmapHero.tsx create mode 100644 frontend/src/pages/RoadmapsPage/RoadmapInterviewPage.tsx create mode 100644 frontend/src/pages/RoadmapsPage/RoadmapPage.tsx create mode 100644 frontend/src/pages/RoadmapsPage/RoadmapPath.tsx create mode 100644 frontend/src/pages/RoadmapsPage/StepPanel.tsx delete mode 100644 frontend/src/pages/RoadmapsPage/TimelineStep.tsx diff --git a/frontend/src/components/achievements/AchievementsPanel.tsx b/frontend/src/components/achievements/AchievementsPanel.tsx new file mode 100644 index 0000000..e9277bf --- /dev/null +++ b/frontend/src/components/achievements/AchievementsPanel.tsx @@ -0,0 +1,88 @@ +import { useEffect, useRef } from 'react'; +import { Link as RouterLink, useLocation } from 'react-router-dom'; +import { Box, LinearProgress, Skeleton, Stack, Typography } from '@mui/material'; +import { radius, useTokens } from '../../theme/tokens'; +import { BadgeGrid } from './BadgeTile'; +import { BadgeUnlockDialog } from './BadgeUnlockDialog'; +import { useAchievements, useBadgeCelebration } from './useAchievements'; + +/** Витрина всех значков: общие и по каждому роадмапу. Якорь `#achievements`. */ +export const AchievementsPanel = () => { + const { c } = useTokens(); + const { hash } = useLocation(); + const ref = useRef(null); + const achievements = useAchievements(); + const celebration = useBadgeCelebration(achievements.all, achievements.ready); + const earned = achievements.all.filter((b) => b.unlocked).length; + const total = achievements.all.length; + + useEffect(() => { + if (hash === '#achievements' && achievements.ready) ref.current?.scrollIntoView({ block: 'start' }); + }, [hash, achievements.ready]); + + return ( + + + + Достижения + + {total > 0 && ( + + {earned} из {total} + + )} + + {total > 0 && ( + + )} + + {!achievements.ready ? ( + + + + + ) : ( + + {achievements.general.length > 0 && ( + + + Общие + + + + )} + {achievements.roadmaps.map((r) => ( + + + + Роадмап «{r.detail.title}» + + + Открыть маршрут → + + + + + ))} + + )} + + + ); +}; diff --git a/frontend/src/components/achievements/BadgeMedal.tsx b/frontend/src/components/achievements/BadgeMedal.tsx new file mode 100644 index 0000000..082151c --- /dev/null +++ b/frontend/src/components/achievements/BadgeMedal.tsx @@ -0,0 +1,79 @@ +import { useId } from 'react'; +import { Box } from '@mui/material'; +import { useTokens } from '../../theme/tokens'; +import type { BadgeTier } from './achievements'; + +/** Цвета металла: верх и низ градиента, обводка. */ +const METAL: Record, [string, string, string]> = { + bronze: ['#E2A272', '#8F5530', '#F3C29B'], + silver: ['#E6E9EF', '#8D93A0', '#FFFFFF'], + gold: ['#FFD978', '#B7812A', '#FFF0B8'], +}; + +interface BadgeMedalProps { + tier: BadgeTier; + glyph: string; + unlocked: boolean; + size?: number; +} + +/** Медаль-шестиугольник: металл по уровню, серая с замком, пока значок не получен. */ +export const BadgeMedal = ({ tier, glyph, unlocked, size = 56 }: BadgeMedalProps) => { + const { c } = useTokens(); + const gid = useId().replace(/:/g, ''); + const [top, bottom, rim] = + tier === 'milestone' ? [c.accentHover, c.accent, c.accentHover] : METAL[tier]; + const fillTop = unlocked ? top : c.surface2; + const fillBottom = unlocked ? bottom : c.surface2; + const stroke = unlocked ? rim : c.borderStrong; + const fontSize = glyph.length >= 4 ? 15 : glyph.length === 3 ? 17 : 21; + + return ( + + + + + + + + + + {unlocked ? ( + + {glyph} + + ) : ( + + + + + )} + + ); +}; diff --git a/frontend/src/components/achievements/BadgeTile.tsx b/frontend/src/components/achievements/BadgeTile.tsx new file mode 100644 index 0000000..bf30294 --- /dev/null +++ b/frontend/src/components/achievements/BadgeTile.tsx @@ -0,0 +1,68 @@ +import { Box, LinearProgress, Tooltip, Typography } from '@mui/material'; +import { radius, useTokens } from '../../theme/tokens'; +import { BadgeMedal } from './BadgeMedal'; +import { TIER_LABEL } from './achievements'; +import type { Badge } from './achievements'; + +/** Плитка значка: медаль, название, условие и прогресс до получения. */ +export const BadgeTile = ({ badge }: { badge: Badge }) => { + const { c } = useTokens(); + const percent = badge.target > 0 ? Math.min(100, (badge.progress / badge.target) * 100) : 0; + return ( + + + + + {badge.title} + + + {badge.description} + + {badge.unlocked ? ( + + Получен · {TIER_LABEL[badge.tier]} + + ) : ( + + + + + {badge.progress}/{badge.target} + + + + )} + + + ); +}; + +/** Сетка значков. */ +export const BadgeGrid = ({ badges }: { badges: Badge[] }) => ( + + {badges.map((badge) => ( + + ))} + +); diff --git a/frontend/src/components/achievements/BadgeUnlockDialog.tsx b/frontend/src/components/achievements/BadgeUnlockDialog.tsx new file mode 100644 index 0000000..3e40655 --- /dev/null +++ b/frontend/src/components/achievements/BadgeUnlockDialog.tsx @@ -0,0 +1,97 @@ +import { useEffect, useRef } from 'react'; +import { Box, Button, Dialog, DialogActions, DialogContent, Stack, Typography, keyframes } from '@mui/material'; +import { bitSay } from '../ui/bitVoice'; +import { plural } from '../../utils/difficulty'; +import { useTokens } from '../../theme/tokens'; +import { BadgeMedal } from './BadgeMedal'; +import { TIER_LABEL } from './achievements'; +import type { Badge } from './achievements'; + +const pop = keyframes` + 0% { transform: scale(.4) rotate(-12deg); opacity: 0; } + 60% { transform: scale(1.12) rotate(4deg); opacity: 1; } + 100% { transform: scale(1) rotate(0); } +`; +const shine = keyframes` + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } +`; + +/** Поздравление с новыми значками: появляется, когда значок получен впервые. */ +export const BadgeUnlockDialog = ({ badges, onClose }: { badges: Badge[]; onClose: () => void }) => { + const { c } = useTokens(); + const open = badges.length > 0; + const said = useRef(''); + const top = badges.find((b) => b.tier === 'gold') ?? badges.find((b) => b.tier === 'silver') ?? badges[0]; + + useEffect(() => { + if (!open) return; + const key = badges.map((b) => b.id).join(','); + if (said.current === key) return; + said.current = key; + const text = + badges.length === 1 + ? `Новый значок «${badges[0].title}»! Бип-бип, горжусь.` + : `Сразу ${badges.length} ${plural(badges.length, ['значок', 'значка', 'значков'])}! Главный — «${top.title}».`; + bitSay(text, 'cheer', { move: 'spin' }); + }, [open, badges, top]); + + if (!open) return null; + const single = badges.length === 1; + + return ( + + + + + + + + + + {single ? `Новый значок · ${TIER_LABEL[top.tier]}` : `Новые значки · ${badges.length}`} + + + {top.title} + + + {top.group !== 'Общие' ? `Роадмап «${top.group}» · ` : ''} + {top.description} + + {' '}✓ + + + {!single && ( + + {badges + .filter((b) => b.id !== top.id) + .map((b) => ( + + + + {b.title} + + + ))} + + )} + + + + + + ); +}; diff --git a/frontend/src/components/achievements/achievements.test.ts b/frontend/src/components/achievements/achievements.test.ts new file mode 100644 index 0000000..c01cd02 --- /dev/null +++ b/frontend/src/components/achievements/achievements.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest'; +import type { RoadmapQuestionItem } from '../../services/roadmapService'; +import { freshUnlocks, generalBadges, rankStatus, roadmapBadges } from './achievements'; + +const item = (id: string, difficulty: 'easy' | 'medium' | 'hard', done: boolean): RoadmapQuestionItem => ({ + id, + title: id, + slug: id, + difficulty, + order: 0, + is_completed: done, +}); + +const roadmap = (items: RoadmapQuestionItem[]) => ({ slug: 'python', title: 'Python', items }); +const byId = (badges: ReturnType) => new Map(badges.map((b) => [b.id.split(':').pop()!, b])); + +describe('roadmapBadges', () => { + it('ранги накопительные: все лёгкие → лёгкие и средние → весь роадмап', () => { + const items = [item('e1', 'easy', true), item('e2', 'easy', true), item('m1', 'medium', true), item('h1', 'hard', false)]; + const b = byId(roadmapBadges(roadmap(items), [{ completed: 2, total: 2 }])); + expect(b.get('bronze')).toMatchObject({ title: 'Питонист', unlocked: true }); + expect(b.get('silver')).toMatchObject({ title: 'Суперпитонист', unlocked: true }); + expect(b.get('gold')).toMatchObject({ title: 'Гиперпитонист', unlocked: false, progress: 3, target: 4 }); + expect(b.get('first-step')?.unlocked).toBe(true); + expect(b.get('half')?.unlocked).toBe(true); + }); + + it('без вопросов нужной сложности ранг не выдаётся даром', () => { + const items = [item('m1', 'medium', false), item('h1', 'hard', false)]; + const b = byId(roadmapBadges(roadmap(items), [{ completed: 0, total: 2 }])); + expect(b.get('bronze')).toMatchObject({ unlocked: false, target: 2 }); + }); + + it('неизвестный роадмап получает общие названия рангов', () => { + const badges = roadmapBadges({ slug: 'go', title: 'Go', items: [item('e', 'easy', false)] }, []); + expect(badges.map((x) => x.title)).toContain('Гуру · Go'); + }); +}); + +describe('rankStatus', () => { + it('показывает текущий ранг и сколько осталось до следующего', () => { + const items = [item('e1', 'easy', true), item('m1', 'medium', false), item('m2', 'medium', false)]; + const { current, next, left } = rankStatus(roadmapBadges(roadmap(items), [])); + expect(current?.title).toBe('Питонист'); + expect(next?.title).toBe('Суперпитонист'); + expect(left).toBe(2); + }); +}); + +describe('generalBadges', () => { + const stats = { + total: 100, + total_completed: 50, + total_easy: 30, + easy_completed: 30, + total_medium: 50, + medium_completed: 20, + total_hard: 20, + hard_completed: 0, + }; + + it('пороги по доле всех вопросов и по сложности', () => { + const badges = new Map(generalBadges(stats, 0, 3).map((b) => [b.id, b])); + expect(badges.get('all:50')?.unlocked).toBe(true); + expect(badges.get('all:100')?.unlocked).toBe(false); + expect(badges.get('all:easy')?.unlocked).toBe(true); + expect(badges.get('all:hard')?.unlocked).toBe(false); + expect(badges.get('all:roadmap-finisher')?.unlocked).toBe(false); + }); + + it('поздравляем только с неувиденными значками', () => { + const badges = generalBadges(stats, 1, 3); + const fresh = freshUnlocks(badges, new Set(['all:10', 'all:25'])); + expect(fresh.map((b) => b.id)).toEqual(['all:50', 'all:easy', 'all:roadmap-finisher']); + }); +}); diff --git a/frontend/src/components/achievements/achievements.ts b/frontend/src/components/achievements/achievements.ts new file mode 100644 index 0000000..a4d43e0 --- /dev/null +++ b/frontend/src/components/achievements/achievements.ts @@ -0,0 +1,235 @@ +import type { RoadmapQuestionItem } from '../../services/roadmapService'; +import { normalizeDifficulty } from '../../utils/difficulty'; +import type { Difficulty } from '../../utils/difficulty'; + +/** + * Значки (ачивки). Считаются на клиенте из прогресса: «Прошёл» по вопросу — это и есть выполнение. + * Ничего не хранится на сервере, поэтому снятая отметка снимает и значок. + */ + +/** Уровень значка: веха (первый шаг, экватор) и три ранга роадмапа. */ +export type BadgeTier = 'milestone' | 'bronze' | 'silver' | 'gold'; + +export interface Badge { + id: string; + title: string; + description: string; + tier: BadgeTier; + /** Короткая надпись на медали: «Py», «SQL», «50%». */ + glyph: string; + /** Группа на витрине: название роадмапа или «Общие». */ + group: string; + progress: number; + target: number; + unlocked: boolean; + roadmapSlug?: string; +} + +export const TIER_LABEL: Record = { + milestone: 'Веха', + bronze: 'Бронза', + silver: 'Серебро', + gold: 'Золото', +}; + +/** Ранги роадмапа: все лёгкие → все лёгкие и средние → весь роадмап. */ +const RANKS: Record = { + python: ['Питонист', 'Суперпитонист', 'Гиперпитонист'], + sql: ['Джойнер', 'Суперджойнер', 'Гиперджойнер'], + algorithms: ['Алгоритмист', 'Супералгоритмист', 'Гипералгоритмист'], +}; + +const GLYPHS: Record = { python: 'Py', sql: 'SQL', algorithms: 'O(n)' }; + +export const roadmapGlyph = (slug: string, title: string) => GLYPHS[slug] ?? (title.trim().charAt(0).toUpperCase() || '?'); + +export const roadmapRanks = (slug: string, title: string): [string, string, string] => + RANKS[slug] ?? [`Знаток · ${title}`, `Профи · ${title}`, `Гуру · ${title}`]; + +const RANK_TIERS = ['bronze', 'silver', 'gold'] as const; +/** Какие сложности нужно закрыть целиком для ранга. */ +const RANK_SCOPE: Record<(typeof RANK_TIERS)[number], Difficulty[]> = { + bronze: ['easy'], + silver: ['easy', 'medium'], + gold: ['easy', 'medium', 'hard'], +}; +const RANK_HINT: Record<(typeof RANK_TIERS)[number], string> = { + bronze: 'Закройте все лёгкие вопросы роадмапа', + silver: 'Закройте все лёгкие и средние вопросы', + gold: 'Пройдите роадмап целиком, включая сложные', +}; + +interface RoadmapLike { + slug: string; + title: string; + items: RoadmapQuestionItem[]; +} + +interface StepLike { + completed: number; + total: number; +} + +export const roadmapBadges = (roadmap: RoadmapLike, steps: StepLike[]): Badge[] => { + const { slug, title, items } = roadmap; + const done = items.filter((i) => i.is_completed).length; + const total = items.length; + const base = { group: title, roadmapSlug: slug }; + const badges: Badge[] = []; + + const first = steps.find((s) => s.total > 0); + if (first) { + badges.push({ + ...base, + id: `rm:${slug}:first-step`, + title: 'Первый шаг', + description: 'Закройте первый шаг маршрута', + tier: 'milestone', + glyph: '1', + progress: first.completed, + target: first.total, + unlocked: first.completed >= first.total, + }); + } + if (total >= 2) { + const half = Math.ceil(total / 2); + badges.push({ + ...base, + id: `rm:${slug}:half`, + title: 'Экватор', + description: 'Пройдите половину роадмапа', + tier: 'milestone', + glyph: '50%', + progress: Math.min(done, half), + target: half, + unlocked: done >= half, + }); + } + + const ranks = roadmapRanks(slug, title); + const glyph = roadmapGlyph(slug, title); + RANK_TIERS.forEach((tier, i) => { + const scope = RANK_SCOPE[tier]; + const inScope = items.filter((item) => { + const d = normalizeDifficulty(item.difficulty); + return d !== null && scope.includes(d); + }); + // Нет вопросов нужной сложности — ранг считается по всему роадмапу, чтобы не выдавать его даром + const pool = inScope.length > 0 ? inScope : items; + const poolDone = pool.filter((item) => item.is_completed).length; + badges.push({ + ...base, + id: `rm:${slug}:${tier}`, + title: ranks[i], + description: RANK_HINT[tier], + tier, + glyph, + progress: poolDone, + target: pool.length, + unlocked: pool.length > 0 && poolDone >= pool.length, + }); + }); + return badges; +}; + +/** Текущий ранг роадмапа и что нужно до следующего. */ +export const rankStatus = (badges: Badge[]) => { + const ranks = badges.filter((b) => b.tier !== 'milestone'); + const current = [...ranks].reverse().find((b) => b.unlocked) ?? null; + const next = ranks.find((b) => !b.unlocked) ?? null; + return { current, next, left: next ? next.target - next.progress : 0 }; +}; + +export interface CompletionStatsLike { + total: number; + total_completed: number; + total_easy: number; + easy_completed: number; + total_medium: number; + medium_completed: number; + total_hard: number; + hard_completed: number; +} + +const GENERAL = 'Общие'; + +export const generalBadges = (stats: CompletionStatsLike, roadmapsDone: number, roadmapsTotal: number): Badge[] => { + const share = (p: number) => Math.ceil((stats.total * p) / 100); + const steps: [number, string, BadgeTier][] = [ + [10, 'Новичок', 'milestone'], + [25, 'Знаток', 'bronze'], + [50, 'Эксперт', 'silver'], + [100, 'Мастер', 'gold'], + ]; + const badges: Badge[] = stats.total > 0 + ? steps.map(([p, title, tier]) => ({ + id: `all:${p}`, + title, + description: `Пройдите ${p}% всех вопросов`, + tier, + glyph: `${p}%`, + group: GENERAL, + progress: Math.min(stats.total_completed, share(p)), + target: share(p), + unlocked: stats.total_completed >= share(p), + })) + : []; + const byDifficulty: [string, string, number, number, BadgeTier][] = [ + ['easy', 'Мастер лёгких', stats.easy_completed, stats.total_easy, 'bronze'], + ['medium', 'Мастер средних', stats.medium_completed, stats.total_medium, 'silver'], + ['hard', 'Мастер сложных', stats.hard_completed, stats.total_hard, 'gold'], + ]; + for (const [key, title, doneN, totalN, tier] of byDifficulty) { + if (totalN === 0) continue; + badges.push({ + id: `all:${key}`, + title, + description: `Пройдите все вопросы этой сложности (${totalN})`, + tier, + glyph: key === 'easy' ? 'E' : key === 'medium' ? 'M' : 'H', + group: GENERAL, + progress: Math.min(doneN, totalN), + target: totalN, + unlocked: doneN >= totalN, + }); + } + if (roadmapsTotal > 0) { + badges.push({ + id: 'all:roadmap-finisher', + title: 'Первопроходец', + description: 'Пройдите любой роадмап целиком', + tier: 'gold', + glyph: '★', + group: GENERAL, + progress: Math.min(roadmapsDone, 1), + target: 1, + unlocked: roadmapsDone >= 1, + }); + } + return badges; +}; + +// ---- какие значки пользователь уже видел (чтобы поздравить с новыми один раз) ---- + +const seenKey = (userId: string) => `achievements:seen:v1:${userId}`; + +export const loadSeen = (userId: string): Set => { + try { + const raw = window.localStorage.getItem(seenKey(userId)); + const parsed = raw ? (JSON.parse(raw) as unknown) : []; + return new Set(Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : []); + } catch { + return new Set(); + } +}; + +export const saveSeen = (userId: string, ids: Iterable) => { + try { + window.localStorage.setItem(seenKey(userId), JSON.stringify([...ids])); + } catch { + /* приватный режим: поздравим ещё раз, не страшно */ + } +}; + +/** Новые значки: открыты, но ещё не показаны. */ +export const freshUnlocks = (badges: Badge[], seen: Set) => badges.filter((b) => b.unlocked && !seen.has(b.id)); diff --git a/frontend/src/components/achievements/useAchievements.ts b/frontend/src/components/achievements/useAchievements.ts new file mode 100644 index 0000000..58ac9b5 --- /dev/null +++ b/frontend/src/components/achievements/useAchievements.ts @@ -0,0 +1,89 @@ +import { useMemo, useState } from 'react'; +import { useAuth } from '../../context/auth-context'; +import { useRoadmapDetails, useRoadmaps } from '../../queries/roadmaps'; +import { useCompletionStats, useProgress } from '../../queries/progress'; +import type { RoadmapDetail } from '../../services/roadmapService'; +import { buildSteps } from '../../pages/RoadmapsPage/roadmapUtils'; +import type { RoadmapStep } from '../../pages/RoadmapsPage/roadmapUtils'; +import { freshUnlocks, generalBadges, loadSeen, roadmapBadges, saveSeen } from './achievements'; +import type { Badge } from './achievements'; + +export interface RoadmapWithProgress { + detail: RoadmapDetail; + steps: RoadmapStep[]; + badges: Badge[]; + done: number; + total: number; +} + +/** + * Все роадмапы с прогрессом и значками + общие значки. Роадмапов немного, поэтому детали + * грузятся для всех сразу (и кэшируются): по ним считаются прогресс карточек и ранги. + */ +export const useAchievements = () => { + const { isAuthenticated } = useAuth(); + const list = useRoadmaps(); + const slugs = useMemo(() => (list.data ?? []).map((r) => r.slug), [list.data]); + const detailQueries = useRoadmapDetails(slugs); + const progress = useProgress(); + const stats = useCompletionStats(); + + // useQueries отдаёт новый массив на каждый рендер: пересчитываем, только когда данные обновились + const detailsKey = detailQueries.map((q) => q.dataUpdatedAt).join(','); + const completed = progress.completed; + const completedKey = [...completed].sort().join(','); + + const roadmaps = useMemo( + () => + detailQueries.flatMap((q) => { + if (!q.data) return []; + const detail = { ...q.data, items: q.data.items.map((item) => ({ ...item, is_completed: completed.has(item.id) })) }; + const steps = buildSteps(detail.items, detail.steps); + const done = detail.items.filter((i) => i.is_completed).length; + return [{ detail, steps, badges: roadmapBadges(detail, steps), done, total: detail.items.length }]; + }), + [detailsKey, completedKey], // eslint-disable-line react-hooks/exhaustive-deps + ); + + const general = useMemo(() => { + if (!stats.data) return []; + const finished = roadmaps.filter((r) => r.total > 0 && r.done >= r.total).length; + return generalBadges(stats.data, finished, roadmaps.length); + }, [stats.data, roadmaps]); + + const all = useMemo(() => [...roadmaps.flatMap((r) => r.badges), ...general], [roadmaps, general]); + const detailsReady = !list.isPending && detailQueries.every((q) => !q.isPending); + const ready = isAuthenticated && detailsReady && progress.isSuccess && stats.isSuccess; + + return { + roadmaps, + general, + all, + ready, + listQuery: list, + detailQueries, + progressReady: !isAuthenticated || !progress.isPending, + }; +}; + +/** + * Поздравление с новыми значками. Видимые значки запоминаются по пользователю в localStorage: + * каждый поздравляем один раз, даже если отметку снимут и поставят снова. + */ +export const useBadgeCelebration = (badges: Badge[], ready: boolean) => { + const { user } = useAuth(); + const userId = user?.id ? String(user.id) : null; + const [state, setState] = useState(() => ({ userId, seen: userId ? loadSeen(userId) : new Set() })); + if (state.userId !== userId) setState({ userId, seen: userId ? loadSeen(userId) : new Set() }); + + const fresh = useMemo(() => (ready && userId ? freshUnlocks(badges, state.seen) : []), [ready, userId, badges, state.seen]); + + const dismiss = () => { + if (!userId) return; + const next = new Set([...state.seen, ...fresh.map((b) => b.id)]); + saveSeen(userId, next); + setState({ userId, seen: next }); + }; + + return { fresh, dismiss }; +}; diff --git a/frontend/src/components/interview/InterviewResults.tsx b/frontend/src/components/interview/InterviewResults.tsx index a24af2a..05e6c2d 100644 --- a/frontend/src/components/interview/InterviewResults.tsx +++ b/frontend/src/components/interview/InterviewResults.tsx @@ -36,9 +36,11 @@ interface InterviewResultsProps { onOpen: (index: number) => void; onMarkCompleted: (ids: string[]) => void; backTo: string; + /** Подпись ссылки «назад»: к вопросам компании, к роадмапу. */ + backLabel?: string; } -export const InterviewResults = ({ session, questions, completed, onRetry, onNew, onOpen, onMarkCompleted, backTo }: InterviewResultsProps) => { +export const InterviewResults = ({ session, questions, completed, onRetry, onNew, onOpen, onMarkCompleted, backTo, backLabel = 'К вопросам компании' }: InterviewResultsProps) => { const { c } = useTokens(); const colors = useScoreColors(); const [marked, setMarked] = useState(false); @@ -140,7 +142,7 @@ export const InterviewResults = ({ session, questions, completed, onRetry, onNew Новое собеседование diff --git a/frontend/src/components/interview/InterviewSetup.tsx b/frontend/src/components/interview/InterviewSetup.tsx index 690a010..18943ca 100644 --- a/frontend/src/components/interview/InterviewSetup.tsx +++ b/frontend/src/components/interview/InterviewSetup.tsx @@ -30,14 +30,17 @@ interface InterviewSetupProps { current: InterviewSession | null; onStart: (options: InterviewOptions) => void; onResume: () => void; + /** Заголовок и параметры по умолчанию: у шага роадмапа — все вопросы по порядку. */ + title?: string; + defaults?: InterviewOptions; } /** Параметры собеседования: сколько вопросов, в каком порядке, какие. */ -export const InterviewSetup = ({ questions, completed, ai, current, onStart, onResume }: InterviewSetupProps) => { +export const InterviewSetup = ({ questions, completed, ai, current, onStart, onResume, title = 'Пробное собеседование', defaults = DEFAULT_OPTIONS }: InterviewSetupProps) => { const { c } = useTokens(); const isAdmin = Boolean(useAuth().user?.is_admin); const hasNew = questions.some((q) => !completed.has(q.id)); - const [options, setOptions] = useState(() => ({ ...(current?.options ?? DEFAULT_OPTIONS), onlyNew: hasNew && (current?.options.onlyNew ?? true) })); + const [options, setOptions] = useState(() => ({ ...(current?.options ?? defaults), onlyNew: hasNew && (current?.options.onlyNew ?? true) })); const available = useMemo(() => eligibleQuestions(questions, options, completed).length, [questions, options, completed]); const planned = options.count > 0 ? Math.min(options.count, available) : available; const set = (patch: Partial) => setOptions((o) => ({ ...o, ...patch })); @@ -47,8 +50,8 @@ export const InterviewSetup = ({ questions, completed, ai, current, onStart, onR return ( - - Пробное собеседование + + {title} Отвечайте своими словами, как интервьюеру. ИИ оценит ответ по шкале 0–10, покажет пробелы и ошибки и задаст уточняющий вопрос. diff --git a/frontend/src/components/ui/PracticeMascot.tsx b/frontend/src/components/ui/PracticeMascot.tsx index 474d768..502f826 100644 --- a/frontend/src/components/ui/PracticeMascot.tsx +++ b/frontend/src/components/ui/PracticeMascot.tsx @@ -52,7 +52,7 @@ function getSection(pathname: string) { if (pathname === '/favorites') return 'favorites'; if (pathname.includes('/interview/')) return 'interview'; if (pathname.startsWith('/companies')) return 'companies'; - if (pathname === '/roadmap') return 'roadmap'; + if (pathname.startsWith('/roadmap')) return 'roadmap'; if (['/login', '/register', '/forgot-password'].includes(pathname)) return 'account'; return 'home'; } diff --git a/frontend/src/pages/InterviewModePage.tsx b/frontend/src/pages/InterviewModePage.tsx index 3c483e1..dde383b 100644 --- a/frontend/src/pages/InterviewModePage.tsx +++ b/frontend/src/pages/InterviewModePage.tsx @@ -137,31 +137,55 @@ const Frame = ({ children, wide }: { children: ReactNode; wide?: boolean }) => ( ); +interface InterviewFlowProps { + /** Ключ сессии в localStorage: id компании или «roadmap::<шаг>». */ + sessionKey: string | undefined; + /** setup | results | номер вопроса плана. */ + questionIndex: string | undefined; + questions: Question[]; + loading: boolean; + /** Адрес собеседования: `${base}/setup`, `${base}/`, `${base}/results`. */ + base: string; + backUrl: string; + backLabel: string; + emptyText: string; + setupTitle?: string; + setupDefaults?: InterviewOptions; +} + /** - * Режим собеседования по компании. - * `/interview/setup` — параметры, `/interview/` — n-й вопрос плана, `/interview/results` — итоги. - * План и ответы лежат в localStorage по компании: перезагрузка и выход не теряют прогресс. + * Собеседование с Битом по готовому списку вопросов (компания, шаг роадмапа). + * `setup` — параметры, `` — n-й вопрос плана, `results` — итоги. + * План и ответы лежат в localStorage по ключу сессии: перезагрузка и выход не теряют прогресс. */ -export const InterviewModePage = () => { +export const InterviewFlow = ({ + sessionKey, + questionIndex, + questions: source, + loading, + base, + backUrl, + backLabel, + emptyText, + setupTitle, + setupDefaults, +}: InterviewFlowProps) => { const navigate = useNavigate(); - const { companyId, questionIndex } = useParams<{ companyId: string; questionIndex: string }>(); const { c } = useTokens(); const masteryColor = useMasteryColor(); - const questionsQuery = useCompanyQuestionsWithContent(companyId); const { completed } = useProgress(); const toggleCompleted = useToggleCompleted(); const ai = useAIReviewStatus(); const prefetchQuestion = usePrefetchQuestion(); - const questions = useMemo(() => questionsQuery.data ?? [], [questionsQuery.data]); + const questions = source; const byId = useMemo(() => new Map(questions.map((q) => [q.id, q])), [questions]); - const [session, setSession] = useState(() => loadSession(companyId)); - useEffect(() => saveSession(companyId, session), [companyId, session]); + const [session, setSession] = useState(() => loadSession(sessionKey)); + useEffect(() => saveSession(sessionKey, session), [sessionKey, session]); - const base = `/companies/${companyId}/interview`; - const questionsUrl = `/companies/${companyId}/questions`; - // Старые ссылки /interview/ без сессии: весь список компании по порядку + const questionsUrl = backUrl; + // Старые ссылки /interview/ без сессии: весь список по порядку const plan = useMemo( () => (session?.ids ?? questions.map((q) => q.id)).filter((id) => byId.has(id)), [session, questions, byId], @@ -219,7 +243,7 @@ export const InterviewModePage = () => { navigate(`${base}/results`); }; - if (questionsQuery.isPending) { + if (loading) { return ( @@ -231,7 +255,7 @@ export const InterviewModePage = () => { const backButton = ( ); @@ -241,13 +265,15 @@ export const InterviewModePage = () => { {backButton} {questions.length === 0 ? ( - } title="Нет вопросов" description="У этой компании пока нет вопросов для собеседования." /> + } title="Нет вопросов" description={emptyText} /> ) : ( { const firstOpen = session ? session.ids.findIndex((id) => !session.results[id]?.answer?.trim() && !session.results[id]?.self) : -1; @@ -269,6 +295,7 @@ export const InterviewModePage = () => { questions={byId} completed={completed} backTo={questionsUrl} + backLabel={backLabel} onOpen={(i) => navigate(`${base}/${i}`)} onNew={() => navigate(`${base}/setup`)} onRetry={(ids) => { @@ -291,7 +318,7 @@ export const InterviewModePage = () => { } title="Вопрос не найден" - description={questions.length === 0 ? 'У этой компании пока нет вопросов для собеседования.' : undefined} + description={questions.length === 0 ? emptyText : undefined} action={ - - - {roadmap.description && ( - - {roadmap.description} - - )} - - - - - {progress.completed} из {progress.total} {plural(progress.total, ['вопрос', 'вопроса', 'вопросов'])}{' '} - выполнено - - - {progress.percent}% - - - - - - - - - {steps.length} {plural(steps.length, ['шаг', 'шага', 'шагов'])} · осталось {remaining} - - {breakdown.map((entry) => ( - - - - {entry.completed}/{entry.total} - - - ))} - - - - - - {steps.length === 0 ? ( - - } title="В этом роадмапе пока нет вопросов" /> - - ) : ( - - - - Шаг маршрута - - - - {steps.map((step, index) => )} - - - - {steps.map((step, index) => expandedSteps.has(step.id) && {}} onToggleCompletion={onToggleCompletion} onItemClick={onItemClick} />{index + 1 < steps.length && })} - - - )} - - ); -}; diff --git a/frontend/src/pages/RoadmapsPage/RoadmapHero.tsx b/frontend/src/pages/RoadmapsPage/RoadmapHero.tsx new file mode 100644 index 0000000..85d3c5c --- /dev/null +++ b/frontend/src/pages/RoadmapsPage/RoadmapHero.tsx @@ -0,0 +1,192 @@ +import { Box, Button, LinearProgress, Stack, Typography } from '@mui/material'; +import { ArrowForward as ArrowForwardIcon, RecordVoiceOverOutlined as InterviewIcon } from '@mui/icons-material'; +import type { RoadmapDetail } from '../../services/roadmapService'; +import { BadgeMedal } from '../../components/achievements/BadgeMedal'; +import { rankStatus } from '../../components/achievements/achievements'; +import type { Badge } from '../../components/achievements/achievements'; +import { radius, useTokens } from '../../theme/tokens'; +import { DIFFICULTY_LABELS, plural } from '../../utils/difficulty'; +import { RoadmapCover } from './RoadmapCover'; +import { findNextItem, getDifficultyBreakdown, getProgress } from './roadmapUtils'; +import type { RoadmapStep } from './roadmapUtils'; + +const Ring = ({ percent, size = 128 }: { percent: number; size?: number }) => { + const { c } = useTokens(); + const r = 52; + const len = 2 * Math.PI * r; + return ( + + + + + + + + + {percent}% + + + пройдено + + + + + ); +}; + +interface RoadmapHeroProps { + roadmap: RoadmapDetail; + steps: RoadmapStep[]; + badges: Badge[]; + onInterview: (stepId: string) => void; + onOpenQuestion: (questionId: string) => void; +} + +/** Шапка роадмапа: прогресс, ранг и что делать дальше. */ +export const RoadmapHero = ({ roadmap, steps, badges, onInterview, onOpenQuestion }: RoadmapHeroProps) => { + const { c, difficulty } = useTokens(); + const progress = getProgress(roadmap.items); + const breakdown = getDifficultyBreakdown(roadmap.items); + const nextItem = findNextItem(roadmap.items); + const current = steps.find((s) => s.status === 'current'); + const currentIndex = current ? steps.indexOf(current) : -1; + const allDone = progress.total > 0 && progress.completed === progress.total; + const { current: rank, next, left } = rankStatus(badges); + const shownRank = rank ?? badges.find((b) => b.tier === 'bronze') ?? null; + + return ( + + + + + + {roadmap.profession} + + + {roadmap.title} + + {roadmap.description && ( + + {roadmap.description} + + )} + + + {breakdown.map((entry) => ( + + + + {DIFFICULTY_LABELS[entry.difficulty]} + + + {entry.completed}/{entry.total} + + + + + ))} + + + + {current && ( + + )} + {nextItem && ( + + )} + {allDone && ( + Маршрут пройден целиком. Красота! + )} + + + + + + + + {progress.completed} из {progress.total} {plural(progress.total, ['вопроса', 'вопросов', 'вопросов'])} ·{' '} + {steps.length} {plural(steps.length, ['шаг', 'шага', 'шагов'])} + + {shownRank && ( + + + + + {rank ? 'Ваш ранг' : 'Первый ранг'} + + + {shownRank.title} + + + + )} + {next && ( + + До «{next.title}» — {left} {plural(left, ['вопрос', 'вопроса', 'вопросов'])} + + )} + + + + + ); +}; diff --git a/frontend/src/pages/RoadmapsPage/RoadmapInterviewPage.tsx b/frontend/src/pages/RoadmapsPage/RoadmapInterviewPage.tsx new file mode 100644 index 0000000..8c4bd69 --- /dev/null +++ b/frontend/src/pages/RoadmapsPage/RoadmapInterviewPage.tsx @@ -0,0 +1,40 @@ +import { useMemo } from 'react'; +import { useParams } from 'react-router-dom'; +import { useRoadmapDetails } from '../../queries/roadmaps'; +import { useQuestionsByIds } from '../../queries/interview'; +import { InterviewFlow } from '../InterviewModePage'; +import type { InterviewOptions } from '../../components/interview/session'; +import { buildSteps } from './roadmapUtils'; + +/** Шаг роадмапа короткий: по умолчанию все непройденные вопросы по порядку маршрута. */ +const STEP_DEFAULTS: InterviewOptions = { count: 0, order: 'sequential', difficulty: '', onlyNew: true }; + +/** Собеседование с Битом по одному шагу роадмапа: `/roadmap/:slug/step/:stepId/interview/:questionIndex`. */ +export const RoadmapInterviewPage = () => { + const { slug = '', stepId = '', questionIndex } = useParams<{ slug: string; stepId: string; questionIndex: string }>(); + const [detailQuery] = useRoadmapDetails([slug]); + const detail = detailQuery?.data; + const step = useMemo( + () => (detail ? buildSteps(detail.items, detail.steps).find((s) => s.id === stepId) ?? null : null), + [detail, stepId], + ); + const ids = useMemo(() => step?.items.map((i) => i.id) ?? [], [step]); + const { questions, pending } = useQuestionsByIds(ids); + const stepNumber = detail ? buildSteps(detail.items, detail.steps).findIndex((s) => s.id === stepId) + 1 : 0; + + return ( + 0 && pending)} + base={`/roadmap/${slug}/step/${stepId}/interview`} + backUrl={`/roadmap/${slug}`} + backLabel={detail ? `К роадмапу «${detail.title}»` : 'К роадмапу'} + emptyText="В этом шаге пока нет вопросов." + setupTitle={step ? `Шаг ${stepNumber}: ${step.title}` : 'Шаг роадмапа'} + setupDefaults={STEP_DEFAULTS} + /> + ); +}; diff --git a/frontend/src/pages/RoadmapsPage/RoadmapPage.tsx b/frontend/src/pages/RoadmapsPage/RoadmapPage.tsx new file mode 100644 index 0000000..e0c291c --- /dev/null +++ b/frontend/src/pages/RoadmapsPage/RoadmapPage.tsx @@ -0,0 +1,228 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom'; +import { Alert, Box, Button, Container, Skeleton, Stack, Typography, useMediaQuery, useTheme } from '@mui/material'; +import { ArrowBack as ArrowBackIcon, QuizOutlined as QuizIcon } from '@mui/icons-material'; +import { EmptyState } from '../../components/ui'; +import { bitSay } from '../../components/ui/bitVoice'; +import { useProgress, useToggleCompleted } from '../../queries/progress'; +import { layout, radius, useTokens, wideFrame } from '../../theme/tokens'; +import { BadgeGrid } from '../../components/achievements/BadgeTile'; +import { BadgeUnlockDialog } from '../../components/achievements/BadgeUnlockDialog'; +import { useAchievements, useBadgeCelebration } from '../../components/achievements/useAchievements'; +import { RoadmapHero } from './RoadmapHero'; +import { RoadmapPath } from './RoadmapPath'; +import { StepPanel } from './StepPanel'; +import { openLine, stepLine, toggleLine } from './bitRoadmap'; + +const toggleInSet = (set: Set, value: string, include: boolean): Set => { + const next = new Set(set); + if (include) next.add(value); + else next.delete(value); + return next; +}; + +/** Страница роадмапа `/roadmap/:slug`: карта маршрута, открытый шаг и значки. */ +export const RoadmapPage = () => { + const { slug = '' } = useParams<{ slug: string }>(); + const navigate = useNavigate(); + const { c } = useTokens(); + const theme = useTheme(); + const stacked = useMediaQuery(theme.breakpoints.down('lg')); + const panelRef = useRef(null); + const achievements = useAchievements(); + const progress = useProgress(); + const toggleCompleted = useToggleCompleted(); + const celebration = useBadgeCelebration(achievements.all, achievements.ready); + + const entry = achievements.roadmaps.find((r) => r.detail.slug === slug) ?? null; + const listed = achievements.listQuery.data?.some((r) => r.slug === slug); + const detailQuery = achievements.detailQueries[achievements.listQuery.data?.findIndex((r) => r.slug === slug) ?? -1]; + const loading = achievements.listQuery.isPending || Boolean(detailQuery?.isPending) || !achievements.progressReady; + const notFound = !achievements.listQuery.isPending && !listed; + + const steps = useMemo(() => entry?.steps ?? [], [entry]); + const currentStep = steps.find((s) => s.status === 'current') ?? null; + const [selected, setSelected] = useState<{ slug: string; stepId: string } | null>(null); + const selectedId = (selected?.slug === slug ? selected.stepId : null) ?? currentStep?.id ?? steps[0]?.id ?? null; + const selectedIndex = steps.findIndex((s) => s.id === selectedId); + const selectedStep = selectedIndex >= 0 ? steps[selectedIndex] : null; + const [pendingItems, setPendingItems] = useState>(new Set()); + const [actionError, setActionError] = useState(null); + + // Открыли роадмап (детали и прогресс готовы) — Бит рассказывает, где мы на маршруте + const ready = Boolean(entry) && achievements.progressReady; + useEffect(() => { + if (!ready || !entry) return; + const line = openLine(entry.detail.title, entry.steps); + bitSay(line.text, line.tone); + }, [ready, slug]); // eslint-disable-line react-hooks/exhaustive-deps + + const selectStep = (stepId: string) => { + const step = steps.find((s) => s.id === stepId); + if (step && stepId !== selectedId) { + const line = stepLine(step); + bitSay(line.text, line.tone); + } + setSelected({ slug, stepId }); + // В одну колонку панель шага стоит над картой: показываем её после выбора шага + if (stacked) { + const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + requestAnimationFrame(() => panelRef.current?.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'start' })); + } + }; + + const handleToggle = async (itemId: string, completed: boolean) => { + setPendingItems((prev) => toggleInSet(prev, itemId, true)); + const line = toggleLine(steps, itemId, completed); + bitSay(line.text, line.tone); + try { + await toggleCompleted.mutateAsync({ id: itemId, on: completed }); + } catch { + setActionError('Не удалось сохранить отметку. Попробуйте ещё раз.'); + } finally { + setPendingItems((prev) => toggleInSet(prev, itemId, false)); + } + }; + + const startInterview = (stepId: string) => navigate(`/roadmap/${slug}/step/${stepId}/interview/setup`); + const openQuestion = (questionId: string) => navigate(`/questions/${questionId}`); + + const back = ( + + ); + + if (notFound || (detailQuery?.isError && !entry)) { + return ( + + {back} + } + title={notFound ? 'Роадмап не найден' : 'Не удалось загрузить роадмап'} + description={notFound ? 'Возможно, он переименован или снят с публикации.' : 'Попробуйте обновить страницу чуть позже.'} + action={ + + } + /> + + ); + } + + if (loading || !entry) { + return ( + + {back} + + + + + + + ); + } + + const blockedBy = selectedStep?.status === 'future' ? currentStep : null; + const finish = entry.badges.find((b) => b.tier === 'gold') ?? null; + const earned = entry.badges.filter((b) => b.unlocked).length; + + return ( + + {back} + {actionError && ( + setActionError(null)} sx={{ mb: 2 }}> + {actionError} + + )} + + + + {steps.length === 0 ? ( + + } title="В этом роадмапе пока нет вопросов" /> + + ) : ( + + + + + Маршрут + + + Нажмите на шаг, чтобы открыть его + + + + + + {selectedStep && ( + + selectStep(steps[selectedIndex + 1].id) : null} + /> + + )} + + )} + + + + + Значки маршрута + + + {earned} из {entry.badges.length} + + + + + + + + ); +}; diff --git a/frontend/src/pages/RoadmapsPage/RoadmapPath.tsx b/frontend/src/pages/RoadmapsPage/RoadmapPath.tsx new file mode 100644 index 0000000..2f6eb59 --- /dev/null +++ b/frontend/src/pages/RoadmapsPage/RoadmapPath.tsx @@ -0,0 +1,205 @@ +import { Box, ButtonBase, Typography, keyframes, useMediaQuery, useTheme } from '@mui/material'; +import { Check as CheckIcon, LockOutlined as LockIcon } from '@mui/icons-material'; +import { radius, useTokens } from '../../theme/tokens'; +import { BadgeMedal } from '../../components/achievements/BadgeMedal'; +import type { Badge } from '../../components/achievements/achievements'; +import type { RoadmapStep } from './roadmapUtils'; + +const ROW = 128; +const NODE = 56; +/** Горизонтальная позиция узлов «змейки», в процентах ширины. */ +const SNAKE = [22, 50, 78, 50]; + +const pulse = keyframes` + 0% { box-shadow: 0 0 0 0 var(--pulse); } + 70% { box-shadow: 0 0 0 14px transparent; } + 100% { box-shadow: 0 0 0 0 transparent; } +`; + +interface RoadmapPathProps { + steps: RoadmapStep[]; + selectedId: string | null; + onSelect: (stepId: string) => void; + /** Финишная медаль — золотой ранг роадмапа. */ + finish: Badge | null; +} + +/** + * Карта маршрута: шаги лежат на извилистой тропе. Пройденные — зелёные, текущий пульсирует, + * следующие закрыты замком (их можно открыть и посмотреть заранее). В конце — финишная медаль. + */ +export const RoadmapPath = ({ steps, selectedId, onSelect, finish }: RoadmapPathProps) => { + const { c } = useTokens(); + const theme = useTheme(); + const narrow = useMediaQuery(theme.breakpoints.down('sm')); + + const count = steps.length + (finish ? 1 : 0); + const xOf = (i: number) => (narrow ? 12 : SNAKE[i % SNAKE.length]); + const yOf = (i: number) => i * ROW + ROW / 2; + const height = count * ROW; + const currentIndex = steps.findIndex((s) => s.status === 'current'); + // Докуда тропа «пройдена»: до текущего шага, либо до конца, если всё закрыто + const reached = currentIndex === -1 ? count - 1 : currentIndex; + + const segment = (i: number) => { + const x0 = xOf(i); + const x1 = xOf(i + 1); + const y0 = yOf(i); + const y1 = yOf(i + 1); + const mid = (y0 + y1) / 2; + return `M ${x0} ${y0} C ${x0} ${mid}, ${x1} ${mid}, ${x1} ${y1}`; + }; + + return ( + + + {Array.from({ length: Math.max(0, count - 1) }).map((_, i) => ( + + ))} + + + {steps.map((step, i) => { + const x = xOf(i); + const labelRight = narrow || x <= 50; + const selected = step.id === selectedId; + const locked = step.status === 'future'; + const current = step.status === 'current'; + const done = step.status === 'completed'; + const nodeColor = done ? c.success : current ? c.accent : c.borderStrong; + return ( + + onSelect(step.id)} + aria-current={selected ? 'step' : undefined} + aria-label={`Шаг ${i + 1}: ${step.title}. ${done ? 'Пройден' : current ? 'Текущий' : 'Впереди'}, ${step.completed} из ${step.total}`} + sx={{ + position: 'absolute', + top: ROW / 2 - NODE / 2, + left: `calc(${x}% - ${NODE / 2}px)`, + width: NODE, + height: NODE, + borderRadius: '50%', + display: 'grid', + placeItems: 'center', + zIndex: 2, + color: done ? c.bg : current ? c.accent : c.textSubtle, + backgroundColor: done ? c.success : c.surface, + border: `${current ? 3 : 2}px solid ${nodeColor}`, + outline: selected ? `3px solid ${c.text}` : 'none', + outlineOffset: 3, + transition: 'transform .15s ease', + '&:hover': { transform: 'scale(1.08)' }, + '--pulse': c.accentBorder, + animation: current ? `${pulse} 2.2s ease-out infinite` : 'none', + '@media (prefers-reduced-motion: reduce)': { animation: 'none' }, + fontWeight: 800, + fontSize: '1.05rem', + fontVariantNumeric: 'tabular-nums', + }} + > + {done ? : locked ? : i + 1} + + + onSelect(step.id)} + sx={{ + position: 'absolute', + top: '50%', + transform: 'translateY(-50%)', + ...(labelRight + ? { left: `calc(${x}% + ${NODE / 2 + 14}px)`, right: 0, justifyContent: 'flex-start', textAlign: 'left' } + : { left: 0, right: `calc(${100 - x}% + ${NODE / 2 + 14}px)`, justifyContent: 'flex-end', textAlign: 'right' }), + display: 'flex', + zIndex: 1, + }} + > + + + Шаг {i + 1} + {current ? ' · вы здесь' : done ? ' · пройден' : ''} + + + {step.title} + + + {step.completed}/{step.total} + + + + + ); + })} + + {finish && ( + + + + + + + {finish.unlocked ? 'Финиш · получено' : 'Финиш'} + + + Значок «{finish.title}» + + + + )} + + ); +}; diff --git a/frontend/src/pages/RoadmapsPage/StepPanel.tsx b/frontend/src/pages/RoadmapsPage/StepPanel.tsx new file mode 100644 index 0000000..296d474 --- /dev/null +++ b/frontend/src/pages/RoadmapsPage/StepPanel.tsx @@ -0,0 +1,208 @@ +import { Box, Button, ButtonBase, IconButton, LinearProgress, Stack, Tooltip, Typography } from '@mui/material'; +import { + ArrowForward as ArrowForwardIcon, + CheckCircle as CheckCircleIcon, + ChevronRight as ChevronRightIcon, + LockOutlined as LockIcon, + RadioButtonUnchecked as RadioButtonUncheckedIcon, + RecordVoiceOverOutlined as InterviewIcon, + RemoveCircle as PartialIcon, + Cancel as FailedIcon, +} from '@mui/icons-material'; +import type { RoadmapQuestionItem } from '../../services/roadmapService'; +import { DifficultyChip } from '../../components/ui'; +import { MASTERY_LABEL, useMasteryColor } from '../../components/ui/masteryLevels'; +import type { MasteryLevel } from '../../types'; +import { radius, useTokens } from '../../theme/tokens'; +import { plural } from '../../utils/difficulty'; +import type { RoadmapStep } from './roadmapUtils'; + +interface ItemRowProps { + item: RoadmapQuestionItem; + level: MasteryLevel | null; + pending: boolean; + onToggleCompletion: (itemId: string, completed: boolean) => void; + onOpen: (questionId: string) => void; +} + +const LevelIcon = ({ level }: { level: MasteryLevel | null }) => { + const sx = { fontSize: 20 }; + if (level === 'passed') return ; + if (level === 'partial') return ; + if (level === 'failed') return ; + return ; +}; + +const ItemRow = ({ item, level, pending, onToggleCompletion, onOpen }: ItemRowProps) => { + const { c } = useTokens(); + const color = useMasteryColor()(level); + const passed = level === 'passed'; + return ( + + + + onToggleCompletion(item.id, !passed)} + disabled={pending} + aria-pressed={passed} + aria-label={passed ? 'Снять отметку о выполнении' : 'Отметить как выполненный'} + sx={{ width: 36, height: 36, color: color.fg }} + > + + + + + onOpen(item.id)} + sx={{ + flex: 1, + minWidth: 0, + minHeight: 40, + px: 1, + py: 0.75, + gap: 1, + justifyContent: 'flex-start', + textAlign: 'left', + borderRadius: `${radius.md}px`, + '&:hover': { backgroundColor: c.surfaceHover }, + '&:hover .rm-arrow': { color: c.text }, + }} + > + + {item.title} + + + + + + ); +}; + +interface StepPanelProps { + step: RoadmapStep; + index: number; + stepsCount: number; + /** Шаг, после которого откроется этот (для закрытых шагов). */ + blockedBy: RoadmapStep | null; + levelOf: (id: string) => MasteryLevel | null; + pendingItems: Set; + onToggleCompletion: (itemId: string, completed: boolean) => void; + onOpenQuestion: (questionId: string) => void; + onInterview: (stepId: string) => void; + onNext: (() => void) | null; +} + +/** Открытый шаг: что в нём, как продвинуться, и кнопка пройти шаг собеседованием с Битом. */ +export const StepPanel = ({ + step, + index, + stepsCount, + blockedBy, + levelOf, + pendingItems, + onToggleCompletion, + onOpenQuestion, + onInterview, + onNext, +}: StepPanelProps) => { + const { c } = useTokens(); + const percent = step.total > 0 ? Math.round((step.completed / step.total) * 100) : 0; + const done = step.status === 'completed'; + const left = step.total - step.completed; + const statusText = done ? 'пройден' : step.status === 'current' ? 'текущий' : 'впереди'; + const statusColor = done ? c.success : step.status === 'current' ? c.accent : c.textSubtle; + + return ( + + + + Шаг {index + 1} из {stepsCount} · {statusText} + + + {step.title} + + + + + {step.completed}/{step.total} + + + + {blockedBy && ( + + + + Шаг откроется после «{blockedBy.title}». Заглянуть можно уже сейчас. + + + )} + + {step.total > 0 && ( + + + + )} + {!done && step.total > 0 && !blockedBy && ( + + Бит задаст {left} {plural(left, ['вопрос', 'вопроса', 'вопросов'])} как на собеседовании, ИИ оценит ответы и + отметит пройденные. + + )} + + + {step.items.length === 0 ? ( + + В этом шаге пока нет вопросов + + ) : ( + + {step.items.map((item) => ( + + ))} + + )} + + {onNext && ( + + + + )} + + ); +}; diff --git a/frontend/src/pages/RoadmapsPage/TimelineStep.tsx b/frontend/src/pages/RoadmapsPage/TimelineStep.tsx deleted file mode 100644 index 0426615..0000000 --- a/frontend/src/pages/RoadmapsPage/TimelineStep.tsx +++ /dev/null @@ -1,269 +0,0 @@ -import { Box, ButtonBase, IconButton, LinearProgress, Typography } from '@mui/material'; -import { - Check as CheckIcon, - CheckCircle as CheckCircleIcon, - ChevronRight as ChevronRightIcon, - ExpandMore as ExpandMoreIcon, - RadioButtonUnchecked as RadioButtonUncheckedIcon, -} from '@mui/icons-material'; -import type { RoadmapQuestionItem } from '../../services/roadmapService'; -import { DifficultyChip } from '../../components/ui'; -import { radius, useTokens } from '../../theme/tokens'; -import type { RoadmapStep, StepStatus } from './roadmapUtils'; - -const NODE_SIZE = 28; -/** Минимальная высота шапки шага: узел на рельсе выравнивается по её центру. */ -const STEP_HEADER_MIN_HEIGHT = 56; - -const STATUS_LABELS: Record = { - completed: 'пройден', - current: 'текущий', - future: '', -}; - -const StepNode = ({ status, number }: { status: StepStatus; number: number }) => { - const { c } = useTokens(); - const base = { - width: NODE_SIZE, - height: NODE_SIZE, - borderRadius: '50%', - display: 'grid', - placeItems: 'center', - flexShrink: 0, - mt: `${(STEP_HEADER_MIN_HEIGHT - NODE_SIZE) / 2}px`, - }; - - if (status === 'completed') { - return ( - - - - ); - } - if (status === 'current') { - return ( - - - - ); - } - return ( - - {number} - - ); -}; - -interface StepItemRowProps { - item: RoadmapQuestionItem; - pending: boolean; - onToggleCompletion: (itemId: string, completed: boolean) => void; - onItemClick: (questionId: string) => void; -} - -const StepItemRow = ({ item, pending, onToggleCompletion, onItemClick }: StepItemRowProps) => { - const { c } = useTokens(); - const completed = Boolean(item.is_completed); - - return ( - - onToggleCompletion(item.id, !completed)} - disabled={pending} - aria-pressed={completed} - aria-label={completed ? 'Снять отметку о выполнении' : 'Отметить как выполненный'} - sx={{ width: 36, height: 36, flexShrink: 0, color: completed ? c.success : c.textSubtle }} - > - {completed ? : } - - onItemClick(item.id)} - sx={{ - flex: 1, - minWidth: 0, - minHeight: 36, - px: 1, - py: 0.75, - gap: 1, - justifyContent: 'flex-start', - textAlign: 'left', - borderRadius: `${radius.md}px`, - transition: 'background-color 0.15s ease', - '&:hover': { backgroundColor: c.surfaceHover }, - '&:hover .roadmap-item-arrow': { color: c.text }, - }} - > - - - {item.title} - - - - - - - ); -}; - -interface TimelineStepProps { - step: RoadmapStep; - index: number; - isLast: boolean; - expanded: boolean; - pendingItems: Set; - onToggle: (stepId: string) => void; - onToggleCompletion: (itemId: string, completed: boolean) => void; - onItemClick: (questionId: string) => void; -} - -export const TimelineStep = ({ - step, - index, - isLast, - expanded, - pendingItems, - onToggle, - onToggleCompletion, - onItemClick, -}: TimelineStepProps) => { - const { c, shadow } = useTokens(); - const percent = step.total > 0 ? (step.completed / step.total) * 100 : 0; - const statusLabel = STATUS_LABELS[step.status]; - const panelId = `roadmap-step-${step.id}`; - - return ( - - - - {!isLast && } - - - - - onToggle(step.id)} - aria-expanded={expanded} - aria-controls={panelId} - sx={{ - width: '100%', - minHeight: STEP_HEADER_MIN_HEIGHT, - px: { xs: 1.5, sm: 2 }, - py: 1, - gap: 1.5, - justifyContent: 'flex-start', - textAlign: 'left', - '&.Mui-focusVisible': { boxShadow: `inset ${shadow.focus}` }, - }} - > - - - Шаг {index + 1} - {statusLabel && ` · ${statusLabel}`} - - - {step.title} - - - - - - - {step.completed}/{step.total} - - - - - {expanded && ( - - {step.items.length === 0 ? ( - - В этом шаге пока нет вопросов - - ) : ( - step.items.map((item) => ( - - )) - )} - - )} - - - - ); -}; diff --git a/frontend/src/pages/RoadmapsPage/index.tsx b/frontend/src/pages/RoadmapsPage/index.tsx index 64aeb85..76639c9 100644 --- a/frontend/src/pages/RoadmapsPage/index.tsx +++ b/frontend/src/pages/RoadmapsPage/index.tsx @@ -1,79 +1,100 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useMemo, useState } from 'react'; import { Link as RouterLink, useNavigate } from 'react-router-dom'; -import { Alert, Box, Button, Container, Grid, Skeleton } from '@mui/material'; +import { Box, Button, Container, Grid, LinearProgress, Skeleton, Stack, Typography } from '@mui/material'; import { - ArrowBack as ArrowBackIcon, + ArrowForward as ArrowForwardIcon, + EmojiEventsOutlined as TrophyIcon, MapOutlined as MapIcon, SearchOff as SearchOffIcon, } from '@mui/icons-material'; -import type { RoadmapDetail as RoadmapDetailData, RoadmapListResponse } from '../../services/roadmapService'; -import { useProfessions, useRoadmapDetails, useRoadmaps } from '../../queries/roadmaps'; -import { useProgress, useToggleCompleted } from '../../queries/progress'; +import { useProfessions } from '../../queries/roadmaps'; import { EmptyState, PageHeader } from '../../components/ui'; -import { layout, radius, wideFrame } from '../../theme/tokens'; +import { bitSay } from '../../components/ui/bitVoice'; +import { BadgeUnlockDialog } from '../../components/achievements/BadgeUnlockDialog'; +import { useAchievements, useBadgeCelebration } from '../../components/achievements/useAchievements'; +import type { RoadmapWithProgress } from '../../components/achievements/useAchievements'; +import { radius, useTokens, wideFrame } from '../../theme/tokens'; import { RoadmapCard } from './RoadmapCard'; -import { RoadmapDetail } from './RoadmapDetail'; +import { RoadmapCover } from './RoadmapCover'; import { RoadmapFilters } from './RoadmapFilters'; -import { buildSteps, getProgress } from './roadmapUtils'; -import { bitSay } from '../../components/ui/bitVoice'; -import { openLine, professionLine, stepLine, toggleLine } from './bitRoadmap'; +import { professionLine } from './bitRoadmap'; -const toggleInSet = (set: Set, value: string, include: boolean): Set => { - const next = new Set(set); - if (include) next.add(value); - else next.delete(value); - return next; +/** Баннер «Продолжить маршрут»: роадмап, на котором остановились. */ +const ContinueBanner = ({ entry }: { entry: RoadmapWithProgress }) => { + const { c } = useTokens(); + const navigate = useNavigate(); + const current = entry.steps.find((s) => s.status === 'current'); + const index = current ? entry.steps.indexOf(current) : -1; + const percent = entry.total ? Math.round((entry.done / entry.total) * 100) : 0; + return ( + + + + + Продолжить маршрут + + + {entry.detail.title} + {current && ( + + {' '} + · шаг {index + 1}: {current.title} + + )} + + + + + {entry.done}/{entry.total} + + + + + + ); }; -const NONE: RoadmapListResponse[] = []; - export const RoadmapsPage = () => { - const navigate = useNavigate(); - const detailRef = useRef(null); - const returnFocusRef = useRef(null); - - const roadmapsQuery = useRoadmaps(); + const { c } = useTokens(); + const achievements = useAchievements(); + const celebration = useBadgeCelebration(achievements.all, achievements.ready); const professionsQuery = useProfessions(); - const progress = useProgress(); - const toggleCompleted = useToggleCompleted(); - const roadmaps = roadmapsQuery.data ?? NONE; + const roadmapsQuery = achievements.listQuery; + const roadmaps = useMemo(() => roadmapsQuery.data ?? [], [roadmapsQuery.data]); const professions = professionsQuery.data ?? []; - const loading = roadmapsQuery.isPending; - const listError = roadmapsQuery.isError ? 'Ошибка при загрузке роадмапов. Пожалуйста, попробуйте позже.' : null; const [searchQuery, setSearchQuery] = useState(''); const [selectedProfession, setSelectedProfession] = useState(''); - // Детали открытых роадмапов лежат в кэше запросов; карточки уже открытых показывают прогресс. - const [openedSlugs, setOpenedSlugs] = useState([]); - const [selectedSlug, setSelectedSlug] = useState(null); - const [actionError, setActionError] = useState(null); - const [dismissedError, setDismissedError] = useState(null); - const [expandedSteps, setExpandedSteps] = useState>(new Set()); - const [expandedFor, setExpandedFor] = useState(null); - const [pendingItems, setPendingItems] = useState>(new Set()); - - const detailQueries = useRoadmapDetails(openedSlugs); - const details = useMemo(() => { - const done = progress.completed; - const map: Record = {}; - openedSlugs.forEach((slug, i) => { - const data = detailQueries[i]?.data; - if (data) map[slug] = { ...data, items: data.items.map((item) => ({ ...item, is_completed: done.has(item.id) })) }; - }); - return map; - }, [openedSlugs, detailQueries, progress.completed]); - const selectedIndex = selectedSlug ? openedSlugs.indexOf(selectedSlug) : -1; - const selectedQuery = selectedIndex >= 0 ? detailQueries[selectedIndex] : undefined; - const loadingSlug = selectedSlug && selectedQuery?.isPending ? selectedSlug : null; - const detailError = actionError ?? (selectedQuery?.isError ? 'Не удалось загрузить роадмап. Пожалуйста, попробуйте позже.' : null); - - useEffect(() => { - if (!selectedSlug || !details[selectedSlug]) return; - const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; - detailRef.current?.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'start' }); - detailRef.current?.querySelector('h2')?.focus({ preventScroll: true }); - }, [selectedSlug, Boolean(selectedSlug && details[selectedSlug])]); // eslint-disable-line react-hooks/exhaustive-deps + const bySlug = useMemo(() => new Map(achievements.roadmaps.map((r) => [r.detail.slug, r])), [achievements.roadmaps]); + // Где остановились: начатый, но не пройденный роадмап с наибольшим прогрессом + const inProgress = useMemo( + () => + achievements.roadmaps + .filter((r) => r.done > 0 && r.done < r.total) + .sort((a, b) => b.done / b.total - a.done / a.total)[0] ?? null, + [achievements.roadmaps], + ); + const earned = achievements.all.filter((b) => b.unlocked).length; const filteredRoadmaps = useMemo(() => { let filtered = roadmaps; @@ -92,64 +113,11 @@ export const RoadmapsPage = () => { return filtered; }, [roadmaps, searchQuery, selectedProfession]); - const selectedRoadmap = selectedSlug ? details[selectedSlug] ?? null : null; - const progressReady = !progress.isLoading; - const steps = useMemo(() => (selectedRoadmap ? buildSteps(selectedRoadmap.items, selectedRoadmap.steps) : []), [selectedRoadmap]); - - const handleRetry = () => { - void roadmapsQuery.refetch(); - void professionsQuery.refetch(); - }; - const handleClearFilters = () => { setSearchQuery(''); setSelectedProfession(''); }; - const handleOpenRoadmap = (slug: string, opener: HTMLElement) => { - if (loadingSlug) return; - returnFocusRef.current = opener; - setActionError(null); - const existing = detailQueries[openedSlugs.indexOf(slug)]; - if (existing?.isError) void existing.refetch(); - setOpenedSlugs((prev) => (prev.includes(slug) ? prev : [...prev, slug])); - setSelectedSlug(slug); - }; - - // Раскрытый шаг по умолчанию — текущий; считается один раз, когда детали и прогресс загружены. - if (selectedRoadmap && progressReady && expandedFor !== selectedSlug) { - const available = buildSteps(selectedRoadmap.items, selectedRoadmap.steps); - const current = available.find((step) => step.status === 'current') ?? available[0]; - setExpandedFor(selectedSlug); - setExpandedSteps(new Set(current ? [current.id] : [])); - } - - // Открыли роадмап (детали и прогресс готовы) — Бит рассказывает, где мы на маршруте - useEffect(() => { - if (!expandedFor || !selectedRoadmap || expandedFor !== selectedRoadmap.slug) return; - const line = openLine(selectedRoadmap.title, steps); - bitSay(line.text, line.tone); - }, [expandedFor]); // eslint-disable-line react-hooks/exhaustive-deps - - const handleCloseRoadmap = () => { - setSelectedSlug(null); - setExpandedFor(null); - requestAnimationFrame(() => returnFocusRef.current?.focus()); - }; - - const handleItemClick = (questionId: string) => { - navigate(`/questions/${questionId}`); - }; - - const handleToggleStep = (stepId: string) => { - const step = steps.find((s) => s.id === stepId); - if (step && !expandedSteps.has(stepId)) { - const line = stepLine(step); - bitSay(line.text, line.tone); - } - setExpandedSteps(new Set([stepId])); - }; - const handleProfessionChange = (value: string) => { setSelectedProfession(value); const count = roadmaps.filter((rm) => !value || rm.profession.toLowerCase() === value.toLowerCase()).length; @@ -157,43 +125,26 @@ export const RoadmapsPage = () => { bitSay(line.text, line.tone); }; - const handleToggleCompletion = async (itemId: string, completed: boolean) => { - if (!selectedRoadmap) return; - - setPendingItems((prev) => toggleInSet(prev, itemId, true)); - const line = toggleLine(steps, itemId, completed); - bitSay(line.text, line.tone); - try { - // Один вопрос может входить в несколько роадмапов: состояние берётся из общего кэша progress. - await toggleCompleted.mutateAsync({ id: itemId, on: completed }); - } catch (err) { - console.error('Ошибка при изменении статуса выполнения:', err); - setActionError('Не удалось сохранить отметку. Попробуйте ещё раз.'); - } finally { - setPendingItems((prev) => toggleInSet(prev, itemId, false)); - } - }; - const renderContent = () => { - if (loading) { + if (roadmapsQuery.isPending) { return ( - {Array.from({ length: 6 }).map((_, i) => ( + {Array.from({ length: 3 }).map((_, i) => ( - + ))} ); } - if (listError) { + if (roadmapsQuery.isError) { return ( + } @@ -218,8 +169,7 @@ export const RoadmapsPage = () => { return ( <> - {detailError && detailError !== dismissedError && { setActionError(null); setDismissedError(detailError); }} sx={{ mb: 3 }}>{detailError}} - + {inProgress && } { ) : ( {filteredRoadmaps.map((roadmap) => { - const detail = details[roadmap.slug]; + const entry = bySlug.get(roadmap.slug); return ( b.tier !== 'milestone') : []} /> ); })} )} - - - {selectedRoadmap && ( - - - - )} ); }; @@ -285,14 +217,22 @@ export const RoadmapsPage = () => { }> - К вопросам - + achievements.all.length > 0 && ( + + ) } /> {renderContent()} + ); }; diff --git a/frontend/src/pages/UserProfilePage/index.tsx b/frontend/src/pages/UserProfilePage/index.tsx index 9eb69ad..7646852 100644 --- a/frontend/src/pages/UserProfilePage/index.tsx +++ b/frontend/src/pages/UserProfilePage/index.tsx @@ -9,6 +9,7 @@ import { layout } from '../../theme/tokens'; import { ProfileSummary } from './ProfileSummary'; import { ProfileSettings } from './ProfileSettings'; import { CategoryProgress } from './CategoryProgress'; +import { AchievementsPanel } from '../../components/achievements/AchievementsPanel'; export const UserProfilePage = () => { const { user, isLoading: authLoading } = useAuth(); @@ -58,6 +59,7 @@ export const UserProfilePage = () => { + {categories.length > 0 && } diff --git a/frontend/src/queries/interview.ts b/frontend/src/queries/interview.ts index 4194b99..e304dc3 100644 --- a/frontend/src/queries/interview.ts +++ b/frontend/src/queries/interview.ts @@ -1,6 +1,6 @@ import { isAxiosError } from 'axios'; -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { useCallback } from 'react'; +import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useCallback, useMemo } from 'react'; import api from '../services/api'; import type { AIReview, AIReviewStatus, Question, QuestionListResponse } from '../types'; import { keys } from './keys'; @@ -32,6 +32,20 @@ const questionQuery = (id: string) => ({ (await api.get(`/questions/${id}`, { signal })).data, }); +/** + * Вопросы по списку id (шаг роадмапа) в том же порядке. Кэш общий с карточкой интервью, + * поэтому каждый вопрос грузится один раз. + */ +export const useQuestionsByIds = (ids: string[]) => { + const results = useQueries({ queries: ids.map((id) => questionQuery(id)) }); + const pending = results.some((r) => r.isPending); + const data = results.map((r) => r.data).filter((q): q is Question => Boolean(q)); + const key = data.map((q) => q.id).join(','); + // useQueries отдаёт новый массив на каждый рендер: держим ссылку стабильной, пока состав тот же + const questions = useMemo(() => data, [key]); // eslint-disable-line react-hooks/exhaustive-deps + return { questions, pending, error: results.some((r) => r.isError) }; +}; + /** Полный вопрос (с опубликованными ответами) для открытой карточки интервью. */ export const useInterviewCard = (id: string | undefined) => useQuery({ ...questionQuery(id ?? ''), enabled: Boolean(id) }); diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 1795f78..7e0c3cd 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -77,6 +77,14 @@ export const routes: RouteObject[] = [ { path: 'profile', lazy: () => import('./pages/UserProfilePage').then((m) => ({ Component: m.UserProfilePage })) }, { path: 'favorites', lazy: () => import('./pages/FavoritesPage').then((m) => ({ Component: m.FavoritesPage })) }, { path: 'roadmap', lazy: () => import('./pages/RoadmapsPage').then((m) => ({ Component: m.RoadmapsPage })) }, + { + path: 'roadmap/:slug', + lazy: () => import('./pages/RoadmapsPage/RoadmapPage').then((m) => ({ Component: m.RoadmapPage })), + }, + { + path: 'roadmap/:slug/step/:stepId/interview/:questionIndex', + lazy: () => import('./pages/RoadmapsPage/RoadmapInterviewPage').then((m) => ({ Component: m.RoadmapInterviewPage })), + }, ], }, {