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
3 changes: 3 additions & 0 deletions frontend/src/components/ui/BitAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ export const BitAvatar = ({ height = { xs: 37, md: 42 } }: BitAvatarProps) => {
data-bit-mood={mood}
sx={{
position: 'relative', height, aspectRatio: '197 / 250', flexShrink: 0, display: 'inline-block',
// слой движения пересоздаётся на каждое движение: без этого клик, попавший между
// нажатием и отпусканием на старый слой, терялся бы. Кликабельна обёртка, а не картинка.
pointerEvents: 'none',
transformOrigin: '50% 82%',
transition: 'opacity .6s, filter .6s',
opacity: asleep ? 0.7 : 1,
Expand Down
62 changes: 62 additions & 0 deletions frontend/src/components/ui/BitDialog.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { MemoryRouter } from 'react-router-dom';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { ThemeProvider as MuiThemeProvider } from '@mui/material';
import { beforeEach, describe, expect, it } from 'vitest';
import { ThemeProvider } from '../../context/ThemeContext';
import { darkTheme } from '../../theme/muiTheme';
import { BitDialog } from './BitDialog';
import type { BitSection } from './BitDialog';
import { bitSay, resetBitForTests } from './bitVoice';

const renderDialog = (section: BitSection, isAuthenticated = true) =>
render(
<ThemeProvider>
<MuiThemeProvider theme={darkTheme}>
<MemoryRouter>
<BitDialog open onClose={() => {}} section={section} isAuthenticated={isAuthenticated} />
</MemoryRouter>
</MuiThemeProvider>
</ThemeProvider>,
);

beforeEach(() => {
resetBitForTests();
window.localStorage.removeItem('bit:sound');
});

describe('BitDialog', () => {
it('cycles page tips with a visible counter', () => {
renderDialog('roadmap');
expect(screen.getByText(/Совет · 1 из 2/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Ещё совет' }));
expect(screen.getByText(/Совет · 2 из 2/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Ещё совет' }));
expect(screen.getByText(/1 из 2/)).toBeInTheDocument();
});

it('offers a page action when there is one, otherwise only «Понятно»', () => {
const { unmount } = renderDialog('questions');
expect(screen.getByRole('link', { name: 'Собеседование по компании' })).toHaveAttribute('href', '/companies');
unmount();
renderDialog('roadmap');
expect(screen.queryByRole('link')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Понятно' })).toBeInTheDocument();
});

it('shows what Bit said recently', () => {
act(() => bitSay('Шаг «Основы» закрыт!', 'cheer'));
renderDialog('roadmap');
expect(screen.getByText('Недавно говорил')).toBeInTheDocument();
expect(screen.getByText('Шаг «Основы» закрыт!')).toBeInTheDocument();
});

it('toggles sound and remembers the choice', () => {
renderDialog('home');
const toggle = screen.getByRole('button', { name: 'Выключить звук Бита' });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(toggle);
expect(screen.getByRole('button', { name: 'Включить звук Бита' })).toHaveAttribute('aria-pressed', 'false');
expect(window.localStorage.getItem('bit:sound')).toBe('0');
fireEvent.click(screen.getByRole('button', { name: 'Включить звук Бита' }));
});
});
216 changes: 216 additions & 0 deletions frontend/src/components/ui/BitDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import { useEffect, useId, useState } from 'react';
import { Box, Button, Dialog, IconButton, Stack, Tooltip, Typography } from '@mui/material';
import { ArrowForward, Close, VolumeOff, VolumeUp } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom';
import { useTokens } from '../../theme/tokens';
import { BitAvatar } from './BitAvatar';
import { playBitSound, setBitSoundEnabled, useBitSoundEnabled } from './bitSound';
import { bitMove, useBitHistory, useBitPose } from './bitVoice';
import type { BitMood, BitTone } from './bitVoice';

export type BitSection = 'home' | 'questions' | 'question' | 'companies' | 'interview' | 'roadmap' | 'favorites' | 'account';

/** Советы для страницы: листаются по кругу кнопкой «Ещё совет». */
const TIPS: Record<BitSection, string[]> = {
home: [
'Начните с одного вопроса. Сформулируйте ответ своими словами и только потом откройте разбор.',
'Не знаете, с чего начать? Возьмите тему, которую давно не повторяли. Одного вопроса достаточно.',
'Пять минут каждый день полезнее, чем три часа накануне собеседования.',
],
questions: [
'Выберите одну тему и ответьте на вопрос вслух. Так легче заметить, где в объяснении не хватает связки.',
'Застряли? Придумайте самый маленький пример и разберите его вручную.',
'Отмечайте честно: «Частично» вернёт вопрос в фильтр «На повтор», и вы к нему вернётесь.',
],
question: [
'Перед разбором попробуйте дать короткий ответ: что происходит, почему и на каком примере это видно.',
'После разбора закройте ответ и перескажите суть. Один честный повтор полезнее нескольких быстрых просмотров.',
'Включите «Тренировку» — ответ спрячется, пока вы не сформулируете свой.',
],
companies: [
'Откройте компанию, которая вам интересна. Сначала попробуйте ответить на один вопрос без подсказок.',
'В компании есть пробное собеседование: я задам вопросы по очереди и подведу итоги.',
],
interview: [
'Объясняйте ход мысли вслух. Если не знаете ответ сразу, начните с того, что уже понятно.',
'Назовите одно допущение и проверьте его на примере. Это даст вам следующую точку опоры.',
'Можно надиктовать ответ голосом — так ближе к настоящему собеседованию.',
],
roadmap: [
'Откройте текущий шаг и возьмите первый неотмеченный вопрос. Остальные подождут.',
'Если тема уже знакома, проверьте её одним вопросом. Если вспоминается тяжело, останьтесь на этом шаге.',
],
favorites: [
'Возьмите один вопрос из избранного и ответьте на него без подсказки.',
'Начните с того, что добавили раньше всех: его вы помните хуже всего.',
],
account: [
'Войдите в аккаунт, чтобы сохранять прогресс. На главной можно попробовать демовопрос без входа.',
'После входа начните с одной темы и одного вопроса. Маленький шаг тоже считается.',
],
};

/** Главное действие для страницы: куда Бит предлагает пойти. null — только «Понятно». */
const actionFor = (section: BitSection, auth: boolean): { label: string; to: string } | null => {
if (section === 'account') return { label: 'К демовопросу', to: '/' };
if (!auth) return section === 'home' ? { label: 'Начать подготовку', to: '/register' } : null;
if (section === 'home' || section === 'favorites') return { label: 'К вопросам', to: '/questions' };
if (section === 'questions') return { label: 'Собеседование по компании', to: '/companies' };
if (section === 'question') return { label: 'Все вопросы', to: '/questions' };
return null;
};

const STATUS: Record<BitMood, string> = {
idle: 'на связи',
listening: 'слушает',
thinking: 'думает',
sleeping: 'дремлет',
};

const ago = (at: number) => {
const s = Math.round((Date.now() - at) / 1000);
if (s < 60) return 'только что';
const m = Math.round(s / 60);
return m < 60 ? `${m} мин назад` : 'давно';
};

const SectionLabel = ({ children }: { children: string }) => {
const { c } = useTokens();
return (
<Typography component="h3" sx={{ fontSize: '.7rem', fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: c.textMuted }}>
{children}
</Typography>
);
};

interface BitDialogProps {
open: boolean;
onClose: () => void;
section: BitSection;
isAuthenticated: boolean;
}

/** Окно Бита: статус, совет для текущей страницы, недавние реплики, звук и одно понятное действие. */
export const BitDialog = ({ open, onClose, section, isAuthenticated }: BitDialogProps) => {
const titleId = useId();
const { c, shadow } = useTokens();
const { mood } = useBitPose();
const history = useBitHistory();
const sound = useBitSoundEnabled();
const [tip, setTip] = useState(0);
const tips = TIPS[section];
const action = actionFor(section, isAuthenticated);
const toneColor: Record<BitTone, string> = { calm: c.accent, cheer: c.success, fire: c.danger, focus: c.warning };

useEffect(() => {
if (!open) return;
playBitSound('open');
bitMove('hop');
}, [open]);

const nextTip = () => {
setTip((i) => (i + 1) % tips.length);
playBitSound('focus');
bitMove('nod');
};

const toggleSound = () => {
setBitSoundEnabled(!sound);
// включили — сразу слышно, как звучит
if (!sound) window.setTimeout(() => playBitSound('cheer'), 0);
};

return (
<Dialog
open={open}
onClose={onClose}
aria-labelledby={titleId}
fullWidth
maxWidth="xs"
sx={{ '& .MuiDialog-container': { alignItems: { xs: 'flex-end', sm: 'flex-start' }, justifyContent: { xs: 'center', sm: 'flex-end' } } }}
slotProps={{
paper: {
sx: {
m: { xs: 1.5, md: 3 }, mt: { sm: 9 }, width: { xs: 'calc(100% - 24px)', md: 400 },
border: `1px solid ${c.borderStrong}`, borderRadius: '20px', background: c.surface, boxShadow: shadow.lg,
overflow: 'hidden',
},
},
}}
>
{/* шапка: кто это и что он сейчас делает */}
<Stack direction="row" alignItems="center" spacing={1.5} sx={{ px: 2.25, pt: 2, pb: 1.5 }}>
<BitAvatar height={54} />
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography id={titleId} component="h2" sx={{ fontSize: '1.05rem', fontWeight: 750, lineHeight: 1.2 }}>
Бит
</Typography>
<Stack direction="row" alignItems="center" spacing={0.75} sx={{ mt: 0.25 }}>
<Box
component="span"
aria-hidden
sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: mood === 'sleeping' ? c.textMuted : c.success, flexShrink: 0 }}
/>
<Typography noWrap sx={{ fontSize: '.78rem', color: c.textMuted }}>Помощник · {STATUS[mood]}</Typography>
</Stack>
</Box>
<Tooltip title={sound ? 'Выключить звук' : 'Включить звук'}>
<IconButton
aria-label={sound ? 'Выключить звук Бита' : 'Включить звук Бита'}
aria-pressed={sound}
onClick={toggleSound}
size="small"
sx={{ color: sound ? c.accent : c.textMuted }}
>
{sound ? <VolumeUp fontSize="small" /> : <VolumeOff fontSize="small" />}
</IconButton>
</Tooltip>
<IconButton aria-label="Закрыть окно Бита" onClick={onClose} size="small">
<Close fontSize="small" />
</IconButton>
</Stack>

{/* совет для этой страницы */}
<Box sx={{ mx: 2.25, p: 1.75, borderRadius: '14px', bgcolor: c.accentSoft, border: `1px solid ${c.accentBorder}` }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 0.75 }}>
<SectionLabel>{tips.length > 1 ? `Совет · ${tip + 1} из ${tips.length}` : 'Совет'}</SectionLabel>
{tips.length > 1 && (
<Button size="small" onClick={nextTip} endIcon={<ArrowForward sx={{ fontSize: 14 }} />} sx={{ minWidth: 0, py: 0, px: 0.75, fontSize: '.75rem' }}>
Ещё совет
</Button>
)}
</Stack>
<Typography aria-live="polite" sx={{ fontSize: '.92rem', lineHeight: 1.5, color: c.text }}>
{tips[tip]}
</Typography>
</Box>

{/* что Бит недавно говорил: реплики в облачке исчезают, здесь их можно перечитать */}
{history.length > 0 && (
<Box sx={{ px: 2.25, pt: 1.75 }}>
<SectionLabel>Недавно говорил</SectionLabel>
<Stack component="ul" spacing={0.75} sx={{ listStyle: 'none', p: 0, m: 0, mt: 0.75 }}>
{history.map((line) => (
<Stack component="li" key={line.id} direction="row" spacing={1} alignItems="baseline">
<Box component="span" aria-hidden sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: toneColor[line.tone], flexShrink: 0, transform: 'translateY(-1px)' }} />
<Typography sx={{ fontSize: '.82rem', lineHeight: 1.4, color: c.text, flex: 1, minWidth: 0 }}>{line.text}</Typography>
<Typography sx={{ fontSize: '.7rem', color: c.textMuted, whiteSpace: 'nowrap' }}>{ago(line.at)}</Typography>
</Stack>
))}
</Stack>
</Box>
)}

<Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ px: 2.25, pt: 2, pb: 2 }}>
<Button variant={action ? 'text' : 'contained'} onClick={onClose}>
Понятно
</Button>
{action && (
<Button component={RouterLink} to={action.to} variant="contained" endIcon={<ArrowForward />} onClick={onClose}>
{action.label}
</Button>
)}
</Stack>
</Dialog>
);
};
Loading
Loading