diff --git a/frontend/src/components/ui/PracticeMascot.test.tsx b/frontend/src/components/ui/PracticeMascot.test.tsx new file mode 100644 index 0000000..16a7882 --- /dev/null +++ b/frontend/src/components/ui/PracticeMascot.test.tsx @@ -0,0 +1,48 @@ +import { http, HttpResponse } from 'msw'; +import { setupServer } from 'msw/node'; +import { MemoryRouter } from 'react-router-dom'; +import { QueryClient } from '@tanstack/react-query'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { ThemeProvider as MuiThemeProvider } from '@mui/material'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { AuthProvider } from '../../context/AuthContext'; +import { ThemeProvider } from '../../context/ThemeContext'; +import { darkTheme } from '../../theme/muiTheme'; +import { TestQueryProvider } from '../../test/TestQueryProvider'; +import { PracticeMascot } from './PracticeMascot'; +import { bitSay } from './bitVoice'; + +const server = setupServer(http.get('*/auth/me', () => new HttpResponse(null, { status: 401 }))); +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +const renderMascot = () => + render( + + + + + + + + + + + , + ); + +describe('PracticeMascot speech', () => { + it('does not repeat a line said before it mounted, shows new lines and hides on click', async () => { + bitSay('старая реплика'); + renderMascot(); + expect(screen.queryByText('старая реплика')).not.toBeInTheDocument(); + + act(() => bitSay('Хардкор-режим включён!', 'fire')); + expect(screen.getByRole('status')).toHaveTextContent('Бит: Хардкор-режим включён!'); + const bubble = await screen.findByText('Хардкор-режим включён!', { selector: 'p' }); + + fireEvent.click(bubble); + expect(screen.getByRole('status')).toHaveTextContent(''); + }); +}); diff --git a/frontend/src/components/ui/PracticeMascot.tsx b/frontend/src/components/ui/PracticeMascot.tsx index da835db..1f25f52 100644 --- a/frontend/src/components/ui/PracticeMascot.tsx +++ b/frontend/src/components/ui/PracticeMascot.tsx @@ -1,10 +1,12 @@ import { useEffect, useId, useState } from 'react'; -import { Box, Button, Dialog, DialogContent, DialogTitle, IconButton, Stack, Typography } from '@mui/material'; +import { Box, Button, ClickAwayListener, Dialog, DialogContent, DialogTitle, Grow, IconButton, Popper, Stack, Typography } from '@mui/material'; import { ArrowForward, Close, Loop } from '@mui/icons-material'; import { Link as RouterLink, useLocation } from 'react-router-dom'; import { useAuth } from '../../context/auth-context'; import { useTokens } from '../../theme/tokens'; import bit from '../../assets/mascot/bit.webp'; +import { useBitVoice } from './bitVoice'; +import type { BitTone } from './bitVoice'; type TipSet = [string, string]; @@ -61,14 +63,22 @@ const comments = [ 'Код сам себя не прочтёт', ]; -const BitAvatar = () => ( +const BitAvatar = ({ talking = false }: { talking?: boolean }) => ( { const [alternate, setAlternate] = useState(false); const [commentIndex, setCommentIndex] = useState(0); const section = getSection(pathname); + // Реплики (bitSay) показываются облачком под Битом; сказанное до перехода на страницу не повторяем. + const voice = useBitVoice(); + const [seenId] = useState(() => voice?.id ?? 0); + const [hiddenId, setHiddenId] = useState(0); + const [anchor, setAnchor] = useState(null); + const [arrow, setArrow] = useState(null); + const said = voice && voice.id > seenId && voice.id > hiddenId && !open ? voice : null; + useEffect(() => { + if (!voice) return; + const timer = window.setTimeout(() => setHiddenId(voice.id), 6500); + return () => window.clearTimeout(timer); + }, [voice]); + const toneColor: Record = { calm: c.accent, cheer: c.success, fire: c.danger, focus: c.warning }; useEffect(() => { const timer = window.setInterval(() => { @@ -119,6 +142,7 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { return ( <> + + {said ? `Бит: ${said.text}` : ''} + + t.zIndex.appBar + 1 }} + modifiers={[ + { name: 'offset', options: { offset: [0, 10] } }, + { name: 'preventOverflow', options: { padding: 8 } }, + // хвостик всегда указывает на Бита, даже если облачко прижато к краю экрана + { name: 'arrow', enabled: Boolean(arrow), options: { element: arrow, padding: 14 } }, + ]} + > + {({ TransitionProps }) => ( + + + voice && setHiddenId(voice.id)}> + voice && setHiddenId(voice.id)} + sx={{ + position: 'relative', + maxWidth: { xs: 'calc(100vw - 24px)', sm: 300 }, + px: 1.75, + py: 1.25, + borderRadius: '14px', + border: `1px solid ${c.borderStrong}`, + borderTop: `3px solid ${said ? toneColor[said.tone] : c.accent}`, + bgcolor: c.surface, + boxShadow: shadow.lg, + cursor: 'pointer', + }} + > + + Бит + {said?.text} + + + + + )} + setOpen(false)} diff --git a/frontend/src/components/ui/bitVoice.ts b/frontend/src/components/ui/bitVoice.ts new file mode 100644 index 0000000..351b83f --- /dev/null +++ b/frontend/src/components/ui/bitVoice.ts @@ -0,0 +1,36 @@ +import { useSyncExternalStore } from 'react'; + +/** Настроение реплики: подкрашивает облачко Бита. */ +export type BitTone = 'calm' | 'cheer' | 'fire' | 'focus'; + +export interface BitLine { + id: number; + text: string; + tone: BitTone; +} + +let current: BitLine | null = null; +let seq = 0; +const listeners = new Set<() => void>(); + +/** Бит говорит реплику в шапке (облачко над страницей, несколько секунд). */ +export const bitSay = (text: string, tone: BitTone = 'calm') => { + current = { id: ++seq, text, tone }; + listeners.forEach((l) => l()); +}; + +const subscribe = (listener: () => void) => { + listeners.add(listener); + return () => listeners.delete(listener); +}; + +export const useBitVoice = () => useSyncExternalStore(subscribe, () => current, () => null); + +/** Случайная фраза, не повторяющая прошлую из того же набора. */ +const lastPicked = new Map(); +export const pickLine = (key: string, lines: string[]) => { + const pool = lines.length > 1 ? lines.filter((l) => l !== lastPicked.get(key)) : lines; + const line = pool[Math.floor(Math.random() * pool.length)]; + lastPicked.set(key, line); + return line; +}; diff --git a/frontend/src/pages/QuestionsPage/ModeBadge.tsx b/frontend/src/pages/QuestionsPage/ModeBadge.tsx new file mode 100644 index 0000000..6d00ef3 --- /dev/null +++ b/frontend/src/pages/QuestionsPage/ModeBadge.tsx @@ -0,0 +1,37 @@ +import { Box, alpha } from '@mui/material'; +import { useTokens } from '../../theme/tokens'; +import type { ListMode } from './listMode'; + +/** Бейдж режима в шапке списка; при смене режима «выпрыгивает». */ +export const ModeBadge = ({ mode }: { mode: ListMode }) => { + const { c } = useTokens(); + const color = mode.color(c); + return ( + + + {mode.title} + + ); +}; diff --git a/frontend/src/pages/QuestionsPage/bitLines.test.ts b/frontend/src/pages/QuestionsPage/bitLines.test.ts new file mode 100644 index 0000000..5b5c4a5 --- /dev/null +++ b/frontend/src/pages/QuestionsPage/bitLines.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { pickLine } from '../../components/ui/bitVoice'; +import { difficultyLine, sortLine, statusLine } from './bitLines'; +import { LIST_MODES, listModeOf } from './listMode'; + +describe('Bit lines', () => { + it('has a line and a mode for every sort option', () => { + for (const key of Object.keys(LIST_MODES)) { + const [sort, dir] = key.split(':'); + expect(sortLine(sort, dir).text).toBeTruthy(); + expect(sortLine(sort, dir).tone).toBe(LIST_MODES[key].tone); + } + }); + + it('falls back to the default mode for an unknown sort', () => { + expect(listModeOf('updated_at', 'asc')).toBe(LIST_MODES['updated_at:desc']); + expect(sortLine('updated_at', 'asc').text).toBeTruthy(); + }); + + it('does not repeat the previous line', () => { + const picks = Array.from({ length: 6 }, () => pickLine('alternate', ['a', 'b'])); + picks.slice(1).forEach((p, i) => expect(p).not.toBe(picks[i])); + }); + + it('puts counts into difficulty and status lines with correct plural', () => { + expect(difficultyLine('medium', 689).text).toMatch(/689 вопросов/); + expect(statusLine('new', { fresh: 1, review: 0, passed: 0 }).text).toMatch(/1 вопрос ждёт /); + expect(statusLine('done', { fresh: 0, review: 0, passed: 3 }).text).toMatch(/3 вопроса\./); + expect(statusLine('review', { fresh: 5, review: 0, passed: 0 }).text).toMatch(/Повторять нечего/); + expect(statusLine('new', { fresh: 1096, review: 2, passed: 2 }).text).toMatch(/1096 вопросов/); + expect(statusLine('done', null).tone).toBe('calm'); + }); +}); diff --git a/frontend/src/pages/QuestionsPage/bitLines.ts b/frontend/src/pages/QuestionsPage/bitLines.ts new file mode 100644 index 0000000..8d58baa --- /dev/null +++ b/frontend/src/pages/QuestionsPage/bitLines.ts @@ -0,0 +1,76 @@ +import { pickLine } from '../../components/ui/bitVoice'; +import type { BitTone } from '../../components/ui/bitVoice'; +import { plural } from '../../utils/difficulty'; +import type { Difficulty } from '../../utils/difficulty'; +import { listModeOf } from './listMode'; +import type { Status } from './urlState'; + +/** Реплики Бита на смену сортировки и фильтров на странице вопросов. */ + +const Q: [string, string, string] = ['вопрос', 'вопроса', 'вопросов']; +const q = (n: number) => `${n} ${plural(n, Q)}`; +/** «1 вопрос ждёт», «5 вопросов ждут». */ +const wait = (n: number) => plural(n, ['ждёт', 'ждут', 'ждут']); + +type Line = { text: string; tone: BitTone }; + +const SORT_LINES: Record = { + 'updated_at:desc': [ + 'Свежак! Сверху то, что недавно подкрутили. Проверим, что изменилось?', + 'Бип! Самое актуальное наверху. Начни с первого и не листай долго.', + ], + 'created_at:desc': [ + 'Новенькие! Ответь на свежий вопрос раньше всех.', + 'Свежая партия из печки. Пахнет собеседованием.', + ], + 'created_at:asc': [ + 'Классика жанра: эти вопросы любят задавать годами.', + 'Начинаем с истоков. Фундамент — это не скучно, это надёжно.', + ], + 'difficulty:asc': [ + 'Разминка! От простого к сложному — так мозг быстрее входит в поток.', + 'Сначала лёгкие: пара быстрых побед, и темп набран.', + ], + 'difficulty:desc': [ + 'Хардкор-режим включён! Застрял — разбей задачу на маленькие шаги.', + 'Сначала сложные? Уважаю. Ошибки здесь — лучшие учителя.', + ], + 'title:asc': [ + 'По алфавиту, как в словаре. Ищешь что-то конкретное — жми «/».', + 'А, Б, В… Порядок в голове начинается с порядка в списке.', + ], +}; +SORT_LINES['title:desc'] = SORT_LINES['title:asc']; + +export const sortLine = (sort: string, dir: string): Line => { + const key = `${sort}:${dir}`; + return { text: pickLine(`sort:${key}`, SORT_LINES[key] ?? SORT_LINES['updated_at:desc']), tone: listModeOf(sort, dir).tone }; +}; + +export const difficultyLine = (d: Difficulty | '', count: number | undefined): Line => { + const n = count ?? 0; + if (d === 'easy') return { tone: 'cheer', text: pickLine('d:easy', [`${q(n)} для разгона. Пять подряд — и ты в потоке.`, `Лёгкие — не значит лишние: на них проверяют базу. ${q(n)} ${wait(n)}.`]) }; + if (d === 'medium') return { tone: 'focus', text: pickLine('d:medium', [`${q(n)} среднего уровня — их чаще всего и спрашивают.`, `Золотая середина: ${q(n)}. Отвечай вслух, будто интервьюер рядом.`]) }; + if (d === 'hard') return { tone: 'fire', text: pickLine('d:hard', [`${q(n)} со звёздочкой. Даже я компилировался не с первого раза.`, `Сложные! Сначала назови идею решения, детали подтянутся.`]) }; + return { tone: 'calm', text: 'Все уровни вперемешку — почти как на настоящем интервью.' }; +}; + +export const statusLine = (status: Status, counts: { fresh: number; review: number; passed: number } | null): Line => { + if (status === 'new') { + const n = counts?.fresh ?? 0; + return { tone: 'cheer', text: n ? `Неизведанные земли: ${q(n)} ${wait(n)} первого ответа. Начни с одного.` : 'Нетронутых вопросов не осталось. Бип-бип, это впечатляет!' }; + } + if (status === 'review') { + const n = counts?.review ?? 0; + return n + ? { tone: 'focus', text: pickLine('s:review', [`Повторение — мать учения. ${q(n)} ${wait(n)} реванша.`, `${q(n)} на доработку. Закрой ответ и перескажи суть своими словами.`]) } + : { tone: 'cheer', text: 'Повторять нечего — всё, что начато, доведено до конца!' }; + } + if (status === 'done') { + const n = counts?.passed ?? 0; + return n + ? { tone: 'cheer', text: `Твоя коллекция побед: ${q(n)}. Освежи пару ответов, чтобы не остыли.` } + : { tone: 'calm', text: 'Пока пусто, но первое «Знаю» уже совсем близко.' }; + } + return { tone: 'calm', text: 'Весь список на месте. Выбирай, с чего начать.' }; +}; diff --git a/frontend/src/pages/QuestionsPage/index.tsx b/frontend/src/pages/QuestionsPage/index.tsx index 2968c77..87c6555 100644 --- a/frontend/src/pages/QuestionsPage/index.tsx +++ b/frontend/src/pages/QuestionsPage/index.tsx @@ -18,6 +18,7 @@ import { } from '@mui/material'; import { useTheme } from '@mui/material/styles'; import { AddOutlined, Close, ErrorOutlineOutlined, QuizOutlined, SearchOffOutlined } from '@mui/icons-material'; +import { alpha } from '@mui/material/styles'; import { useQueryClient } from '@tanstack/react-query'; import { keys } from '../../queries/keys'; import { useCategoryStats, useCompletionStats } from '../../queries/progress'; @@ -26,6 +27,10 @@ import { useAuth } from '../../context/auth-context'; import { EmptyState, FilterBar, PageHeader, SearchInput } from '../../components/ui'; import { radius, useTokens, wideFrame } from '../../theme/tokens'; import { DIFFICULTY_LABELS, plural } from '../../utils/difficulty'; +import { bitSay } from '../../components/ui/bitVoice'; +import { difficultyLine, sortLine, statusLine } from './bitLines'; +import { listModeOf } from './listMode'; +import { ModeBadge } from './ModeBadge'; import { CategoryChips, CategoryNav } from './CategoryNav'; import { ProgressOverview } from './ProgressOverview'; import type { MasterySummary } from './ProgressOverview'; @@ -185,9 +190,25 @@ export const QuestionsPage = () => { }; const handleCategoryChange = (id: string) => update({ category: categories.find((cat) => cat.id === id)?.slug ?? '' }); - const handleDifficultyChange = (value: ListState['difficulty']) => update({ difficulty: value }); - const handleStatusChange = (value: Status) => update({ status: value }); - const handleSortChange = (sort: string, dir: ListState['dir']) => update({ sort, dir }); + // Смена режима — повод для Бита сказать пару слов (только на действие пользователя, не при загрузке). + const say = ({ text, tone }: { text: string; tone: Parameters[1] }) => bitSay(text, tone); + const handleDifficultyChange = (value: ListState['difficulty']) => { + if (value !== difficulty) say(difficultyLine(value, value ? counts?.[value] : undefined)); + update({ difficulty: value }); + }; + const handleStatusChange = (value: Status) => { + if (value !== status) { + const review = scopeSummary ? scopeSummary.partial + scopeSummary.failed : 0; + say(statusLine(value, scopeSummary && { passed: scopeSummary.passed, review, fresh: Math.max(0, scopeSummary.total - scopeSummary.passed - review) })); + } + update({ status: value }); + }; + const handleSortChange = (sort: string, dir: ListState['dir']) => { + if (sort !== sortBy || dir !== sortDir) say(sortLine(sort, dir)); + update({ sort, dir }); + }; + const mode = listModeOf(sortBy, sortDir); + const modeColor = mode.color(c); const setPage = (value: number) => update({ page: value }); const handleResetFilters = () => { @@ -385,15 +406,16 @@ export const QuestionsPage = () => { - + + {isLoading && !result ? 'Загружаем…' : total ? `${rangeStart}–${rangeEnd} из ${total}` : '0 вопросов'} diff --git a/frontend/src/pages/QuestionsPage/listMode.ts b/frontend/src/pages/QuestionsPage/listMode.ts new file mode 100644 index 0000000..181b596 --- /dev/null +++ b/frontend/src/pages/QuestionsPage/listMode.ts @@ -0,0 +1,25 @@ +import type { SvgIconComponent } from '@mui/icons-material'; +import { AutoAwesomeOutlined, FitnessCenterOutlined, HistoryEduOutlined, NewReleasesOutlined, SortByAlphaOutlined, WhatshotOutlined } from '@mui/icons-material'; +import type { Palette } from '../../theme/tokens'; +import type { BitTone } from '../../components/ui/bitVoice'; + +export interface ListMode { + title: string; + hint: string; + Icon: SvgIconComponent; + tone: BitTone; + color: (c: Palette) => string; +} + +/** Режим списка по сортировке: свой цвет, иконка и настроение реплики Бита. */ +export const LIST_MODES: Record = { + 'updated_at:desc': { title: 'Свежие правки', hint: 'Сверху — недавно обновлённые', Icon: AutoAwesomeOutlined, tone: 'calm', color: (c) => c.accent }, + 'created_at:desc': { title: 'Новинки', hint: 'Сверху — новые вопросы', Icon: NewReleasesOutlined, tone: 'cheer', color: (c) => c.info }, + 'created_at:asc': { title: 'Классика', hint: 'Проверенные временем вопросы', Icon: HistoryEduOutlined, tone: 'calm', color: (c) => c.accent }, + 'difficulty:asc': { title: 'Разминка', hint: 'От простого к сложному', Icon: FitnessCenterOutlined, tone: 'cheer', color: (c) => c.success }, + 'difficulty:desc': { title: 'Хардкор', hint: 'Сначала самое сложное', Icon: WhatshotOutlined, tone: 'fire', color: (c) => c.danger }, + 'title:asc': { title: 'Словарь', hint: 'По алфавиту, А→Я', Icon: SortByAlphaOutlined, tone: 'focus', color: (c) => c.info }, + 'title:desc': { title: 'Словарь', hint: 'По алфавиту, Я→А', Icon: SortByAlphaOutlined, tone: 'focus', color: (c) => c.info }, +}; + +export const listModeOf = (sort: string, dir: string): ListMode => LIST_MODES[`${sort}:${dir}`] ?? LIST_MODES['updated_at:desc'];