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
55 changes: 55 additions & 0 deletions frontend/src/components/interview/QuestionSteps.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { ThemeProvider as MuiThemeProvider } from '@mui/material';
import { describe, expect, it, vi } from 'vitest';
import { ThemeProvider } from '../../context/ThemeContext';
import { darkTheme } from '../../theme/muiTheme';
import type { AIReview } from '../../types';
import { QuestionSteps } from './QuestionSteps';
import { DEFAULT_OPTIONS, newSession } from './session';

const renderSteps = (ui: React.ReactNode) =>
render(
<ThemeProvider>
<MuiThemeProvider theme={darkTheme}>{ui}</MuiThemeProvider>
</ThemeProvider>,
);

describe('QuestionSteps', () => {
it('numbers every question, says its outcome and opens it on click', () => {
const session = newSession(['a', 'b', 'c', 'd'], DEFAULT_OPTIONS, 0);
session.results = {
a: { answer: 'x', review: { score: 9 } as AIReview, self: 'knew' },
b: { answer: '', revealed: true, self: 'missed' },
c: { answer: 'черновик' },
};
const onOpen = vi.fn();
renderSteps(<QuestionSteps plan={['a', 'b', 'c', 'd']} session={session} currentIndex={2} onOpen={onOpen} />);

expect(screen.getByText('Вопрос 3 из 4')).toBeInTheDocument();
expect(screen.getByText('Отвечено: 3 из 4')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Вопрос 1: прошёл (ИИ 9/10)' })).toHaveTextContent('1');
expect(screen.getByRole('button', { name: 'Вопрос 2: не прошёл (подсмотрен эталон)' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Вопрос 3: есть ответ, не оценён' })).toHaveAttribute('aria-current', 'step');
fireEvent.click(screen.getByRole('button', { name: 'Вопрос 4: ещё без ответа' }));
expect(onOpen).toHaveBeenCalledWith(3);
// легенда объясняет цвета
for (const label of ['Прошёл', 'Частично', 'Не прошёл', 'Без оценки', 'Не начат']) expect(screen.getByText(label)).toBeInTheDocument();
});

it('counts a constructor build as an answer and names its score', () => {
const session = newSession(['a', 'b'], DEFAULT_OPTIONS, 0);
session.results = {
a: { answer: '', build: { order: [], score: 6 }, self: 'partial' },
b: { answer: '', build: { order: [{ id: 's1' }] as never } },
};
renderSteps(<QuestionSteps plan={['a', 'b']} session={session} currentIndex={0} onOpen={() => {}} />);
expect(screen.getByRole('button', { name: 'Вопрос 1: частично (сборка 6/10)' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Вопрос 2: есть ответ, не оценён' })).toBeInTheDocument();
});

it('falls back to a progress bar for a single question', () => {
renderSteps(<QuestionSteps plan={['a']} session={newSession(['a'], DEFAULT_OPTIONS, 0)} currentIndex={0} onOpen={() => {}} />);
expect(screen.getByRole('progressbar', { name: 'Вопрос 1 из 1' })).toBeInTheDocument();
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
});
145 changes: 145 additions & 0 deletions frontend/src/components/interview/QuestionSteps.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { Box, LinearProgress, Stack, Tooltip, Typography } from '@mui/material';
import { MASTERY_LABEL, useMasteryColor } from '../ui/masteryLevels';
import { radius, useTokens } from '../../theme/tokens';
import type { MasteryLevel } from '../../types';
import { isAnswered, SELF_TO_LEVEL, type InterviewSession, type QuestionResult } from './session';

/** Больше шагов в ряд не помещается осмысленно: дальше только полоса прогресса. */
const MAX_STEPS = 30;

type StepState = MasteryLevel | 'answered' | 'empty';

const stateOf = (r: QuestionResult | undefined): StepState =>
r?.self ? SELF_TO_LEVEL[r.self] : isAnswered(r) ? 'answered' : 'empty';

const stepLabel = (r: QuestionResult | undefined, state: StepState) => {
if (state === 'empty') return 'ещё без ответа';
if (state === 'answered') return 'есть ответ, не оценён';
const how = r?.review
? `ИИ ${r.review.score}/10`
: r?.build?.score !== undefined
? `сборка ${r.build.score}/10`
: r?.revealed
? 'подсмотрен эталон'
: 'своя оценка';
return `${MASTERY_LABEL[state].toLowerCase()} (${how})`;
};

interface QuestionStepsProps {
plan: string[];
session: InterviewSession | null;
currentIndex: number;
onOpen: (index: number) => void;
}

/**
* Шаги собеседования: номер каждого вопроса, цвет — итог по нему, клик — перейти.
* Под рядом — легенда, чтобы цвета не приходилось угадывать.
*/
export const QuestionSteps = ({ plan, session, currentIndex, onOpen }: QuestionStepsProps) => {
const { c } = useTokens();
const masteryColor = useMasteryColor();
const total = plan.length;
const states = plan.map((id) => stateOf(session?.results[id]));
const touched = states.filter((s) => s !== 'empty').length;
const showSteps = Boolean(session) && total > 1 && total <= MAX_STEPS;

const look = (state: StepState) =>
state === 'empty'
? { fg: c.textMuted, bg: 'transparent', border: c.borderStrong }
: state === 'answered'
? { fg: c.accent, bg: c.accentSoft, border: c.accent }
: { ...masteryColor(state), border: masteryColor(state).fg };

const legend: { state: StepState; label: string }[] = [
{ state: 'passed', label: MASTERY_LABEL.passed },
{ state: 'partial', label: MASTERY_LABEL.partial },
{ state: 'failed', label: MASTERY_LABEL.failed },
{ state: 'answered', label: 'Без оценки' },
{ state: 'empty', label: 'Не начат' },
];

return (
<Box sx={{ mb: 3 }}>
<Stack direction="row" justifyContent="space-between" alignItems="baseline" spacing={2} sx={{ mb: 1 }}>
<Typography variant="body2" sx={{ color: c.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
Вопрос {currentIndex + 1} из {total}
</Typography>
{session && (
<Typography variant="caption" sx={{ color: c.textMuted, fontVariantNumeric: 'tabular-nums' }}>
Отвечено: {touched} из {total}
</Typography>
)}
</Stack>

{!showSteps ? (
<LinearProgress
variant="determinate"
value={((currentIndex + 1) / total) * 100}
aria-label={`Вопрос ${currentIndex + 1} из ${total}`}
sx={{ height: 4, '& .MuiLinearProgress-bar': { backgroundColor: c.accent } }}
/>
) : (
<>
<Box component="ol" aria-label="Вопросы собеседования" sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, m: 0, p: 0, listStyle: 'none' }}>
{plan.map((id, i) => {
const state = states[i];
const current = i === currentIndex;
const { fg, bg, border } = look(state);
const text = `Вопрос ${i + 1}: ${stepLabel(session?.results[id], state)}`;
return (
<li key={id}>
<Tooltip title={text} arrow>
<Box
component="button"
type="button"
aria-label={text}
aria-current={current ? 'step' : undefined}
onClick={() => onOpen(i)}
sx={{
all: 'unset',
boxSizing: 'border-box',
cursor: 'pointer',
minWidth: 32,
height: 32,
px: 0.75,
display: 'grid',
placeItems: 'center',
borderRadius: `${radius.md}px`,
border: `1px ${state === 'empty' ? 'dashed' : 'solid'} ${border}`,
bgcolor: bg,
color: fg,
fontSize: '.8125rem',
fontWeight: current ? 750 : 550,
fontVariantNumeric: 'tabular-nums',
boxShadow: current ? `0 0 0 2px ${c.bg}, 0 0 0 4px ${c.text}` : 'none',
transition: 'transform .15s, box-shadow .15s',
'&:hover': { transform: 'translateY(-1px)' },
'&:focus-visible': { outline: `2px solid ${c.accent}`, outlineOffset: 3 },
}}
>
{i + 1}
</Box>
</Tooltip>
</li>
);
})}
</Box>
<Stack direction="row" sx={{ mt: 1.25, flexWrap: 'wrap', columnGap: 2, rowGap: 0.5 }} aria-hidden>
{legend.map(({ state, label }) => {
const { bg, border } = look(state);
return (
<Stack key={state} direction="row" spacing={0.75} alignItems="center">
<Box sx={{ width: 10, height: 10, borderRadius: '3px', bgcolor: bg === 'transparent' ? 'transparent' : border, border: `1px ${state === 'empty' ? 'dashed' : 'solid'} ${border}` }} />
<Typography variant="caption" sx={{ color: c.textMuted }}>
{label}
</Typography>
</Stack>
);
})}
</Stack>
</>
)}
</Box>
);
};
2 changes: 1 addition & 1 deletion frontend/src/pages/InterviewModePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ describe('InterviewModePage', () => {
expect(screen.getByText('2 вопроса из 2 подходящих')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Начать' }));
expect(await screen.findByText('Question body 2')).toBeInTheDocument();
expect(screen.getByText('1 / 2')).toBeInTheDocument();
expect(screen.getByText('Вопрос 1 из 2')).toBeInTheDocument();
// без ИИ кнопки проверки нет, самооценка доступна
expect(screen.queryByRole('button', { name: 'Сдать ответ' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Не прошёл' }));
Expand Down
56 changes: 3 additions & 53 deletions frontend/src/pages/InterviewModePage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Button, Chip, CircularProgress, Container, Divider, LinearProgress, Stack, Typography } from '@mui/material';
import { Box, Button, Chip, CircularProgress, Container, Divider, Stack, Typography } from '@mui/material';
import {
ArrowBack as ArrowBackIcon,
ArrowForward as ArrowForwardIcon,
Expand Down Expand Up @@ -29,14 +29,13 @@ import { findSequenceTask, withoutConstructor } from '../components/interview/co
import { InterviewResults } from '../components/interview/InterviewResults';
import { InterviewSetup } from '../components/interview/InterviewSetup';
import { GradeScale } from '../components/interview/GradeScale';
import { QuestionSteps } from '../components/interview/QuestionSteps';
import { ScoreBadge } from '../components/interview/ScoreBadge';
import { MASTERY_LABEL, useMasteryColor } from '../components/ui/masteryLevels';
import {
buildPlan,
DEFAULT_OPTIONS,
isAnswered,
scoreOf,
SELF_TO_LEVEL,
type InterviewOptions,
type InterviewSession,
loadSession,
Expand Down Expand Up @@ -204,8 +203,6 @@ export const InterviewFlow = ({
setupDefaults,
}: InterviewFlowProps) => {
const navigate = useNavigate();
const { c } = useTokens();
const masteryColor = useMasteryColor();

const { completed } = useProgress();
const toggleCompleted = useToggleCompleted();
Expand Down Expand Up @@ -365,7 +362,6 @@ export const InterviewFlow = ({
}

const isLast = currentIndex === plan.length - 1;
const progress = ((currentIndex + 1) / plan.length) * 100;
const currentResult = session?.results[currentQuestion.id];

const aiAvailable = Boolean(ai.data?.enabled) && ai.data!.used_today < ai.data!.daily_limit;
Expand All @@ -384,53 +380,7 @@ export const InterviewFlow = ({
{session && <ElapsedTimer startedAt={session.startedAt} />}
</Stack>

<Box sx={{ mb: 3 }}>
<Stack direction="row" justifyContent="space-between" alignItems="baseline" sx={{ mb: 1 }}>
<Typography variant="body2" sx={{ color: c.textMuted }}>
Вопрос
</Typography>
<Typography variant="body2" sx={{ color: c.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
{currentIndex + 1} / {plan.length}
</Typography>
</Stack>
<LinearProgress
variant="determinate"
value={progress}
aria-label={`Вопрос ${currentIndex + 1} из ${plan.length}`}
sx={{ height: 4, '& .MuiLinearProgress-bar': { backgroundColor: c.accent } }}
/>
{session && plan.length <= 30 && (
<Stack direction="row" spacing={0.5} sx={{ mt: 1, flexWrap: 'wrap', rowGap: 0.5 }} aria-label="Навигация по вопросам">
{plan.map((id, i) => {
const r = session.results[id];
const done = isAnswered(r);
// точка окрашена уровнем, который поставил ИИ (или сам кандидат, когда ИИ недоступен)
const fill = r?.self ? masteryColor(SELF_TO_LEVEL[r.self]).fg : done ? c.accent : 'transparent';
return (
<Box
key={id}
component="button"
type="button"
aria-label={`Вопрос ${i + 1}${r?.self ? `, ${MASTERY_LABEL[SELF_TO_LEVEL[r.self]].toLowerCase()}` : done ? ', есть ответ' : ''}`}
aria-current={i === currentIndex ? 'step' : undefined}
onClick={() => navigate(`${base}/${i}`)}
sx={{
all: 'unset',
cursor: 'pointer',
width: 10,
height: 10,
borderRadius: '50%',
border: `1px solid ${i === currentIndex ? c.text : fill === 'transparent' ? c.borderStrong : fill}`,
boxShadow: i === currentIndex ? `0 0 0 2px ${c.bg}, 0 0 0 3px ${c.accent}` : 'none',
backgroundColor: fill,
'&:focus-visible': { outline: `2px solid ${c.accent}`, outlineOffset: 2 },
}}
/>
);
})}
</Stack>
)}
</Box>
<QuestionSteps plan={plan} session={session} currentIndex={currentIndex} onOpen={(i) => navigate(`${base}/${i}`)} />

<Box sx={{ display: 'grid', gridTemplateColumns: { xs: 'minmax(0, 1fr)', md: 'minmax(0, 1fr) 280px' }, gap: 3, alignItems: 'start' }}>
<Box sx={{ minWidth: 0 }}>
Expand Down
Loading