Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions frontend/src/components/ui/PracticeMascot.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<TestQueryProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<ThemeProvider>
<MuiThemeProvider theme={darkTheme}>
<AuthProvider>
<MemoryRouter initialEntries={['/questions']}>
<PracticeMascot />
</MemoryRouter>
</AuthProvider>
</MuiThemeProvider>
</ThemeProvider>
</TestQueryProvider>,
);

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('');
});
});
80 changes: 75 additions & 5 deletions frontend/src/components/ui/PracticeMascot.tsx
Original file line number Diff line number Diff line change
@@ -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];

Expand Down Expand Up @@ -61,14 +63,22 @@ const comments = [
'Код сам себя не прочтёт',
];

const BitAvatar = () => (
const BitAvatar = ({ talking = false }: { talking?: boolean }) => (
<Box
component="span"
aria-hidden
sx={{
position: 'relative', height: { xs: 37, md: 42 }, aspectRatio: '197 / 250', flexShrink: 0,
transformOrigin: '50% 82%',
'@media (prefers-reduced-motion: no-preference)': { animation: 'bit-greeting 10s ease-in-out infinite' },
'@media (prefers-reduced-motion: no-preference)': {
animation: talking ? 'bit-talk .5s ease-in-out 3' : 'bit-greeting 10s ease-in-out infinite',
},
// реплика: Бит подпрыгивает и покачивается
'@keyframes bit-talk': {
'0%, 100%': { transform: 'none' },
'30%': { transform: 'translateY(-4px) rotate(-6deg)' },
'60%': { transform: 'translateY(0) scaleY(.94) rotate(4deg)' },
},
'@keyframes bit-greeting': {
'0%, 19%, 100%': { transform: 'none' },
'5%': { transform: 'translateX(-1px) rotate(-5deg)' },
Expand Down Expand Up @@ -103,6 +113,19 @@ const MascotPanel = ({ pathname }: { pathname: string }) => {
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<HTMLElement | null>(null);
const [arrow, setArrow] = useState<HTMLElement | null>(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<BitTone, string> = { calm: c.accent, cheer: c.success, fire: c.danger, focus: c.warning };

useEffect(() => {
const timer = window.setInterval(() => {
Expand All @@ -119,6 +142,7 @@ const MascotPanel = ({ pathname }: { pathname: string }) => {
return (
<>
<Button
ref={setAnchor}
aria-label="Открыть подсказку Бита"
aria-haspopup="dialog"
aria-expanded={open}
Expand All @@ -132,18 +156,64 @@ const MascotPanel = ({ pathname }: { pathname: string }) => {
'&.Mui-focusVisible': { outline: `2px solid ${c.accent}`, outlineOffset: 3 },
}}
>
<BitAvatar />
<BitAvatar key={said?.id ?? 'idle'} talking={Boolean(said)} />
<Box component="span" sx={{ display: 'grid', minWidth: 0 }}>
<Typography component="span" sx={{ fontWeight: 750, fontSize: '0.8rem', lineHeight: 1.15 }}>Бит</Typography>
<Typography
component="span"
aria-hidden
sx={{ display: { xs: 'none', lg: 'block' }, width: 132, fontSize: '0.71rem', color: c.textMuted, overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{comment}
{said ? said.text : comment}
</Typography>
</Box>
</Button>
<Box component="span" role="status" aria-live="polite" sx={{ position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)' }}>
{said ? `Бит: ${said.text}` : ''}
</Box>
<Popper open={Boolean(said) && Boolean(anchor)} anchorEl={anchor} placement="bottom-end" transition sx={{ zIndex: (t) => 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 }) => (
<Grow {...TransitionProps} style={{ transformOrigin: 'top right' }} timeout={220}>
<Box>
<ClickAwayListener onClickAway={() => voice && setHiddenId(voice.id)}>
<Box
onClick={() => 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',
}}
>
<Box
ref={setArrow}
aria-hidden
sx={{
position: 'absolute', top: -9, width: 12, height: 12,
'&::before': { content: '""', position: 'absolute', inset: 0, bgcolor: said ? toneColor[said.tone] : c.accent, transform: 'rotate(45deg)', borderRadius: '2px' },
}}
/>
<Typography sx={{ fontSize: '.72rem', fontWeight: 750, color: said ? toneColor[said.tone] : c.accent, mb: 0.25 }}>Бит</Typography>
<Typography sx={{ fontSize: '.875rem', lineHeight: 1.45, color: c.text }}>{said?.text}</Typography>
</Box>
</ClickAwayListener>
</Box>
</Grow>
)}
</Popper>
<Dialog
open={open}
onClose={() => setOpen(false)}
Expand Down
36 changes: 36 additions & 0 deletions frontend/src/components/ui/bitVoice.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>();
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;
};
37 changes: 37 additions & 0 deletions frontend/src/pages/QuestionsPage/ModeBadge.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Box
title={mode.hint}
sx={{
display: 'inline-flex',
alignItems: 'center',
gap: 0.6,
pl: 0.75,
pr: 1.1,
height: 26,
borderRadius: 99,
fontSize: '.75rem',
fontWeight: 700,
color,
bgcolor: alpha(color, 0.12),
border: `1px solid ${alpha(color, 0.4)}`,
whiteSpace: 'nowrap',
'@media (prefers-reduced-motion: no-preference)': { animation: 'mode-pop .45s cubic-bezier(.3,1.6,.5,1)' },
'@keyframes mode-pop': {
'0%': { transform: 'scale(.6)', opacity: 0 },
'100%': { transform: 'none', opacity: 1 },
},
}}
>
<mode.Icon sx={{ fontSize: 16 }} />
{mode.title}
</Box>
);
};
33 changes: 33 additions & 0 deletions frontend/src/pages/QuestionsPage/bitLines.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
76 changes: 76 additions & 0 deletions frontend/src/pages/QuestionsPage/bitLines.ts
Original file line number Diff line number Diff line change
@@ -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<string, string[]> = {
'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: 'Весь список на месте. Выбирай, с чего начать.' };
};
Loading
Loading