From c94434cd0987232ce8ff9c195262dbbbf02f4164 Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 21:32:55 +0300 Subject: [PATCH] feat(frontend): keep focus, field errors and unsent answers on the minimal path --- docs/en/TESTING.md | 21 +- docs/ru/TESTING.md | 21 +- frontend/e2e/invitation-compose.spec.ts | 2 +- frontend/e2e/minimal-path-a11y.spec.ts | 734 ++++++++++++++++++ .../src/features/answer-assessment/index.ts | 1 + .../model/answer-draft-store.test.ts | 191 +++++ .../model/answer-draft-store.ts | 132 ++++ .../answer-assessment/ui/answer-form.tsx | 26 +- .../src/features/edit-need/ui/need-editor.tsx | 48 +- .../send-invitation/ui/invitation-form.tsx | 3 + .../src/features/sign-in/ui/sign-in-form.tsx | 10 +- .../assessment/ui/assessment-attempt-page.tsx | 3 + 12 files changed, 1174 insertions(+), 18 deletions(-) create mode 100644 frontend/e2e/minimal-path-a11y.spec.ts create mode 100644 frontend/src/features/answer-assessment/model/answer-draft-store.test.ts create mode 100644 frontend/src/features/answer-assessment/model/answer-draft-store.ts diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index fd6a4fa..55ef6db 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -71,7 +71,7 @@ Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8 The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used. -The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. +The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified. @@ -85,6 +85,25 @@ The same command also seeds a second synthetic candidate for `frontend/e2e/priva `frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`. +## Minimal path states and accessibility + +`frontend/e2e/minimal-path-a11y.spec.ts` checks the states, the keyboard path, and the error binding of the sign-in, the candidate test start and profile, the candidate inbox, and the candidate invitation screen. Failures come from route interception, so no data is needed on the stand: HTTP 500 and 403 answers, a dropped connection, and the empty and forbidden answers. Each stubbed screen is checked at 360, 768, and 1280 px for horizontal overflow; the real-backend assessment check covers 360 and 768 px. Each control reached with Tab must match `:focus-visible` and draw a focus outline. The stubbed part runs in both `make -C deploy test-e2e` and `make -C deploy test-e2e-registration`. The one real-backend test runs only in the registration mode, because it needs the mail and questionnaire fixtures. + +The other screens of the minimal path are covered by their existing specs: the employer candidate search and match list (`match-search.spec.ts`: a failed search with a retry, a refused search, an empty result, confirmed and declared grades as text, keyboard reach at every width), the invitation compose (`invitation-compose.spec.ts`: errors bound to fields, a lost send response retried with the same key, overflow at 360, 768, and 1280 px), registration and confirmation (`auth-registration.spec.ts`), and the profile and questionnaire (`profile-edit.spec.ts`, `questionnaire.spec.ts`). + +Checklist for the minimal path. Each item is checked by the spec named in brackets; the result is the outcome of the last run of that spec. + +- Sign-in [`minimal-path-a11y.spec.ts`]: Tab reaches both fields and the submit control with a visible outline at 360, 768, and 1280 px. An empty submit marks both fields `aria-invalid` and gives each one its message through `aria-describedby`. A failed answer keeps the typed email and keeps the focus in the form. While the answer is pending, the password field stays focused and read-only; it is not disabled, because a disabled field drops the focus. +- Candidate profile [`minimal-path-a11y.spec.ts`]: a loading text while the profile loads, an alert with a retry after a failed load, and no retry after an access refusal. +- Candidate test start [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed availability read; a candidate without a specialization sees the empty state with a link to the questionnaire. +- Candidate inbox [`minimal-path-a11y.spec.ts`]: a loading text; a server error or a dropped connection gives an alert with a retry that works from the keyboard; the empty state; no retry after an access refusal; each card names the company, the role, and the state as text. +- Candidate invitation [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed load; a failed decline keeps the chosen reason and the comment and moves the focus to the alert; the declined state is shown as text. +- Assessment on a phone with the real backend [`minimal-path-a11y.spec.ts`, registration mode]: an unsent numeric answer survives a reload at 360 px, and the stored copy is removed when the answer is accepted. +- Employer match list and invitation compose: see the specs named above; the compose page is also checked at 768 px. +- Not covered by these checks: screen reader output, the contrast of the focus outline, and zoom above 200 percent. They were not checked by hand in this pass. + +An unsent answer is kept in `sessionStorage` of the same browser tab, under a key that names the attempt and the item. It is never sent to the server. A reload restores it only when it fits the item; a stored value larger than 64 KiB is not kept; a blocked or full store leaves the answer in the form only. An accepted answer removes the stored copy. Answers accepted by the server come from the server after a reload. + ## Release manifest tests `make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile or backend/Dockerfile.demo-seed stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that: diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index a084b67..0a13fdf 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -71,7 +71,7 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются. -Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. +Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись. @@ -85,6 +85,25 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f `frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`. +## Состояния и доступность основного пути + +`frontend/e2e/minimal-path-a11y.spec.ts` проверяет состояния, путь с клавиатуры и привязку ошибок на экранах входа, начала проверки знаний, профиля кандидата, входящих приглашений и отдельного приглашения кандидата. Отказы создаются перехватом запросов, поэтому на стенде не нужны данные: ответы HTTP 500 и 403, обрыв соединения, пустые и запрещенные ответы. Каждый экран с заглушками проверяется при 360, 768 и 1280 px на горизонтальное переполнение; проверка с настоящим backend покрывает 360 и 768 px. Каждый элемент, до которого доходит Tab, должен соответствовать `:focus-visible` и рисовать контур фокуса. Часть с перехватом запускается и в `make -C deploy test-e2e`, и в `make -C deploy test-e2e-registration`. Один тест с настоящим backend запускается только в режиме регистрации, потому что ему нужны почтовый и анкетный fixture. + +Остальные экраны основного пути покрыты существующими спецификациями: поиск кандидатов и список совпадений работодателя (`match-search.spec.ts`: неуспешный поиск с повтором, отказ в поиске, пустой результат, подтвержденный и заявленный грейд текстом, достижение элементов с клавиатуры при каждой ширине), составление приглашения (`invitation-compose.spec.ts`: ошибки, привязанные к полям, потерянный ответ на отправку с повтором под тем же ключом, переполнение при 360, 768 и 1280 px), регистрация и подтверждение (`auth-registration.spec.ts`), профиль и анкета (`profile-edit.spec.ts`, `questionnaire.spec.ts`). + +Чек-лист основного пути. Каждый пункт проверяет спецификация, указанная в скобках; результат - итог последнего прогона этой спецификации. + +- Вход [`minimal-path-a11y.spec.ts`]: Tab доходит до обоих полей и кнопки отправки с видимым контуром при 360, 768 и 1280 px. Пустая отправка помечает оба поля `aria-invalid` и связывает каждое поле с его текстом через `aria-describedby`. Неуспешный ответ сохраняет введенную почту и оставляет фокус в форме. Пока ответ ожидается, поле пароля остается в фокусе и только для чтения; оно не отключается, потому что отключенное поле теряет фокус. +- Профиль кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки, пока профиль загружается; сообщение с кнопкой повтора после неуспешной загрузки; без повтора после отказа в доступе. +- Начало пробной проверки кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешного чтения доступности; кандидат без специализации видит пустое состояние со ссылкой на анкету. +- Входящие приглашения кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки; ошибка сервера или обрыв соединения дают сообщение с кнопкой повтора, которая работает с клавиатуры; пустое состояние; без повтора после отказа в доступе; каждая карточка называет компанию, роль и состояние текстом. +- Приглашение кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешной загрузки; неуспешный отказ сохраняет выбранную причину и комментарий и переводит фокус на сообщение; состояние "отклонено" показано текстом. +- Проверка на телефоне с настоящим backend [`minimal-path-a11y.spec.ts`, режим регистрации]: неотправленный числовой ответ переживает перезагрузку при 360 px, а сохраненная копия удаляется, когда ответ принят. +- Список совпадений работодателя и составление приглашения: см. спецификации выше; страница составления дополнительно проверяется при 768 px. +- Эти проверки не покрывают: вывод для программ чтения с экрана, контраст контура фокуса и масштаб выше 200 процентов. В этом проходе они вручную не проверялись. + +Неотправленный ответ хранится в `sessionStorage` той же вкладки браузера под ключом, который называет попытку и задание. На сервер он не отправляется. Перезагрузка восстанавливает его, только если значение подходит заданию; сохраненное значение больше 64 KiB не сохраняется; заблокированное или переполненное хранилище оставляет ответ только в форме. Принятый ответ удаляет сохраненную копию. Ответы, принятые сервером, после перезагрузки берутся с сервера. + ## Тесты манифеста выпуска `make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile или backend/Dockerfile.demo-seed перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что: diff --git a/frontend/e2e/invitation-compose.spec.ts b/frontend/e2e/invitation-compose.spec.ts index cf582d6..461d543 100644 --- a/frontend/e2e/invitation-compose.spec.ts +++ b/frontend/e2e/invitation-compose.spec.ts @@ -185,7 +185,7 @@ function isInvitationCommand(request: Request): boolean { } async function expectNoHorizontalOverflow(page: Page): Promise { - for (const width of [360, 1280]) { + for (const width of [360, 768, 1280]) { await page.setViewportSize({ width, height: 900 }); const overflow = await page.evaluate( () => document.documentElement.scrollWidth > window.innerWidth, diff --git a/frontend/e2e/minimal-path-a11y.spec.ts b/frontend/e2e/minimal-path-a11y.spec.ts new file mode 100644 index 0000000..5289aa2 --- /dev/null +++ b/frontend/e2e/minimal-path-a11y.spec.ts @@ -0,0 +1,734 @@ +import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test"; + +// States, focus, and error binding of the minimal path with a stubbed API. The +// API answers come from this file, so each test controls one failure at a time +// and needs no fixtures on the stand. Every screen is checked at 360, 768, and +// 1280 px: the stubbed content must fit without horizontal scrolling, and each +// control is reached with the Tab key and shows a focus outline. +// +// The last describe block runs against the real backend: it registers a +// candidate through the local mail fixture and checks the unsent assessment +// answer after a reload. The registration helpers are copies of the ones in +// assessment.spec.ts. See docs/en/TESTING.md, "Minimal path states and +// accessibility", for what each part proves. + +const widths = [360, 768, 1280] as const; +const accountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4001"; +const invitationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4101"; +const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4201"; +const csrfToken = "A".repeat(43); +const openDeadline = "2099-10-16T10:00:00Z"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +type Answer = { status: number; body?: unknown; code?: string } | "abort"; +type Responder = Answer | ((call: number, request: Request) => Answer | Promise); +// Keys are "METHOD /api/v1/path". Each responder sees the number of its calls. +type Routes = Record; + +function candidateSession() { + return { + account: { + id: accountId, + email: "candidate@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: csrfToken, + }; +} + +function problem(code: string, status: number): Answer { + return { status, code }; +} + +const candidateTerms = { + role_title: "Middle Go-разработчик в команду платежей", + specialization: "backend", + grade: "middle", + offer_type: "full_time", + tasks: ["Развивать сервис выплат", "Перевести отчеты на события"], + team: "Пять бэкенд-разработчиков\nи QA-инженер", + tech_stack: ["Go", "PostgreSQL"], + work_formats: ["remote", "hybrid"], + location: "Москва", + communication_method: { channel: "video_call", details: "Созвон с тимлидом" }, + salary: { + salary_from: 100000, + salary_to: 140000, + currency: "RUB", + period: "month", + tax_basis: "net", + }, + package: { + bonus: { status: "provided", description: "Квартальная премия до 20%" }, + equipment: { status: "provided", description: "Ноутбук и монитор" }, + training: { status: "not_provided" }, + health_insurance: { status: "not_provided" }, + }, +}; + +function candidateInvitation(overrides: Record = {}) { + return { + id: invitationId, + organization: { id: organizationId, name: "Северный ветер" }, + state: "delivered", + expiry_reason: null, + version: 1, + terms_version: 1, + terms: candidateTerms, + response_deadline_at: openDeadline, + delivered_at: "2026-10-09T10:00:00Z", + viewed_at: null, + responded_at: null, + updated_at: "2026-10-09T10:00:00Z", + contact_consent: null, + decline: null, + contact_grant: null, + ...overrides, + }; +} + +function inboxItem() { + const invitation = candidateInvitation(); + return { + id: invitation.id, + organization: invitation.organization, + state: invitation.state, + expiry_reason: null, + version: 1, + terms_version: 1, + role_title: candidateTerms.role_title, + salary: candidateTerms.salary, + work_formats: candidateTerms.work_formats, + response_deadline_at: openDeadline, + delivered_at: invitation.delivered_at, + viewed_at: null, + updated_at: invitation.updated_at, + }; +} + +function deferred() { + let resolve: (value: T) => void = () => undefined; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +// Answers every /api/v1 request from the routes; an unknown request is a 404 +// problem, so a missing stub shows up as a failed state instead of a hang. +async function mockApi(page: Page, routes: Routes): Promise> { + const calls = new Map(); + await page.route("**/api/v1/**", async (route: Route) => { + const request = route.request(); + const { pathname } = new URL(request.url()); + const key = `${request.method()} ${pathname}`; + const count = (calls.get(key) ?? 0) + 1; + calls.set(key, count); + const responder = routes[key]; + const answer: Answer = + responder === undefined + ? problem("not_found", 404) + : typeof responder === "function" + ? await responder(count, request) + : responder; + if (answer === "abort") { + await route.abort("failed"); + return; + } + if (answer.status >= 400) { + await route.fulfill({ + status: answer.status, + contentType: "application/problem+json", + body: JSON.stringify({ + type: `urn:lincodex:problem:${answer.code ?? "error"}`, + title: answer.code ?? "error", + status: answer.status, + code: answer.code ?? "error", + }), + }); + return; + } + await route.fulfill({ + status: answer.status, + contentType: "application/json", + body: JSON.stringify(answer.body ?? null), + }); + }); + return calls; +} + +async function expectNoHorizontalOverflow(page: Page, width: number): Promise { + await page.setViewportSize({ width, height: 900 }); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(overflow, `no horizontal overflow at ${width}px`).toBe(false); +} + +// The focus outline comes from the global :focus-visible rule. A control that +// has focus from the keyboard must match that selector and draw an outline. +async function expectFocusOutline(target: Locator): Promise { + const style = await target.evaluate((element) => { + const computed = getComputedStyle(element); + return { + focusVisible: element.matches(":focus-visible"), + outlineStyle: computed.outlineStyle, + outlineWidth: Number.parseFloat(computed.outlineWidth), + }; + }); + expect(style.focusVisible, "the control matches :focus-visible").toBe(true); + expect(style.outlineStyle, "the focus outline is drawn").not.toBe("none"); + expect(style.outlineWidth, "the focus outline has a width").toBeGreaterThan(0); +} + +// Moves focus to the target with Tab from the top of the document, as a +// keyboard user does, and checks that the target shows its focus outline. +async function tabTo(page: Page, target: Locator, maxSteps = 80): Promise { + await expect(target).toBeVisible(); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + for (let step = 0; step < maxSteps; step += 1) { + await page.keyboard.press("Tab"); + if (await target.evaluate((element) => element === document.activeElement)) { + await expectFocusOutline(target); + return; + } + } + throw new Error("Keyboard navigation did not reach the target control."); +} + +test.describe("minimal path states with a stubbed API", () => { + for (const width of widths) { + test(`sign-in at ${width}px: bound field errors and failed answers keep the typed email`, async ({ + page, + }) => { + let answers = 0; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": problem("unauthenticated", 401), + "POST /api/v1/identity/sessions": () => { + answers += 1; + return answers === 1 + ? problem("internal_error", 500) + : problem("invalid_credentials", 401); + }, + }); + await page.goto("/login"); + await expect(page.getByRole("heading", { level: 1, name: "Вход" })).toBeVisible(); + await expectNoHorizontalOverflow(page, width); + + const email = page.getByLabel("Электронная почта"); + const password = page.getByLabel("Пароль", { exact: true }); + const submit = page.locator('button[type="submit"]'); + + // An empty submit binds each message to its field and marks it invalid. + await tabTo(page, submit); + await page.keyboard.press("Enter"); + await expect(email).toHaveAttribute("aria-invalid", "true"); + await expect(email).toHaveAccessibleDescription( + "Введите корректный адрес электронной почты.", + ); + await expect(password).toHaveAttribute("aria-invalid", "true"); + await expect(password).toHaveAccessibleDescription("Введите пароль."); + + // A server failure is an alert; the typed email stays in place. + await tabTo(page, email); + await page.keyboard.type("candidate@example.test"); + await tabTo(page, password); + await page.keyboard.type("correct horse battery staple 2026"); + await page.keyboard.press("Enter"); + await expect(page.getByRole("alert")).toHaveText( + "Не удалось выполнить вход. Проверьте соединение и повторите попытку.", + ); + await expect(email).toHaveValue("candidate@example.test"); + await expect(email).not.toHaveAttribute("aria-invalid", "true"); + await expect(password).toBeFocused(); + await expectNoHorizontalOverflow(page, width); + + // A second answer with invalid credentials is a different alert. + await page.keyboard.press("Enter"); + await expect(page.getByRole("alert")).toHaveText( + "Не удалось войти. Проверьте адрес и пароль.", + ); + await expect(email).toHaveValue("candidate@example.test"); + await expect(submit).toHaveText("Войти"); + await expectNoHorizontalOverflow(page, width); + }); + + test(`sign-in at ${width}px: a pending answer keeps the focus in the form and reads as busy`, async ({ + page, + }) => { + const release = deferred(); + await mockApi(page, { + "GET /api/v1/identity/sessions/current": problem("unauthenticated", 401), + "POST /api/v1/identity/sessions": () => release.promise, + }); + await page.goto("/login"); + await expectNoHorizontalOverflow(page, width); + const email = page.getByLabel("Электронная почта"); + const password = page.getByLabel("Пароль", { exact: true }); + const submit = page.locator('button[type="submit"]'); + await tabTo(page, email); + await page.keyboard.type("candidate@example.test"); + await tabTo(page, password); + await page.keyboard.type("correct horse battery staple 2026"); + await page.keyboard.press("Enter"); + + await expect(submit).toHaveText("Входим..."); + await expect(submit).toHaveAttribute("aria-busy", "true"); + await expect( + page.getByRole("status").filter({ hasText: "Проверяем учетные данные" }), + ).toBeVisible(); + // A read-only field keeps the keyboard focus while the answer is pending. + await expect(password).toBeFocused(); + await expect(password).toHaveAttribute("readonly", ""); + release.resolve(problem("invalid_credentials", 401)); + await expect(page.getByRole("alert")).toHaveText( + "Не удалось войти. Проверьте адрес и пароль.", + ); + await expect(submit).toHaveText("Войти"); + await expect(password).not.toHaveAttribute("readonly"); + }); + + test(`candidate inbox at ${width}px: loading, error with a keyboard retry, empty, and forbidden`, async ({ + page, + }) => { + const gate = deferred(); + let failing = true; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/invitations": async () => { + await gate.promise; + return failing + ? problem("internal_error", 500) + : { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } }; + }, + }); + await page.goto("/candidate/invitations"); + await expectNoHorizontalOverflow(page, width); + await expect(page.getByText("Загружаем приглашения...")).toBeVisible(); + gate.resolve(); + + // Queries retry server errors twice, so the error appears after the retries. + await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", { + timeout: 15_000, + }); + failing = false; + await tabTo(page, page.getByRole("button", { name: "Повторить" })); + await page.keyboard.press("Enter"); + await expect(page.getByText("Приглашений пока нет")).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + await expectNoHorizontalOverflow(page, width); + }); + + test(`candidate inbox at ${width}px: a dropped connection is named and can be retried`, async ({ + page, + }) => { + let online = false; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/invitations": () => + online + ? { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } } + : "abort", + }); + await page.goto("/candidate/invitations"); + // A network error is retried like a server error, so the message follows the retries. + await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", { + timeout: 15_000, + }); + await expect(page.getByRole("alert")).toContainText("Проверьте подключение к интернету"); + await expectNoHorizontalOverflow(page, width); + online = true; + await tabTo(page, page.getByRole("button", { name: "Повторить" })); + await page.keyboard.press("Enter"); + await expect(page.getByText("Приглашений пока нет")).toBeVisible(); + }); + + test(`candidate inbox at ${width}px: a forbidden answer shows no retry`, async ({ page }) => { + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/invitations": problem("forbidden", 403), + }); + await page.goto("/candidate/invitations"); + await expect(page.getByText("Нет доступа")).toBeVisible(); + await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0); + await expectNoHorizontalOverflow(page, width); + }); + + test(`candidate inbox at ${width}px: an invitation card names the company, the role, and the state in text`, async ({ + page, + }) => { + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/invitations": { + status: 200, + body: { items: [inboxItem()], page: { has_more: false, next_cursor: null } }, + }, + }); + await page.goto("/candidate/invitations"); + const list = page.getByRole("region", { name: "Список приглашений" }); + await expect(list).toBeVisible(); + await expect(list).toContainText("Северный ветер"); + await expect(list).toContainText("Middle Go-разработчик в команду платежей"); + await expect(list).toContainText("Ждет вашего решения"); + await expectNoHorizontalOverflow(page, width); + await tabTo(page, list.getByRole("link").first()); + }); + + test(`candidate invitation at ${width}px: an error with a retry, then a failed decline keeps the comment`, async ({ + page, + }) => { + let failing = true; + let declines = 0; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + [`GET /api/v1/me/invitations/${invitationId}`]: () => + failing ? problem("internal_error", 500) : { status: 200, body: candidateInvitation() }, + [`POST /api/v1/me/invitations/${invitationId}/view`]: { + status: 200, + body: candidateInvitation({ state: "viewed", viewed_at: "2026-10-09T10:05:00Z" }), + }, + [`POST /api/v1/me/invitations/${invitationId}/decline`]: () => { + declines += 1; + if (declines === 1) return problem("internal_error", 500); + return { + status: 200, + body: candidateInvitation({ + state: "declined", + version: 2, + responded_at: "2026-10-09T10:06:00Z", + decline: { + reason: "salary", + comment: "Ждали вилку выше.", + declined_at: "2026-10-09T10:06:00Z", + }, + }), + }; + }, + }); + await page.goto(`/candidate/invitations/${invitationId}`); + await expect(page.getByRole("alert")).toContainText("Не удалось открыть приглашение", { + timeout: 15_000, + }); + failing = false; + await tabTo(page, page.getByRole("button", { name: "Повторить" })); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1, name: "Приглашение" })).toBeVisible(); + await expectNoHorizontalOverflow(page, width); + + await tabTo(page, page.getByLabel("Вилка зарплаты не подходит")); + await page.keyboard.press("Space"); + const comment = page.getByLabel("Комментарий (необязательно)"); + await tabTo(page, comment); + await page.keyboard.type("Ждали вилку выше."); + const decline = page.getByRole("button", { name: "Отклонить приглашение" }); + await tabTo(page, decline); + await page.keyboard.press("Enter"); + + const alert = page.getByRole("alert"); + await expect(alert).toBeVisible(); + await expect(alert).toBeFocused(); + await expect(comment).toHaveValue("Ждали вилку выше."); + await expect(page.getByLabel("Вилка зарплаты не подходит")).toBeChecked(); + await expectNoHorizontalOverflow(page, width); + + await tabTo(page, decline); + await page.keyboard.press("Enter"); + await expect(page.getByText("Вы отклонили приглашение").first()).toBeVisible(); + await expect(page.getByRole("button", { name: "Отклонить приглашение" })).toHaveCount(0); + await expectNoHorizontalOverflow(page, width); + }); + + test(`assessment availability at ${width}px: an error with a retry, then the empty specialization state`, async ({ + page, + }) => { + let failing = true; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/assessment-availability": () => + failing ? problem("internal_error", 500) : { status: 200, body: { specializations: [] } }, + "GET /api/v1/me/questionnaire": { + status: 200, + body: { version: 0, specializations: [], work_context: null, updated_at: null }, + }, + }); + await page.goto("/candidate/assessment"); + await expect(page.getByRole("alert")).toContainText( + "Не удалось загрузить состояние проверки", + { timeout: 15_000 }, + ); + await expectNoHorizontalOverflow(page, width); + failing = false; + await tabTo(page, page.getByRole("button", { name: "Повторить" })); + await page.keyboard.press("Enter"); + await expect(page.getByText("Сначала выберите специализацию")).toBeVisible(); + await expect(page.getByRole("link", { name: "Открыть анкету" })).toBeVisible(); + await expectNoHorizontalOverflow(page, width); + }); + + test(`candidate profile at ${width}px: loading, an error with a retry, and access denied`, async ({ + page, + }) => { + // The profile query does not retry, so the state changes only when the + // candidate presses the retry button: the second answer is a 403. + const release = deferred(); + let stage: "error" | "forbidden" = "error"; + await mockApi(page, { + "GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() }, + "GET /api/v1/me/profile": async () => { + await release.promise; + return stage === "error" ? problem("internal_error", 500) : problem("forbidden", 403); + }, + }); + await page.goto("/candidate/profile"); + await expect(page.getByText("Загружаем профиль кандидата...")).toBeVisible(); + await expectNoHorizontalOverflow(page, width); + release.resolve(); + await expect(page.getByRole("alert")).toContainText("Не удалось загрузить профиль"); + stage = "forbidden"; + await tabTo(page, page.getByRole("button", { name: "Повторить" })); + await page.keyboard.press("Enter"); + await expect(page.getByText("Профиль недоступен")).toBeVisible(); + await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0); + await expectNoHorizontalOverflow(page, width); + }); + } +}); + +// Real-backend part. It needs the mail fixture for registration and the +// questionnaire fixture for a reviewed assessment bank, so it runs only in +// `make -C deploy test-e2e-registration`, like the assessment specs. + +type InboxMessage = { text?: string; html?: string }; +type InboxResponse = { messages: InboxMessage[] }; +type AttemptSnapshot = { id: string; version: number; current_item: { id: string } | null }; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1"; +const password = "correct horse battery staple 2026"; +const draftKeyPrefix = "lincodex.assessment-answer-draft.v1:"; + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) + throw new Error("The local registration mailbox fixture is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as InboxResponse).messages; +} + +async function waitForVerificationMessage(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readInbox(email)).at(-1); + if (message) return message; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local registration mailbox did not receive the verification message."); +} + +function verificationToken(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The local registration message had no verification link."); + return token; +} + +async function registerVerifiedCandidate(page: Page): Promise { + const email = `assessment-${crypto.randomUUID()}@example.test`; + await page.goto("/register"); + await expect( + page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }), + ).toBeVisible(); + await expect(page.getByText(/C4/)).toHaveCount(0); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("radio", { name: /Кандидат/ }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const message = await waitForVerificationMessage(email); + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${verificationToken(message)}`; + await page.goto(verificationUrl.toString()); + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); + await expect.poll(() => page.evaluate(() => window.location.hash)).toBe(""); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + const confirmResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/email-verifications", + ); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + expect((await confirmResponse).status()).toBe(200); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto("/candidate/questionnaire"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await loginResponse).status()).toBe(201); + return email; +} + +async function grantC3(page: Page): Promise { + await page.goto("/candidate/privacy"); + await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); + await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); + const response = page.waitForResponse( + (item) => + item.request().method() === "PUT" && + new URL(item.url()).pathname === "/api/v1/me/consents/c3", + ); + await page.getByRole("button", { name: "Дать согласие C3" }).click(); + expect((await response).status()).toBe(200); +} + +async function saveAssessmentQuestionnaire(page: Page): Promise { + await page.goto("/candidate/questionnaire"); + await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByLabel("Моя оценка уровня").selectOption("junior"); + await page.getByRole("checkbox", { name: "Go", exact: true }).check(); + await page.getByRole("checkbox", { name: "Python", exact: true }).check(); + await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + const response = page.waitForResponse( + (item) => + item.request().method() === "PUT" && + new URL(item.url()).pathname === "/api/v1/me/questionnaire", + ); + await page.getByRole("button", { name: "Сохранить анкету" }).click(); + expect((await response).status()).toBe(200); +} + +// Waits for the control, then walks the Tab order to it with the keyboard and +// checks its focus outline. The control can appear after a save, so the wait is +// longer than the default expectation on a loaded stand. +async function focusWithKeyboard(page: Page, target: Locator): Promise { + await expect(target).toBeVisible({ timeout: 20_000 }); + await tabTo(page, target, 120); +} + +test.describe("minimal path with the real backend", () => { + test.skip( + !mailFixtureEnabled || !questionnaireFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + + test("an unsent answer on a phone survives a reload, and an accepted answer clears it", async ({ + page, + }) => { + test.setTimeout(180_000); + await page.setViewportSize({ width: 360, height: 800 }); + await registerVerifiedCandidate(page); + await grantC3(page); + await saveAssessmentQuestionnaire(page); + + await page.goto("/candidate/assessment"); + await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); + await page.getByLabel("Язык задания").selectOption("python"); + const createResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await focusWithKeyboard(page, page.getByRole("button", { name: "Начать полную проверку" })); + await page.keyboard.press("Enter"); + await expect(page.getByRole("dialog", { name: /какие сигналы собираются/ })).toBeVisible(); + await focusWithKeyboard( + page, + page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }), + ); + await page.keyboard.press("Enter"); + const createResponse = await createResponsePromise; + expect(createResponse.status()).toBe(201); + const attempt = (await createResponse.json()) as AttemptSnapshot; + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); + + const startPromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, + ); + await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" })); + await page.keyboard.press("Enter"); + expect((await startPromise).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + + // The typed answer is not sent: the candidate reloads before submitting it. + const answer = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await focusWithKeyboard(page, answer); + await page.keyboard.type("42"); + await expect + .poll(() => + page.evaluate( + (prefix) => + Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length, + draftKeyPrefix, + ), + ) + .toBe(1); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + + const reloadPromise = page.waitForResponse( + (response) => + response.request().method() === "GET" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}`, + ); + await page.reload(); + expect((await reloadPromise).status()).toBe(200); + const resumePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, + ); + await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" })); + await page.keyboard.press("Enter"); + expect((await resumePromise).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect(page.getByRole("textbox", { name: /^Числовой ответ/ })).toHaveValue("42"); + await expectNoHorizontalOverflow(page, 768); + await expectNoHorizontalOverflow(page, 360); + + // An accepted answer moves to the next item and removes the stored draft. + const answerPromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/answers`, + ); + await focusWithKeyboard(page, page.getByRole("button", { name: "Отправить ответ" })); + await page.keyboard.press("Enter"); + expect((await answerPromise).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); + await expect + .poll(() => + page.evaluate( + (prefix) => + Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length, + draftKeyPrefix, + ), + ) + .toBe(0); + }); +}); diff --git a/frontend/src/features/answer-assessment/index.ts b/frontend/src/features/answer-assessment/index.ts index 0063d30..1348f87 100644 --- a/frontend/src/features/answer-assessment/index.ts +++ b/frontend/src/features/answer-assessment/index.ts @@ -1,5 +1,6 @@ export { AnswerForm } from "./ui/answer-form"; export { buildAnswerSubmission, emptyAnswerDraft, newIdempotencyKey } from "./model/answer-draft"; export { submitPendingAnswerCommand } from "./model/answer-command"; +export { clearAnswerDraft } from "./model/answer-draft-store"; export type { AnswerDraft, AnswerBuildResult } from "./model/answer-draft"; export type { AnswerCommandOutcome, PendingAnswerCommand } from "./model/answer-command"; diff --git a/frontend/src/features/answer-assessment/model/answer-draft-store.test.ts b/frontend/src/features/answer-assessment/model/answer-draft-store.test.ts new file mode 100644 index 0000000..c7ca08c --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-draft-store.test.ts @@ -0,0 +1,191 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { AssessmentItem } from "../../../shared/api/schemas"; +import type { AnswerDraft } from "./answer-draft"; +import { + clearAnswerDraft, + maxStoredDraftLength, + restoredAnswerDraft, + saveAnswerDraft, +} from "./answer-draft-store"; + +const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01"; +const itemId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02"; + +const stringItem = { + id: itemId, + sequence: 1, + prompt: "Назовите протокол", + content: { format: "string", max_length: 64 }, +} satisfies AssessmentItem; + +const orderItem = { + id: itemId, + sequence: 1, + prompt: "Расставьте шаги", + content: { + format: "order", + elements: [ + { id: "a", text: "Первый" }, + { id: "b", text: "Второй" }, + ], + }, +} satisfies AssessmentItem; + +const practiceItem = { + id: itemId, + sequence: 1, + prompt: "Решите задачу", + content: { + format: "practice", + languages: ["python", "go"], + public_examples: [], + max_source_length: 4096, + }, +} satisfies AssessmentItem; + +// A minimal in-memory sessionStorage; its methods can be made to throw. +function fakeSessionStorage() { + const values = new Map(); + return { + values, + failWrites: false, + failReads: false, + getItem(key: string) { + if (this.failReads) throw new Error("blocked"); + return values.get(key) ?? null; + }, + setItem(key: string, value: string) { + if (this.failWrites) throw new Error("quota"); + values.set(key, value); + }, + removeItem(key: string) { + values.delete(key); + }, + }; +} + +function useStorage(store: ReturnType) { + vi.stubGlobal("window", { sessionStorage: store }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("answer draft store", () => { + it("restores an unsent string answer for the same attempt and item", () => { + const store = fakeSessionStorage(); + useStorage(store); + const draft: AnswerDraft = { format: "string", value: "HTTP/2" }; + + saveAnswerDraft(attemptId, itemId, draft); + + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual(draft); + }); + + it("keeps drafts of other attempts and items apart", () => { + const store = fakeSessionStorage(); + useStorage(store); + saveAnswerDraft(attemptId, itemId, { format: "string", value: "HTTP/2" }); + + expect(restoredAnswerDraft("01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d09", stringItem)).toEqual({ + format: "string", + value: "", + }); + expect( + restoredAnswerDraft(attemptId, { ...stringItem, id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03" }), + ).toEqual({ format: "string", value: "" }); + }); + + it("ignores a stored value that does not fit the item format", () => { + const store = fakeSessionStorage(); + useStorage(store); + saveAnswerDraft(attemptId, itemId, { format: "choice", optionIds: ["a"] }); + + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" }); + }); + + it("ignores malformed JSON and an order that is not a permutation of the elements", () => { + const store = fakeSessionStorage(); + useStorage(store); + store.setItem(`lincodex.assessment-answer-draft.v1:${attemptId}:${itemId}`, "{not json"); + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" }); + + saveAnswerDraft(attemptId, itemId, { format: "order", elementIds: ["a", "a"] }); + expect(restoredAnswerDraft(attemptId, orderItem)).toEqual({ + format: "order", + elementIds: ["a", "b"], + }); + }); + + it("restores a practice language only when the item offers it", () => { + const store = fakeSessionStorage(); + useStorage(store); + saveAnswerDraft(attemptId, itemId, { + format: "practice", + language: "go", + sourceCode: "package main", + }); + expect(restoredAnswerDraft(attemptId, practiceItem)).toEqual({ + format: "practice", + language: "go", + sourceCode: "package main", + }); + + saveAnswerDraft(attemptId, itemId, { + format: "practice", + language: "rust" as "go", + sourceCode: "fn main() {}", + }); + // The fallback is the empty draft of the item, whose language is its first one. + expect(restoredAnswerDraft(attemptId, practiceItem)).toEqual({ + format: "practice", + language: "python", + sourceCode: "", + }); + }); + + it("removes a stored draft once the answer is accepted", () => { + const store = fakeSessionStorage(); + useStorage(store); + saveAnswerDraft(attemptId, itemId, { format: "string", value: "HTTP/2" }); + + clearAnswerDraft(attemptId, itemId); + + expect(store.values.size).toBe(0); + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" }); + }); + + it("does not store a draft larger than the limit and drops an older copy", () => { + const store = fakeSessionStorage(); + useStorage(store); + saveAnswerDraft(attemptId, itemId, { format: "string", value: "short" }); + + saveAnswerDraft(attemptId, itemId, { + format: "string", + value: "x".repeat(maxStoredDraftLength), + }); + + expect(store.values.size).toBe(0); + }); + + it("never throws when storage is blocked or full, and falls back to an empty answer", () => { + const store = fakeSessionStorage(); + useStorage(store); + store.failWrites = true; + store.failReads = true; + + expect(() => + saveAnswerDraft(attemptId, itemId, { format: "string", value: "a" }), + ).not.toThrow(); + expect(() => clearAnswerDraft(attemptId, itemId)).not.toThrow(); + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" }); + }); + + it("works without any browser storage, for example outside a window", () => { + expect(() => + saveAnswerDraft(attemptId, itemId, { format: "string", value: "a" }), + ).not.toThrow(); + expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" }); + }); +}); diff --git a/frontend/src/features/answer-assessment/model/answer-draft-store.ts b/frontend/src/features/answer-assessment/model/answer-draft-store.ts new file mode 100644 index 0000000..e49a899 --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-draft-store.ts @@ -0,0 +1,132 @@ +import type { AssessmentItem } from "../../../shared/api/schemas"; +import { emptyAnswerDraft, type AnswerDraft } from "./answer-draft"; + +// An unsent answer is kept in this tab's sessionStorage, so a reload restores +// what the candidate typed. The server never reads this copy. An accepted +// answer removes it, and the attempt itself comes from the server after a +// reload. Storage can be blocked or full, so every access is guarded and the +// form works without it. + +const keyPrefix = "lincodex.assessment-answer-draft.v1"; + +/** Drafts whose JSON is longer than this stay in the form state only. */ +export const maxStoredDraftLength = 64 * 1024; + +function draftKey(attemptId: string, itemId: string): string { + return `${keyPrefix}:${attemptId}:${itemId}`; +} + +function sessionStore(): Storage | null { + try { + return window.sessionStorage; + } catch { + return null; + } +} + +/** Keeps the unsent answer of one item of one attempt; a failed write is ignored. */ +export function saveAnswerDraft(attemptId: string, itemId: string, draft: AnswerDraft): void { + const store = sessionStore(); + if (!store) return; + const key = draftKey(attemptId, itemId); + try { + const value = JSON.stringify(draft); + if (value.length > maxStoredDraftLength) { + store.removeItem(key); + } else { + store.setItem(key, value); + } + } catch { + // A full or blocked store leaves the draft in the form state only. + } +} + +/** Removes the stored draft once the server has accepted the answer. */ +export function clearAnswerDraft(attemptId: string, itemId: string): void { + try { + sessionStore()?.removeItem(draftKey(attemptId, itemId)); + } catch { + // Nothing to clear when storage is blocked. + } +} + +/** + * The draft an item's form starts with: the stored one when it fits the item + * exactly, otherwise the empty draft. The server still validates the answer on + * submit, so a stored value only has to be safe to render. + */ +export function restoredAnswerDraft(attemptId: string, item: AssessmentItem): AnswerDraft { + const fallback = emptyAnswerDraft(item); + let raw: string | null; + try { + raw = sessionStore()?.getItem(draftKey(attemptId, item.id)) ?? null; + } catch { + return fallback; + } + if (raw === null) return fallback; + return parseStoredDraft(raw, item) ?? fallback; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((entry) => typeof entry === "string"); +} + +function parseStoredDraft(raw: string, item: AssessmentItem): AnswerDraft | null { + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return null; + } + if (!isRecord(value) || value.format !== item.content.format) return null; + const content = item.content; + + switch (content.format) { + case "choice": { + const known = new Set(content.options.map((option) => option.id)); + if (!isStringArray(value.optionIds) || !value.optionIds.every((id) => known.has(id))) { + return null; + } + return { format: "choice", optionIds: [...value.optionIds] }; + } + case "number": + return typeof value.value === "string" ? { format: "number", value: value.value } : null; + case "string": + return typeof value.value === "string" ? { format: "string", value: value.value } : null; + case "configuration": + return typeof value.value === "string" + ? { format: "configuration", value: value.value } + : null; + case "order": { + const stored = value.elementIds; + const ids = content.elements.map((element) => element.id); + if ( + !isStringArray(stored) || + stored.length !== ids.length || + !ids.every((id) => stored.includes(id)) + ) { + return null; + } + return { format: "order", elementIds: [...stored] }; + } + case "find_error": + return Array.isArray(value.lineNumbers) && + value.lineNumbers.every((line) => Number.isInteger(line)) + ? { format: "find_error", lineNumbers: value.lineNumbers as number[] } + : null; + case "practice": { + const language = value.language; + const allowed: readonly unknown[] = [null, ...content.languages]; + if (!allowed.includes(language) || typeof value.sourceCode !== "string") return null; + return { + format: "practice", + language: language === null ? null : (language as "go" | "python"), + sourceCode: value.sourceCode, + }; + } + } +} diff --git a/frontend/src/features/answer-assessment/ui/answer-form.tsx b/frontend/src/features/answer-assessment/ui/answer-form.tsx index b0021c1..85596ae 100644 --- a/frontend/src/features/answer-assessment/ui/answer-form.tsx +++ b/frontend/src/features/answer-assessment/ui/answer-form.tsx @@ -1,10 +1,12 @@ -import { useState, type FormEvent } from "react"; +import { useId, useState, type FormEvent } from "react"; import type { AssessmentItem } from "../../../shared/api/schemas"; import { Button } from "../../../shared/ui"; -import { emptyAnswerDraft, type AnswerDraft } from "../model/answer-draft"; +import type { AnswerDraft } from "../model/answer-draft"; +import { restoredAnswerDraft, saveAnswerDraft } from "../model/answer-draft-store"; import styles from "./answer-form.module.css"; type AnswerFormProps = { + attemptId: string; item: AssessmentItem; isSaving: boolean; retryable: boolean; @@ -14,6 +16,7 @@ type AnswerFormProps = { }; export function AnswerForm({ + attemptId, item, isSaving, retryable, @@ -21,23 +24,36 @@ export function AnswerForm({ onSubmit, onRetry, }: AnswerFormProps) { - const [draft, setDraft] = useState(() => emptyAnswerDraft(item)); + // The unsent answer survives a reload in this tab; see answer-draft-store. + const [draft, setDraftState] = useState(() => restoredAnswerDraft(attemptId, item)); + const errorId = useId(); + const setDraft = (next: AnswerDraft) => { + setDraftState(next); + saveAnswerDraft(attemptId, item.id, next); + }; const frozen = isSaving || retryable; function submit(event: FormEvent) { event.preventDefault(); if (frozen) return; + // The fields are disabled while the answer is saved, which would drop the + // focus of a keyboard user; the submit control keeps it instead. + event.currentTarget.querySelector('button[type="submit"]')?.focus(); onSubmit(draft); } return (
-
+
Ваш ответ
{errorMessage ? ( -

+

) : null} diff --git a/frontend/src/features/edit-need/ui/need-editor.tsx b/frontend/src/features/edit-need/ui/need-editor.tsx index 560a198..9cdb521 100644 --- a/frontend/src/features/edit-need/ui/need-editor.tsx +++ b/frontend/src/features/edit-need/ui/need-editor.tsx @@ -287,6 +287,8 @@ export function NeedEditor({ draft.location.status !== "unknown" || draft.salary.status !== "unknown"; const salaryError = salaryInputError(salaryDraft); + const salaryMessage = salaryError ?? fieldErrors.salary ?? null; + const salaryMessageId = `${inputId}-salary-error`; const csrfValid = session.account.id === accountId && session.account.scenario === "employer" && @@ -691,12 +693,17 @@ export function NeedEditor({ required value={draft.title} aria-invalid={Boolean(fieldErrors.title)} + aria-describedby={fieldErrors.title ? `${inputId}-title-error` : undefined} onChange={(event) => { const title = event.currentTarget.value; changeDraft((current) => ({ ...current, title })); }} /> - {fieldErrors.title ?

{fieldErrors.title}

: null} + {fieldErrors.title ? ( +

+ {fieldErrors.title} +

+ ) : null}
@@ -733,6 +740,9 @@ export function NeedEditor({ id={`${inputId}-specialization`} value={draft.specialization.status === "unknown" ? "" : draft.specialization.value} aria-invalid={Boolean(fieldErrors.specialization)} + aria-describedby={ + fieldErrors.specialization ? `${inputId}-specialization-error` : undefined + } onChange={(event) => changeSpecialization(event.currentTarget.value as SpecializationCode | "") } @@ -747,7 +757,9 @@ export function NeedEditor({ {missing("specialization")} {fieldErrors.specialization ? ( -

{fieldErrors.specialization}

+

+ {fieldErrors.specialization} +

) : null} {draft.specialization.status === "extracted" ? (
@@ -910,6 +928,7 @@ export function NeedEditor({ step={1000} value={salaryDraft.to} aria-invalid={Boolean(salaryError || fieldErrors.salary)} + aria-describedby={salaryMessage ? salaryMessageId : undefined} onChange={(event) => changeSalary("to", event.currentTarget.value)} /> @@ -919,6 +938,7 @@ export function NeedEditor({ id={`${inputId}-salary-basis`} value={salaryDraft.taxBasis} aria-invalid={Boolean(salaryError || fieldErrors.salary)} + aria-describedby={salaryMessage ? salaryMessageId : undefined} onChange={(event) => changeSalary("taxBasis", event.currentTarget.value)} > @@ -932,8 +952,10 @@ export function NeedEditor({

{missing("salary")} - {salaryError || fieldErrors.salary ? ( -

{salaryError ?? fieldErrors.salary}

+ {salaryMessage ? ( +

+ {salaryMessage} +

) : null} {draft.salary.status !== "unknown" ? ( - {error ?

{error}

: null} + {error ? ( +

+ {error} +

+ ) : null} ); } @@ -1156,6 +1184,8 @@ function TaskList({ id={`${id}-add`} maxLength={300} disabled={disabled} + aria-invalid={Boolean(error) || undefined} + aria-describedby={error ? `${id}-error` : undefined} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); @@ -1174,7 +1204,11 @@ function TaskList({ Добавить - {error ?

{error}

: null} + {error ? ( +

+ {error} +

+ ) : null} ); } diff --git a/frontend/src/features/send-invitation/ui/invitation-form.tsx b/frontend/src/features/send-invitation/ui/invitation-form.tsx index 09d5a68..d581ec1 100644 --- a/frontend/src/features/send-invitation/ui/invitation-form.tsx +++ b/frontend/src/features/send-invitation/ui/invitation-form.tsx @@ -259,6 +259,9 @@ export function InvitationForm({ function submit(event: FormEvent): void { event.preventDefault(); + // The fields are disabled while the send runs, which would drop the focus + // of a keyboard user; the submit control keeps it instead. + event.currentTarget.querySelector('button[type="submit"]')?.focus(); void send(); } diff --git a/frontend/src/features/sign-in/ui/sign-in-form.tsx b/frontend/src/features/sign-in/ui/sign-in-form.tsx index 7ac63f3..92edc53 100644 --- a/frontend/src/features/sign-in/ui/sign-in-form.tsx +++ b/frontend/src/features/sign-in/ui/sign-in-form.tsx @@ -35,7 +35,9 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) { errors.email = "Введите корректный адрес электронной почты."; } const passwordLength = Array.from(password.normalize("NFKC")).length; - if (passwordLength < 1 || passwordLength > 128) { + if (passwordLength < 1) { + errors.password = "Введите пароль."; + } else if (passwordLength > 128) { errors.password = "Введите пароль длиной не более 128 символов."; } setFieldError(errors); @@ -72,6 +74,8 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) { onUnverified(""); } + // The fields are read-only while the request is pending, not disabled: a + // disabled field drops keyboard focus, and the user would lose the place. return (
void submit(event)} noValidate> @@ -89,7 +93,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) { required maxLength={254} value={email} - disabled={login.isPending} + readOnly={login.isPending} aria-invalid={Boolean(fieldError.email)} aria-describedby={fieldError.email ? `${id}-email-error` : undefined} onChange={(event) => { @@ -117,7 +121,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) { required maxLength={512} value={password} - disabled={login.isPending} + readOnly={login.isPending} aria-invalid={Boolean(fieldError.password)} aria-describedby={fieldError.password ? `${id}-password-error` : undefined} onChange={(event) => { diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx index 04b1154..2c2a717 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx @@ -44,6 +44,7 @@ import { import { AnswerForm, buildAnswerSubmission, + clearAnswerDraft, newIdempotencyKey, submitPendingAnswerCommand, } from "../../../features/answer-assessment"; @@ -325,6 +326,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { } if (outcome.kind === "rejected") throw outcome.error; const saved = outcome.attempt; + clearAnswerDraft(currentAttemptId, command.itemId); const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId); queryClient.setQueryData(key, (current) => current && current.version > saved.version ? current : saved, @@ -604,6 +606,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {

{currentItem.prompt}