diff --git a/app/content/importer.py b/app/content/importer.py index 15acf4c..f5b1b9f 100644 --- a/app/content/importer.py +++ b/app/content/importer.py @@ -22,7 +22,12 @@ from sqlalchemy import delete, func, select, text -from app.content.loader import Content, build_answer_blocks, question_positions +from app.content.loader import ( + Content, + build_answer_blocks, + build_question_blocks, + question_positions, +) from app.db.database import AsyncSessionFactory from app.db.models.question import ( Answer, @@ -199,7 +204,7 @@ async def _apply( fields = dict( slug=q.slug, title=q.title, - content=[b.to_api() for b in q.question], + content=build_question_blocks(q), difficulty=DifficultyQuestionLevel(q.difficulty), category_id=categories[q.category].id, is_published=q.published, diff --git a/app/content/loader.py b/app/content/loader.py index f9e5d2a..21b2d08 100644 --- a/app/content/loader.py +++ b/app/content/loader.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import re from dataclasses import dataclass, field from pathlib import Path @@ -149,6 +150,77 @@ def to_api(self) -> dict[str, Any]: return {"type": "warning", "data": {"text": self.warning.strip()}} +class BuildStep(Strict): + text: str = Field(min_length=1, max_length=200) + # Вложенность: тело цикла или ветки — на уровень глубже заголовка + indent: int = Field(0, ge=0, le=3) + + +class BuildTask(Strict): + """Задание-конструктор: решение собирается из блоков (задача Парсонса). + + Шаги пишутся в правильном порядке; в вопрос уходят перемешанные куски вместе + с отвлекающими, в эталонный ответ — решение с вложенностью. + """ + + kind: Literal["sequence"] = "sequence" + # replace — конструктор вместо текстового ответа + mode: Literal["replace"] = "replace" + prompt: str = Field(min_length=5, max_length=300) + steps: list[BuildStep] = Field(min_length=3, max_length=12) + distractors: list[str] = Field(default_factory=list, max_length=4) + + @model_validator(mode="after") + def check_steps(self) -> BuildTask: + if self.steps[0].indent != 0: + raise ValueError("первый шаг конструктора должен быть без отступа") + for prev, cur in zip(self.steps, self.steps[1:], strict=False): + if cur.indent > prev.indent + 1: + raise ValueError(f"шаг «{cur.text}»: отступ растёт больше чем на один уровень") + texts = [_norm(s.text) for s in self.steps] + [_norm(d) for d in self.distractors] + if len(set(texts)) != len(texts): + raise ValueError("тексты шагов и отвлекающих блоков должны различаться") + if any(not d.strip() for d in self.distractors): + raise ValueError("пустой отвлекающий блок") + return self + + def _piece_id(self, slug: str, text: str) -> str: + # id не выдаёт позицию шага: короткий хэш текста + return hashlib.sha1(f"{slug}:{_norm(text)}".encode()).hexdigest()[:8] + + def question_block(self, slug: str) -> dict[str, Any]: + """Куски для сборки: правильные и отвлекающие вперемешку, порядок стабилен между импортами.""" + texts = [s.text.strip() for s in self.steps] + [d.strip() for d in self.distractors] + pieces = [{"id": self._piece_id(slug, t), "text": t} for t in texts] + shuffled = sorted( + pieces, key=lambda p: hashlib.sha1(f"{slug}:{p['id']}".encode()).hexdigest() + ) + step_ids = [p["id"] for p in pieces[: len(self.steps)]] + if [p["id"] for p in shuffled if p["id"] in step_ids] == step_ids: + shuffled.reverse() # перемешивание не должно случайно совпасть с ответом + return { + "type": "constructor", + "data": { + "kind": self.kind, + "mode": self.mode, + "prompt": self.prompt.strip(), + "pieces": shuffled, + }, + } + + def answer_block(self, slug: str) -> dict[str, Any]: + """Эталон: шаги в правильном порядке с вложенностью.""" + solution = [ + {"id": self._piece_id(slug, s.text), "text": s.text.strip(), "indent": s.indent} + for s in self.steps + ] + return {"type": "constructor", "data": {"kind": self.kind, "solution": solution}} + + +def _norm(text: str) -> str: + return " ".join(text.split()).lower() + + class CompanyLink(Strict): company: str source: HttpUrl @@ -164,6 +236,8 @@ class QuestionEntry(Strict): companies: list[CompanyLink] = Field(default_factory=list) question: list[Block] = Field(min_length=1) answer: list[Block] = Field(min_length=2) + # Необязательное задание-конструктор (собирается в режиме собеседования) + build: BuildTask | None = None sources: list[HttpUrl] = Field(default_factory=list) @@ -320,8 +394,12 @@ def _cross_check(content: Content) -> None: for b in blocks: if b.image and content.root and not (content.root / IMAGES_DIR / b.image).is_file(): errors.append(f"{where}: {part}: нет файла {IMAGES_DIR}/{b.image}") + for part, api_blocks in ( + ("question", build_question_blocks(q)), + ("answer", build_answer_blocks(q, {c.company: c.company for c in q.companies})), + ): try: - validate_content_structure([b.to_api() for b in blocks]) + validate_content_structure(api_blocks) except ValueError as e: errors.append(f"{where}: {part}: {e}") @@ -367,9 +445,19 @@ def question_positions(content: Content) -> dict[str, int]: return positions +def build_question_blocks(q: QuestionEntry) -> list[dict[str, Any]]: + """Блоки вопроса для API: текст условия, затем куски конструктора, если он есть.""" + blocks = [b.to_api() for b in q.question] + if q.build: + blocks.append(q.build.question_block(q.slug)) + return blocks + + def build_answer_blocks(q: QuestionEntry, company_names: dict[str, str]) -> list[dict[str, Any]]: - """Блоки ответа для API: текст ответа, затем источники по компаниям и общие.""" + """Блоки ответа для API: суть, эталон конструктора, остальной текст, затем источники.""" blocks = [b.to_api() for b in q.answer] + if q.build: + blocks.insert(1, q.build.answer_block(q.slug)) lines = [f"- {company_names[c.company]}: {c.source}" for c in q.companies] lines += [f"- {url}" for url in q.sources] if lines: diff --git a/app/db/models/question.py b/app/db/models/question.py index be62129..011acba 100644 --- a/app/db/models/question.py +++ b/app/db/models/question.py @@ -44,6 +44,8 @@ class ContentType(str, Enum): WARNING = "warning" IMAGE = "image" DIAGRAM = "diagram" + # Задание-конструктор: кандидат собирает решение из блоков (см. app/content/loader.py BuildTask) + CONSTRUCTOR = "constructor" class ProgrammingLanguage(str, Enum): diff --git a/app/validators.py b/app/validators.py index 0c70898..6999add 100644 --- a/app/validators.py +++ b/app/validators.py @@ -46,4 +46,30 @@ def validate_content_structure(contents: list[dict[str, Any]]) -> list[dict[str, if not isinstance(data, dict) or not str(data.get("code", "")).strip(): raise ValueError("Diagram-блок должен содержать поле 'data.code' (схема Mermaid)") + if block["type"] == ContentType.CONSTRUCTOR.value: + _validate_constructor(block.get("data")) + return contents + + +CONSTRUCTOR_KINDS = ("sequence",) + + +def _validate_constructor(data: Any) -> None: + """Блок конструктора: в вопросе — перемешанные куски (pieces), в ответе — эталон (solution).""" + if not isinstance(data, dict) or data.get("kind") not in CONSTRUCTOR_KINDS: + raise ValueError(f"Constructor-блок: data.kind должен быть одним из {CONSTRUCTOR_KINDS}") + items = data.get("pieces") if "pieces" in data else data.get("solution") + if not isinstance(items, list) or not items: + raise ValueError("Constructor-блок должен содержать непустой data.pieces или data.solution") + ids = [] + for item in items: + if ( + not isinstance(item, dict) + or not str(item.get("id", "")).strip() + or not str(item.get("text", "")).strip() + ): + raise ValueError("Каждый кусок конструктора должен содержать id и text") + ids.append(item["id"]) + if len(set(ids)) != len(ids): + raise ValueError("id кусков конструктора должны быть уникальны") diff --git a/content/questions/algorithms/algo-number-of-islands.yaml b/content/questions/algorithms/algo-number-of-islands.yaml index c8e5b5f..1ff86a0 100644 --- a/content/questions/algorithms/algo-number-of-islands.yaml +++ b/content/questions/algorithms/algo-number-of-islands.yaml @@ -91,6 +91,30 @@ answer: | Union-Find | O(R·C·α) | O(R·C) | суша добавляется | - warning: 'Частые ошибки: помечать клетку при извлечении из стека, а не при добавлении (тогда она попадает в стек несколько раз, а на больших сетках это заметно по памяти); рекурсивный DFS на большой сетке (RecursionError в Python); проверять границы после обращения к g[nx][ny] (в Python индекс −1 молча берёт последний элемент); считать диагональных соседей, если условие этого не просит; сравнивать с числом 1, когда в сетке символы.' - info: 'Уточняющие вопросы интервьюера: можно ли менять входную матрицу; как посчитать площадь наибольшего острова (обход возвращает размер); как быть, если суша добавляется по одной клетке и после каждой нужен ответ (Union-Find, вариант «острова II»); как подсчитать различные по форме острова (нормализовать координаты относительно стартовой клетки и сложить формы во множество).' +build: + kind: sequence + prompt: 'Соберите итеративный обход сетки из блоков: расставьте шаги по порядку и задайте вложенность. Лишние блоки оставьте в стороне.' + steps: + - text: 'Скопировать сетку и завести счётчик островов = 0' + - text: 'Для каждой клетки (r, c) сетки' + - text: 'Если клетка — вода, перейти к следующей' + indent: 1 + - text: 'Увеличить счётчик островов' + indent: 1 + - text: 'Пометить клетку водой и положить её в стек' + indent: 1 + - text: 'Пока стек не пуст' + indent: 1 + - text: 'Снять клетку с вершины стека' + indent: 2 + - text: 'Для каждого соседа сверху, снизу, слева и справа' + indent: 2 + - text: 'Если сосед внутри сетки и это суша — пометить водой и положить в стек' + indent: 3 + - text: 'Вернуть счётчик островов' + distractors: + - 'Пометить соседа водой только когда его снимут со стека' + - 'Добавить в обход диагональных соседей' sources: - https://leetcode.com/problems/number-of-islands/ - https://docs.python.org/3/library/sys.html#sys.setrecursionlimit diff --git a/content/questions/algorithms/algo-valid-parentheses.yaml b/content/questions/algorithms/algo-valid-parentheses.yaml index 5688388..070ac9e 100644 --- a/content/questions/algorithms/algo-valid-parentheses.yaml +++ b/content/questions/algorithms/algo-valid-parentheses.yaml @@ -71,5 +71,23 @@ answer: - p: "Время O(n): каждый символ кладётся и снимается не более одного раза. Память O(n) в худшем случае, когда все скобки открывающие. Для одного типа скобок стек заменяется счётчиком глубины, и память становится O(1)." - warning: "Забыть проверить пустоту стека перед pop: на строке «)» получите IndexError. Забыть проверку пустоты в конце: «(((» не должна проходить. Заменить стек тремя счётчиками: «([)]» ошибочно пройдёт." - info: "Уточняющие вопросы интервьюера: найти длину самой длинной правильной подстроки (стек индексов); минимальное число удалений, чтобы строка стала правильной; сгенерировать все правильные последовательности из n пар (их число — n-е число Каталана). Тот же стек лежит в основе разбора выражений, проверки вложенности HTML-тегов и вычисления обратной польской записи." +build: + kind: sequence + prompt: 'Соберите алгоритм проверки скобок из блоков: расставьте шаги по порядку и задайте вложенность. Лишние блоки оставьте в стороне.' + steps: + - text: 'Завести словарь пар: закрывающая скобка → открывающая' + - text: 'Завести пустой стек' + - text: 'Для каждого символа ch строки' + - text: 'Если ch — закрывающая скобка' + indent: 1 + - text: 'Если стек пуст или снятая вершина не пара для ch — вернуть False' + indent: 2 + - text: 'Иначе положить ch в стек' + indent: 1 + - text: 'Вернуть True, только если стек пуст' + distractors: + - 'Отсортировать символы строки' + - 'Вернуть True, если открывающих столько же, сколько закрывающих' + - 'Положить закрывающую скобку в стек' sources: - https://leetcode.com/problems/valid-parentheses/ diff --git a/docs/content.md b/docs/content.md index 90e6f41..28e7792 100644 --- a/docs/content.md +++ b/docs/content.md @@ -112,6 +112,30 @@ GFM-таблица — до 5 колонок с короткими ячейка длиннее прокручиваются по горизонтали даже на десктопе. Пишем своими словами: условия задач LeetCode и тексты статей не копируем, а пересказываем и даём ссылку. +### Конструктор (`build`) + +Необязательное задание, которое в режиме собеседования заменяет текстовый ответ: кандидат собирает +алгоритм из блоков (задача Парсонса), расставляет порядок и вложенность. Шаги пишутся **в правильном +порядке**, импортёр сам перемешивает их для вопроса и кладёт эталон в ответ сразу после сути. + +```yaml +build: + kind: sequence # пока только алгоритм из шагов + prompt: 'Соберите алгоритм из блоков: порядок и вложенность. Лишние блоки оставьте.' + steps: # 3–12 шагов + - text: 'Завести пустой стек' + - text: 'Для каждого символа ch строки' + - text: 'Если ch — закрывающая скобка' + indent: 1 # 0–3; тело цикла или ветки на уровень глубже, рост не больше чем на 1 + distractors: # до 4 правдоподобных, но лишних шагов + - 'Отсортировать символы строки' +``` + +Тексты шагов и отвлекающих блоков не повторяются, каждый шаг — одно действие до 200 символов. Балл +считает браузер: 10 × (наибольшая общая подпоследовательность с эталоном) / число шагов, минус 1 за +неверную вложенность и минус 2 за каждый взятый отвлекающий блок. Вопрос с `build` должен быть +привязан к компании, иначе в режиме собеседования его не увидят. + ### Сложность - `easy`: базовое знание, которое ждут от любого junior. diff --git a/frontend/package.json b/frontend/package.json index eaec72f..132af82 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -21,6 +21,9 @@ "check:diagrams": "node scripts/check-diagrams.mjs" }, "dependencies": { + "@dnd-kit/core": "6.3.1", + "@dnd-kit/sortable": "10.0.0", + "@dnd-kit/utilities": "3.2.2", "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@fontsource-variable/inter": "^5.3.0", diff --git a/frontend/src/components/ContentRenderer.tsx b/frontend/src/components/ContentRenderer.tsx index 5e89e61..247d307 100644 --- a/frontend/src/components/ContentRenderer.tsx +++ b/frontend/src/components/ContentRenderer.tsx @@ -95,6 +95,59 @@ const extractData = (block: ContentBlock): BlockData => { return raw; }; +/** + * Задание-конструктор вне режима собеседования: в вопросе — блоки для сборки, + * в эталонном ответе — правильный порядок с вложенностью. + */ +const ConstructorBlockView = ({ block }: { block: ContentBlock }) => { + const { c } = useTokens(); + const solution = block.data?.solution; + const pieces = block.data?.pieces; + const rowSx = { fontFamily: fonts.mono, fontSize: '0.8125rem', lineHeight: 1.5, color: c.text, overflowWrap: 'anywhere' } as const; + + if (solution?.length) { + return ( + + + Эталонная сборка + + + {solution.map((step, i) => ( + + + {i + 1} + + + {step.text} + + + ))} + + + ); + } + if (!pieces?.length) return null; + return ( + + {block.data?.prompt && ( + + {block.data.prompt} + + )} + + {pieces.map((p) => ( + + {p.text} + + ))} + + + Собрать решение из этих блоков можно в режиме собеседования: порядок и вложенность проверятся автоматически. + + + ); +}; + export const ContentRenderer: React.FC = ({ blocks, anchorPrefix, leadLabel }) => { const { c } = useTokens(); @@ -248,6 +301,9 @@ export const ContentRenderer: React.FC = ({ blocks, anchor ); } + case 'constructor': + return ; + case 'list': { const items: string[] = data.items || []; const ListComponent = data.style === 'ordered' ? 'ol' : 'ul'; diff --git a/frontend/src/components/interview/AnswerPanel.tsx b/frontend/src/components/interview/AnswerPanel.tsx index 4263b8c..1fc4491 100644 --- a/frontend/src/components/interview/AnswerPanel.tsx +++ b/frontend/src/components/interview/AnswerPanel.tsx @@ -119,6 +119,40 @@ export const ReviewCard = ({ review, stale }: { review: AIReview; stale: boolean ); }; +/** Эталонный ответ под полем ответа: открывается после оценки или ценой «Не прошёл». */ +export const ReferenceAnswer = ({ blocks, loading, failed }: { blocks: ContentBlock[] | undefined; loading: boolean; failed: boolean }) => { + const { c } = useTokens(); + return ( + + + Эталонный ответ + + + {loading ? ( + + ) : failed ? ( + + Не удалось загрузить ответ. Закройте и откройте его ещё раз. + + ) : blocks && blocks.length > 0 ? ( + + ) : ( + + Ответ пока не добавлен. + + )} + + + ); +}; + +/** Предупреждение: эталон открыт до сдачи, вопрос засчитан как «Не прошёл». */ +export const RevealedAlert = () => ( + } sx={{ mt: 2 }}> + Эталон открыт до ответа — вопрос засчитан как «Не прошёл». Прочитайте и вернитесь к нему после итогов. + +); + interface AnswerPanelProps { questionId: string; result: QuestionResult | undefined; @@ -311,11 +345,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe )} - {revealed && !result?.review && ( - } sx={{ mt: 2 }}> - Эталон открыт до ответа — вопрос засчитан как «Не прошёл». Прочитайте и вернитесь к нему после итогов. - - )} + {revealed && !result?.review && } {review.isError && ( {aiReviewErrorMessage(review.error)} @@ -323,28 +353,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe )} {result?.review && } - {showReference && ( - - - Эталонный ответ - - - {answersLoading ? ( - - ) : answersFailed ? ( - - Не удалось загрузить ответ. Закройте и откройте его ещё раз. - - ) : answerBlocks && answerBlocks.length > 0 ? ( - - ) : ( - - Ответ пока не добавлен. - - )} - - - )} + {showReference && } {manualReason && ( diff --git a/frontend/src/components/interview/GradeScale.tsx b/frontend/src/components/interview/GradeScale.tsx index dcb2993..8887d84 100644 --- a/frontend/src/components/interview/GradeScale.tsx +++ b/frontend/src/components/interview/GradeScale.tsx @@ -17,17 +17,28 @@ const HOW_TO = ['Суть в одной фразе', 'Как это устрое const sourceOf = (result: QuestionResult | undefined) => result?.review ? `Оценка ИИ: ${result.review.score}/10` - : result?.revealed + : result?.build?.score !== undefined + ? `Сборка: ${result.build.score}/10` + : result?.revealed ? 'Подсмотрен эталон' : result?.self ? 'Своя оценка' : null; +/** Для конструктора шкала та же, но за баллом стоит сравнение с эталонной сборкой. */ +const BUILD_SCALE: Record = { + passed: 'Порядок верный, максимум одна ошибка', + partial: 'Каркас есть, но порядок или вложенность хромают', + failed: 'Много ошибок, лишние блоки или подсмотренный эталон', +}; + +const BUILD_HOW_TO = ['Что нужно до цикла', 'Заголовок цикла или условия', 'Тело — с отступом вправо', 'Лишние блоки не брать']; + /** * Шкала собеседования сбоку от вопроса: какие уровни можно получить и за что. * Полученный уровень подсвечивается, но выставляет его ИИ, а не кандидат. */ -export const GradeScale = ({ result, aiAvailable }: { result: QuestionResult | undefined; aiAvailable: boolean }) => { +export const GradeScale = ({ result, aiAvailable, build = false }: { result: QuestionResult | undefined; aiAvailable: boolean; build?: boolean }) => { const { c } = useTokens(); const color = useMasteryColor(); const current = result?.self ? SELF_TO_LEVEL[result.self] : null; @@ -59,23 +70,28 @@ export const GradeScale = ({ result, aiAvailable }: { result: QuestionResult | u {MASTERY_LABEL[level]} {SCALE[level].range} - {SCALE[level].hint} + {build ? BUILD_SCALE[level] : SCALE[level].hint} ); })} - {source ?? (aiAvailable ? 'Оценку поставит ИИ, когда сдадите ответ.' : 'ИИ недоступен — оцените ответ сами под полем ответа.')} + {source ?? + (build + ? 'Балл посчитается по эталону сразу после сдачи сборки.' + : aiAvailable + ? 'Оценку поставит ИИ, когда сдадите ответ.' + : 'ИИ недоступен — оцените ответ сами под полем ответа.')} - Как отвечать + {build ? 'Как собирать' : 'Как отвечать'} - {HOW_TO.map((step) => ( + {(build ? BUILD_HOW_TO : HOW_TO).map((step) => ( {label.text} - {result?.revealed && !result.review + {result?.revealed && scoreOf(result) === undefined ? ' · подсмотрен эталон' - : result?.self && !result.review - ? ` · своя оценка: ${SELF_LABEL[result.self]}` - : ''} + : result?.build?.score !== undefined && !result.review + ? ' · конструктор' + : result?.self && scoreOf(result) === undefined + ? ` · своя оценка: ${SELF_LABEL[result.self]}` + : ''} - {result?.review && } + {scoreOf(result) !== undefined && } ); })} diff --git a/frontend/src/components/interview/InterviewSetup.tsx b/frontend/src/components/interview/InterviewSetup.tsx index 690a010..357f27e 100644 --- a/frontend/src/components/interview/InterviewSetup.tsx +++ b/frontend/src/components/interview/InterviewSetup.tsx @@ -19,7 +19,7 @@ import { useAuth } from '../../context/auth-context'; import { plural } from '../../utils/difficulty'; import { radius, useTokens } from '../../theme/tokens'; import type { AIReviewStatus, Question } from '../../types'; -import { DEFAULT_OPTIONS, eligibleQuestions, type InterviewOptions, type InterviewSession } from './session'; +import { DEFAULT_OPTIONS, eligibleQuestions, type InterviewOptions, type InterviewSession, isAnswered } from './session'; const COUNTS = [5, 10, 20, 0]; @@ -42,7 +42,7 @@ export const InterviewSetup = ({ questions, completed, ai, current, onStart, onR const planned = options.count > 0 ? Math.min(options.count, available) : available; const set = (patch: Partial) => setOptions((o) => ({ ...o, ...patch })); const resumable = current && !current.finishedAt && current.ids.length > 0; - const touched = resumable ? current.ids.filter((id) => current.results[id]?.answer?.trim() || current.results[id]?.self).length : 0; + const touched = resumable ? current.ids.filter((id) => isAnswered(current.results[id])).length : 0; const remaining = ai ? Math.max(0, ai.daily_limit - ai.used_today) : 0; return ( diff --git a/frontend/src/components/interview/bitInterview.ts b/frontend/src/components/interview/bitInterview.ts index 1ef7e18..8c50440 100644 --- a/frontend/src/components/interview/bitInterview.ts +++ b/frontend/src/components/interview/bitInterview.ts @@ -3,7 +3,7 @@ import type { BitTone } from '../ui/bitVoice'; import { plural } from '../../utils/difficulty'; import type { Question } from '../../types'; import type { InterviewSession, SelfMark } from './session'; -import { STRONG_SCORE } from './session'; +import { isAnswered, scoreOf, STRONG_SCORE } from './session'; /** Реплики Бита-интервьюера. */ @@ -55,6 +55,35 @@ export const reviewLine = (score: number): Line => ? { tone: 'focus', text: `${score}/10. База есть, но интервьюер копнул бы глубже — смотри «Чего не хватает».` } : { tone: 'fire', text: `${score}/10. Не расстраивайся: открой эталон и попробуй ещё раз своими словами.` }; +/** Вопрос-конструктор: объявляем формат вместо обычной подсказки по сложности. */ +export const buildQuestionLine = (index: number, total: number, revisit: boolean): Line => { + const head = `Вопрос ${index + 1} из ${total}.`; + if (revisit) return { tone: 'calm', text: `${head} Возвращаемся к сборке.` }; + return { + tone: 'focus', + text: `${head} ${pickLine('build:start', [ + 'Тут конструктор: собери алгоритм из блоков. Следи за порядком и вложенностью, лишние блоки не бери.', + 'Задание-конструктор. Сначала что завести до цикла, потом тело цикла — с отступом.', + ])}`, + }; +}; + +export const BUILD_SILENCE_LINES = [ + 'С чего начинается алгоритм? Найди блок, который нужен до цикла.', + 'Тело цикла сдвигается вправо: кнопка с отступом или Alt+→.', + 'Не всё в блоках нужно: пара шагов там для отвода глаз.', +]; + +/** Сборка проверена по эталону. */ +export const buildLine = (score: number): Line => + score >= 9 + ? { tone: 'cheer', text: `${score}/10! Алгоритм собран как по учебнику.` } + : score >= STRONG_SCORE + ? { tone: 'cheer', text: `${score}/10 — почти идеально. Посмотри, какая строка подвела.` } + : score >= 5 + ? { tone: 'focus', text: `${score}/10. Каркас верный, но порядок или вложенность хромают — смотри пометки.` } + : { tone: 'fire', text: `${score}/10. Открой эталон и пройди алгоритм по шагам, потом соберём ещё раз.` }; + export const REVIEW_FAILED: Line = { tone: 'calm', text: 'ИИ не ответил. Оцени себя сам — это тоже считается.' }; /** Эталон открыт до ответа: вопрос не засчитан. */ @@ -69,8 +98,8 @@ export const DICTATION_LINE: Line = { tone: 'focus', text: 'Слушаю! Гов export const resultsLine = (session: InterviewSession): Line => { const results = session.ids.map((id) => session.results[id]); - const answered = results.filter((r) => r?.answer?.trim() || r?.self).length; - const strong = results.filter((r) => r?.self === 'knew' || (r?.review && r.review.score >= STRONG_SCORE)).length; + const answered = results.filter(isAnswered).length; + const strong = results.filter((r) => r?.self === 'knew' || (scoreOf(r) ?? 0) >= STRONG_SCORE).length; const total = session.ids.length; if (!answered) return { tone: 'calm', text: 'Ни одного ответа — ничего, такое собеседование тоже чему-то учит. Попробуем ещё раз?' }; if (strong === total) return { tone: 'cheer', text: `Все ${total} — уверенно. Оффер почти в кармане!` }; diff --git a/frontend/src/components/interview/constructor/BuildPanel.test.tsx b/frontend/src/components/interview/constructor/BuildPanel.test.tsx new file mode 100644 index 0000000..8b2e657 --- /dev/null +++ b/frontend/src/components/interview/constructor/BuildPanel.test.tsx @@ -0,0 +1,149 @@ +import { useState } from 'react'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { ThemeProvider as MuiThemeProvider } from '@mui/material'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ThemeProvider } from '../../../context/ThemeContext'; +import { darkTheme } from '../../../theme/muiTheme'; +import type { ContentBlock } from '../../../types'; +import { GradeScale } from '../GradeScale'; +import type { QuestionResult } from '../session'; +import { BuildPanel } from './BuildPanel'; +import type { SequenceTask } from './sequence'; + +const setMastery = vi.fn(); +vi.mock('../../../queries/progress', () => ({ useSetMastery: () => ({ mutate: setMastery }) })); + +const STEPS = ['Завести стек', 'Для каждого символа', 'Положить в стек']; +const task: SequenceTask = { + prompt: 'Соберите алгоритм', + // куски вперемешку, плюс отвлекающий + pieces: [ + { id: 'c', text: STEPS[2] }, + { id: 'x', text: 'Отсортировать строку' }, + { id: 'a', text: STEPS[0] }, + { id: 'b', text: STEPS[1] }, + ], +}; +const answer: ContentBlock[] = [ + { type: 'paragraph', data: { text: 'Суть' } }, + { + type: 'constructor', + data: { + kind: 'sequence', + solution: [ + { id: 'a', text: STEPS[0], indent: 0 }, + { id: 'b', text: STEPS[1], indent: 0 }, + { id: 'c', text: STEPS[2], indent: 1 }, + ], + }, + }, +]; + +let latest: QuestionResult | undefined; +const Harness = ({ initial }: { initial?: QuestionResult }) => { + const [result, setResult] = useState(initial); + return ( + <> + + setResult((r) => { + latest = { answer: '', ...r, ...patch }; + return latest; + }) + } + answerBlocks={answer} + answersLoading={false} + answersFailed={false} + /> + + + ); +}; + +const renderPanel = (initial?: QuestionResult) => + render( + + + + + , + ); + +const add = (text: string) => fireEvent.click(screen.getByRole('button', { name: `Добавить в решение: ${text}` })); +const solutionRows = () => within(screen.getByRole('list', { name: 'Ваше решение' })).queryAllByRole('listitem'); + +describe('BuildPanel', () => { + beforeEach(() => { + setMastery.mockReset(); + latest = undefined; + }); + + it('builds the algorithm by tapping blocks and adjusting rows with the keyboard, then grades it without AI', () => { + renderPanel(); + expect(screen.getByText('Балл посчитается по эталону сразу после сдачи сборки.')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Сдать сборку' })).toBeDisabled(); + + add(STEPS[1]); + add(STEPS[0]); + add(STEPS[2]); + expect(solutionRows()).toHaveLength(3); + expect(screen.getByText(`Шаг «${STEPS[2]}» добавлен на позицию 3`)).toBeInTheDocument(); + + // «Завести стек» поднимаем наверх, «Положить в стек» сдвигаем в тело цикла + fireEvent.keyDown(screen.getByLabelText(`2. ${STEPS[0]}`), { key: 'ArrowUp', altKey: true }); + fireEvent.keyDown(screen.getByLabelText(`3. ${STEPS[2]}`), { key: 'ArrowRight', altKey: true }); + expect(latest?.build?.order).toEqual([ + { id: 'a', indent: 0 }, + { id: 'b', indent: 0 }, + { id: 'c', indent: 1 }, + ]); + + fireEvent.click(screen.getByRole('button', { name: 'Сдать сборку' })); + expect(latest?.build?.score).toBe(10); + expect(latest?.self).toBe('knew'); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'passed' }); + expect(screen.getByText('Сборка: 10/10')).toBeInTheDocument(); + // оценка зафиксирована: повторно сдать и переставить нельзя, эталон открыт без штрафа + expect(screen.queryByRole('button', { name: 'Сдать сборку' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Перетащить шаг/ })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Показать эталон' })); + expect(screen.getByText('Эталонная сборка')).toBeInTheDocument(); + }); + + it('marks wrong rows after submit and lowers the level for a distractor', () => { + renderPanel(); + add(STEPS[0]); + add('Отсортировать строку'); + add(STEPS[1]); + add(STEPS[2]); + fireEvent.click(screen.getByRole('button', { name: 'Сдать сборку' })); + // 10 − 1 (вложенность) − 2 (лишний блок) + expect(latest?.build?.score).toBe(7); + expect(latest?.self).toBe('partial'); + expect(screen.getByLabelText(/Отсортировать строку, лишний шаг/)).toBeInTheDocument(); + expect(screen.getByLabelText(new RegExp(`${STEPS[2]}, не та вложенность`))).toBeInTheDocument(); + }); + + it('removes a row back to the blocks with Delete', () => { + renderPanel(); + add(STEPS[0]); + fireEvent.keyDown(screen.getByLabelText(`1. ${STEPS[0]}`), { key: 'Delete' }); + expect(solutionRows()).toHaveLength(0); + expect(screen.getByRole('button', { name: `Добавить в решение: ${STEPS[0]}` })).toBeInTheDocument(); + }); + + it('peeking at the reference before submitting fails the question and locks the build', async () => { + renderPanel({ answer: '', build: { order: [{ id: 'a', indent: 0 }] } }); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть эталон' })); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть' })); + expect(latest?.revealed).toBe(true); + expect(latest?.self).toBe('missed'); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'failed' }); + // пока диалог закрывается, остальная страница скрыта от скринридера + await waitFor(() => expect(screen.getByRole('button', { name: 'Сдать сборку' })).toBeDisabled()); + expect(screen.getByText('Подсмотрен эталон')).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/interview/constructor/BuildPanel.tsx b/frontend/src/components/interview/constructor/BuildPanel.tsx new file mode 100644 index 0000000..6495664 --- /dev/null +++ b/frontend/src/components/interview/constructor/BuildPanel.tsx @@ -0,0 +1,160 @@ +import { useState } from 'react'; +import { Alert, Box, Button, Stack, Typography } from '@mui/material'; +import { + FactCheckOutlined as SubmitIcon, + FlagOutlined as FlagIcon, + VisibilityOffOutlined as VisibilityOffIcon, + VisibilityOutlined as VisibilityIcon, +} from '@mui/icons-material'; +import { useSetMastery } from '../../../queries/progress'; +import { ConfirmDialog } from '../../ui/ConfirmDialog'; +import { bitSay } from '../../ui/bitVoice'; +import { levelFromScore } from '../../ui/masteryLevels'; +import { radius, useTokens } from '../../../theme/tokens'; +import type { ContentBlock } from '../../../types'; +import { ReferenceAnswer, RevealedAlert } from '../AnswerPanel'; +import { buildLine, revealLine } from '../bitInterview'; +import { ScoreBadge } from '../ScoreBadge'; +import { scoreLabel } from '../score'; +import { LEVEL_TO_SELF, type QuestionResult } from '../session'; +import { SequenceBuilder } from './SequenceBuilder'; +import { findSequenceSolution, scoreSequence, type PlacedStep, type SequenceTask } from './sequence'; + +interface BuildPanelProps { + questionId: string; + task: SequenceTask; + result: QuestionResult | undefined; + onChange: (patch: Partial) => void; + answerBlocks: ContentBlock[] | undefined; + answersLoading: boolean; + answersFailed: boolean; +} + +/** + * Ответ-конструктор: кандидат собирает алгоритм из блоков, балл считается по эталону без ИИ. + * Первая сдача фиксирует оценку; эталон до сдачи, как и в текстовом ответе, — «Не прошёл». + */ +export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, answersLoading, answersFailed }: BuildPanelProps) => { + const { c } = useTokens(); + const setMastery = useSetMastery(); + const [showReference, setShowReference] = useState(false); + const [confirmReveal, setConfirmReveal] = useState(false); + + const build = result?.build; + const order = build?.order ?? []; + const submitted = build?.score !== undefined; + const revealed = Boolean(result?.revealed); + const solution = findSequenceSolution(answerBlocks); + const referenceFree = submitted || revealed; + const canSubmit = !submitted && !revealed && order.length > 0 && Boolean(solution); + + const setOrder = (next: PlacedStep[]) => onChange({ build: { order: next } }); + + const submit = () => { + if (!solution) return; + const { score, marks, missing } = scoreSequence(solution, order); + const level = levelFromScore(score); + onChange({ build: { order, score, marks, missing }, self: LEVEL_TO_SELF[level] }); + setMastery.mutate({ id: questionId, level }); + const line = buildLine(score); + bitSay(line.text, line.tone); + }; + + const reveal = () => { + setConfirmReveal(false); + setShowReference(true); + onChange({ revealed: true, self: 'missed' }); + setMastery.mutate({ id: questionId, level: 'failed' }); + const line = revealLine(); + bitSay(line.text, line.tone, { move: 'shake' }); + }; + + const placedCount = build?.marks?.filter((m) => m === 'ok').length ?? 0; + const extraCount = build?.marks?.filter((m) => m === 'extra').length ?? 0; + + return ( + + + {task.prompt} + + + + + + {!submitted && ( + + )} + + {!submitted && !revealed && ( + + Оценка — по первой сдаче, проверка без ИИ + + )} + + + {!solution && !answersLoading && ( + + {answersFailed ? 'Не удалось загрузить эталон для проверки. Обновите страницу.' : 'У задания нет эталона — сдать сборку нельзя.'} + + )} + {revealed && !submitted && } + + {submitted && build?.score !== undefined && ( + + + + + {scoreLabel(build.score)} + + На месте {placedCount} из {solution?.length ?? order.length} + {extraCount ? ` · лишних блоков: ${extraCount}` : ''} + {build.missing?.length ? ` · пропущено: ${build.missing.length}` : ''} + + + + + )} + + {showReference && } + + setConfirmReveal(false)} + /> + + ); +}; diff --git a/frontend/src/components/interview/constructor/SequenceBuilder.tsx b/frontend/src/components/interview/constructor/SequenceBuilder.tsx new file mode 100644 index 0000000..4887eee --- /dev/null +++ b/frontend/src/components/interview/constructor/SequenceBuilder.tsx @@ -0,0 +1,438 @@ +import { type KeyboardEvent, type ReactNode, useEffect, useMemo, useRef, useState } from 'react'; +import { Box, IconButton, Stack, Tooltip, Typography } from '@mui/material'; +import { + AddRounded as AddIcon, + ArrowDownwardRounded as DownIcon, + ArrowUpwardRounded as UpIcon, + CheckCircleOutlineRounded as OkIcon, + CloseRounded as RemoveIcon, + DragIndicatorRounded as DragIcon, + FormatIndentDecreaseRounded as OutdentIcon, + FormatIndentIncreaseRounded as IndentIcon, + HighlightOffRounded as ExtraIcon, + SwapVertRounded as OrderIcon, + WarningAmberRounded as IndentWarnIcon, +} from '@mui/icons-material'; +import { + type Announcements, + DndContext, + type DragEndEvent, + DragOverlay, + type DragStartEvent, + KeyboardSensor, + MouseSensor, + TouchSensor, + closestCenter, + useDraggable, + useDroppable, + useSensor, + useSensors, +} from '@dnd-kit/core'; +import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; +import { fonts, radius, useTokens } from '../../../theme/tokens'; +import type { ConstructorPiece } from '../../../types'; +import { MAX_INDENT, type PlacedStep, type StepMark, insertStep, moveStep, shiftIndent } from './sequence'; + +/** Сдвиг на один уровень вложенности: в пикселях при отрисовке и при перетаскивании вбок. */ +const INDENT_PX = 24; +const SOLUTION_ZONE = 'zone:solution'; +const POOL_ZONE = 'zone:pool'; +const sid = (id: string) => `s:${id}`; +const pid = (id: string) => `p:${id}`; +const pieceOf = (dndId: string | number) => String(dndId).slice(2); + +const MARK_LABEL: Record = { + ok: 'на месте', + indent: 'не та вложенность', + order: 'не на своём месте', + extra: 'лишний шаг', +}; + +interface SequenceBuilderProps { + pieces: ConstructorPiece[]; + order: PlacedStep[]; + onChange: (order: PlacedStep[]) => void; + /** Пометки после сдачи: сборка становится только для чтения. */ + marks?: StepMark[]; + missing?: string[]; + disabled?: boolean; +} + +/** + * Сборка алгоритма из блоков: перетаскивание мышью и пальцем, тап по блоку, кнопки и клавиатура. + * Строка решения: Alt+↑/↓ — переставить, Alt+←/→ — вложенность, Delete — убрать обратно в блоки. + */ +export const SequenceBuilder = ({ pieces, order, onChange, marks, missing, disabled }: SequenceBuilderProps) => { + const { c } = useTokens(); + const locked = Boolean(marks) || Boolean(disabled); + const byId = useMemo(() => new Map(pieces.map((p) => [p.id, p])), [pieces]); + const placed = new Set(order.map((s) => s.id)); + const pool = pieces.filter((p) => !placed.has(p.id)); + const [status, setStatus] = useState(''); + const [dragging, setDragging] = useState(null); + const [focusId, setFocusId] = useState(null); + + const textOf = (id: string) => byId.get(id)?.text ?? ''; + const quote = (id: string) => `«${textOf(id)}»`; + + const sensors = useSensors( + useSensor(MouseSensor, { activationConstraint: { distance: 6 } }), + useSensor(TouchSensor, { activationConstraint: { delay: 150, tolerance: 6 } }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + + const commit = (next: PlacedStep[], message: string, focus?: string) => { + onChange(next); + setStatus(message); + if (focus) setFocusId(focus); + }; + + const add = (id: string, at?: number) => { + const next = insertStep(order, id, at); + const pos = next.findIndex((s) => s.id === id); + commit(next, `Шаг ${quote(id)} добавлен на позицию ${pos + 1}`); + }; + const remove = (index: number) => { + const id = order[index].id; + const next = order.filter((_, i) => i !== index); + commit(next, `Шаг ${quote(id)} убран в блоки`, next[Math.min(index, next.length - 1)]?.id); + }; + const move = (index: number, to: number) => { + if (to < 0 || to >= order.length) return; + const id = order[index].id; + commit(moveStep(order, index, to), `Шаг ${quote(id)} перемещён на позицию ${to + 1}`, id); + }; + const indent = (index: number, delta: number) => { + const next = shiftIndent(order, index, delta); + if (next === order) return; + commit(next, `Вложенность шага ${quote(order[index].id)}: ${next[index].indent}`, order[index].id); + }; + + const onRowKey = (e: KeyboardEvent, index: number) => { + if (locked) return; + if (e.key === 'Delete' || e.key === 'Backspace') { + e.preventDefault(); + remove(index); + return; + } + if (!e.altKey) return; + const actions: Record void> = { + ArrowUp: () => move(index, index - 1), + ArrowDown: () => move(index, index + 1), + ArrowLeft: () => indent(index, -1), + ArrowRight: () => indent(index, 1), + }; + if (actions[e.key]) { + e.preventDefault(); + actions[e.key](); + } + }; + + const onDragStart = (e: DragStartEvent) => setDragging(String(e.active.id)); + const onDragEnd = ({ active, over, delta }: DragEndEvent) => { + setDragging(null); + if (!over) return; + const id = pieceOf(active.id); + const fromPool = String(active.id).startsWith('p:'); + const overId = String(over.id); + const overIndex = overId.startsWith('s:') ? order.findIndex((s) => s.id === pieceOf(overId)) : -1; + + if (fromPool) { + if (overId === SOLUTION_ZONE) add(id); + else if (overIndex >= 0) add(id, overIndex); + return; + } + const from = order.findIndex((s) => s.id === id); + if (overId === POOL_ZONE || overId.startsWith('p:')) { + remove(from); + return; + } + const to = overIndex >= 0 ? overIndex : from; + let next = moveStep(order, from, to); + // перетаскивание вбок меняет вложенность + const shift = Math.round(delta.x / INDENT_PX); + if (shift) next = shiftIndent(next, to, shift); + if (next !== order) commit(next, `Шаг ${quote(id)} на позиции ${to + 1}, вложенность ${next[to].indent}`, id); + }; + + const announcements: Announcements = { + onDragStart: ({ active }) => `Взят шаг ${quote(pieceOf(active.id))}`, + onDragOver: ({ over }) => (over ? (String(over.id).startsWith('s:') ? `Над шагом ${quote(pieceOf(over.id))}` : over.id === POOL_ZONE ? 'Над блоками' : 'Над решением') : 'Вне списков'), + onDragEnd: ({ active, over }) => (over ? `Шаг ${quote(pieceOf(active.id))} отпущен` : 'Перетаскивание отменено'), + onDragCancel: () => 'Перетаскивание отменено', + }; + + return ( + setDragging(null)} + accessibility={{ + announcements, + screenReaderInstructions: { + draggable: + 'Пробел или Enter — взять шаг, стрелки — перенести, пробел — отпустить, Escape — отменить. ' + + 'На строке решения: Alt со стрелками вверх и вниз переставляет, Alt со стрелками влево и вправо меняет вложенность, Delete убирает шаг.', + }, + }} + > + + {!locked && add(id)} dragging={dragging} />} + + + sid(s.id))} strategy={verticalListSortingStrategy}> + + {order.map((step, i) => ( + setFocusId(null)} + onKeyDown={(e) => onRowKey(e, i)} + onMove={(to) => move(i, to)} + onIndent={(d) => indent(i, d)} + onRemove={() => remove(i)} + /> + ))} + + + {order.length === 0 && ( + + Перетащите сюда блоки или нажмите на них — они встанут по порядку. + + )} + + + + {marks && missing && missing.length > 0 && ( + + Пропущено шагов: {missing.length}. Какие — видно в эталоне. + + )} + + + {status} + + + + {dragging ? ( + + {textOf(pieceOf(dragging))} + + ) : null} + + + ); +}; + +const Pool = ({ pieces, onAdd, dragging }: { pieces: ConstructorPiece[]; onAdd: (id: string) => void; dragging: string | null }) => { + const { c } = useTokens(); + const { setNodeRef, isOver } = useDroppable({ id: POOL_ZONE }); + return ( + + + Блоки · {pieces.length} + + + {pieces.map((p) => ( + onAdd(p.id)} /> + ))} + + {pieces.length === 0 && ( + + Все блоки в решении. Лишний можно перетащить обратно. + + )} + + ); +}; + +const PoolItem = ({ piece, onAdd }: { piece: ConstructorPiece; onAdd: () => void }) => { + const { c } = useTokens(); + const { setNodeRef, listeners, attributes, isDragging } = useDraggable({ id: pid(piece.id) }); + // С клавиатуры блок добавляется кнопкой (Enter/пробел), без перетаскивания: порядок правится в решении + const pointerListeners = Object.fromEntries(Object.entries(listeners ?? {}).filter(([name]) => name !== 'onKeyDown')); + return ( + + + + {piece.text} + + + ); +}; + +const SolutionZone = ({ children, empty, locked }: { children: ReactNode; empty: boolean; locked: boolean }) => { + const { c } = useTokens(); + const { setNodeRef, isOver } = useDroppable({ id: SOLUTION_ZONE, disabled: locked }); + return ( + + + Ваше решение + + {children} + + ); +}; + +interface SolutionRowProps { + step: PlacedStep; + index: number; + total: number; + text: string; + mark?: StepMark; + locked: boolean; + autoFocus: boolean; + onFocused: () => void; + onKeyDown: (e: KeyboardEvent) => void; + onMove: (to: number) => void; + onIndent: (delta: number) => void; + onRemove: () => void; +} + +const SolutionRow = ({ step, index, total, text, mark, locked, autoFocus, onFocused, onKeyDown, onMove, onIndent, onRemove }: SolutionRowProps) => { + const { c } = useTokens(); + const rowRef = useRef(null); + // после перестановки с клавиатуры фокус остаётся на переставленной строке + useEffect(() => { + if (!autoFocus) return; + const el = rowRef.current; + if (el && !el.contains(document.activeElement)) el.focus(); + onFocused(); + }, [autoFocus, onFocused]); + const { setNodeRef, setActivatorNodeRef, listeners, attributes, transform, transition, isDragging } = useSortable({ + id: sid(step.id), + disabled: locked, + }); + const markColor = mark ? { ok: c.success, indent: c.warning, order: c.warning, extra: c.danger }[mark] : null; + const markBg = mark ? { ok: c.successSoft, indent: c.warningSoft, order: c.warningSoft, extra: c.dangerSoft }[mark] : null; + const MarkIcon = mark ? { ok: OkIcon, indent: IndentWarnIcon, order: OrderIcon, extra: ExtraIcon }[mark] : null; + const label = `${index + 1}. ${text}${step.indent ? `, вложенность ${step.indent}` : ''}${mark ? `, ${MARK_LABEL[mark]}` : ''}`; + + return ( + + + {locked ? ( + MarkIcon && + ) : ( + + + + )} + + {index + 1} + + + + {text} + + {mark && mark !== 'ok' && ( + + {MARK_LABEL[mark]} + + )} + + {!locked && ( + + onMove(index - 1)} icon={} /> + onMove(index + 1)} icon={} /> + onIndent(-1)} icon={} /> + = MAX_INDENT} onClick={() => onIndent(1)} icon={} /> + } /> + + )} + + + ); +}; + +const RowAction = ({ title, onClick, icon, disabled }: { title: string; onClick: () => void; icon: ReactNode; disabled?: boolean }) => ( + + + + {icon} + + + +); diff --git a/frontend/src/components/interview/constructor/sequence.test.ts b/frontend/src/components/interview/constructor/sequence.test.ts new file mode 100644 index 0000000..3ac36a0 --- /dev/null +++ b/frontend/src/components/interview/constructor/sequence.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest'; +import type { ConstructorStep, ContentBlock } from '../../../types'; +import { + findSequenceSolution, + findSequenceTask, + insertStep, + moveStep, + scoreSequence, + shiftIndent, + withoutConstructor, + type PlacedStep, +} from './sequence'; + +/** Эталон из 7 шагов: a b c [d e] f g, где d и e — тело цикла c. */ +const solution: ConstructorStep[] = [ + { id: 'a', text: 'A', indent: 0 }, + { id: 'b', text: 'B', indent: 0 }, + { id: 'c', text: 'C', indent: 0 }, + { id: 'd', text: 'D', indent: 1 }, + { id: 'e', text: 'E', indent: 1 }, + { id: 'f', text: 'F', indent: 0 }, + { id: 'g', text: 'G', indent: 0 }, +]; +const exact = (): PlacedStep[] => solution.map(({ id, indent }) => ({ id, indent })); + +describe('scoreSequence', () => { + it('gives 10 for the reference order and nesting', () => { + const r = scoreSequence(solution, exact()); + expect(r.score).toBe(10); + expect(r.marks.every((m) => m === 'ok')).toBe(true); + expect(r.missing).toEqual([]); + }); + + it('one swap still passes (8), two swaps are partial (7)', () => { + const one = moveStep(exact(), 0, 1); // b a c d e f g + expect(scoreSequence(solution, one).score).toBe(8); + expect(scoreSequence(solution, one).marks.filter((m) => m === 'order')).toHaveLength(1); + const two = moveStep(one, 5, 6); // b a c d e g f + expect(scoreSequence(solution, two).score).toBe(7); + }); + + it('takes a point per wrong nesting and two per distractor', () => { + const flat = exact().map((s) => ({ ...s, indent: 0 })); + const r = scoreSequence(solution, flat); + expect(r.score).toBe(8); + expect(r.marks.filter((m) => m === 'indent')).toHaveLength(2); + + const withExtra = insertStep(exact(), 'x', 2); + const e = scoreSequence(solution, withExtra); + expect(e.score).toBe(8); + expect(e.marks[2]).toBe('extra'); + }); + + it('reports missing steps and never goes below zero', () => { + const r = scoreSequence(solution, [{ id: 'a', indent: 0 }, { id: 'b', indent: 0 }]); + expect(r.score).toBe(2); + expect(r.missing).toEqual(['c', 'd', 'e', 'f', 'g']); + const junk = ['x', 'y', 'z'].map((id) => ({ id, indent: 0 })); + expect(scoreSequence(solution, junk).score).toBe(0); + expect(scoreSequence(solution, []).score).toBe(0); + }); + + it('reversed order keeps a single step in place', () => { + const r = scoreSequence(solution, [...exact()].reverse()); + expect(r.score).toBe(1); + expect(r.marks.filter((m) => m !== 'order')).toHaveLength(1); + }); +}); + +describe('editing helpers', () => { + it('moves a step and ignores out-of-range moves', () => { + const order = exact(); + expect(moveStep(order, 6, 0).map((s) => s.id).join('')).toBe('gabcdef'); + expect(moveStep(order, 0, 9)).toBe(order); + }); + + it('limits nesting to one level deeper than the previous row', () => { + const order = [{ id: 'a', indent: 0 }, { id: 'b', indent: 0 }]; + expect(shiftIndent(order, 0, 1)).toBe(order); // первая строка всегда без отступа + const once = shiftIndent(order, 1, 1); + expect(once[1].indent).toBe(1); + expect(shiftIndent(once, 1, 1)).toBe(once); + expect(shiftIndent(once, 1, -5)[1].indent).toBe(0); + }); + + it('inserts with the nesting of the row above', () => { + const order = [{ id: 'a', indent: 0 }, { id: 'b', indent: 1 }]; + expect(insertStep(order, 'c')).toEqual([...order, { id: 'c', indent: 1 }]); + expect(insertStep(order, 'c', 0)[0]).toEqual({ id: 'c', indent: 0 }); + }); +}); + +describe('content blocks', () => { + const question: ContentBlock[] = [ + { type: 'paragraph', data: { text: 'Условие' } }, + { type: 'constructor', data: { kind: 'sequence', prompt: 'Соберите', pieces: [{ id: 'a', text: 'A' }] } }, + ]; + const answer: ContentBlock[] = [ + { type: 'paragraph', data: { text: 'Суть' } }, + { type: 'constructor', data: { kind: 'sequence', solution } }, + ]; + + it('finds the task in the question and the solution in the answer', () => { + expect(findSequenceTask(question)).toEqual({ prompt: 'Соберите', pieces: [{ id: 'a', text: 'A' }] }); + expect(findSequenceTask(answer)).toBeNull(); + expect(findSequenceSolution(answer)).toBe(solution); + expect(findSequenceSolution(undefined)).toBeNull(); + expect(withoutConstructor(question)).toHaveLength(1); + }); +}); diff --git a/frontend/src/components/interview/constructor/sequence.ts b/frontend/src/components/interview/constructor/sequence.ts new file mode 100644 index 0000000..8c7728f --- /dev/null +++ b/frontend/src/components/interview/constructor/sequence.ts @@ -0,0 +1,130 @@ +import type { ContentBlock, ConstructorPiece, ConstructorStep } from '../../../types'; + +/** Задание-конструктор вида «алгоритм из блоков» (задача Парсонса). */ +export interface SequenceTask { + prompt: string; + pieces: ConstructorPiece[]; +} + +/** Строка собранного решения: какой кусок и на каком уровне вложенности. */ +export interface PlacedStep { + id: string; + indent: number; +} + +export const MAX_INDENT = 3; + +/** Пометка строки после сдачи: на месте / не та вложенность / не на своём месте / лишний блок. */ +export type StepMark = 'ok' | 'indent' | 'order' | 'extra'; + +export interface SequenceScore { + /** 0..10, как у оценки ИИ: 8–10 «Прошёл», 5–7 «Частично», 0–4 «Не прошёл». */ + score: number; + marks: StepMark[]; + /** Шаги эталона, которых нет в решении. */ + missing: string[]; +} + +const isConstructor = (b: ContentBlock | undefined) => b?.type === 'constructor' && b.data?.kind === 'sequence'; + +/** Задание-конструктор в блоках вопроса, если оно есть. */ +export const findSequenceTask = (blocks: ContentBlock[] | undefined): SequenceTask | null => { + const block = blocks?.find((b) => isConstructor(b) && Array.isArray(b.data?.pieces) && b.data!.pieces!.length > 0); + return block ? { prompt: block.data?.prompt ?? 'Соберите решение из блоков', pieces: block.data!.pieces! } : null; +}; + +/** Эталон сборки в блоках ответа. */ +export const findSequenceSolution = (blocks: ContentBlock[] | undefined): ConstructorStep[] | null => { + const block = blocks?.find((b) => isConstructor(b) && Array.isArray(b.data?.solution) && b.data!.solution!.length > 0); + return block ? block.data!.solution! : null; +}; + +/** Блоки вопроса без конструктора: его рисует сам сборщик, а не текст условия. */ +export const withoutConstructor = (blocks: ContentBlock[]) => blocks.filter((b) => b.type !== 'constructor'); + +/** Индексы в `a`, входящие в одну из наибольших общих подпоследовательностей `a` и `b`. */ +const lcsIndices = (a: string[], b: string[]): Set => { + const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]); + } + } + const picked = new Set(); + let i = 0; + let j = 0; + while (i < a.length && j < b.length) { + if (a[i] === b[j]) { + picked.add(i); + i++; + j++; + } else if (dp[i + 1][j] >= dp[i][j + 1]) i++; + else j++; + } + return picked; +}; + +/** + * Балл сборки: 10 × (НОП с эталоном) / число шагов, с округлением вниз; + * минус 1 за каждую неверную вложенность среди шагов на месте, минус 2 за каждый лишний блок. + */ +export const scoreSequence = (solution: ConstructorStep[], attempt: PlacedStep[]): SequenceScore => { + const byId = new Map(solution.map((s) => [s.id, s])); + const steps = attempt.filter((p) => byId.has(p.id)); + const inOrder = lcsIndices( + steps.map((p) => p.id), + solution.map((s) => s.id), + ); + + let k = 0; + let indentErrors = 0; + let extra = 0; + const marks = attempt.map((p): StepMark => { + const ref = byId.get(p.id); + if (!ref) { + extra++; + return 'extra'; + } + const placed = inOrder.has(k++); + if (!placed) return 'order'; + if (ref.indent !== p.indent) { + indentErrors++; + return 'indent'; + } + return 'ok'; + }); + + const used = new Set(attempt.map((p) => p.id)); + const base = solution.length ? Math.floor((10 * inOrder.size) / solution.length) : 0; + return { + score: Math.max(0, Math.min(10, base - indentErrors - 2 * extra)), + marks, + missing: solution.filter((s) => !used.has(s.id)).map((s) => s.id), + }; +}; + +/** Перестановка строки решения: перенос с позиции from на to. */ +export const moveStep = (order: PlacedStep[], from: number, to: number): PlacedStep[] => { + if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return order; + const next = [...order]; + const [item] = next.splice(from, 1); + next.splice(to, 0, item); + return next; +}; + +/** Сдвиг вложенности: не глубже предыдущей строки + 1 и не больше MAX_INDENT. */ +export const shiftIndent = (order: PlacedStep[], index: number, delta: number): PlacedStep[] => { + const step = order[index]; + if (!step) return order; + const limit = index === 0 ? 0 : Math.min(MAX_INDENT, order[index - 1].indent + 1); + const indent = Math.max(0, Math.min(limit, step.indent + delta)); + if (indent === step.indent) return order; + return order.map((s, i) => (i === index ? { ...s, indent } : s)); +}; + +/** Новая строка встаёт на уровень предыдущей: так тело цикла собирается без лишних нажатий. */ +export const insertStep = (order: PlacedStep[], id: string, at = order.length): PlacedStep[] => { + const pos = Math.max(0, Math.min(at, order.length)); + const indent = pos === 0 ? 0 : order[pos - 1].indent; + return [...order.slice(0, pos), { id, indent }, ...order.slice(pos)]; +}; diff --git a/frontend/src/components/interview/session.test.ts b/frontend/src/components/interview/session.test.ts index 0f2ef90..862dae7 100644 --- a/frontend/src/components/interview/session.test.ts +++ b/frontend/src/components/interview/session.test.ts @@ -42,4 +42,20 @@ describe('interview session', () => { // эталон после оценки ИИ — разбор ошибок, оценка остаётся expect(outcomeOf({ answer: 'x', review: review(9), revealed: true })).toBe('strong'); }); + + it('grades constructor questions by the build score and counts an unsubmitted build as answered', () => { + const order = [{ id: 'a', indent: 0 }]; + expect(outcomeOf({ answer: '', build: { order, score: 9 }, self: 'knew' })).toBe('strong'); + expect(outcomeOf({ answer: '', build: { order, score: 6 }, self: 'partial' })).toBe('weak'); + expect(outcomeOf({ answer: '', build: { order } })).toBe('ok'); + expect(outcomeOf({ answer: '', build: { order: [] } })).toBe('skipped'); + expect(outcomeOf({ answer: '', build: { order }, revealed: true, self: 'missed' })).toBe('weak'); + + const s = newSession(['a', 'b'], DEFAULT_OPTIONS, 0); + s.results = { a: { answer: '', build: { order, score: 10 } }, b: { answer: 'x', review: review(6) } }; + const sum = summarize(s); + expect(sum.average).toBe(8); + expect(sum.reviewed).toBe(2); + expect(sum.strongIds).toEqual(['a']); + }); }); diff --git a/frontend/src/components/interview/session.ts b/frontend/src/components/interview/session.ts index 5e8abf1..d44ca2e 100644 --- a/frontend/src/components/interview/session.ts +++ b/frontend/src/components/interview/session.ts @@ -1,4 +1,5 @@ import type { AIReview, MasteryLevel, Question } from '../../types'; +import type { PlacedStep, StepMark } from './constructor/sequence'; /** Уровень по вопросу: ставит ИИ, сам кандидат — только если ИИ недоступен. */ export type SelfMark = 'knew' | 'partial' | 'missed'; @@ -15,8 +16,25 @@ export interface QuestionResult { self?: SelfMark; /** Эталон открыт до оценки: вопрос засчитан как «Не прошёл», проверка ИИ закрыта. */ revealed?: boolean; + /** Задание-конструктор: собранный порядок, после сдачи — балл и пометки строк. */ + build?: BuildResult; } +export interface BuildResult { + order: PlacedStep[]; + /** Балл 0..10 фиксируется первой сдачей: перебором порядок не подобрать. */ + score?: number; + marks?: StepMark[]; + missing?: string[]; +} + +/** Балл по вопросу: оценка ИИ или балл сборки конструктора. */ +export const scoreOf = (result: QuestionResult | undefined): number | undefined => result?.review?.score ?? result?.build?.score; + +/** На вопрос ответили: есть текст, оценка или начатая сборка. */ +export const isAnswered = (result: QuestionResult | undefined) => + Boolean(result?.answer?.trim() || result?.self || result?.build?.order.length); + export interface InterviewOptions { /** 0 — все подходящие вопросы. */ count: number; @@ -98,23 +116,24 @@ export type Outcome = 'strong' | 'ok' | 'weak' | 'skipped'; /** Итог по вопросу: оценка ИИ важнее самооценки. */ export const outcomeOf = (result: QuestionResult | undefined): Outcome => { - if (result?.revealed && !result.review) return 'weak'; - if (result?.review) { - if (result.review.score >= STRONG_SCORE) return 'strong'; - return result.review.score >= WEAK_SCORE ? 'ok' : 'weak'; + const score = scoreOf(result); + if (result?.revealed && score === undefined) return 'weak'; + if (score !== undefined) { + if (score >= STRONG_SCORE) return 'strong'; + return score >= WEAK_SCORE ? 'ok' : 'weak'; } if (result?.self === 'knew') return 'strong'; if (result?.self === 'partial') return 'weak'; if (result?.self === 'missed') return 'weak'; - return result?.answer.trim() ? 'ok' : 'skipped'; + return isAnswered(result) ? 'ok' : 'skipped'; }; export const summarize = (session: InterviewSession) => { const results = session.ids.map((id) => ({ id, result: session.results[id], outcome: outcomeOf(session.results[id]) })); - const scores = results.map((r) => r.result?.review?.score).filter((s): s is number => typeof s === 'number'); + const scores = results.map((r) => scoreOf(r.result)).filter((s): s is number => typeof s === 'number'); return { results, - answered: results.filter((r) => r.result?.answer.trim() || r.result?.self).length, + answered: results.filter((r) => isAnswered(r.result)).length, reviewed: scores.length, average: scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : null, weakIds: results.filter((r) => r.outcome === 'weak' || r.outcome === 'skipped').map((r) => r.id), diff --git a/frontend/src/pages/InterviewModePage.tsx b/frontend/src/pages/InterviewModePage.tsx index 3c483e1..7cf798a 100644 --- a/frontend/src/pages/InterviewModePage.tsx +++ b/frontend/src/pages/InterviewModePage.tsx @@ -11,9 +11,21 @@ import { Navigate, useNavigate, useParams } from 'react-router-dom'; import { CategoryChip, DifficultyChip, EmptyState } from '../components/ui'; import { BitHost } from '../components/ui/BitHost'; import { bitSay, pickLine } from '../components/ui/bitVoice'; -import { INTERVIEW_ROLE, markedLine, questionLine, resultsLine, SETUP_LINE, SILENCE_LINES, startLine } from '../components/interview/bitInterview'; +import { + BUILD_SILENCE_LINES, + buildQuestionLine, + INTERVIEW_ROLE, + markedLine, + questionLine, + resultsLine, + SETUP_LINE, + SILENCE_LINES, + startLine, +} from '../components/interview/bitInterview'; import { ContentRenderer } from '../components/ContentRenderer'; import { AnswerPanel } from '../components/interview/AnswerPanel'; +import { BuildPanel } from '../components/interview/constructor/BuildPanel'; +import { findSequenceTask, withoutConstructor } from '../components/interview/constructor/sequence'; import { InterviewResults } from '../components/interview/InterviewResults'; import { InterviewSetup } from '../components/interview/InterviewSetup'; import { GradeScale } from '../components/interview/GradeScale'; @@ -22,6 +34,8 @@ import { MASTERY_LABEL, useMasteryColor } from '../components/ui/masteryLevels'; import { buildPlan, DEFAULT_OPTIONS, + isAnswered, + scoreOf, SELF_TO_LEVEL, type InterviewOptions, type InterviewSession, @@ -84,21 +98,28 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => { const { c } = useTokens(); const card = useInterviewCard(question.id); const ai = useAIReviewStatus(); - const hasAnswer = Boolean(result?.answer?.trim() || result?.self); + const hasAnswer = isAnswered(result); + const task = useMemo(() => findSequenceTask(question.content), [question.content]); + const blocks = useMemo(() => withoutConstructor(question.content ?? []), [question.content]); // Молчание на вопросе: Бит один раз мягко подталкивает начать useEffect(() => { if (hasAnswer) return; - const timer = window.setTimeout(() => bitSay(pickLine('silence', SILENCE_LINES), 'focus', { move: 'nod' }), SILENCE_MS); + const timer = window.setTimeout( + () => (task ? bitSay(pickLine('silence:build', BUILD_SILENCE_LINES), 'focus', { move: 'nod' }) : bitSay(pickLine('silence', SILENCE_LINES), 'focus', { move: 'nod' })), + SILENCE_MS, + ); return () => window.clearTimeout(timer); - }, [hasAnswer]); + }, [hasAnswer, task]); return ( {question.category?.name && } + {task && } {result?.review && } + {result?.build?.score !== undefined && } @@ -106,8 +127,8 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => { - {question.content && question.content.length > 0 ? ( - + {blocks.length > 0 ? ( + ) : ( Текст вопроса не загружен @@ -117,16 +138,28 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => { - + {task ? ( + + ) : ( + + )} ); }; @@ -198,8 +231,10 @@ export const InterviewModePage = () => { const currentId = currentQuestion?.id; useEffect(() => { if (!currentQuestion) return; - const revisit = Boolean(session?.results[currentQuestion.id]?.answer?.trim() || session?.results[currentQuestion.id]?.self); - const line = questionLine(currentIndex, plan.length, currentQuestion, revisit); + const revisit = isAnswered(session?.results[currentQuestion.id]); + const line = findSequenceTask(currentQuestion.content) + ? buildQuestionLine(currentIndex, plan.length, revisit) + : questionLine(currentIndex, plan.length, currentQuestion, revisit); if (startedRef.current && currentIndex === 0) { bitSay(`${startLine(startedRef.current).text} ${line.text}`, 'cheer'); startedRef.current = 0; @@ -250,7 +285,7 @@ export const InterviewModePage = () => { current={session} onStart={start} onResume={() => { - const firstOpen = session ? session.ids.findIndex((id) => !session.results[id]?.answer?.trim() && !session.results[id]?.self) : -1; + const firstOpen = session ? session.ids.findIndex((id) => !isAnswered(session.results[id])) : -1; navigate(`${base}/${Math.max(0, firstOpen)}`); }} /> @@ -341,7 +376,7 @@ export const InterviewModePage = () => { {plan.map((id, i) => { const r = session.results[id]; - const done = Boolean(r?.answer?.trim() || r?.self); + const done = isAnswered(r); // точка окрашена уровнем, который поставил ИИ (или сам кандидат, когда ИИ недоступен) const fill = r?.self ? masteryColor(SELF_TO_LEVEL[r.self]).fg : done ? c.accent : 'transparent'; return ( @@ -389,7 +424,7 @@ export const InterviewModePage = () => { > Назад - {currentResult?.review && } + {scoreOf(currentResult) !== undefined && }