From c836d02ea3fc44b4d0f66310125d1a993b524bdb Mon Sep 17 00:00:00 2001 From: shira Date: Sat, 10 Oct 2026 09:50:27 +0300 Subject: [PATCH] feat(frontend): redesign the candidate cabinet with step-by-step profile and questionnaire forms --- docs/en/TESTING.md | 6 +- docs/ru/TESTING.md | 6 +- frontend/e2e/assessment.spec.ts | 32 + frontend/e2e/candidate-home.spec.ts | 13 + frontend/e2e/minimal-path-a11y.spec.ts | 7 + frontend/e2e/privacy-visibility.spec.ts | 9 + frontend/e2e/profile-edit.spec.ts | 61 +- frontend/e2e/questionnaire.spec.ts | 74 +- .../ui/assessment-result-view.module.css | 38 +- .../assessment/ui/assessment-result-view.tsx | 10 +- .../ui/accept-contact-consent-form.module.css | 23 +- .../ui/answer-form.module.css | 122 ++- .../answer-assessment/ui/answer-form.tsx | 46 +- .../ui/consent-management.module.css | 49 +- .../ui/consent-management.tsx | 66 +- .../ui/create-support-case.module.css | 52 +- .../edit-profile/model/profile-steps.test.ts | 16 + .../edit-profile/model/profile-steps.ts | 26 + .../edit-profile/ui/edit-profile.module.css | 101 +- .../features/edit-profile/ui/edit-profile.tsx | 150 ++- .../edit-profile/ui/form-steps.module.css | 140 +++ .../features/edit-profile/ui/form-steps.tsx | 111 +++ .../edit-profile/ui/profile-form.module.css | 258 +++-- .../edit-profile/ui/profile-form.test.tsx | 23 + .../features/edit-profile/ui/profile-form.tsx | 911 ++++++++++++------ .../edit-profile/ui/use-form-steps.ts | 66 ++ .../model/questionnaire-form.test.ts | 15 + .../model/questionnaire-form.ts | 15 + .../ui/fill-questionnaire.module.css | 112 ++- .../ui/fill-questionnaire.tsx | 219 +++-- .../ui/form-steps.module.css | 140 +++ .../fill-questionnaire/ui/form-steps.tsx | 111 +++ .../ui/questionnaire-form.module.css | 285 +++--- .../ui/questionnaire-form.test.tsx | 13 + .../ui/questionnaire-form.tsx | 718 ++++++++++---- .../fill-questionnaire/ui/use-form-steps.ts | 66 ++ .../ui/notification-inbox.module.css | 26 +- .../notifications/ui/notification-inbox.tsx | 17 +- .../ui/visibility-controls.module.css | 26 +- .../ui/request-manual-assessment.module.css | 24 +- .../ui/decline-invitation-form.module.css | 23 +- .../ui/assessment-result-page.tsx | 12 +- .../ui/assessment-results-page.tsx | 1 - .../pages/assessment/model/countdown.test.ts | 19 + .../src/pages/assessment/model/countdown.ts | 29 + .../assessment/model/express-start.test.ts | 140 +++ .../pages/assessment/model/express-start.ts | 206 ++++ .../ui/assessment-attempt-page.module.css | 249 ++++- .../assessment/ui/assessment-attempt-page.tsx | 267 +++-- .../ui/assessment-express-start.test.ts | 187 ++++ .../assessment/ui/assessment-page.model.ts | 79 +- .../assessment/ui/assessment-page.module.css | 157 ++- .../pages/assessment/ui/assessment-page.tsx | 229 +++-- .../pages/assessment/ui/attempt-focus-bar.tsx | 89 ++ .../candidate-home/ui/candidate-home-page.tsx | 26 +- .../model/status-tone.test.ts | 32 + .../model/status-tone.ts | 31 + .../ui/candidate-invitation-page.tsx | 68 +- .../ui/candidate-invitations-page.tsx | 36 +- .../ui/candidate-invitations.module.css | 117 ++- .../ui/candidate-onboarding-page.module.css | 64 ++ .../ui/candidate-onboarding-page.tsx | 101 +- .../ui/notifications-pages.test.tsx | 4 +- .../notifications/ui/notifications-pages.tsx | 2 +- .../pages/privacy/ui/privacy-page.module.css | 82 +- .../src/pages/privacy/ui/privacy-page.tsx | 239 +++-- .../src/pages/profile/ui/profile-page.tsx | 1 - .../questionnaire/ui/questionnaire-page.tsx | 1 - .../ui/support-cases-pages.module.css | 21 +- .../support-cases/ui/support-cases-pages.tsx | 22 +- .../ui/assessment-history-list.tsx | 6 +- .../ui/assessment-history.module.css | 46 +- .../ui/assessment-history.tsx | 26 +- .../ui/candidate-next-step.module.css | 74 +- .../ui/candidate-next-step.tsx | 74 +- .../ui/candidate-shell.module.css | 20 + .../candidate-shell/ui/candidate-shell.tsx | 44 +- 77 files changed, 5409 insertions(+), 1618 deletions(-) create mode 100644 frontend/src/features/edit-profile/model/profile-steps.test.ts create mode 100644 frontend/src/features/edit-profile/model/profile-steps.ts create mode 100644 frontend/src/features/edit-profile/ui/form-steps.module.css create mode 100644 frontend/src/features/edit-profile/ui/form-steps.tsx create mode 100644 frontend/src/features/edit-profile/ui/use-form-steps.ts create mode 100644 frontend/src/features/fill-questionnaire/ui/form-steps.module.css create mode 100644 frontend/src/features/fill-questionnaire/ui/form-steps.tsx create mode 100644 frontend/src/features/fill-questionnaire/ui/use-form-steps.ts create mode 100644 frontend/src/pages/assessment/model/countdown.test.ts create mode 100644 frontend/src/pages/assessment/model/countdown.ts create mode 100644 frontend/src/pages/assessment/model/express-start.test.ts create mode 100644 frontend/src/pages/assessment/model/express-start.ts create mode 100644 frontend/src/pages/assessment/ui/assessment-express-start.test.ts create mode 100644 frontend/src/pages/assessment/ui/attempt-focus-bar.tsx create mode 100644 frontend/src/pages/candidate-invitations/model/status-tone.test.ts create mode 100644 frontend/src/pages/candidate-invitations/model/status-tone.ts create mode 100644 frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.module.css diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index d881ed8..1d25b06 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -83,7 +83,7 @@ In the same mode, the runner invokes `/consent-fixture` from the test backend im The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser. -`frontend/e2e/profile-edit.spec.ts` fills the manual profile at 360px after real registration, acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step. +`frontend/e2e/profile-edit.spec.ts` walks the steps of the manual profile at 360px after real registration ("Далее" with the focus on the heading, a step blocked until overlapping periods are confirmed, "Назад" without losing data), acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step. `frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data. @@ -453,9 +453,9 @@ Unit tests (`make -C backend test`) check the profile rules without a database: The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged. -`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled. +`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario walks the questionnaire steps (step validation, the focus on the heading, "Назад" and "Изменить" without losing answers) and covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled. -`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training, offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration. +`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration. ## Candidate visibility tests diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 35d81e8..dc4b3d1 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -83,7 +83,7 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется. -`frontend/e2e/profile-edit.spec.ts` заполняет ручной профиль на 360 px после реальной регистрации, подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля. +`frontend/e2e/profile-edit.spec.ts` проходит шаги ручного профиля на 360 px после реальной регистрации (переход "Далее" с фокусом на заголовке, блокировка шага без подтверждения пересечения, "Назад" без потери данных), подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля. `frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные. @@ -453,9 +453,9 @@ Unit-тесты (`make -C backend test`) проверяют правила жу Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются. -`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается. +`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проходит шаги анкеты (проверка шага, фокус на заголовке, "Назад" и "Изменить" без потери ответов) и проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается. -`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим, отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки. +`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки. ## Тесты видимости кандидата diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index 622dadc..560b6dc 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -131,11 +131,18 @@ async function grantC3(page: Page): Promise { async function saveAssessmentQuestionnaire(page: Page): Promise { await page.goto("/candidate/questionnaire"); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + // The questionnaire is a form in steps; "Далее" moves the focus to the next heading. await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); 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("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); const response = page.waitForResponse( (item) => item.request().method() === "PUT" && @@ -369,6 +376,31 @@ test("candidate can review, resume, and finish separate assessment modes", async const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot; expect(firstExpressSnapshot.current_item?.id).toBeTruthy(); + // An unfinished express run is resumed: after a full reload of the + // assessment page, a new start answers 409, and the page replays the start + // with the key stored in this tab, which returns the stored 201 of the run. + await page.goto("/candidate/assessment"); + await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible(); + const expressStarts: { status: number; key: string | null }[] = []; + const recordExpressStart = (response: Response) => { + if ( + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts" + ) { + expressStarts.push({ + status: response.status(), + key: response.request().headers()["idempotency-key"] ?? null, + }); + } + }; + page.on("response", recordExpressStart); + await page.getByRole("button", { name: "Начать демонстрацию" }).click(); + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`)); + await expect(page.getByText("Незавершенная демонстрация продолжена")).toBeVisible(); + page.off("response", recordExpressStart); + expect(expressStarts.map((start) => start.status)).toEqual([409, 201]); + expect(expressStarts[0]?.key).not.toBe(expressStarts[1]?.key); + await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0); diff --git a/frontend/e2e/candidate-home.spec.ts b/frontend/e2e/candidate-home.spec.ts index 772352e..cabdce4 100644 --- a/frontend/e2e/candidate-home.spec.ts +++ b/frontend/e2e/candidate-home.spec.ts @@ -159,6 +159,13 @@ test.describe("candidate home with the real backend", () => { await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click(); await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible(); await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат"); + // The profile is a form in steps: walk to the review step, then save. + for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect( + page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }), + ).toBeFocused(); + } const profileSaved = page.waitForResponse( (response) => response.request().method() === "PUT" && @@ -173,9 +180,15 @@ test.describe("candidate home with the real backend", () => { await page.getByRole("link", { name: "Заполнить анкету", exact: true }).first().click(); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); await page.getByLabel("Моя оценка уровня").selectOption("middle"); await page.getByRole("checkbox", { name: "Python", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); const questionnaireSaved = page.waitForResponse( (response) => response.request().method() === "PUT" && diff --git a/frontend/e2e/minimal-path-a11y.spec.ts b/frontend/e2e/minimal-path-a11y.spec.ts index 5289aa2..c5c9939 100644 --- a/frontend/e2e/minimal-path-a11y.spec.ts +++ b/frontend/e2e/minimal-path-a11y.spec.ts @@ -606,11 +606,18 @@ async function grantC3(page: Page): Promise { async function saveAssessmentQuestionnaire(page: Page): Promise { await page.goto("/candidate/questionnaire"); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + // The questionnaire is a form in steps; "Далее" moves the focus to the next heading. await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); 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("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); const response = page.waitForResponse( (item) => item.request().method() === "PUT" && diff --git a/frontend/e2e/privacy-visibility.spec.ts b/frontend/e2e/privacy-visibility.spec.ts index c6ada1f..68bc0e4 100644 --- a/frontend/e2e/privacy-visibility.spec.ts +++ b/frontend/e2e/privacy-visibility.spec.ts @@ -394,12 +394,21 @@ test.describe("candidate without a confirmed grade with the real backend", () => // Two declared specializations in the profile, none confirmed by a test. await page.goto("/candidate/profile"); await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат"); + // The profile is a form in steps: roles are the second step. + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Роли$/ })).toBeFocused(); await page.getByRole("button", { name: "Добавить специализацию" }).click(); await page.getByRole("button", { name: "Добавить специализацию" }).click(); await page.getByLabel("Специализация").nth(0).selectOption("backend"); await page.getByLabel("Специализация").nth(1).selectOption("network_engineer"); await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle"); await page.getByLabel("Моя оценка уровня").nth(1).selectOption("junior"); + for (const heading of ["Опыт", "Навыки", "Условия", "Проверка"]) { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect( + page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }), + ).toBeFocused(); + } const profileSaved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile")); await page.getByRole("button", { name: "Сохранить профиль" }).click(); expect((await profileSaved).status()).toBe(200); diff --git a/frontend/e2e/profile-edit.spec.ts b/frontend/e2e/profile-edit.spec.ts index 6471e10..8aca735 100644 --- a/frontend/e2e/profile-edit.spec.ts +++ b/frontend/e2e/profile-edit.spec.ts @@ -109,7 +109,36 @@ test.describe("candidate profile", () => { } } + // The profile is a form in steps. "Далее" checks the visible step and moves + // the focus to the heading of the next one; the save is on the last step. + async function nextStep(page: Page, heading: string): Promise { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); + } + + async function editStep(page: Page, step: string, heading: string): Promise { + await page.getByRole("button", { name: `Изменить: ${step}` }).click(); + await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); + } + + async function openReview(page: Page): Promise { + const save = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ }); + const jump = page.getByRole("button", { name: "К проверке и сохранению" }); + if (await save.isVisible()) return; + if (await jump.isVisible()) { + await jump.click(); + await expect(page.getByRole("heading", { name: /\. Проверка$/ })).toBeFocused(); + return; + } + for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) { + if (await save.isVisible()) break; + await nextStep(page, heading); + } + await expect(save).toBeVisible(); + } + async function saveProfile(page: Page, expectedStatus = 200): Promise { + await openReview(page); const responsePromise = page.waitForResponse( (response) => response.request().method() === "PUT" && @@ -182,29 +211,47 @@ test.describe("candidate profile", () => { await page.getByLabel("Телефон").fill("+79990000000"); await page.getByLabel("Telegram").fill("@candidate_123"); + await expect(page.getByText("Шаг 1 из 6", { exact: true })).toBeVisible(); + await nextStep(page, "Роли"); + await page.getByRole("button", { name: "Добавить специализацию" }).click(); + await page.getByLabel("Специализация").selectOption("backend"); + await page.getByLabel("Моя оценка уровня").selectOption("senior"); + + await nextStep(page, "Опыт"); await page.getByRole("button", { name: "Добавить место работы" }).click(); await page.getByRole("button", { name: "Добавить место работы" }).click(); + const experienceSpecialization = page.getByLabel("Специализация").filter({ visible: true }); await page.getByLabel("Компания").nth(0).fill("Первая компания"); await page.getByLabel("Компания").nth(1).fill("Вторая компания"); - await page.getByLabel("Специализация").nth(0).selectOption("backend"); - await page.getByLabel("Специализация").nth(1).selectOption("frontend"); + await experienceSpecialization.nth(0).selectOption("backend"); + await experienceSpecialization.nth(1).selectOption("frontend"); await page.getByLabel("Начало работы").nth(0).fill("2024-01"); await page.getByLabel("Окончание работы").nth(0).fill("2024-12"); await page.getByLabel("Начало работы").nth(1).fill("2024-06"); await page.getByLabel("Окончание работы").nth(1).fill("2025-01"); + // The overlapping periods block the step until they are confirmed. + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect( + page.getByRole("alert").filter({ hasText: "действительно шли параллельно" }), + ).toBeFocused(); await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check(); - await page.getByRole("button", { name: "Добавить специализацию" }).click(); - await page.getByLabel("Специализация").nth(2).selectOption("backend"); - await page.getByLabel("Моя оценка уровня").selectOption("senior"); + await nextStep(page, "Навыки"); await page.getByRole("button", { name: "Добавить навык" }).click(); await page.getByLabel("Навык 1", { exact: true }).fill("Go"); await page.getByRole("button", { name: "Добавить гибкий навык" }).click(); await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация"); + await nextStep(page, "Условия"); await page.getByLabel("Желаемое место работы").fill("Москва"); await page.getByLabel("Готовность к переезду").selectOption("true"); await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000"); await page.getByLabel("Сумма до или после налога").selectOption("gross"); + await nextStep(page, "Проверка"); + // Back keeps the entered data. + await page.getByRole("button", { name: "Назад", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Условия$/ })).toBeFocused(); + await expect(page.getByLabel("Желаемое место работы")).toHaveValue("Москва"); + await nextStep(page, "Проверка"); const pausedSave = await pauseProfileSave(page); try { @@ -226,6 +273,7 @@ test.describe("candidate profile", () => { ).toBeVisible(); await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible(); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name); + await editStep(page, "опыт", "Опыт"); await expect( page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/), ).toBeVisible(); @@ -287,9 +335,11 @@ test.describe("candidate profile", () => { await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click(); await latestRead; await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName); + await editStep(page, "контакты", "Контакты"); await page.getByLabel("Имя и фамилия").fill(staleName); await saveProfile(page); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName); + await editStep(page, "контакты", "Контакты"); await expectResponsiveKeyboardFlow(page); await page.reload(); @@ -303,6 +353,7 @@ test.describe("candidate profile", () => { const firstAccount = await registerCandidate(page); const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`; await page.getByLabel("Имя и фамилия").fill(firstProfileName); + await openReview(page); const pausedSave = await pauseProfileSave(page); try { diff --git a/frontend/e2e/questionnaire.spec.ts b/frontend/e2e/questionnaire.spec.ts index 7ca3f98..4af55fa 100644 --- a/frontend/e2e/questionnaire.spec.ts +++ b/frontend/e2e/questionnaire.spec.ts @@ -170,6 +170,30 @@ async function saveFromKeyboard(page: Page, expectedStatus: number): Promise { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); +} + +async function editStep(page: Page, step: string, heading: string): Promise { + await page.getByRole("button", { name: `Изменить: ${step}` }).click(); + await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); +} + +async function fillAnswers( + page: Page, + answers: { specialization: string; grade: string; formats: string[] }, +): Promise { + await page.getByLabel("Специализация", { exact: true }).selectOption(answers.specialization); + await nextStep(page, "Уровень и опыт"); + await page.getByLabel("Моя оценка уровня").selectOption(answers.grade); + await nextStep(page, "Формат работы"); + for (const format of answers.formats) await page.getByLabel(format).check(); + await nextStep(page, "Проверка и сохранение"); +} + async function createSecondSession(browser: Browser, email: string): Promise { const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); const page = await context.newPage(); @@ -228,25 +252,44 @@ test.describe("candidate questionnaire", () => { expect(initial.version).toBe(0); const specialization = page.getByLabel("Специализация", { exact: true }); + await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible(); await specialization.selectOption("ds_ml"); await expect(page.getByText("Проверка: в разработке")).toBeVisible(); await expect( page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."), ).toBeVisible(); await expect(page.getByRole("button", { name: /проверку/i })).toHaveCount(0); + // A step with a missing answer does not let the form move on. + await nextStep(page, "Уровень и опыт"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect( + page.getByRole("alert").filter({ hasText: "Укажите свою оценку уровня." }), + ).toBeFocused(); + await expect(page.getByLabel("Моя оценка уровня")).toHaveAttribute("aria-invalid", "true"); await page.getByLabel("Моя оценка уровня").selectOption("senior"); + await nextStep(page, "Формат работы"); await page.getByLabel("Удаленно").check(); + await nextStep(page, "Проверка и сохранение"); + // Going back keeps what was entered. + await page.getByRole("button", { name: "Назад", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); + await expect(page.getByLabel("Удаленно")).toBeChecked(); + await nextStep(page, "Проверка и сохранение"); await saveFromKeyboard(page, 200); await expect( page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/), ).toBeVisible(); await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible(); + await editStep(page, "направления", "Направления"); await specialization.selectOption("backend"); + await nextStep(page, "Уровень и опыт"); await page.getByLabel("Моя оценка уровня").selectOption("junior"); await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByLabel("Стек технологий").fill("Go"); await page.getByRole("button", { name: "Добавить технологию" }).click(); + await nextStep(page, "Формат работы"); + await nextStep(page, "Проверка и сохранение"); const backendSave = page.waitForResponse( (response) => response.request().method() === "PUT" && @@ -267,9 +310,13 @@ test.describe("candidate questionnaire", () => { ]); await expect(page.getByText(/Анкета сохранена/)).toBeVisible(); await page.reload(); + // A reload restores the server record and opens the first step. + await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible(); await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("backend"); await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("junior"); - await expect(page.getByRole("checkbox", { name: "Go", exact: true })).toBeChecked(); + await expect( + page.getByRole("checkbox", { name: "Go", exact: true, includeHidden: true }), + ).toBeChecked(); await expect(page.getByLabel("Стек технологий")).toHaveValue(""); await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible(); await page.screenshot({ @@ -280,7 +327,10 @@ test.describe("candidate questionnaire", () => { const secondPage = await createSecondSession(browser, email); try { await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); + await nextStep(secondPage, "Уровень и опыт"); await secondPage.getByLabel("Моя оценка уровня").selectOption("senior"); + await nextStep(secondPage, "Формат работы"); + await nextStep(secondPage, "Проверка и сохранение"); const concurrentSave = secondPage.waitForResponse( (response) => response.request().method() === "PUT" && @@ -289,8 +339,11 @@ test.describe("candidate questionnaire", () => { await secondPage.getByRole("button", { name: "Сохранить анкету" }).click(); expect((await concurrentSave).status()).toBe(200); + await nextStep(page, "Уровень и опыт"); + await nextStep(page, "Формат работы"); await page.getByLabel("Удаленно").uncheck(); await page.getByLabel("В офисе").check(); + await nextStep(page, "Проверка и сохранение"); const staleSave = page.waitForResponse( (response) => response.request().method() === "PUT" && @@ -319,6 +372,7 @@ test.describe("candidate questionnaire", () => { await expect(secondPage.getByLabel("В офисе")).toBeChecked(); await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked(); + await editStep(page, "направления", "Направления"); await checkResponsiveLayout(page); } finally { await secondPage.context().close(); @@ -361,9 +415,7 @@ test.describe("candidate questionnaire", () => { ); await registerVerifiedCandidate(page); - await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); - await page.getByLabel("Моя оценка уровня").selectOption("senior"); - await page.getByLabel("Удаленно").check(); + await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] }); await page.route("**/api/v1/me/questionnaire", async (route) => { if (route.request().method() === "PUT") { await fulfillProblem(route, 403, "forbidden"); @@ -393,9 +445,7 @@ test.describe("candidate questionnaire", () => { ); await registerVerifiedCandidate(page); - await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); - await page.getByLabel("Моя оценка уровня").selectOption("senior"); - await page.getByLabel("Удаленно").check(); + await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] }); let rejectSessionRefresh = false; await page.route("**/api/v1/identity/sessions/current", async (route) => { if (rejectSessionRefresh) { @@ -455,9 +505,7 @@ test.describe("candidate questionnaire", () => { } await registerVerifiedCandidate(page); - await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); - await page.getByLabel("Моя оценка уровня").selectOption("senior"); - await page.getByLabel("Удаленно").check(); + await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] }); let releaseOldResponse: () => void = () => undefined; let markOldRequestHeld: () => void = () => undefined; @@ -517,7 +565,11 @@ test.describe("candidate questionnaire", () => { expect((await oldSaveResponse).status()).toBe(200); await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue(""); await expect(page.getByLabel("Моя оценка уровня")).toHaveValue(""); - await expect(page.getByRole("button", { name: "Сохранить анкету" })).toBeEnabled(); + // The new account's editor opens at its first step and is not saving: + // the fields and the step action are enabled. + await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible(); + await expect(page.getByLabel("Специализация", { exact: true })).toBeEnabled(); + await expect(page.getByRole("button", { name: "Далее", exact: true })).toBeEnabled(); await expect(page.getByRole("button", { name: "Сохраняем анкету..." })).toHaveCount(0); } finally { cleanupStarted = true; diff --git a/frontend/src/entities/assessment/ui/assessment-result-view.module.css b/frontend/src/entities/assessment/ui/assessment-result-view.module.css index 526a4b0..c42c9c6 100644 --- a/frontend/src/entities/assessment/ui/assessment-result-view.module.css +++ b/frontend/src/entities/assessment/ui/assessment-result-view.module.css @@ -1,16 +1,18 @@ +/* A card of the system; a demonstration run has a dashed boundary, so it is + * never mistaken for a qualification result. */ .root { display: grid; gap: var(--space-4); min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); - border-inline-start: var(--line-strong) solid var(--color-accent); border-radius: var(--radius-m); - background: var(--color-canvas); + background: var(--color-surface); } .root[data-express="true"] { - border-inline-start-style: dashed; + border-style: dashed; + border-color: var(--color-border-hover); } .root p { @@ -24,7 +26,8 @@ } .kind { - color: var(--color-text-secondary); + color: var(--color-accent); + font-family: var(--font-mono); font-size: var(--font-size-xs); letter-spacing: var(--letter-spacing-label); text-transform: uppercase; @@ -32,6 +35,7 @@ .title { margin: 0; + color: var(--color-text-strong); font-size: var(--font-size-xl); line-height: var(--line-height-snug); overflow-wrap: anywhere; @@ -47,17 +51,12 @@ display: none; } -.badge { - padding: var(--space-1) var(--space-3); - border: var(--line-strong) solid var(--color-border-strong); - border-radius: var(--radius-pill); - font-size: var(--font-size-xs); - font-weight: var(--font-weight-bold); -} - .summary { - font-size: var(--font-size-m); - font-weight: var(--font-weight-bold); + color: var(--color-text-strong); + font-family: var(--font-mono); + font-size: 1.125rem; + font-weight: var(--font-weight-medium); + line-height: var(--line-height-snug); } .demo { @@ -87,6 +86,13 @@ overflow-wrap: anywhere; } +/* The decision facts as small readouts on nested surfaces. */ +.facts-main > div { + padding: var(--space-3); + border-radius: var(--radius-s); + background: var(--color-canvas); +} + .block { display: grid; gap: var(--space-3); @@ -119,6 +125,6 @@ @media (width < 42rem) { .root { - padding: var(--space-3); + padding: var(--space-4); } } diff --git a/frontend/src/entities/assessment/ui/assessment-result-view.tsx b/frontend/src/entities/assessment/ui/assessment-result-view.tsx index 86ef7da..0d4aa27 100644 --- a/frontend/src/entities/assessment/ui/assessment-result-view.tsx +++ b/frontend/src/entities/assessment/ui/assessment-result-view.tsx @@ -1,7 +1,7 @@ import { useId, type ReactNode } from "react"; import type { AssessmentResult } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config/paths"; -import { ButtonLink, Mono } from "../../../shared/ui"; +import { ButtonLink, Mono, Tag } from "../../../shared/ui"; import { describeAssessmentResult } from "../model/result-presentation"; import styles from "./assessment-result-view.module.css"; @@ -54,9 +54,11 @@ export function AssessmentResultView({ {view.title}

- {view.isExpress ? Демонстрация : null} + {view.isExpress ? Демонстрация : null} {!view.isExpress && view.isProvisional ? ( - Предварительный результат + + Предварительный результат + ) : null}

@@ -72,7 +74,7 @@ export function AssessmentResultView({ ) : null} -
+
{view.facts.map((fact) => (
{fact.label}
diff --git a/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css index d99dfd0..7afd3c3 100644 --- a/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css +++ b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css @@ -1,16 +1,17 @@ .form { display: grid; gap: var(--space-4); + align-content: start; min-width: 0; - padding: var(--space-4); - border: var(--line-strong) solid var(--color-accent); + padding: var(--space-5); + border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); } .title { + color: var(--color-text-strong); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); } .fieldset { @@ -71,9 +72,9 @@ min-height: 2.75rem; min-width: 0; padding: var(--space-2) var(--space-3); - border: var(--line-thin) solid var(--color-divider); + border: var(--line-thin) solid var(--color-border-strong); border-radius: var(--radius-s); - background: var(--color-surface); + background: var(--color-canvas); line-height: var(--line-height-body); cursor: pointer; } @@ -91,18 +92,24 @@ overflow-wrap: anywhere; } +.option:has(input:checked) { + border-color: var(--color-accent); + background: var(--color-accent-tint); +} + .option:has(input:focus-visible) { outline: var(--focus-ring-width) solid var(--color-focus-ring); outline-offset: var(--focus-ring-offset); } .alert { - padding: var(--space-3); - border: var(--line-strong) solid var(--color-danger); + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-danger); border-radius: var(--radius-s); - background: var(--color-surface); color: var(--color-text); line-height: var(--line-height-body); + background: + linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas); } .alert:focus-visible { diff --git a/frontend/src/features/answer-assessment/ui/answer-form.module.css b/frontend/src/features/answer-assessment/ui/answer-form.module.css index 984da64..90dce99 100644 --- a/frontend/src/features/answer-assessment/ui/answer-form.module.css +++ b/frontend/src/features/answer-assessment/ui/answer-form.module.css @@ -4,49 +4,116 @@ min-width: 0; } +/* The answer sits directly in the item panel: no second frame around it. */ .fields, .code-lines { display: grid; gap: var(--space-3); min-width: 0; margin: 0; - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); + padding: 0; + border: 0; } .legend, .code-lines legend { - padding: 0 var(--space-2); - font-weight: var(--font-weight-bold); + float: left; + width: 100%; + margin-bottom: var(--space-1); + padding: 0; + color: var(--color-text-secondary); + font-family: var(--font-mono); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; } .options, .practice { display: grid; - gap: var(--space-3); + gap: var(--space-2); min-width: 0; } +/* An option is a nested surface; a keycap gives its keyboard digit. The + * chosen option gets the accent border and tint and its native mark. */ .option, .code-line { display: flex; - align-items: flex-start; gap: var(--space-3); + align-items: flex-start; min-width: 0; - padding: var(--space-3); + padding: var(--space-3) var(--space-4); border: var(--line-thin) solid var(--color-border-strong); border-radius: var(--radius-s); + background: var(--color-canvas); cursor: pointer; + transition: + border-color var(--duration-fast) var(--easing-standard), + background-color var(--duration-fast) var(--easing-standard); +} + +.code-line { + align-items: baseline; + font-family: var(--font-mono); + overflow-wrap: anywhere; +} + +.option:hover, +.code-line:hover { + border-color: var(--color-text-secondary); +} + +.option[data-checked], +.code-line:has(input:checked) { + border-color: var(--color-accent); + background: var(--color-accent-tint); +} + +.option:has(input:focus-visible) { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); } .option input, .code-line input { flex: 0 0 auto; - width: 1.2rem; - height: 1.2rem; - margin-block-start: 0.15rem; - accent-color: var(--color-action); + margin-block-start: 0.2rem; +} + +.option-text { + min-width: 0; + line-height: var(--line-height-body); + overflow-wrap: anywhere; +} + +.keycap, +.keys kbd { + display: inline-grid; + flex: none; + place-items: center; + min-width: 1.5rem; + height: 1.5rem; + padding: 0 var(--space-1); + border: var(--line-thin) solid var(--color-border-hover); + border-radius: var(--radius-xs); + color: var(--color-text-secondary); + font-family: var(--font-mono); + font-size: var(--font-size-xs); + background: var(--color-surface-elevated); +} + +.keys { + color: var(--color-text-muted); + font-size: var(--font-size-xs); +} + +.keys kbd { + display: inline-flex; + min-width: 1.25rem; + height: 1.25rem; + vertical-align: 0.05em; } .field { @@ -61,15 +128,14 @@ .field textarea { width: 100%; min-width: 0; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); - color: var(--color-text); - background: var(--color-surface); - font: inherit; font-weight: var(--font-weight-regular); } +.field input { + font-family: var(--font-mono); +} + .field textarea { resize: vertical; font-family: var(--font-mono); @@ -77,13 +143,6 @@ overflow-wrap: anywhere; } -.field :is(input, select, textarea):focus-visible, -.option input:focus-visible, -.code-line input:focus-visible { - outline: var(--line-strong) solid var(--color-accent); - outline-offset: 2px; -} - .hint { margin: 0; color: var(--color-text-secondary); @@ -109,6 +168,7 @@ padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); border-radius: var(--radius-s); + background: var(--color-canvas); } .order-actions, @@ -119,16 +179,6 @@ align-items: center; } -.code-lines { - padding-inline: var(--space-3); -} - -.code-line { - align-items: baseline; - font-family: var(--font-mono); - overflow-wrap: anywhere; -} - .line-number { flex: 0 0 2.5rem; color: var(--color-text-secondary); @@ -171,10 +221,6 @@ } @media (width < 42rem) { - .fields { - padding: var(--space-3); - } - .order-item { align-items: flex-start; } diff --git a/frontend/src/features/answer-assessment/ui/answer-form.tsx b/frontend/src/features/answer-assessment/ui/answer-form.tsx index 85596ae..1c6cd61 100644 --- a/frontend/src/features/answer-assessment/ui/answer-form.tsx +++ b/frontend/src/features/answer-assessment/ui/answer-form.tsx @@ -1,4 +1,4 @@ -import { useId, useState, type FormEvent } from "react"; +import { useId, useState, type FormEvent, type KeyboardEvent } from "react"; import type { AssessmentItem } from "../../../shared/api/schemas"; import { Button } from "../../../shared/ui"; import type { AnswerDraft } from "../model/answer-draft"; @@ -42,8 +42,33 @@ export function AnswerForm({ onSubmit(draft); } + // Keyboard first: digits 1-9 pick an option of a choice item, and Enter on + // an option sends the answer like Enter in a text field. Text fields keep + // their digits; modifier keys are left to the browser and assistive tools. + function handleKeyDown(event: KeyboardEvent) { + if (frozen || event.altKey || event.ctrlKey || event.metaKey) return; + const target = event.target as HTMLElement; + const isOption = + target instanceof HTMLInputElement && (target.type === "radio" || target.type === "checkbox"); + if (event.key === "Enter" && isOption) { + event.preventDefault(); + event.currentTarget.requestSubmit(); + return; + } + if (item.content.format !== "choice" || !/^[1-9]$/.test(event.key)) return; + if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return; + if (target instanceof HTMLInputElement && !isOption) return; + const option = event.currentTarget.querySelectorAll( + `input[name="answer-${item.id}"]`, + )[Number(event.key) - 1]; + if (!option) return; + event.preventDefault(); + option.focus(); + option.click(); + } + return ( -
+
Ваш ответ + {item.content.format === "choice" ? ( +

+ 1-{Math.min(item.content.options.length, 9)} выбирают вариант,{" "} + Enter отправляет ответ. +

+ ) : null}
{errorMessage ? (
- {content.options.map((option) => { + {content.options.map((option, index) => { const checked = selected.includes(option.id); return ( -
- + -
-

Подтвержденные категории

-

Эти результаты устанавливает оценка. Их нельзя изменить в профиле.

- {draft.confirmedCategories.length > 0 ? ( -
    - {draft.confirmedCategories.map((category) => ( -
  • - {specializations.find((option) => option.value === category.specialization) - ?.label ?? category.specialization} - ,{" "} - {grades.find((option) => option.value === category.grade)?.label ?? - category.grade} -
  • - ))} -
- ) : ( -

Подтвержденных категорий пока нет.

- )} -
+ + goTo(id)} /> + -
- - -
+ + Назад + + ) + } + > + {steps.isLast ? ( + <> + + + + ) : ( + <> + {draft.expectedVersion > 0 ? ( + + ) : null} + + + )} +
); } +function specializationLabel(value: Specialization | ""): string { + return specializations.find((option) => option.value === value)?.label ?? (value || "Не выбрана"); +} + +function gradeLabel(value: Grade | null): string { + return grades.find((option) => option.value === value)?.label ?? "уровень не указан"; +} + +const moneyFormat = new Intl.NumberFormat("ru-RU"); + +function ReviewValue({ children }: { children: ReactNode }) { + return children === "" || children === null ? ( + не указано + ) : ( + <>{children} + ); +} + +/** The last step: everything the save will send, grouped by the step that owns it. */ +function ProfileReview({ + draft, + disabled, + onEdit, +}: { + draft: CandidateProfileDraft; + disabled: boolean; + onEdit: (step: ProfileStepId) => void; +}) { + const stack = draft.stack.filter((item) => item.tag.trim()); + const softSkills = draft.softSkills.filter((item) => item.skill.trim()); + const salary = draft.terms.salaryMinimum; + const salaryAmount = Number(salary.amount); + const overlaps = reviewExperienceOverlaps(draft).length; + return ( +
+ onEdit("contacts")} + > +
+
+
Имя
+
+ {draft.fullName.value.trim()} +
+
+
+
Email
+
+ {draft.contacts.email.value.trim()} +
+
+
+
Телефон
+
+ + {draft.contacts.phone.value.trim() ? ( + {draft.contacts.phone.value.trim()} + ) : ( + "" + )} + +
+
+
+
Telegram
+
+ {draft.contacts.telegram.value.trim()} +
+
+
+
+ onEdit("roles")}> + {draft.roles.length > 0 ? ( +
    + {draft.roles.map((role) => ( +
  • + + {`${specializationLabel(role.specialization)} · ${gradeLabel(role.self_assessed_grade)}`} + +
  • + ))} +
  • + +
  • +
+ ) : ( +

Роли не добавлены.

+ )} +
+ onEdit("experience")} + > + {draft.experience.length > 0 ? ( +
    + {draft.experience.map((item) => ( +
  1. + + {item.employer_name?.trim() || "Компания не указана"} + + + {specializationLabel(item.specialization)},{" "} + + {item.started_on || "?"} — {item.ended_on || "сейчас"} + + +
  2. + ))} +
+ ) : ( +

Места работы не добавлены.

+ )} + {overlaps > 0 ? ( +

+ Пересекающихся пар периодов: {overlaps}. +

+ ) : null} +
+ onEdit("skills")} + > + {stack.length > 0 || softSkills.length > 0 ? ( +
    + {stack.map((item) => ( +
  • + {item.tag.trim()} +
  • + ))} + {softSkills.map((item) => ( +
  • + {item.skill.trim()} +
  • + ))} +
+ ) : ( +

Навыки не добавлены.

+ )} +
+ onEdit("terms")} + > +
+
+
Место работы
+
+ {draft.terms.location.value.trim()} +
+
+
+
Переезд
+
+ + {draft.terms.relocation.value === null + ? "" + : draft.terms.relocation.value + ? "готов(а)" + : "не готов(а)"} + +
+
+
+
Зарплата
+
+ + {salary.amount.trim() && Number.isFinite(salaryAmount) ? ( + + от {moneyFormat.format(salaryAmount)} ₽ + {salary.tax_basis ? ( + + {" "} + {salary.tax_basis === "gross" ? "до налога" : "на руки"} + + ) : null} + + ) : ( + "" + )} + +
+
+
+
+
+ ); +} + function formatPeriod(period: { started_on: string; ended_on: string | null }): string { return `${period.started_on} - ${period.ended_on ?? "сейчас"}`; } diff --git a/frontend/src/features/edit-profile/ui/use-form-steps.ts b/frontend/src/features/edit-profile/ui/use-form-steps.ts new file mode 100644 index 0000000..9a4a291 --- /dev/null +++ b/frontend/src/features/edit-profile/ui/use-form-steps.ts @@ -0,0 +1,66 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +/* The same hook lives in the questionnaire feature; see form-steps.tsx. */ + +export type FormStep = { id: TId; label: string }; + +/** + * Index of the visible step. Moving to another step moves the focus to its + * heading, so a screen reader starts reading at the new step; the first + * render keeps the focus where it is. + */ +export function useFormSteps(steps: readonly FormStep[]) { + const [index, setIndex] = useState(0); + const headings = useRef(new Map()); + const pendingFocus = useRef(false); + const current = steps[Math.min(index, steps.length - 1)] ?? steps[0]; + + useEffect(() => { + if (!pendingFocus.current || !current) return; + pendingFocus.current = false; + headings.current.get(current.id)?.focus(); + }, [current]); + + const goTo = useCallback( + (id: TId) => { + const next = steps.findIndex((step) => step.id === id); + if (next === -1) return; + if (next === index) { + headings.current.get(id)?.focus(); + return; + } + pendingFocus.current = true; + setIndex(next); + }, + [index, steps], + ); + + /** Shows a step without moving the focus; safe to call while rendering. */ + const show = useCallback( + (id: TId) => { + const next = steps.findIndex((step) => step.id === id); + if (next !== -1) setIndex(next); + }, + [steps], + ); + + return { + index, + current: current as FormStep, + isFirst: index === 0, + isLast: index === steps.length - 1, + goTo, + show, + next: () => { + const step = steps[index + 1]; + if (step) goTo(step.id); + }, + back: () => { + const step = steps[index - 1]; + if (step) goTo(step.id); + }, + headingRef: (id: TId) => (element: HTMLHeadingElement | null) => { + headings.current.set(id, element); + }, + }; +} diff --git a/frontend/src/features/fill-questionnaire/model/questionnaire-form.test.ts b/frontend/src/features/fill-questionnaire/model/questionnaire-form.test.ts index 2fd2f5c..fdcde4d 100644 --- a/frontend/src/features/fill-questionnaire/model/questionnaire-form.test.ts +++ b/frontend/src/features/fill-questionnaire/model/questionnaire-form.test.ts @@ -14,6 +14,7 @@ import { removeQuestionnaireSpecialization, toQuestionnaireDraft, toggleQuestionnaireWorkFormat, + questionnaireStepOfField, } from "./questionnaire-form"; const catalog: SpecializationCatalog = { @@ -272,3 +273,17 @@ describe("questionnaire form model", () => { ]); }); }); + +describe("questionnaire steps", () => { + it("opens the step that owns a client or server issue", () => { + expect(questionnaireStepOfField("specializations")).toBe("specializations"); + expect(questionnaireStepOfField("specializations.1.specialization")).toBe("specializations"); + expect(questionnaireStepOfField("specializations.0.selfAssessedGrade")).toBe("details"); + expect(questionnaireStepOfField("specializations.0.stack.3")).toBe("details"); + expect(questionnaireStepOfField("specializations.1")).toBe("details"); + expect(questionnaireStepOfField("workFormats")).toBe("work"); + expect(questionnaireStepOfField("work_context.work_formats")).toBe("work"); + expect(questionnaireStepOfField("form")).toBe("review"); + expect(questionnaireStepOfField("expected_version")).toBe("review"); + }); +}); diff --git a/frontend/src/features/fill-questionnaire/model/questionnaire-form.ts b/frontend/src/features/fill-questionnaire/model/questionnaire-form.ts index f236aba..68c1066 100644 --- a/frontend/src/features/fill-questionnaire/model/questionnaire-form.ts +++ b/frontend/src/features/fill-questionnaire/model/questionnaire-form.ts @@ -359,3 +359,18 @@ export function mapQuestionnaireServerErrors( message: "Сервер не принял это значение. Проверьте выбор и повторите сохранение.", })); } + +/** Steps of the questionnaire form, in order. */ +export type QuestionnaireStepId = "specializations" | "details" | "work" | "review"; + +/** + * The step that owns a form field, so a client or server issue opens the step + * where it can be fixed. Unknown fields and general issues belong to review. + */ +export function questionnaireStepOfField(field: string): QuestionnaireStepId { + if (field === "specializations") return "specializations"; + const row = /^specializations\.\d+(?:\.(\w+))?/.exec(field); + if (row) return row[1] === "specialization" ? "specializations" : "details"; + if (field === "workFormats" || field.startsWith("work_context")) return "work"; + return "review"; +} diff --git a/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.module.css b/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.module.css index 434ae3b..1959146 100644 --- a/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.module.css +++ b/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.module.css @@ -1,72 +1,90 @@ -.root { +/* Phone first: one column; from 1024px the form and a side note. */ +.layout { display: grid; gap: var(--space-5); + align-items: start; min-width: 0; } -.root > section { - min-width: 0; +@media (width >= 64rem) { + .layout { + grid-template-columns: minmax(0, 1fr) 18rem; + } + + .aside { + position: sticky; + top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4)); + } } -.server-step, -.warning, -.form-error, -.conflict, -.continuation { - min-width: 0; - margin: 0 0 var(--space-4); - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); - background: var(--color-surface); - overflow-wrap: anywhere; +.panel { + gap: var(--space-5); +} + +.panel-header { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: baseline; + justify-content: space-between; +} + +.panel-title { + color: var(--color-text-strong); + font-size: var(--font-size-l); } .server-step { color: var(--color-text-secondary); + font-size: var(--font-size-s); } -.warning, -.form-error, -.conflict { - border-width: var(--line-strong); - border-color: var(--color-danger); +.server-step strong { + color: var(--color-text); + font-family: var(--font-mono); + font-weight: var(--font-weight-medium); } -.warning, -.conflict { - display: grid; - gap: var(--space-3); +.notice-title { + margin-bottom: var(--space-1); + color: var(--color-danger); + font-size: var(--font-size-m); } -.warning p, -.conflict p, -.continuation p { - margin: 0; - line-height: var(--line-height-body); +.notice-text { + color: var(--color-text); } -.conflict h2 { - margin: 0; - font-size: var(--font-size-l); -} - -.conflict-actions { - display: flex; - flex-wrap: wrap; - gap: var(--space-3); +.aside { min-width: 0; } -.continuation { - display: flex; - flex-wrap: wrap; - gap: var(--space-3); - align-items: center; - justify-content: space-between; - margin: var(--space-5) 0 0; +.aside-title { + color: var(--color-text-strong); + font-size: var(--font-size-m); } -.continuation p { - flex: 1 1 16rem; +.aside-text, +.aside-note { + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.aside-note { + padding-top: var(--space-3); + border-top: var(--line-thin) solid var(--color-divider); +} + +.legend { + display: grid; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; +} + +.loading { + display: grid; + gap: var(--space-4); } diff --git a/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.tsx b/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.tsx index 5c46f4a..ac9cf9e 100644 --- a/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.tsx +++ b/frontend/src/features/fill-questionnaire/ui/fill-questionnaire.tsx @@ -29,10 +29,14 @@ import { paths } from "../../../shared/config"; import { Button, ButtonLink, + Card, ErrorState, ForbiddenState, LoadingState, - Section, + Mono, + Notice, + Skeleton, + TrustLevel, } from "../../../shared/ui"; import { buildCandidateQuestionnaireUpdate, @@ -84,6 +88,15 @@ function actorMatches(queryClient: ReturnType, actor: Ses ); } +function EditorLoading({ label }: { label: string }) { + return ( +
+ + +
+ ); +} + export function FillQuestionnaire() { const queryClient = useQueryClient(); const session = useGetCurrentSession(); @@ -161,7 +174,7 @@ export function FillQuestionnaire() { ); } if (session.isPending || !session.data) { - return ; + return ; } if (session.data.account.scenario !== "candidate") { return ( @@ -181,7 +194,7 @@ export function FillQuestionnaire() { ); } if (questionnaire.isPending && !questionnaire.data) { - return ; + return ; } if (questionnaireAccessError) { return ( @@ -204,7 +217,7 @@ export function FillQuestionnaire() { ); } if (catalog.isPending && !catalog.data) { - return ; + return ; } if (!catalog.data) { return ( @@ -444,76 +457,99 @@ function QuestionnaireEditor({ savedStep === "candidate_assessment" ? paths.candidate.assessment : null; return ( -
-
- {currentStep ? ( -

- Шаг аккаунта на сервере: {stepLabel(currentStep)}. -

- ) : null} +
+ +
+

+ Ответы кандидата +

+ {currentStep ? ( +

+ Шаг аккаунта на сервере: {stepLabel(currentStep)}. +

+ ) : null} +
{catalogUnavailable ? ( -
-

Не удалось обновить каталог. Показаны последние загруженные сведения.

- + } > - {catalogQuery.isRefetching ? "Обновляем каталог..." : "Повторить загрузку каталога"} - +

Показаны последние загруженные сведения.

+
) : null} {formError ? ( -
- {formError} +
+ +

{formError}

+
) : null} {conflict ? ( -
-

Анкета изменилась в другом окне

-

- Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие ответы - оставить. Перезапись отправит весь черновик поверх актуальной анкеты. -

- {latestLoadError ? ( -

Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.

- ) : null} - {latest ?

Последняя прочитанная серверная версия: {latest.version}.

: null} -
- - - -
-

- Замена удалит введенные в этой форме изменения. -

+
+ + + + + + } + > +

+ Анкета изменилась в другом окне +

+

+ Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие + ответы оставить. Перезапись отправит весь черновик поверх актуальной анкеты. +

+ {latestLoadError ? ( +

Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.

+ ) : null} + {latest ? ( +

+ Последняя прочитанная серверная версия: {latest.version}. +

+ ) : null} +

+ Замена удалит введенные в этой форме изменения. +

+
) : null} void submit()} /> {saveState === "saved" ? ( -
-

- Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "} - {savedStep ? stepLabel(savedStep) : "не удалось прочитать"}. -

- {onboardingDestination ? ( - - Перейти к следующему шагу - - ) : null} +
+ + Перейти к следующему шагу + + ) : null + } + > +

+ Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "} + {savedStep ? stepLabel(savedStep) : "не удалось прочитать"}. +

+
) : null} -
+ +
); } diff --git a/frontend/src/features/fill-questionnaire/ui/form-steps.module.css b/frontend/src/features/fill-questionnaire/ui/form-steps.module.css new file mode 100644 index 0000000..a099773 --- /dev/null +++ b/frontend/src/features/fill-questionnaire/ui/form-steps.module.css @@ -0,0 +1,140 @@ +/* Phone first. The same rules live in the profile feature. */ +.progress { + min-width: 0; +} + +/* Below 700px the step labels are read by assistive technology but not + * drawn: four or six labels do not fit in a row at 360px, and the current + * label is the heading of the visible step anyway. */ +@media (width < 43.75rem) { + .progress ol > li > span:last-child { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } +} + +.step { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.step[hidden] { + display: none; +} + +.header { + display: grid; + gap: var(--space-2); + min-width: 0; +} + +.title { + color: var(--color-text-strong); + font-size: var(--font-size-xl); + line-height: var(--line-height-snug); + scroll-margin-block-start: calc(var(--header-height) + var(--space-6)); + overflow-wrap: anywhere; +} + +.title:focus { + outline: none; +} + +.title:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.description { + max-width: 44rem; + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.body { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.footer { + display: flex; + flex-wrap: wrap-reverse; + gap: var(--space-3); + align-items: center; + justify-content: space-between; + padding-top: var(--space-5); + border-top: var(--line-thin) solid var(--color-divider); +} + +.footer-back, +.footer-forward { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; + min-width: 0; +} + +.footer-forward { + justify-content: flex-end; + margin-inline-start: auto; +} + +/* On a phone the forward action spans the width, within thumb reach. */ +@media (width < 43.75rem) { + .footer-forward { + flex: 1 1 100%; + flex-direction: column-reverse; + align-items: stretch; + } +} + +.review { + display: grid; + gap: var(--space-3); + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-canvas); +} + +.review-header { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: baseline; + justify-content: space-between; +} + +.review-title { + color: var(--color-text-strong); + font-size: var(--font-size-m); +} + +/* A text action with a capsule focus ring, as small as a link. */ +.edit { + min-height: 2rem; + padding: 0 var(--space-3); + border: 0; + border-radius: var(--radius-pill); + color: var(--color-link); + font-family: var(--font-mono); + font-size: var(--font-size-s); + background: none; + text-decoration: underline; + text-decoration-thickness: var(--line-thin); + text-underline-offset: 0.25em; + cursor: pointer; +} + +.edit:hover { + color: var(--color-link-hover); +} diff --git a/frontend/src/features/fill-questionnaire/ui/form-steps.tsx b/frontend/src/features/fill-questionnaire/ui/form-steps.tsx new file mode 100644 index 0000000..47f3784 --- /dev/null +++ b/frontend/src/features/fill-questionnaire/ui/form-steps.tsx @@ -0,0 +1,111 @@ +import { useId, type ReactNode } from "react"; +import { buildSteps, Stepper, VisuallyHidden } from "../../../shared/ui"; +import styles from "./form-steps.module.css"; +import type { FormStep } from "./use-form-steps"; + +/* + * Steps of a long form. The same small module lives in the profile feature; + * it belongs in shared/ui once both forms settle (see the frontend README). + */ + +export type { FormStep }; + +type FormProgressProps = { + label: string; + steps: readonly FormStep[]; + index: number; +}; + +/** The Stepper of the form; on a phone only the markers and the count stay. */ +export function FormProgress({ label, steps, index }: FormProgressProps) { + return ( +
+ +
+ ); +} + +type FormStepPanelProps = { + step: { label: string }; + position: number; + total: number; + active: boolean; + headingRef: (element: HTMLHeadingElement | null) => void; + description?: ReactNode; + children: ReactNode; +}; + +/** + * One step. Inactive steps stay mounted with the hidden attribute, so field + * ids, descriptions, and server errors keep pointing at real elements. + */ +export function FormStepPanel({ + step, + position, + total, + active, + headingRef, + description, + children, +}: FormStepPanelProps) { + const headingId = useId(); + return ( + + ); +} + +type FormStepFooterProps = { + back?: ReactNode; + children: ReactNode; +}; + +/** Navigation under the steps: back on the left, the forward actions on the right. */ +export function FormStepFooter({ back, children }: FormStepFooterProps) { + return ( +
+
{back}
+
{children}
+
+ ); +} + +type ReviewBlockProps = { + title: string; + editLabel: string; + onEdit: () => void; + disabled?: boolean; + children: ReactNode; +}; + +/** A block of the review step with a way back to the step that owns it. */ +export function ReviewBlock({ title, editLabel, onEdit, disabled, children }: ReviewBlockProps) { + const headingId = useId(); + return ( +
+
+

+ {title} +

+ +
+ {children} +
+ ); +} diff --git a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.module.css b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.module.css index 747cc70..8a4d47d 100644 --- a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.module.css +++ b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.module.css @@ -1,12 +1,12 @@ .form { display: grid; - gap: var(--space-6); + gap: var(--space-5); min-width: 0; } .editor-fields { display: grid; - gap: var(--space-6); + gap: var(--space-5); min-width: 0; margin: 0; padding: 0; @@ -24,53 +24,85 @@ .issue-summary { min-width: 0; - padding: var(--space-4); - border: var(--line-strong) solid var(--color-danger); - border-radius: var(--radius-m); - background: var(--color-surface); + border-radius: var(--radius-s); } -.issue-summary:focus { - outline: var(--line-strong) solid var(--color-focus-ring); - outline-offset: 2px; -} - -.issue-summary h2 { +.issue-list { + display: grid; + gap: var(--space-1); margin: 0; - font-size: var(--font-size-l); -} - -.issue-summary ul { - margin: var(--space-3) 0 0; padding-left: var(--space-5); } -.group, -.specialization, -.option-group { +.issue-step { + color: var(--color-text); + font-weight: var(--font-weight-medium); +} + +/* A row of the form: a nested surface with a mono index in the legend. */ +.row { display: grid; gap: var(--space-4); min-width: 0; margin: 0; padding: var(--space-4); border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); + border-radius: var(--radius-s); + background: var(--color-canvas); } -.group legend, -.specialization legend, -.option-group legend { - max-width: 100%; - padding-inline: var(--space-2); - font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); +/* A legend cannot be a grid item; floating it puts it inside the row. */ +.row-legend { + display: flex; + float: left; + gap: var(--space-2); + align-items: baseline; + width: 100%; + padding: 0; + color: var(--color-text-strong); + font-family: var(--font-mono); + font-size: var(--font-size-m); + font-weight: var(--font-weight-medium); overflow-wrap: anywhere; } -.hint, -.availability p { +.row-legend > span:first-child { + color: var(--color-accent); + font-size: var(--font-size-xs); +} + +.row-actions { + display: flex; + justify-content: flex-end; +} + +.add-row { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: center; +} + +.option-group { + display: grid; + gap: var(--space-3); + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} + +.option-group legend { + float: left; + width: 100%; + padding: 0; + font-weight: var(--font-weight-bold); +} + +.hint { margin: 0; color: var(--color-text-secondary); + font-size: var(--font-size-s); line-height: var(--line-height-body); } @@ -86,68 +118,68 @@ .field input, .field select { - box-sizing: border-box; width: 100%; min-width: 0; max-width: 100%; - min-height: 2.75rem; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); - color: var(--color-text); - background: var(--color-surface); - font: inherit; +} + +.number { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; } .error { margin: 0; - color: var(--color-text); + color: var(--color-danger); font-size: var(--font-size-s); font-weight: var(--font-weight-bold); line-height: var(--line-height-body); } -.availability { - display: grid; - gap: var(--space-2); - min-width: 0; - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-accent); - background: var(--color-canvas); - overflow-wrap: anywhere; -} - -.availability-title { - color: var(--color-text); - font-weight: var(--font-weight-bold); -} - -.check-list { +/* Checkbox choices as capsules: the whole capsule is the click target. */ +.choice-list { display: flex; flex-wrap: wrap; - gap: var(--space-3) var(--space-5); - min-width: 0; -} - -.check-item { - display: flex; gap: var(--space-2); - align-items: flex-start; min-width: 0; - line-height: var(--line-height-body); - overflow-wrap: anywhere; } -.check-item input { - width: 1.25rem; - height: 1.25rem; - margin: 0.125rem 0 0; - flex: 0 0 auto; +.choice { + display: inline-flex; + gap: var(--space-2); + align-items: center; + min-width: 0; + min-height: var(--control-height); + padding: var(--space-2) var(--space-4); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-pill); + font-family: var(--font-mono); + font-size: var(--font-size-s); + line-height: var(--line-height-snug); + overflow-wrap: anywhere; + cursor: pointer; + transition: + border-color var(--duration-fast) var(--easing-standard), + background-color var(--duration-fast) var(--easing-standard); +} + +.choice:hover { + border-color: var(--color-text-secondary); +} + +.choice:has(input:checked) { + border-color: var(--color-accent); + background: var(--color-accent-tint); +} + +.choice:has(input:disabled) { + cursor: not-allowed; } .month-grid { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: minmax(0, 1fr); gap: var(--space-4); min-width: 0; } @@ -164,20 +196,13 @@ flex: 1 1 15rem; } -.field input:focus-visible, -.field select:focus-visible, -.check-item input:focus-visible { - outline: var(--line-strong) solid var(--color-focus-ring); - outline-offset: 2px; -} - .field input[aria-invalid="true"], .field select[aria-invalid="true"] { - border-width: var(--line-strong); border-color: var(--color-danger); } -.tag-list { +.tag-list, +.review-tags { display: flex; flex-wrap: wrap; gap: var(--space-2); @@ -186,54 +211,94 @@ list-style: none; } -.tag { +.review-tags li { display: flex; flex-wrap: wrap; gap: var(--space-2); - align-items: center; - max-width: 100%; - padding: var(--space-2) var(--space-3); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-s); - overflow-wrap: anywhere; } -.actions { - display: flex; - flex-wrap: wrap; - gap: var(--space-3); - align-items: center; - justify-content: space-between; - min-width: 0; +.tag-remove { + display: inline-grid; + place-items: center; + width: 1.5rem; + height: 1.5rem; + margin-inline: var(--space-1) calc(-1 * var(--space-2)); + border: 0; + border-radius: 50%; + color: var(--color-text-secondary); + font-size: 1rem; + line-height: 1; + background: none; + cursor: pointer; } -.actions > .hint { - flex: 1 1 18rem; +.tag-remove:hover { + color: var(--color-text-strong); + background: var(--color-surface-tint-hover); } .form-error { margin: 0; - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-danger); - background: var(--color-canvas); + color: var(--color-danger); line-height: var(--line-height-body); } -@media (width < 48rem) { +.review { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.review-list { + display: grid; + gap: var(--space-4); + margin: 0; + padding: 0; + list-style: none; +} + +.review-row { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.review-name { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; +} + +.review-facts { + display: grid; + gap: var(--space-2); + margin: 0; +} + +.review-facts > div { + display: grid; + gap: var(--space-1); + min-width: 0; +} + +.review-facts dt { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.review-facts dd { + min-width: 0; + overflow-wrap: anywhere; +} + +@media (width >= 48rem) { .month-grid { - grid-template-columns: minmax(0, 1fr); - } -} - -@media (width < 30rem) { - .group, - .specialization, - .option-group { - padding: var(--space-3); + grid-template-columns: repeat(2, minmax(0, 1fr)); } - .actions { - align-items: stretch; - flex-direction: column; + .review-facts > div { + grid-template-columns: 9rem minmax(0, 1fr); + align-items: baseline; } } diff --git a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.test.tsx b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.test.tsx index 61d5558..71d2ec4 100644 --- a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.test.tsx +++ b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.test.tsx @@ -112,4 +112,17 @@ describe("questionnaire form", () => { expect(markup).toContain('value="senior" selected=""'); expect(markup).not.toMatch(/]*>[^<]*(?:Перейти|Начать) проверку/); }); + + it("shows the first of four steps and keeps the other steps mounted but hidden", () => { + const markup = renderQuestionnaireForm("backend"); + + expect(markup).toContain("Шаг 1 из 4"); + expect(markup).toMatch(/]*aria-current="step"[^>]*>[\s\S]*?Направления/); + // Every step is in the markup, so field ids and server errors stay valid; + // only the first one is shown. + expect(markup.match(/]*hidden=""/g)).toHaveLength(3); + expect(markup).toContain("Моя оценка уровня"); + expect(markup).toContain(">Далее<"); + expect(markup).not.toContain("Сохранить анкету"); + }); }); diff --git a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.tsx b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.tsx index 19e768b..03a1fc8 100644 --- a/frontend/src/features/fill-questionnaire/ui/questionnaire-form.tsx +++ b/frontend/src/features/fill-questionnaire/ui/questionnaire-form.tsx @@ -1,15 +1,18 @@ -import { useEffect, useId, useRef, type FormEvent, type ReactNode } from "react"; +import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react"; import { addQuestionnaireSpecialization, addQuestionnaireStackTag, + buildCandidateQuestionnaireUpdate, changeQuestionnaireSpecialization, patchQuestionnaireSpecialization, + questionnaireStepOfField, removeQuestionnaireSpecialization, removeQuestionnaireStackTag, toggleQuestionnaireWorkFormat, type QuestionnaireDraft, type QuestionnaireFormIssue, type QuestionnaireSpecializationDraft, + type QuestionnaireStepId, } from "../model/questionnaire-form"; import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization"; import type { @@ -18,7 +21,15 @@ import type { TaskLanguage, WorkFormat, } from "../../../shared/api/schemas"; -import { Button } from "../../../shared/ui"; +import { Button, Mono, Notice, Tag, TrustLevel } from "../../../shared/ui"; +import { + FormProgress, + FormStepFooter, + FormStepPanel, + ReviewBlock, + type FormStep, +} from "./form-steps"; +import { useFormSteps } from "./use-form-steps"; import styles from "./questionnaire-form.module.css"; const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [ @@ -32,6 +43,13 @@ const taskLanguageLabels: Record = { go: "Go", }; +const questionnaireSteps: readonly FormStep[] = [ + { id: "specializations", label: "Направления" }, + { id: "details", label: "Уровень и опыт" }, + { id: "work", label: "Формат работы" }, + { id: "review", label: "Проверка и сохранение" }, +]; + type QuestionnaireFormProps = { draft: QuestionnaireDraft; catalog: SpecializationCatalog; @@ -89,6 +107,140 @@ function Field({ ); } +function specializationTitle( + catalog: SpecializationCatalog, + item: QuestionnaireSpecializationDraft, +) { + if (!item.specialization) return "Специализация не выбрана"; + return findSpecializationOption(catalog, item.specialization)?.title ?? item.specialization; +} + +type RowProps = { + draft: QuestionnaireDraft; + item: QuestionnaireSpecializationDraft; + index: number; + catalog: SpecializationCatalog; + issues: readonly QuestionnaireFormIssue[]; + disabled: boolean; + prefix: string; + onDraftChange: (draft: QuestionnaireDraft) => void; + onIssue: (issue: QuestionnaireFormIssue) => void; +}; + +/** Step 1: the specialization of one row and what the catalog offers for it. */ +function SpecializationChoice({ + draft, + item, + index, + catalog, + issues, + disabled, + prefix, + onDraftChange, +}: RowProps) { + const cardId = `${prefix}-specialization-${index}`; + const selectionId = `${cardId}-selection`; + const selectedOption = findSpecializationOption(catalog, item.specialization); + const selectedElsewhere = new Set( + draft.specializations + .filter((candidate) => candidate.id !== item.id) + .map((candidate) => candidate.specialization) + .filter(Boolean), + ); + const specialtyField = `specializations.${index}.specialization`; + const error = issueFor(issues, specialtyField); + + return ( +
+ + {String(index + 1).padStart(2, "0")} Специализация {index + 1} + + + + + + {selectedOption ? ( +
+ {selectedOption.test_availability.status === "in_development" ? ( + +

Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.

+ {selectedOption.test_availability.note ? ( +

{selectedOption.test_availability.note}

+ ) : null} +
+ ) : selectedOption.test_availability.grades.length > 0 ? ( + +

+ Проверка опубликована для уровней:{" "} + {selectedOption.test_availability.grades + .map((grade) => findGradeTitle(catalog, grade)) + .join(", ")} + . +

+
+ ) : ( + +

Сейчас нет опубликованных уровней проверки для этой специализации.

+
+ )} +
+ ) : null} + + {draft.specializations.length > 1 ? ( +
+ +
+ ) : null} +
+ ); +} + function StackTags({ draft, item, @@ -123,7 +275,8 @@ function StackTags({

- Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки. + Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки. Enter + добавляет технологию.

0 ? (
    {item.stack.map((tag) => ( -
  • - {tag} - +
  • + + {tag} + +
  • ))}
@@ -173,7 +329,8 @@ function StackTags({ ); } -function SpecializationCard({ +/** Step 2: self-assessment, task languages, stack, and experience of one row. */ +function SpecializationDetails({ draft, item, index, @@ -183,34 +340,18 @@ function SpecializationCard({ prefix, onDraftChange, onIssue, -}: { - draft: QuestionnaireDraft; - item: QuestionnaireSpecializationDraft; - index: number; - catalog: SpecializationCatalog; - issues: readonly QuestionnaireFormIssue[]; - disabled: boolean; - prefix: string; - onDraftChange: (draft: QuestionnaireDraft) => void; - onIssue: (issue: QuestionnaireFormIssue) => void; -}) { +}: RowProps) { const cardId = `${prefix}-specialization-${index}`; - const selectionId = `${cardId}-selection`; const gradeId = `${cardId}-grade`; const experienceToggleId = `${cardId}-experience-enabled`; const commercialId = `${cardId}-commercial-months`; const academicId = `${cardId}-academic-months`; const taskLanguagesId = `${cardId}-task-languages`; const selectedOption = findSpecializationOption(catalog, item.specialization); - const selectedElsewhere = new Set( - draft.specializations - .filter((candidate) => candidate.id !== item.id) - .map((candidate) => candidate.specialization) - .filter(Boolean), - ); - const specialtyField = `specializations.${index}.specialization`; const gradeField = `specializations.${index}.selfAssessedGrade`; const languagesField = `specializations.${index}.taskLanguages`; + const commercialField = `specializations.${index}.commercialMonths`; + const academicField = `specializations.${index}.academicMonths`; const stackError = issues.find((issue) => issue.field.startsWith(`specializations.${index}.stack`), )?.message; @@ -228,83 +369,14 @@ function SpecializationCard({ } return ( -
- Специализация {index + 1} +
+ + {String(index + 1).padStart(2, "0")} {specializationTitle(catalog, item)} +

Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет только результат проверки.

- - - - - {selectedOption ? ( -
- {selectedOption.test_availability.status === "in_development" ? ( - <> -

Проверка: в разработке

-

Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.

- {selectedOption.test_availability.note ? ( -

{selectedOption.test_availability.note}

- ) : null} - - ) : selectedOption.test_availability.grades.length > 0 ? ( -

- Проверка опубликована для уровней:{" "} - {selectedOption.test_availability.grades - .map((grade) => findGradeTitle(catalog, grade)) - .join(", ")} - . -

- ) : ( -

Сейчас нет опубликованных уровней проверки для этой специализации.

- )} -
- ) : null} - {!selectedOption ? ( -

Сначала выберите специализацию.

+

Сначала выберите специализацию.

) : shownLanguages.length > 0 ? ( -
+
{shownLanguages.map((language) => { const isOld = oldLanguages.includes(language); const languageId = `${taskLanguagesId}-${language}`; return ( -
@@ -388,7 +462,7 @@ function SpecializationCard({
Опыт в этой специализации -
- - {draft.specializations.length > 1 ? ( - - ) : null}
); } +function ReviewSummary({ + draft, + catalog, + disabled, + onEdit, +}: { + draft: QuestionnaireDraft; + catalog: SpecializationCatalog; + disabled: boolean; + onEdit: (step: QuestionnaireStepId) => void; +}) { + const chosen = draft.specializations.filter((item) => item.specialization); + return ( +
+ onEdit("specializations")} + > + {chosen.length > 0 ? ( +
    + {chosen.map((item) => { + const option = findSpecializationOption(catalog, item.specialization); + return ( +
  • + {specializationTitle(catalog, item)} + {option?.test_availability.status === "in_development" ? ( + тест готовится + ) : null} +
  • + ); + })} +
+ ) : ( +

Ни одна специализация не выбрана.

+ )} +
+ onEdit("details")} + > + {chosen.length > 0 ? ( +
    + {chosen.map((item) => ( +
  • + + + {`${specializationTitle(catalog, item)} · ${ + item.selfAssessedGrade + ? findGradeTitle(catalog, item.selfAssessedGrade) + : "уровень не выбран" + }`} + + + +
    +
    +
    Язык заданий
    +
    + {item.taskLanguages.length > 0 + ? item.taskLanguages.map((code) => taskLanguageLabels[code]).join(", ") + : "не выбран"} +
    +
    +
    +
    Стек
    +
    + {item.stack.length > 0 ? ( + + {item.stack.map((tag) => ( + + {tag} + + ))} + + ) : ( + "не указан" + )} +
    +
    +
    +
    Опыт, месяцев
    +
    + {item.hasExperience ? ( + <> + коммерческий {item.commercialMonths || "?"}, учебный{" "} + {item.academicMonths || "?"} + + ) : ( + "не указан" + )} +
    +
    +
    +
  • + ))} +
+ ) : ( +

Появится после выбора специализации.

+ )} +
+ onEdit("work")} + > + {draft.workFormats.length > 0 ? ( +

+ {workFormats + .filter((format) => draft.workFormats.includes(format.value)) + .map((format) => ( + + {format.label.toLowerCase()} + + ))} +

+ ) : ( +

Формат не выбран.

+ )} +
+
+ ); +} + export function QuestionnaireForm({ draft, catalog, @@ -503,23 +694,73 @@ export function QuestionnaireForm({ const prefix = `questionnaire-${useId().replaceAll(":", "")}`; const rowSequence = useRef(0); const issueSummary = useRef(null); + const steps = useFormSteps(questionnaireSteps); + const [stepIssues, setStepIssues] = useState([]); + const shownIssues = issues.length > 0 ? issues : stepIssues; const formDisabled = isSaving || isForbidden; - const generalIssue = issueFor(issues, "form"); + const generalIssue = issueFor(shownIssues, "form"); + const { goTo } = steps; + + // Issues from a save (client or server) open the first step that owns one. + const [seenIssues, setSeenIssues] = useState(issues); + if (seenIssues !== issues) { + setSeenIssues(issues); + const first = issues[0]; + if (first) steps.show(questionnaireStepOfField(first.field)); + } useEffect(() => { - if (issues.length > 0) issueSummary.current?.focus(); - }, [issues.length]); + if (shownIssues.length > 0) issueSummary.current?.focus(); + }, [shownIssues]); + + function changeDraft(next: QuestionnaireDraft) { + setStepIssues([]); + onDraftChange(next); + } + + function goForward() { + const step = steps.current.id; + const found = buildCandidateQuestionnaireUpdate(draft, catalog).issues.filter( + (issue) => questionnaireStepOfField(issue.field) === step, + ); + if (found.length > 0) { + setStepIssues(found); + return; + } + setStepIssues([]); + steps.next(); + } function handleSubmit(event: FormEvent) { event.preventDefault(); - if (issues.length > 0) issueSummary.current?.focus(); + if (!steps.isLast) { + goForward(); + return; + } + if (shownIssues.length > 0) issueSummary.current?.focus(); else event.currentTarget.querySelector('button[type="submit"]')?.focus(); onSubmit(); } + const stepLabel = (field: string) => + questionnaireSteps.find((step) => step.id === questionnaireStepOfField(field))?.label ?? ""; + const total = questionnaireSteps.length; + const panel = (id: QuestionnaireStepId) => { + const position = questionnaireSteps.findIndex((step) => step.id === id); + return { + step: questionnaireSteps[position] as FormStep, + position: position + 1, + total, + active: steps.current.id === id, + headingRef: steps.headingRef(id), + }; + }; + return (
- {issues.length > 0 ? ( + + + {shownIssues.length > 0 ? (
-

Проверьте анкету

-
    - {issues.map((item, index) => ( -
  • {item.message}
  • - ))} -
+ Проверьте анкету}> +
    + {shownIssues.map((item, index) => ( +
  • + {stepLabel(item.field)}:{" "} + {item.message} +
  • + ))} +
+
) : null}
Ответы анкеты -
- Специализации -

- Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой. -

+ + {draft.specializations.map((item, index) => ( - ))} - {issueFor(issues, "specializations")} + {issueFor(shownIssues, "specializations")} - -

- Можно указать не больше двух специализаций. -

-
- -
- Подходящий формат работы -

- Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю. -

-
- {workFormats.map((format) => { - const id = `${prefix}-format-${format.value}`; - return ( - - ); - })} +
+ +

+ Можно указать не больше двух специализаций. +

- - {issueFor(issues, "workFormats")} - -
+ + + + {draft.specializations.map((item, index) => ( + + ))} + + + +
+ Подходящий формат работы +
+ {workFormats.map((format) => { + const id = `${prefix}-format-${format.value}`; + return ( + + ); + })} +
+ + {issueFor(shownIssues, "workFormats")} + +
+
+ + + goTo(id)} + /> +
{generalIssue ? ( @@ -611,24 +892,41 @@ export function QuestionnaireForm({

) : null} -
-

- Сохраненные ответы можно изменить. Данные черновика не записываются в браузерное - хранилище. -

- -
+ + Назад + + ) + } + > + {steps.isLast ? ( + + ) : ( + <> + {draft.expectedVersion > 0 ? ( + + ) : null} + + + )} + ); } diff --git a/frontend/src/features/fill-questionnaire/ui/use-form-steps.ts b/frontend/src/features/fill-questionnaire/ui/use-form-steps.ts new file mode 100644 index 0000000..c740a1d --- /dev/null +++ b/frontend/src/features/fill-questionnaire/ui/use-form-steps.ts @@ -0,0 +1,66 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +/* The same hook lives in the profile feature; see form-steps.tsx. */ + +export type FormStep = { id: TId; label: string }; + +/** + * Index of the visible step. Moving to another step moves the focus to its + * heading, so a screen reader starts reading at the new step; the first + * render keeps the focus where it is. + */ +export function useFormSteps(steps: readonly FormStep[]) { + const [index, setIndex] = useState(0); + const headings = useRef(new Map()); + const pendingFocus = useRef(false); + const current = steps[Math.min(index, steps.length - 1)] ?? steps[0]; + + useEffect(() => { + if (!pendingFocus.current || !current) return; + pendingFocus.current = false; + headings.current.get(current.id)?.focus(); + }, [current]); + + const goTo = useCallback( + (id: TId) => { + const next = steps.findIndex((step) => step.id === id); + if (next === -1) return; + if (next === index) { + headings.current.get(id)?.focus(); + return; + } + pendingFocus.current = true; + setIndex(next); + }, + [index, steps], + ); + + /** Shows a step without moving the focus; safe to call while rendering. */ + const show = useCallback( + (id: TId) => { + const next = steps.findIndex((step) => step.id === id); + if (next !== -1) setIndex(next); + }, + [steps], + ); + + return { + index, + current: current as FormStep, + isFirst: index === 0, + isLast: index === steps.length - 1, + goTo, + show, + next: () => { + const step = steps[index + 1]; + if (step) goTo(step.id); + }, + back: () => { + const step = steps[index - 1]; + if (step) goTo(step.id); + }, + headingRef: (id: TId) => (element: HTMLHeadingElement | null) => { + headings.current.set(id, element); + }, + }; +} diff --git a/frontend/src/features/notifications/ui/notification-inbox.module.css b/frontend/src/features/notifications/ui/notification-inbox.module.css index ef9dd7c..5f7c08c 100644 --- a/frontend/src/features/notifications/ui/notification-inbox.module.css +++ b/frontend/src/features/notifications/ui/notification-inbox.module.css @@ -18,16 +18,16 @@ .item { min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); } -/* Unread is a heavier edge and the word "Не прочитано", never color alone. */ +/* Unread is the red dot, a stronger hairline, and the words "Не прочитано"; + * never color alone. */ .item[data-unread] { - border-color: var(--color-border-strong); - border-inline-start-width: var(--space-2); + border-color: var(--color-border-hover); } .item article { @@ -44,27 +44,25 @@ .meta { display: flex; flex-wrap: wrap; - gap: var(--space-2) var(--space-4); - align-items: baseline; + gap: var(--space-2) var(--space-3); + align-items: center; color: var(--color-text-secondary); font-size: var(--font-size-xs); } .kind { + font-family: var(--font-mono); letter-spacing: var(--letter-spacing-label); text-transform: uppercase; } -.unread { - color: var(--color-text); - font-weight: var(--font-weight-bold); -} - -.read { - font-weight: var(--font-weight-regular); +.meta time { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; } .title { + color: var(--color-text-strong); font-size: var(--font-size-l); line-height: var(--line-height-snug); } @@ -102,6 +100,6 @@ @media (width < 42rem) { .item { - padding: var(--space-3); + padding: var(--space-4); } } diff --git a/frontend/src/features/notifications/ui/notification-inbox.tsx b/frontend/src/features/notifications/ui/notification-inbox.tsx index ad78e15..e08990c 100644 --- a/frontend/src/features/notifications/ui/notification-inbox.tsx +++ b/frontend/src/features/notifications/ui/notification-inbox.tsx @@ -15,12 +15,15 @@ import { import type { Notification, NotificationList, Session } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config/paths"; import { + AttentionDot, Button, ButtonLink, EmptyState, ErrorState, ForbiddenState, LoadingState, + Skeleton, + Tag, TextLink, VisuallyHidden, } from "../../../shared/ui"; @@ -243,7 +246,14 @@ export function NotificationInbox({ scope }: NotificationInboxProps) { /> ); } - if (list.isPending || !list.data) return ; + if (list.isPending || !list.data) { + return ( +
+ + +
+ ); + } const items = list.data.pages.flatMap((page) => page.items); if (items.length === 0) { @@ -326,11 +336,10 @@ function NotificationItem({
  • + {unread ? : null} {notificationKindLabel(item.kind)} - - {unread ? "Не прочитано" : "Прочитано"} - + {unread ? "Не прочитано" : "Прочитано"}

    {title} diff --git a/frontend/src/features/profile-visibility/ui/visibility-controls.module.css b/frontend/src/features/profile-visibility/ui/visibility-controls.module.css index 6bfaefa..6e192aa 100644 --- a/frontend/src/features/profile-visibility/ui/visibility-controls.module.css +++ b/frontend/src/features/profile-visibility/ui/visibility-controls.module.css @@ -37,8 +37,8 @@ } .choice input:focus-visible { - outline: var(--line-strong) solid var(--color-accent); - outline-offset: 2px; + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); } .help, @@ -60,16 +60,24 @@ font-weight: var(--font-weight-bold); } +/* Notes in the shape of the Notice primitive: a nested surface, a hairline, + * and the accent stripe of the state. */ .notice, .message, .error { - padding: var(--space-3); + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-divider); border-inline-start: var(--line-strong) solid var(--color-accent); + border-radius: var(--radius-s); background: var(--color-canvas); } +.message { + border-inline-start-color: var(--color-success); +} + .error { - border-inline-start-color: var(--color-danger); + border-color: var(--color-danger); } .step { @@ -78,7 +86,8 @@ min-width: 0; padding: var(--space-4); border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); + border-radius: var(--radius-s); + background: var(--color-canvas); } /* The state is stated in text; the stronger edge only repeats it for sighted users. */ @@ -92,7 +101,8 @@ .step-title { margin: 0; - font-size: 1rem; + color: var(--color-text-strong); + font-size: var(--font-size-m); } .step-text { @@ -104,8 +114,10 @@ display: grid; gap: var(--space-2); min-width: 0; - padding: var(--space-3); + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-divider); border-inline-start: var(--line-strong) solid var(--color-accent); + border-radius: var(--radius-s); background: var(--color-canvas); } diff --git a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.module.css b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.module.css index 775129a..551f65e 100644 --- a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.module.css +++ b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.module.css @@ -17,11 +17,16 @@ color: var(--color-text); } +/* The form is one card of the system. */ .form { display: grid; gap: var(--space-5); max-width: 52rem; min-width: 0; + padding: var(--space-5); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); } .field { @@ -40,13 +45,9 @@ width: 100%; min-width: 0; max-width: 100%; - min-height: 2.75rem; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); color: var(--color-text); - background: var(--color-surface); - font: inherit; + background-color: var(--color-canvas); line-height: var(--line-height-body); } @@ -65,10 +66,13 @@ font-size: var(--font-size-s); } +/* An error in the shape of the danger Notice. */ .error { - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-danger); - background: var(--color-surface); + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-danger); + border-radius: var(--radius-s); + background: + linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas); } .error:focus { @@ -84,7 +88,7 @@ } @media (width <= 40rem) { - .actions > :first-child { - width: 100%; + .form { + padding: var(--space-4); } } diff --git a/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css b/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css index 757cdff..807eaa0 100644 --- a/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css +++ b/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css @@ -1,16 +1,17 @@ .form { display: grid; gap: var(--space-4); + align-content: start; min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); } .title { + color: var(--color-text-strong); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); } .fieldset { @@ -44,9 +45,9 @@ min-height: 2.75rem; min-width: 0; padding: var(--space-2) var(--space-3); - border: var(--line-thin) solid var(--color-divider); + border: var(--line-thin) solid var(--color-border-strong); border-radius: var(--radius-s); - background: var(--color-surface); + background: var(--color-canvas); line-height: var(--line-height-body); cursor: pointer; } @@ -64,6 +65,11 @@ overflow-wrap: anywhere; } +.option:has(input:checked) { + border-color: var(--color-accent); + background: var(--color-accent-tint); +} + .option:has(input:focus-visible) { outline: var(--focus-ring-width) solid var(--color-focus-ring); outline-offset: var(--focus-ring-offset); @@ -80,7 +86,7 @@ width: 100%; min-width: 0; padding: var(--space-3); - border: var(--line-strong) solid var(--color-border-strong); + border: var(--line-thin) solid var(--color-border-strong); border-radius: var(--radius-s); background: var(--color-surface); color: var(--color-text); @@ -99,12 +105,13 @@ } .alert { - padding: var(--space-3); - border: var(--line-strong) solid var(--color-danger); + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-danger); border-radius: var(--radius-s); - background: var(--color-surface); color: var(--color-text); line-height: var(--line-height-body); + background: + linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas); } .alert:focus-visible { diff --git a/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx b/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx index a59079e..4f05ad2 100644 --- a/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx +++ b/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx @@ -11,6 +11,7 @@ import { ForbiddenState, LoadingState, Page, + Skeleton, } from "../../../shared/ui"; import { AssessmentActorGate, @@ -29,7 +30,7 @@ const attemptIdPattern = export function AssessmentResultPage() { const { attemptId = "" } = useParams(); return ( - + {({ actor, queryClient }) => ( ); } - if (result.isPending) return ; + if (result.isPending) { + return ( +
    + + +
    + ); + } if (!result.data) { return ( <> diff --git a/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx b/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx index d10178c..f804e8d 100644 --- a/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx +++ b/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx @@ -7,7 +7,6 @@ export function AssessmentResultsPage() { return ( diff --git a/frontend/src/pages/assessment/model/countdown.test.ts b/frontend/src/pages/assessment/model/countdown.test.ts new file mode 100644 index 0000000..9e4e889 --- /dev/null +++ b/frontend/src/pages/assessment/model/countdown.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { describeTimeLeft, formatTimeLeft } from "./countdown"; + +describe("attempt countdown", () => { + it("formats the time left in mono-friendly fixed widths", () => { + expect(formatTimeLeft(272_000)).toBe("04:32"); + expect(formatTimeLeft(59_999)).toBe("00:59"); + expect(formatTimeLeft(-5_000)).toBe("00:00"); + expect(formatTimeLeft((2 * 3600 + 5 * 60 + 7) * 1000)).toBe("2:05:07"); + expect(formatTimeLeft((2 * 86_400 + 13 * 3600) * 1000)).toBe("2 д 13 ч"); + }); + + it("describes the time left in words", () => { + expect(describeTimeLeft(272_000)).toBe("Осталось минут: 5"); + expect(describeTimeLeft(0)).toBe("Осталось минут: 0"); + expect(describeTimeLeft((3600 + 120) * 1000)).toBe("Осталось часов: 1, минут: 2"); + expect(describeTimeLeft(2 * 86_400_000)).toBe("Осталось дней: 2, часов: 0"); + }); +}); diff --git a/frontend/src/pages/assessment/model/countdown.ts b/frontend/src/pages/assessment/model/countdown.ts new file mode 100644 index 0000000..9d59677 --- /dev/null +++ b/frontend/src/pages/assessment/model/countdown.ts @@ -0,0 +1,29 @@ +/** + * Text of the time left until a server deadline: "мм:сс" under an hour, + * "ч:мм:сс" under a day, otherwise days and hours. Negative time is zero. + */ +export function formatTimeLeft(milliseconds: number): string { + const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000)); + const days = Math.floor(totalSeconds / 86_400); + const hours = Math.floor((totalSeconds % 86_400) / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + const pad = (value: number) => String(value).padStart(2, "0"); + if (days > 0) return `${days} д ${hours} ч`; + if (hours > 0) return `${hours}:${pad(minutes)}:${pad(seconds)}`; + return `${pad(minutes)}:${pad(seconds)}`; +} + +/** Spoken form of the time left, for assistive technology. */ +export function describeTimeLeft(milliseconds: number): string { + const totalMinutes = Math.max(0, Math.ceil(milliseconds / 60_000)); + if (totalMinutes >= 1440) { + const days = Math.floor(totalMinutes / 1440); + const hours = Math.floor((totalMinutes % 1440) / 60); + return `Осталось дней: ${days}, часов: ${hours}`; + } + if (totalMinutes >= 60) { + return `Осталось часов: ${Math.floor(totalMinutes / 60)}, минут: ${totalMinutes % 60}`; + } + return `Осталось минут: ${totalMinutes}`; +} diff --git a/frontend/src/pages/assessment/model/express-start.test.ts b/frontend/src/pages/assessment/model/express-start.test.ts new file mode 100644 index 0000000..b6acd23 --- /dev/null +++ b/frontend/src/pages/assessment/model/express-start.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; +import { + beginExpressStart, + expressReplayWindowMs, + forgetExpressStart, + readExpressStart, + recordExpressRun, + settleRefusedExpressStart, +} from "./express-start"; + +// A minimal in-memory sessionStorage; it can be made to throw. +function memoryStore(failing = false) { + const values = new Map(); + return { + values, + getItem(key: string) { + if (failing) throw new Error("blocked"); + return values.get(key) ?? null; + }, + setItem(key: string, value: string) { + if (failing) throw new Error("blocked"); + values.set(key, value); + }, + removeItem(key: string) { + if (failing) throw new Error("blocked"); + values.delete(key); + }, + }; +} + +const account = "11111111-1111-4111-8111-111111111111"; +const other = "22222222-2222-4222-8222-222222222222"; +const run = "33333333-3333-4333-8333-333333333333"; +const now = 1_760_000_000_000; + +describe("express start key", () => { + it("stores a pending key before the start and the active key after 201", () => { + const store = memoryStore(); + const key = beginExpressStart(account, null, () => "key-1", store, now); + expect(key).toBe("key-1"); + expect(readExpressStart(account, store, now)).toEqual({ + activeKey: null, + activeAttemptId: null, + pendingKey: "key-1", + storedAt: now, + }); + + recordExpressRun(account, key, run, store, now); + expect(readExpressStart(account, store, now)).toMatchObject({ + activeKey: "key-1", + activeAttemptId: run, + pendingKey: null, + }); + expect(readExpressStart(other, store, now)).toBeNull(); + }); + + it("repeats a start with a lost response with the same key after a reload", () => { + const store = memoryStore(); + beginExpressStart(account, null, () => "lost-key", store, now); + // A reload loses the in-memory key; the stored pending key is reused. + expect(beginExpressStart(account, null, () => "fresh-key", store, now + 1000)).toBe("lost-key"); + // An in-memory pending start keeps its own key. + expect(beginExpressStart(account, "memory-key", () => "fresh-key", store, now)).toBe( + "memory-key", + ); + }); + + it("returns the key of the active run for a replay after 409 to a new start", () => { + const store = memoryStore(); + recordExpressRun(account, "run-key", run, store, now); + const key = beginExpressStart(account, null, () => "new-key", store, now + 1000); + expect(key).toBe("new-key"); + expect(readExpressStart(account, store, now + 1000)).toMatchObject({ + activeKey: "run-key", + pendingKey: "new-key", + }); + + expect(settleRefusedExpressStart(account, key, store, now + 2000)).toBe("run-key"); + expect(readExpressStart(account, store, now + 2000)).toMatchObject({ + activeKey: "run-key", + activeAttemptId: run, + pendingKey: null, + }); + }); + + it("does not replay the key that was just refused", () => { + const store = memoryStore(); + recordExpressRun(account, "run-key", run, store, now); + expect(settleRefusedExpressStart(account, "run-key", store, now)).toBeNull(); + expect(readExpressStart(account, store, now)).toBeNull(); + }); + + it("forgets a finished run and keeps a pending start of another run", () => { + const store = memoryStore(); + recordExpressRun(account, "run-key", run, store, now); + forgetExpressStart(account, "44444444-4444-4444-8444-444444444444", store, now); + expect(readExpressStart(account, store, now)?.activeKey).toBe("run-key"); + forgetExpressStart(account, run, store, now); + expect(readExpressStart(account, store, now)).toBeNull(); + + recordExpressRun(account, "run-key", run, store, now); + beginExpressStart(account, null, () => "pending-key", store, now); + forgetExpressStart(account, run, store, now); + expect(readExpressStart(account, store, now)).toMatchObject({ + activeKey: null, + pendingKey: "pending-key", + }); + forgetExpressStart(account, undefined, store, now); + expect(readExpressStart(account, store, now)).toBeNull(); + }); + + it("drops entries past the 24 hour replay window and invalid values", () => { + const store = memoryStore(); + recordExpressRun(account, "run-key", run, store, now); + expect(readExpressStart(account, store, now + expressReplayWindowMs + 1)).toBeNull(); + + store.values.set(`lincodex.assessment-express-start.v1:${account}`, "{not json"); + expect(readExpressStart(account, store, now)).toBeNull(); + store.values.set( + `lincodex.assessment-express-start.v1:${account}`, + JSON.stringify({ + activeKey: "bad key", + activeAttemptId: run, + pendingKey: null, + storedAt: now, + }), + ); + expect(readExpressStart(account, store, now)).toBeNull(); + }); + + it("works without storage when it is blocked", () => { + const store = memoryStore(true); + expect(beginExpressStart(account, null, () => "key-1", store, now)).toBe("key-1"); + expect(() => recordExpressRun(account, "key-1", run, store, now)).not.toThrow(); + expect(settleRefusedExpressStart(account, "key-1", store, now)).toBeNull(); + expect(() => forgetExpressStart(account, run, store, now)).not.toThrow(); + expect(readExpressStart(account, store, now)).toBeNull(); + expect(beginExpressStart(account, null, () => "key-2", null, now)).toBe("key-2"); + }); +}); diff --git a/frontend/src/pages/assessment/model/express-start.ts b/frontend/src/pages/assessment/model/express-start.ts new file mode 100644 index 0000000..131f31f --- /dev/null +++ b/frontend/src/pages/assessment/model/express-start.ts @@ -0,0 +1,206 @@ +// The Idempotency-Key of the demonstration express start is kept in this +// tab's sessionStorage, one entry per account. The server answers 409 +// state_conflict to a new start while an express run is active, and replays +// the stored 201 with the active attempt when the same start is repeated with +// the key that created it (within 24 hours). Keeping that key lets an +// unfinished run be resumed after a reload instead of being blocked. +// +// The entry holds two keys: +// - activeKey: the key whose start created the newest known run; +// - pendingKey: the key of a start whose outcome is not known yet, so a lost +// response is repeated with the same key after a reload. +// Storage can be blocked or full, so every access is guarded and the flow +// works without it (a reload then cannot resume the run). + +const keyPrefix = "lincodex.assessment-express-start.v1"; + +/** The server keeps an Idempotency-Key for 24 hours; older entries are dropped. */ +export const expressReplayWindowMs = 24 * 60 * 60 * 1000; + +const idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,255}$/; +const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export type ExpressStartEntry = { + activeKey: string | null; + activeAttemptId: string | null; + pendingKey: string | null; + /** Epoch milliseconds of the last write. */ + storedAt: number; +}; + +type StartStore = Pick; + +function sessionStore(): StartStore | null { + try { + return window.sessionStorage; + } catch { + return null; + } +} + +function entryKey(accountId: string): string { + return `${keyPrefix}:${accountId}`; +} + +function optionalMatch(value: unknown, pattern: RegExp): value is string | null { + return value === null || (typeof value === "string" && pattern.test(value)); +} + +function parseEntry(raw: string, now: number): ExpressStartEntry | null { + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return null; + } + if (typeof value !== "object" || value === null) return null; + const entry = value as Record; + if ( + !optionalMatch(entry.activeKey, idempotencyKeyPattern) || + !optionalMatch(entry.pendingKey, idempotencyKeyPattern) || + !optionalMatch(entry.activeAttemptId, uuidPattern) || + typeof entry.storedAt !== "number" || + !Number.isFinite(entry.storedAt) || + now - entry.storedAt > expressReplayWindowMs || + entry.storedAt - now > expressReplayWindowMs + ) { + return null; + } + return { + activeKey: entry.activeKey, + activeAttemptId: entry.activeAttemptId, + pendingKey: entry.pendingKey, + storedAt: entry.storedAt, + }; +} + +/** The stored express start of an account, or null when absent, invalid, or older than 24 h. */ +export function readExpressStart( + accountId: string, + store: StartStore | null = sessionStore(), + now = Date.now(), +): ExpressStartEntry | null { + if (!store) return null; + try { + const raw = store.getItem(entryKey(accountId)); + return raw === null ? null : parseEntry(raw, now); + } catch { + return null; + } +} + +function writeEntry( + accountId: string, + entry: Omit, + store: StartStore | null, + now: number, +): void { + if (!store) return; + try { + if (!entry.activeKey && !entry.pendingKey) { + store.removeItem(entryKey(accountId)); + return; + } + store.setItem(entryKey(accountId), JSON.stringify({ ...entry, storedAt: now })); + } catch { + // A full or blocked store keeps the key in memory only. + } +} + +/** + * The key of the next express start: the start still waiting for an outcome + * keeps its key, otherwise a fresh one. The chosen key is stored as pending + * before the request is sent; the key of the known run is kept for a replay. + */ +export function beginExpressStart( + accountId: string, + inMemoryKey: string | null, + newKey: () => string, + store: StartStore | null = sessionStore(), + now = Date.now(), +): string { + const entry = readExpressStart(accountId, store, now); + const key = inMemoryKey ?? entry?.pendingKey ?? newKey(); + writeEntry( + accountId, + { + activeKey: entry?.activeKey ?? null, + activeAttemptId: entry?.activeAttemptId ?? null, + pendingKey: key, + }, + store, + now, + ); + return key; +} + +/** The start with this key created (or replayed) this run; it becomes the active one. */ +export function recordExpressRun( + accountId: string, + key: string, + attemptId: string, + store: StartStore | null = sessionStore(), + now = Date.now(), +): void { + writeEntry( + accountId, + { activeKey: key, activeAttemptId: attemptId, pendingKey: null }, + store, + now, + ); +} + +/** + * The pending start was answered without a run (for example 409 or 400). The + * key of the known run, if any, stays for a replay and is returned unless it + * is the key that was just refused. + */ +export function settleRefusedExpressStart( + accountId: string, + refusedKey: string, + store: StartStore | null = sessionStore(), + now = Date.now(), +): string | null { + const entry = readExpressStart(accountId, store, now); + const activeKey = entry?.activeKey && entry.activeKey !== refusedKey ? entry.activeKey : null; + writeEntry( + accountId, + { + activeKey, + activeAttemptId: activeKey ? (entry?.activeAttemptId ?? null) : null, + pendingKey: null, + }, + store, + now, + ); + return activeKey; +} + +/** + * Forgets the stored start of an account. With an attempt id, only an entry + * of that run is removed: a finished or expired run cannot be resumed. + */ +export function forgetExpressStart( + accountId: string, + attemptId?: string, + store: StartStore | null = sessionStore(), + now = Date.now(), +): void { + if (!store) return; + const entry = readExpressStart(accountId, store, now); + if (attemptId !== undefined && entry && entry.activeAttemptId !== attemptId) return; + if (attemptId !== undefined && entry?.pendingKey) { + writeEntry( + accountId, + { activeKey: null, activeAttemptId: null, pendingKey: entry.pendingKey }, + store, + now, + ); + return; + } + try { + store.removeItem(entryKey(accountId)); + } catch { + // Nothing to forget when storage is blocked. + } +} diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css index 6cd7d36..773a3a9 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css @@ -1,73 +1,246 @@ +/* The test-taking screen: one narrow reading column with a focus strip. */ .layout { display: grid; gap: var(--space-5); + max-width: 52rem; min-width: 0; } +.session { + display: grid; + gap: var(--space-4); + min-width: 0; +} + +.session-header { + display: grid; + gap: var(--space-2); +} + +.session-title { + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + .meta { - display: flex; - flex-wrap: wrap; - gap: var(--space-3); color: var(--color-text-secondary); font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +/* Focus strip: name, progress, timer, and save state. It stays in view + * under the header on wider screens. */ +.focus-bar { + display: grid; + grid-template-areas: + "name timer" + "progress progress" + "save save"; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-3) var(--space-4); + align-items: center; + min-width: 0; + padding: var(--space-3) var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +@media (width >= 43.75rem) { + .focus-bar { + position: sticky; + z-index: 5; + top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-2)); + grid-template-areas: + "name progress timer" + "save save save"; + grid-template-columns: auto minmax(0, 1fr) auto; + } +} + +.focus-name { + grid-area: name; + min-width: 0; +} + +.focus-progress { + display: grid; + grid-area: progress; + gap: var(--space-1); + min-width: 0; +} + +.focus-count { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.track { + height: 0.375rem; + border-radius: var(--radius-pill); + overflow: hidden; + background: var(--color-surface-elevated); +} + +.fill { + display: block; + height: 100%; + border-radius: inherit; + background: var(--color-inverse); + transition: width var(--duration-slow) var(--easing-emphasized); +} + +.focus-timer { + display: grid; + grid-area: timer; + justify-items: end; +} + +.timer-label { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.timer { + color: var(--color-text-strong); + font-family: var(--font-mono); + font-size: 1.375rem; + font-weight: var(--font-weight-bold); + font-variant-numeric: tabular-nums; + line-height: 1.1; +} + +/* The last minute: the digits turn to the error color and a word says so. */ +.focus-timer[data-urgent] .timer { + color: var(--color-danger); +} + +.focus-timer[data-urgent] .timer-label::after { + content: " · последняя минута"; +} + +.save-state { + display: flex; + grid-area: save; + gap: var(--space-2); + align-items: center; + padding-top: var(--space-2); + border-top: var(--line-thin) solid var(--color-divider); + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +/* The mark differs in shape per state: ring, spinner arc, filled dot, cross. */ +.save-mark { + flex: none; + width: 0.625rem; + height: 0.625rem; + border: var(--line-thin) solid var(--color-border-strong); + border-radius: 50%; +} + +.save-state[data-state="saving"] .save-mark { + border-color: var(--color-accent); + border-right-color: transparent; + animation: spin 0.9s linear infinite; +} + +.save-state[data-state="saved"] { + color: var(--color-success); +} + +.save-state[data-state="saved"] .save-mark { + border-color: var(--color-success); + background: var(--color-success); +} + +.save-state[data-state="unconfirmed"], +.save-state[data-state="failed"] { + color: var(--color-danger); +} + +.save-state[data-state="unconfirmed"] .save-mark, +.save-state[data-state="failed"] .save-mark { + border-radius: var(--radius-xs); + border-color: var(--color-danger); +} + +@keyframes spin { + to { + transform: rotate(360deg); + } } .resume, -.finalize, -.info, -.item { - display: grid; - gap: var(--space-3); - min-width: 0; - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); +.finalize { + gap: var(--space-4); } .resume p, -.finalize p, -.info p { +.finalize p { margin: 0; + color: var(--color-text-secondary); } +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +/* The item: the one panel the eye rests on. */ .item { - gap: var(--space-4); - border-color: var(--color-border-strong); + display: grid; + gap: var(--space-5); + min-width: 0; + padding: var(--space-5); + border: var(--line-thin) solid var(--color-border-hover); + border-radius: var(--radius-m); + background: var(--color-surface); } .item-heading { display: flex; flex-wrap: wrap; + gap: var(--space-2); align-items: baseline; justify-content: space-between; - gap: var(--space-2); } -.item-heading h2, -.result h2 { - margin: 0; +.item-heading h3 { + color: var(--color-text-strong); font-size: var(--font-size-l); } -.item-heading span { +.item-counter { + display: inline-flex; + gap: var(--space-1); + align-items: baseline; color: var(--color-text-secondary); font-size: var(--font-size-s); } +.item-counter > span:first-child { + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + .prompt { margin: 0; + color: var(--color-text); + font-size: 1.0625rem; + line-height: var(--line-height-body); white-space: pre-wrap; overflow-wrap: anywhere; - line-height: var(--line-height-body); } .info { color: var(--color-text-secondary); + font-size: var(--font-size-s); } -.error { - margin: 0; - color: var(--color-danger); +.notice-text { + color: var(--color-text); } .result { @@ -86,21 +259,29 @@ flex-wrap: wrap; } -@media (width < 42rem) { - .resume, - .finalize, - .info, - .item { - padding: var(--space-3); - } -} - .result-heading { margin: 0; + color: var(--color-text-strong); font-size: var(--font-size-l); } +.result-heading:focus { + outline: none; +} + .result-heading:focus-visible { outline: var(--focus-ring-width) solid var(--color-focus-ring); outline-offset: var(--focus-ring-offset); } + +@media (width < 43.75rem) { + .item { + padding: var(--space-4); + } +} + +@media (prefers-reduced-motion: reduce) { + .save-state[data-state="saving"] .save-mark { + animation: none; + } +} diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx index 2c2a717..c4cb1de 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; -import { useParams } from "react-router-dom"; +import { useLocation, useParams } from "react-router-dom"; import { ApiRequestError } from "../../../shared/api"; import { finalizeMyAssessmentAttempt, @@ -20,11 +20,14 @@ import { paths } from "../../../shared/config/paths"; import { Button, ButtonLink, + Card, ErrorState, ForbiddenState, LoadingState, + Mono, + Notice, Page, - Section, + Skeleton, VisuallyHidden, } from "../../../shared/ui"; import { @@ -38,6 +41,7 @@ import { parseAssessmentAttemptResponse, removeAssessmentQueries, removeAssessmentQueriesForSessionChange, + specializationLabels, useAssessmentAttempt, useAssessmentResult, } from "../../../entities/assessment"; @@ -55,6 +59,8 @@ import { useAssessmentSignals, useSignalNoticeGate, } from "../../../features/assessment-signals"; +import { forgetExpressStart } from "../model/express-start"; +import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar"; import attemptStyles from "./assessment-attempt-page.module.css"; type PendingFinalize = { key: string; body: AssessmentFinalization }; @@ -69,7 +75,16 @@ function isTerminal(attempt: AssessmentAttempt): boolean { function attemptName(attempt: AssessmentAttempt): string { if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск"; - return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`; + return `${attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`; +} + +function attemptTag(attempt: AssessmentAttempt): string { + if (attempt.kind === "demo_express") return "Демонстрация"; + const parts = [ + attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка", + attempt.target_grade ? gradeLabels[attempt.target_grade] : null, + ]; + return parts.filter(Boolean).join(" · "); } function answerErrorMessage(error: unknown): string { @@ -144,6 +159,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { const [answerBusy, setAnswerBusy] = useState(false); const [answerError, setAnswerError] = useState(null); const [answerNeedsReview, setAnswerNeedsReview] = useState(false); + const [answerSaved, setAnswerSaved] = useState(false); + const location = useLocation(); + const resumedExpress = Boolean( + (location.state as { expressResumed?: boolean } | null)?.expressResumed, + ); const [pendingFinalize, setPendingFinalize] = useState(null); const [finalizeBusy, setFinalizeBusy] = useState(false); const [pageError, setPageError] = useState(null); @@ -198,6 +218,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { resultQuery.isError, ]); + // A finished or expired express run cannot be resumed; its start key goes. + const expressFinishedId = + attempt && attempt.kind === "demo_express" && isTerminal(attempt) ? attempt.id : null; + const actorId = actor?.account.id ?? null; + useEffect(() => { + if (expressFinishedId && actorId) forgetExpressStart(actorId, expressFinishedId); + }, [actorId, expressFinishedId]); + async function refreshSessionForActor(currentActor: Session): Promise { const key = getGetCurrentSessionQueryKey(); const captured = queryClient.getQueryData(key); @@ -312,6 +340,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { setAnswerBusy(true); setAnswerError(null); setAnswerNeedsReview(false); + setAnswerSaved(false); try { const outcome = await submitPendingAnswerCommand( command, @@ -335,6 +364,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { setPendingAnswer(null); setAnswerError(null); setAnswerNeedsReview(false); + setAnswerSaved(true); setWorkReady(true); } catch (error: unknown) { if (!isCurrentAssessmentSession(queryClient, currentActor)) return; @@ -435,7 +465,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) { return ( - + + ); } if (!actorReady) { return ( - + ); } if (!attemptId) { return ( - + + ); @@ -479,7 +509,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { if (attemptQuery.isError || !attempt) { if (isAccessLoss(attemptQuery.error)) { return ( - + +
    -
    -
    - - Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items} - - - Срок до:{" "} - {new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format( - new Date(attempt.expires_at), - )} - - {attempt.sessions ? ( - - Сеанс {attempt.sessions.used} из {attempt.sessions.max} - - ) : null} -
    +
    +
    +

    + {attemptName(attempt)} +

    +

    + {methodLabel(attempt.mode) !== attemptName(attempt) + ? `${methodLabel(attempt.mode)}. ` + : ""} + Сервер хранит состояние и результат попытки. Срок до {deadline} + {attempt.sessions ? ( + <> + , сеанс {attempt.sessions.used} из{" "} + {attempt.sessions.max} + + ) : null} + . +

    +
    + + {!terminal ? ( + + ) : null} + + {resumedExpress && attempt.kind === "demo_express" && !terminal ? ( + +

    + Это тот же запуск: время идет с момента его начала, ответы сохранены на сервере. +

    +
    + ) : null} {pageError ? ( -

    - {pageError} -

    +
    + +

    {pageError}

    +
    +
    ) : null} {!workReady && !terminal ? ( -
    +

    Продолжение сверит актуальную версию с сервером. При перезагрузке задания не меняются, а ответ не отправляется повторно автоматически.

    {signalNotice.checkError ? ( -

    - {signalNotice.checkError} -

    +
    + +

    {signalNotice.checkError}

    +
    +
    ) : null} - -
    +
    + +
    + ) : null} {workReady && pendingAnswerNeedsReplay && !terminal ? ( -
    -

    Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.

    - +
    + void retryAnswer()}> + {answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"} + + } + > +

    + Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа. +

    +
    ) : null} @@ -598,10 +673,15 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { (!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
    -

    Задание {currentItem.sequence}

    - - {currentItem.sequence} из {attempt.progress.max_items} +

    Задание {currentItem.sequence}

    + + + {`${currentItem.sequence} из ${attempt.progress.max_items}`} +

    {currentItem.prompt}

    - Решение передано на проверку. Результат появится после ответа сервера; страница - обновляет статус автоматически. -

    +
    + +

    + Решение передано на проверку. Результат появится после ответа сервера; страница + обновляет статус автоматически. +

    +
    +
    ) : null} {workReady && @@ -635,18 +719,20 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { canFinalize && !terminal && !pendingAnswerNeedsReplay ? ( -
    +

    Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.

    - -
    +
    + +
    + ) : null} {workReady && @@ -655,20 +741,28 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { !canFinalize && !terminal && !pendingAnswerNeedsReplay ? ( -
    -

    Сервер не вернул следующее задание. Обновите состояние попытки.

    - + } > - Обновить попытку - +

    + Сервер не вернул следующее задание. Обновите состояние попытки. +

    +
    ) : null} {terminal ? : null} -
    +
    К доступным проверкам @@ -682,7 +776,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { function ResultView({ resultQuery }: { resultQuery: ReturnType }) { if (resultQuery.isPending && !resultQuery.data) { - return ; + return ( +
    + + +
    + ); } if (!resultQuery.data) { return ( diff --git a/frontend/src/pages/assessment/ui/assessment-express-start.test.ts b/frontend/src/pages/assessment/ui/assessment-express-start.test.ts new file mode 100644 index 0000000..a532e68 --- /dev/null +++ b/frontend/src/pages/assessment/ui/assessment-express-start.test.ts @@ -0,0 +1,187 @@ +import { setupServer } from "msw/node"; +import { http, HttpResponse } from "msw"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { ExpressRunElsewhereError, startExpressRun } from "./assessment-page.model"; +import { readExpressStart, recordExpressRun } from "../model/express-start"; + +const server = setupServer(); + +beforeAll(() => server.listen()); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +const accountId = "01928f7b-aaaa-7a2b-8c3d-4e5f6a7b8c9d"; +const activeRunId = "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d"; + +function expressAttempt(id: string) { + return { + id, + version: 1, + kind: "demo_express", + specialization: null, + target_grade: null, + task_language: null, + root_attempt_id: null, + chain_deadline: null, + mode: "demo_express", + state: "in_progress", + versions: { + policy_version: 1, + bank_version: "express-demo.2026-10.1", + algorithm_version: "express-interactive.1", + }, + started_at: "2026-10-08T10:00:00Z", + expires_at: "2026-10-08T10:05:00Z", + sessions: null, + finished_at: null, + progress: { answered_items: 0, max_items: 3 }, + current_item: null, + practices: [], + }; +} + +function problem(status: number, code: string) { + return HttpResponse.json( + { type: `urn:lincodex:problem:${code}`, title: code, status, code }, + { status, headers: { "Content-Type": "application/problem+json" } }, + ); +} + +function memoryStore() { + const values = new Map(); + return { + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => void values.set(key, value), + removeItem: (key: string) => void values.delete(key), + }; +} + +function routeFetchToMsw() { + const interceptedFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + interceptedFetch(new URL(input, "http://localhost"), init), + ); +} + +describe("demonstration express start", () => { + it("resumes the active run by replaying its stored key after 409 to a new start", async () => { + routeFetchToMsw(); + const store = memoryStore(); + recordExpressRun(accountId, "active-run-key", activeRunId, store); + const keys: Array = []; + server.use( + http.post("http://localhost/api/v1/me/assessment-attempts", ({ request }) => { + const key = request.headers.get("Idempotency-Key"); + keys.push(key); + // The server replays the stored 201 for the key that created the run. + if (key === "active-run-key") { + return HttpResponse.json(expressAttempt(activeRunId), { status: 201 }); + } + return problem(409, "state_conflict"); + }), + ); + + const outcome = await startExpressRun({ + accountId, + csrfToken: "csrf-token", + pendingKey: null, + newKey: () => "new-start-key", + store, + }); + + expect(keys).toEqual(["new-start-key", "active-run-key"]); + expect(outcome.resumed).toBe(true); + expect(outcome.attempt.id).toBe(activeRunId); + expect(readExpressStart(accountId, store)).toMatchObject({ + activeKey: "active-run-key", + activeAttemptId: activeRunId, + pendingKey: null, + }); + }); + + it("stores the key of a new run, and keeps a lost start's key for the next try", async () => { + routeFetchToMsw(); + const store = memoryStore(); + let fail = true; + const keys: Array = []; + server.use( + http.post("http://localhost/api/v1/me/assessment-attempts", ({ request }) => { + keys.push(request.headers.get("Idempotency-Key")); + if (fail) return problem(503, "service_unavailable"); + return HttpResponse.json(expressAttempt(activeRunId), { status: 201 }); + }), + ); + let factoryCalls = 0; + const newKey = () => `key-${++factoryCalls}`; + + await expect( + startExpressRun({ accountId, csrfToken: "csrf-token", pendingKey: null, newKey, store }), + ).rejects.toMatchObject({ status: 503 }); + expect(readExpressStart(accountId, store)?.pendingKey).toBe("key-1"); + + // After a reload the page has no key in memory; the stored one is repeated. + fail = false; + const outcome = await startExpressRun({ + accountId, + csrfToken: "csrf-token", + pendingKey: null, + newKey, + store, + }); + expect(keys).toEqual(["key-1", "key-1"]); + expect(outcome).toMatchObject({ resumed: false, attempt: { id: activeRunId } }); + expect(readExpressStart(accountId, store)).toMatchObject({ + activeKey: "key-1", + pendingKey: null, + }); + }); + + it("reports a run started elsewhere when 409 arrives without a stored key", async () => { + routeFetchToMsw(); + const store = memoryStore(); + const keys: Array = []; + server.use( + http.post("http://localhost/api/v1/me/assessment-attempts", ({ request }) => { + keys.push(request.headers.get("Idempotency-Key")); + return problem(409, "state_conflict"); + }), + ); + + await expect( + startExpressRun({ + accountId, + csrfToken: "csrf-token", + pendingKey: null, + newKey: () => "only-key", + store, + }), + ).rejects.toBeInstanceOf(ExpressRunElsewhereError); + expect(keys).toEqual(["only-key"]); + expect(readExpressStart(accountId, store)).toBeNull(); + }); + + it("forgets a stored key whose replay the server refuses", async () => { + routeFetchToMsw(); + const store = memoryStore(); + recordExpressRun(accountId, "stale-key", activeRunId, store); + server.use( + http.post("http://localhost/api/v1/me/assessment-attempts", () => + problem(409, "state_conflict"), + ), + ); + + await expect( + startExpressRun({ + accountId, + csrfToken: "csrf-token", + pendingKey: null, + newKey: () => "new-key", + store, + }), + ).rejects.toMatchObject({ status: 409 }); + expect(readExpressStart(accountId, store)).toBeNull(); + }); +}); diff --git a/frontend/src/pages/assessment/ui/assessment-page.model.ts b/frontend/src/pages/assessment/ui/assessment-page.model.ts index 5b1efe3..7b30845 100644 --- a/frontend/src/pages/assessment/ui/assessment-page.model.ts +++ b/frontend/src/pages/assessment/ui/assessment-page.model.ts @@ -4,8 +4,16 @@ import type { SpecializationCode, TaskLanguage, } from "../../../shared/api/schemas"; +import type { AssessmentAttempt } from "../../../shared/api/schemas"; +import { ApiRequestError } from "../../../shared/api"; import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment"; -import { parseAssessmentAttemptResponse } from "../../../entities/assessment"; +import { isOutcomeAmbiguous, parseAssessmentAttemptResponse } from "../../../entities/assessment"; +import { + beginExpressStart, + forgetExpressStart, + recordExpressRun, + settleRefusedExpressStart, +} from "../model/express-start"; export type PendingCreate = { key: string; body: AssessmentAttemptCreate }; @@ -47,3 +55,72 @@ export function submitPendingAttempt(command: PendingCreate, csrfToken: string) { headers: { "X-CSRF-Token": csrfToken } }, ).then((response) => parseAssessmentAttemptResponse(response, 201)); } + +/** 409 to an express start while another express run is active. */ +export function isActiveExpressConflict(error: unknown): boolean { + return ( + error instanceof ApiRequestError && + error.status === 409 && + error.code === "state_conflict" && + !error.fieldErrors.some((field) => field.code === "consent_required") + ); +} + +/** + * An express run is active, but this tab does not know the key that started + * it (another browser, a closed tab, or blocked storage). It ends by itself + * within five minutes. + */ +export class ExpressRunElsewhereError extends Error { + constructor(cause: unknown) { + super("An express run is active, and its start key is not stored in this tab.", { cause }); + this.name = "ExpressRunElsewhereError"; + } +} + +type ExpressStartOptions = { + accountId: string; + csrfToken: string; + /** Key of a start of this page whose outcome is not known yet. */ + pendingKey: string | null; + newKey: () => string; + /** Called with the key before the request, so a retry repeats it. */ + onKey?: (key: string) => void; + store?: Pick | null; +}; + +/** + * Starts the demonstration express run, or resumes the active one. A new start + * answered 409 state_conflict is replayed with the stored key of the active + * run; the server then returns the stored 201 with that run. + */ +export async function startExpressRun({ + accountId, + csrfToken, + pendingKey, + newKey, + onKey, + store, +}: ExpressStartOptions): Promise<{ attempt: AssessmentAttempt; resumed: boolean }> { + const body: AssessmentAttemptCreate = { kind: "demo_express" }; + const key = beginExpressStart(accountId, pendingKey, newKey, store); + onKey?.(key); + try { + const attempt = await submitPendingAttempt({ key, body }, csrfToken); + recordExpressRun(accountId, key, attempt.id, store); + return { attempt, resumed: false }; + } catch (error: unknown) { + if (isOutcomeAmbiguous(error)) throw error; + const activeKey = settleRefusedExpressStart(accountId, key, store); + if (!isActiveExpressConflict(error)) throw error; + if (!activeKey) throw new ExpressRunElsewhereError(error); + try { + const attempt = await submitPendingAttempt({ key: activeKey, body }, csrfToken); + recordExpressRun(accountId, activeKey, attempt.id, store); + return { attempt, resumed: true }; + } catch (replayError: unknown) { + if (!isOutcomeAmbiguous(replayError)) forgetExpressStart(accountId, undefined, store); + throw replayError; + } + } +} diff --git a/frontend/src/pages/assessment/ui/assessment-page.module.css b/frontend/src/pages/assessment/ui/assessment-page.module.css index 43b56f0..3f0aa96 100644 --- a/frontend/src/pages/assessment/ui/assessment-page.module.css +++ b/frontend/src/pages/assessment/ui/assessment-page.module.css @@ -1,12 +1,64 @@ +/* Phone first: one column; from 1024px the full check and the express run + * side by side. */ .layout { display: grid; gap: var(--space-5); + align-items: start; min-width: 0; } +@media (width >= 64rem) { + .layout { + grid-template-columns: minmax(0, 1fr) 20rem; + } + + .aside { + position: sticky; + top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4)); + } +} + +.main { + gap: var(--space-5); +} + +.aside { + min-width: 0; +} + +.block-header { + display: grid; + gap: var(--space-2); +} + +.kicker { + color: var(--color-accent); + font-family: var(--font-mono); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.block-title { + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + +.block-lead { + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.loading { + display: grid; + gap: var(--space-4); +} + .controls { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: minmax(0, 1fr); gap: var(--space-3); } @@ -20,108 +72,123 @@ .field select { width: 100%; min-width: 0; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); - color: var(--color-text); - background: var(--color-surface); - font: inherit; -} - -.field select:focus-visible { - outline: var(--line-strong) solid var(--color-accent); - outline-offset: 2px; + font-weight: var(--font-weight-regular); } .language-note, .language-availability { margin: 0; color: var(--color-text-secondary); + font-size: var(--font-size-s); } -.language-note { - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-divider); +.language-note strong { + color: var(--color-text); + font-family: var(--font-mono); } .language-availability { max-width: 72ch; - font-size: var(--font-size-s); } -.availability, -.express { +/* The chosen level: a nested surface with its category tag and status. */ +.availability { display: grid; - gap: var(--space-3); + gap: var(--space-4); min-width: 0; padding: var(--space-4); border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); + border-radius: var(--radius-s); + background: var(--color-canvas); } -.availability p, -.express p { +.availability p { margin: 0; } .status-row { display: flex; flex-wrap: wrap; - justify-content: space-between; gap: var(--space-2); + align-items: center; + justify-content: space-between; } -.status-row [data-state="available"] { - font-weight: var(--font-weight-bold); -} - +/* Policy limits as small readouts with mono values. */ .limits { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: var(--space-3); + gap: var(--space-2); margin: 0; } .limits div { + display: grid; + gap: var(--space-1); min-width: 0; padding: var(--space-3); - background: var(--color-canvas); - border-radius: var(--radius-s); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-xs); + background: var(--color-surface); } .limits dt { color: var(--color-text-secondary); - font-size: var(--font-size-s); + font-size: var(--font-size-xs); } .limits dd { - margin: var(--space-1) 0 0; - font-weight: var(--font-weight-bold); + margin: 0; + color: var(--color-text-strong); + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } -.express p, -.pending { +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.express { + gap: var(--space-3); +} + +.duration { + display: flex; + gap: var(--space-2); + align-items: baseline; color: var(--color-text-secondary); } +.duration > span:first-child { + color: var(--color-text-strong); + font-size: var(--font-size-title); +} + +.express-note { + color: var(--color-text-muted); + font-size: var(--font-size-xs); +} + .pending { margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); } -.error { - margin: 0; - color: var(--color-danger); +.notice-text { + color: var(--color-text); } -@media (width < 42rem) { - .controls, +@media (width >= 48rem) { + .controls { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .limits { - grid-template-columns: minmax(0, 1fr); - } - - .availability, - .express { - padding: var(--space-3); + grid-template-columns: repeat(4, minmax(0, 1fr)); } } diff --git a/frontend/src/pages/assessment/ui/assessment-page.tsx b/frontend/src/pages/assessment/ui/assessment-page.tsx index 9d97064..b965209 100644 --- a/frontend/src/pages/assessment/ui/assessment-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-page.tsx @@ -18,12 +18,17 @@ import { paths } from "../../../shared/config/paths"; import { Button, ButtonLink, + Card, EmptyState, ErrorState, ForbiddenState, LoadingState, + Mono, + Notice, Page, - Section, + Skeleton, + Tag, + type TagTone, } from "../../../shared/ui"; import { assessmentSessionMatches, @@ -46,7 +51,9 @@ import { } from "../../../features/assessment-signals"; import { buildRootAttemptCreate, + ExpressRunElsewhereError, preservePendingCreate, + startExpressRun, submitPendingAttempt, type PendingCreate, } from "./assessment-page.model"; @@ -78,6 +85,19 @@ function gradeStatusDescription(grade: AssessmentGradeAvailability): string { } } +function gradeStatusTag(grade: AssessmentGradeAvailability): { label: string; tone: TagTone } { + switch (grade.status) { + case "available": + return { label: "Доступна", tone: "success" }; + case "active_attempt": + return { label: "Есть попытка", tone: "accent" }; + case "cooldown": + return { label: "Пауза", tone: "neutral" }; + case "insufficient_bank": + return { label: "Банк не готов", tone: "neutral" }; + } +} + function formatDate(value: string): string { return new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", @@ -197,6 +217,7 @@ export function AssessmentPage() { const [pendingCreate, setPendingCreate] = useState(null); const [createBusy, setCreateBusy] = useState(false); const [formError, setFormError] = useState(null); + const [expressNote, setExpressNote] = useState(null); const [c3Required, setC3Required] = useState(false); const [accessDenied, setAccessDenied] = useState(false); const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null); @@ -370,13 +391,73 @@ export function AssessmentPage() { void signalNotice.guard(() => void startAttempt(body)); }; + async function startExpress() { + if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current) + return; + requestInFlight.current = true; + setCreateBusy(true); + setFormError(null); + setExpressNote(null); + setC3Required(false); + try { + const { attempt, resumed } = await startExpressRun({ + accountId: actor.account.id, + csrfToken: actor.csrf_token, + pendingKey: pendingCreate?.body.kind === "demo_express" ? pendingCreate.key : null, + newKey: newIdempotencyKey, + onKey: (key) => setPendingCreate({ key, body: { kind: "demo_express" } }), + }); + if (!isCurrentAssessmentSession(queryClient, actor)) return; + setPendingCreate(null); + navigate(paths.candidate.assessmentAttempt(attempt.id), { + state: resumed ? { expressResumed: true } : null, + }); + } catch (error: unknown) { + if (!isCurrentAssessmentSession(queryClient, actor)) return; + if ( + error instanceof ApiRequestError && + error.status === 403 && + error.code === "csrf_check_failed" + ) { + const refreshed = await refreshSessionForActor(actor); + if (refreshed) { + setFormError("Проверка входа обновлена. Повторите отправку теми же данными."); + } + return; + } + if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) { + removeAssessmentQueries(queryClient); + setAccessDenied(true); + return; + } + if (error instanceof ExpressRunElsewhereError) { + setPendingCreate(null); + setExpressNote( + "Незавершенная демонстрация открыта в другой вкладке или браузере. Продолжите ее там или подождите: она закончится сама не позже чем через 5 минут после начала.", + ); + return; + } + if (isOutcomeAmbiguous(error)) { + setExpressNote( + "Не удалось подтвердить начало демонстрации. Повторная отправка использует тот же ключ.", + ); + return; + } + setPendingCreate(null); + setExpressNote("Сервер не начал демонстрацию. Обновите страницу и повторите действие."); + } finally { + requestInFlight.current = false; + setCreateBusy(false); + } + } + const handleStartExpress = () => { - void startAttempt({ kind: "demo_express" }); + void startExpress(); }; if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) { return ( - + + ); } if (!actorReady) { return ( - + ); } + const statusTag = grade ? gradeStatusTag(grade) : null; + return (
    -
    + +
    +

    Полная проверка

    +

    + Доступность проверки +

    +

    Состояние и ограничения загружаются с сервера.

    +
    {(availability.isPending && !availability.data) || (questionnaire.isPending && !questionnaire.data) ? ( - +
    + + +
    ) : !data || !questionnaire.data ? ( ) : null} - {specialization && grade ? ( + {specialization && grade && statusTag ? (
    - {gradeLabels[grade.grade]} - - {grade.status === "available" - ? "Доступна" - : grade.status === "active_attempt" - ? "Есть попытка" - : grade.status === "cooldown" - ? "Пауза" - : "Банк не готов"} - + + {`${specializationLabels[specialization.specialization]} · ${gradeLabels[grade.grade]}`} + + + {statusTag.label} +

    {gradeStatusDescription(grade)}

    - {activeAttemptId && grade.status === "active_attempt" ? ( - - Продолжить текущую попытку - - ) : grade.status === "available" ? ( - - ) : null} +
    + {activeAttemptId && grade.status === "active_attempt" ? ( + + Продолжить текущую попытку + + ) : grade.status === "available" ? ( + + ) : null} +
    ) : null} - {pendingCreate ? ( + {pendingCreate && pendingCreate.body.kind !== "demo_express" ? (

    Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите ее с тем же ключом.

    ) : null} {formError ? ( -

    - {formError}{" "} - {c3Required ? ( - Открыть согласие C3 - ) : null} -

    +
    + Открыть согласие C3 + ) : null + } + > +

    {formError}

    +
    +
    ) : null} )} {signalNotice.checkError ? ( -

    - {signalNotice.checkError} -

    +
    + +

    {signalNotice.checkError}

    +
    +
    ) : null} -
    + -
    -
    -

    +

    -
    + {expressNote ? ( +
    + +

    {expressNote}

    +
    +
    + ) : null} + +
    diff --git a/frontend/src/pages/assessment/ui/attempt-focus-bar.tsx b/frontend/src/pages/assessment/ui/attempt-focus-bar.tsx new file mode 100644 index 0000000..cd8f27e --- /dev/null +++ b/frontend/src/pages/assessment/ui/attempt-focus-bar.tsx @@ -0,0 +1,89 @@ +import { useEffect, useState } from "react"; +import { toServerTime } from "../../../shared/api"; +import { Mono, Tag } from "../../../shared/ui"; +import { describeTimeLeft, formatTimeLeft } from "../model/countdown"; +import styles from "./assessment-attempt-page.module.css"; + +export type AnswerSaveState = "idle" | "saving" | "saved" | "unconfirmed" | "failed"; + +const saveLabels: Readonly> = { + idle: "Черновик ответа хранится в этой вкладке", + saving: "Отправляем ответ...", + saved: "Ответ сохранен на сервере", + unconfirmed: "Ответ не подтвержден: повторите отправку", + failed: "Ответ не сохранен", +}; + +/** Server time, refreshed every second while the attempt is open. */ +function useServerSecond(enabled: boolean): number { + const [now, setNow] = useState(() => toServerTime(Date.now())); + useEffect(() => { + if (!enabled) return; + const timer = window.setInterval(() => setNow(toServerTime(Date.now())), 1000); + return () => window.clearInterval(timer); + }, [enabled]); + return now; +} + +type AttemptFocusBarProps = { + label: string; + answered: number; + total: number; + expiresAt: string; + saveState: AnswerSaveState; + running: boolean; +}; + +/** + * The strip above the item: what is being taken, how far along, the time + * left until the server deadline in mono, and whether the last answer is + * saved. The timer is a role=timer element (not announced every second); the + * save state is a polite status message. + */ +export function AttemptFocusBar({ + label, + answered, + total, + expiresAt, + saveState, + running, +}: AttemptFocusBarProps) { + const now = useServerSecond(running); + const left = new Date(expiresAt).getTime() - now; + const urgent = running && left <= 60_000; + const share = total > 0 ? Math.min(100, Math.round((answered / total) * 100)) : 0; + + return ( +
    +
    + {label} +
    +
    +

    + Отвечено {answered} из {total} +

    +
    + +
    +
    +
    + До конца + + {formatTimeLeft(left)} + +
    +

    +

    +
    + ); +} diff --git a/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx b/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx index 3b579cf..31eeab1 100644 --- a/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx +++ b/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx @@ -8,7 +8,16 @@ import { assessmentResultSummary } from "../../../entities/assessment"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config"; -import { ButtonLink, EmptyState, Page, QueryView, Section, TextLink } from "../../../shared/ui"; +import { + ButtonLink, + Card, + EmptyState, + Mono, + Page, + QueryView, + Section, + TextLink, +} from "../../../shared/ui"; import { CandidateNextStep } from "../../../widgets/candidate-next-step"; import styles from "./candidate-home-page.module.css"; @@ -36,7 +45,7 @@ function searchStatusText(search: VisibilitySummary["searchStatus"]): string { function VisibilityFacts({ settings }: { settings: PrivacySettings }) { const visibility = summarizeVisibility(settings); return ( - <> +
    Карточка для компаний
    @@ -55,12 +64,12 @@ function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
    Статус поиска
    {searchStatusText(visibility.searchStatus)}
    -
    +
    Настроить видимость и согласия
    - + ); } @@ -84,17 +93,19 @@ function LatestResult({ page }: { page: AssessmentResultHistoryPage }) { if (!latest) return null; const summary = assessmentResultSummary(latest); return ( - <> +

    {summary.text}

    {summary.reason ?

    {summary.reason}

    : null} -

    Решение сохранено: {formatDate(latest.decided_at)}

    +

    + Решение сохранено: {formatDate(latest.decided_at)} +

    Открыть разбор результата История результатов
    - +
    ); } @@ -134,7 +145,6 @@ export function CandidateHomePage() { return ( diff --git a/frontend/src/pages/candidate-invitations/model/status-tone.test.ts b/frontend/src/pages/candidate-invitations/model/status-tone.test.ts new file mode 100644 index 0000000..cb3c39b --- /dev/null +++ b/frontend/src/pages/candidate-invitations/model/status-tone.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { invitationTagTone, isNewInvitation } from "./status-tone"; + +const now = Date.parse("2026-10-10T10:00:00Z"); +const open = "2026-10-12T10:00:00Z"; +const past = "2026-10-09T10:00:00Z"; + +describe("invitation status tone", () => { + it("accents an open decision and marks only an unopened one as new", () => { + expect(invitationTagTone({ state: "delivered", response_deadline_at: open }, now)).toBe( + "accent", + ); + expect(isNewInvitation({ state: "delivered", response_deadline_at: open }, now)).toBe(true); + expect(isNewInvitation({ state: "viewed", response_deadline_at: open }, now)).toBe(false); + }); + + it("closes an invitation past its deadline even before the server expires it", () => { + expect(invitationTagTone({ state: "delivered", response_deadline_at: past }, now)).toBe( + "neutral", + ); + expect(isNewInvitation({ state: "delivered", response_deadline_at: past }, now)).toBe(false); + }); + + it("repeats accepted and declined outcomes", () => { + expect(invitationTagTone({ state: "accepted", response_deadline_at: open }, now)).toBe( + "success", + ); + expect(invitationTagTone({ state: "declined", response_deadline_at: open }, now)).toBe( + "danger", + ); + }); +}); diff --git a/frontend/src/pages/candidate-invitations/model/status-tone.ts b/frontend/src/pages/candidate-invitations/model/status-tone.ts new file mode 100644 index 0000000..285a2c5 --- /dev/null +++ b/frontend/src/pages/candidate-invitations/model/status-tone.ts @@ -0,0 +1,31 @@ +import { isAnswerable } from "../../../entities/invitation"; +import type { CandidateInvitation } from "../../../shared/api/schemas"; +import type { TagTone } from "../../../shared/ui"; + +/** + * Tone of the status tag of an invitation. The text of the tag states the + * status; the tone only repeats it: an open decision is accented, an accepted + * one is a success, a declined one is danger, everything closed is neutral. + */ +export function invitationTagTone( + invitation: Pick, + serverNowMs: number, +): TagTone { + if (invitation.state === "accepted" || invitation.state === "terms_agreed") return "success"; + if (invitation.state === "declined") return "danger"; + if ( + (invitation.state === "delivered" || invitation.state === "viewed") && + isAnswerable(invitation, serverNowMs) + ) { + return "accent"; + } + return "neutral"; +} + +/** A delivered invitation that the candidate has not opened yet is new. */ +export function isNewInvitation( + invitation: Pick, + serverNowMs: number, +): boolean { + return invitation.state === "delivered" && isAnswerable(invitation, serverNowMs); +} diff --git a/frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.tsx b/frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.tsx index 31b714c..268e3bf 100644 --- a/frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.tsx +++ b/frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.tsx @@ -32,15 +32,20 @@ import type { import { paths } from "../../../shared/config"; import { ButtonLink, + Card, EmptyState, ErrorState, ForbiddenState, isAccessDenied, LoadingState, + Notice, Page, Section, + Skeleton, + Tag, TextLink, } from "../../../shared/ui"; +import { invitationTagTone } from "../model/status-tone"; import { InvitationTermsArticle } from "../../../widgets/invitation-preview"; import styles from "./candidate-invitations.module.css"; @@ -183,16 +188,18 @@ function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerS onFailure={(failure) => onFailure("accept", failure)} /> ) : ( -
    +

    Принять приглашение нельзя

    Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в профиль, чтобы принять приглашение.

    - - Открыть профиль - -
    +
    + + Открыть профиль + +
    + )} -
    + +
    +
    + Компания и срок +

    + {invitation.organization.name} +

    +
    + + + {candidateStatusLabel(invitation, serverNow)} + + +
    -
    Компания
    -
    {invitation.organization.name}
    -
    -
    -
    Состояние
    -
    {candidateStatusLabel(invitation, serverNow)}
    +
    Роль
    +
    {invitation.terms.role_title}
    Срок ответа
    -
    +
    -
    + {notice ? ( -

    - {notice} -

    +
    + +

    {notice}

    +
    +
    ) : null}
    @@ -330,14 +353,13 @@ export function CandidateInvitationPage() { const serverNow = useServerNow(); return ( - + {!validId ? : null} {validId && accountId !== "" && detail.isPending ? ( - + <> + + + ) : null} {validId && detail.isError ? ( isMissing(detail.error) ? ( diff --git a/frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.tsx b/frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.tsx index 36f31f8..df51197 100644 --- a/frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.tsx +++ b/frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.tsx @@ -11,6 +11,7 @@ import { import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { paths } from "../../../shared/config"; import { + AttentionDot, Button, EmptyState, ErrorState, @@ -18,7 +19,10 @@ import { isAccessDenied, LoadingState, Page, + Skeleton, + Tag, } from "../../../shared/ui"; +import { invitationTagTone, isNewInvitation } from "../model/status-tone"; import styles from "./candidate-invitations.module.css"; const lead = @@ -45,9 +49,12 @@ export function CandidateInvitationsPage() { const serverNow = useServerNow(); return ( - + {inbox.isPending && accountId !== "" ? ( - + <> + + + ) : null} {inbox.isError ? ( isAccessDenied(inbox.error) ? ( @@ -77,19 +84,24 @@ export function CandidateInvitationsPage() { {items.map((item) => (
  • - - Компания - {item.organization.name} + + + Компания + + {isNewInvitation(item, serverNow) ? ( + + ) : null} + {item.organization.name} + + + + {candidateStatusLabel(item, serverNow)} + {item.role_title} + {formatSalaryRange(item.salary)} - {formatSalaryRange(item.salary)} - - {`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`} - - - - {candidateStatusLabel(item, serverNow)} + {`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
  • diff --git a/frontend/src/pages/candidate-invitations/ui/candidate-invitations.module.css b/frontend/src/pages/candidate-invitations/ui/candidate-invitations.module.css index 26c2256..a9d03c9 100644 --- a/frontend/src/pages/candidate-invitations/ui/candidate-invitations.module.css +++ b/frontend/src/pages/candidate-invitations/ui/candidate-invitations.module.css @@ -17,19 +17,68 @@ .card { display: grid; - gap: var(--space-2); + gap: var(--space-3); + align-content: start; min-width: 0; min-height: 2.75rem; - padding: var(--space-4); + height: 100%; + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); color: var(--color-text); text-decoration: none; + transition: border-color var(--duration-fast) var(--easing-standard); } .card:hover { - border-color: var(--color-border-strong); + border-color: var(--color-border-hover); +} + +.card-head { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + align-items: flex-start; + justify-content: space-between; +} + +.salary { + color: var(--color-text-strong); + font-family: var(--font-mono); + font-size: 1.125rem; + font-weight: var(--font-weight-bold); + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} + +.mono { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; +} + +.summary { + gap: var(--space-4); +} + +.summary-head { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: flex-start; + justify-content: space-between; +} + +.summary-title { + color: var(--color-text-strong); + font-size: var(--font-size-xl); + overflow-wrap: anywhere; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); } .card:focus-visible { @@ -44,20 +93,28 @@ .card-label { color: var(--color-text-secondary); + font-family: var(--font-mono); font-size: var(--font-size-xs); letter-spacing: var(--letter-spacing-label); text-transform: uppercase; } .card-title { - overflow-wrap: anywhere; + display: inline-flex; + gap: var(--space-2); + align-items: center; + color: var(--color-text-strong); + font-family: var(--font-mono); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); + font-weight: var(--font-weight-medium); + overflow-wrap: anywhere; } .card-role { - overflow-wrap: anywhere; + color: var(--color-text); + font-family: var(--font-mono); font-weight: var(--font-weight-medium); + overflow-wrap: anywhere; } .card-facts { @@ -67,14 +124,6 @@ font-size: var(--font-size-s); } -.card-status { - justify-self: start; - padding: var(--space-1) var(--space-2); - border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-pill); - font-size: var(--font-size-xs); -} - .more { display: flex; justify-content: center; @@ -87,6 +136,12 @@ margin: 0; } +@media (width >= 48rem) { + .facts { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + .fact { display: grid; gap: var(--space-1); @@ -104,13 +159,13 @@ } .section-title { + color: var(--color-text-strong); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); } .subtitle { + color: var(--color-text-strong); font-size: var(--font-size-m); - font-weight: var(--font-weight-bold); } .text { @@ -119,29 +174,21 @@ overflow-wrap: anywhere; } -.notice { - margin: 0; - padding: var(--space-3); - border: var(--line-strong) solid var(--color-accent); - border-radius: var(--radius-s); - background: var(--color-surface); - line-height: var(--line-height-body); -} - .decisions { display: grid; gap: var(--space-5); + align-items: start; min-width: 0; } +@media (width >= 64rem) { + .decisions { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + .no-offer { - display: grid; - gap: var(--space-3); - min-width: 0; - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); - background: var(--color-surface); + align-content: start; } .grant { @@ -166,3 +213,9 @@ grid-template-columns: repeat(2, minmax(0, 1fr)); } } + +@media (width >= 80rem) { + .list { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} diff --git a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.module.css b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.module.css new file mode 100644 index 0000000..180c03c --- /dev/null +++ b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.module.css @@ -0,0 +1,64 @@ +.panel-title { + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + +.steps { + display: grid; + gap: var(--space-3); + margin: 0; + padding: 0; + list-style: none; +} + +@media (width >= 48rem) { + .steps { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +/* Each step is a nested surface; the current one is lit by the accent. */ +.step { + display: grid; + gap: var(--space-3); + align-content: start; + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-canvas); +} + +.step[data-current] { + border-color: var(--color-accent); +} + +.step-head { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + align-items: baseline; + color: var(--color-text-secondary); +} + +.step-title { + color: var(--color-text-strong); + font-size: var(--font-size-m); +} + +.step-text { + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.action { + display: flex; + flex-wrap: wrap; +} + +.note { + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} diff --git a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx index b7bc35b..935ec28 100644 --- a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx +++ b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx @@ -2,7 +2,45 @@ import { Navigate } from "react-router-dom"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { getOnboardingDestination } from "../../../entities/session"; import { paths } from "../../../shared/config"; -import { ButtonLink, LoadingState, Page, Section, StatusView } from "../../../shared/ui"; +import { + buildSteps, + ButtonLink, + Card, + LoadingState, + Mono, + Page, + StatusView, + Stepper, + Tag, +} from "../../../shared/ui"; +import styles from "./candidate-onboarding-page.module.css"; + +/** + * The account steps of a candidate in the order the server advances them. + * This page is shown only while the stored step is the first one. + */ +const accountSteps = [ + { + id: "candidate_consents", + label: "Согласия", + text: "Прочитайте тексты согласий C2-C5 и выберите каждое отдельно. C1 вы уже приняли при регистрации.", + }, + { + id: "candidate_profile", + label: "Профиль", + text: "Контакты, роли, опыт, навыки и условия работы. Все поля необязательны, резюме не нужно.", + }, + { + id: "candidate_questionnaire", + label: "Анкета", + text: "Одна или две специализации и уровень, на который вы претендуете. Это самооценка.", + }, + { + id: "candidate_assessment", + label: "Тест", + text: "Проверка подтверждает уровень. Подтвержденную категорию присваивает только сервер.", + }, +] as const; export function CandidateOnboardingPage() { const session = useGetCurrentSession(); @@ -32,20 +70,57 @@ export function CandidateOnboardingPage() { return ; } + const currentIndex = accountSteps.findIndex((item) => item.id === step); + return ( - -
    -

    - Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие - отдельно. + + +

    + Шаги аккаунта +

    + +
      + {accountSteps.map((item, index) => { + const isCurrent = index === currentIndex; + return ( +
    1. +
      + {String(index + 1).padStart(2, "0")} +

      + {item.label} +

      + {isCurrent ? ( + + сейчас + + ) : null} +
      +

      {item.text}

      + {isCurrent ? ( +
      + + Открыть согласия и настройки приватности + +
      + ) : null} +
    2. + ); + })} +
    +

    + Сохраненный шаг хранит сервер. Профиль, анкета и тест открываются из меню кабинета и + сохраняются независимо от него. Привязка ФСП ID и резюме для этого пути не нужны.

    - - Открыть согласия и настройки приватности - -
    +
    ); } diff --git a/frontend/src/pages/notifications/ui/notifications-pages.test.tsx b/frontend/src/pages/notifications/ui/notifications-pages.test.tsx index 89279fb..869c184 100644 --- a/frontend/src/pages/notifications/ui/notifications-pages.test.tsx +++ b/frontend/src/pages/notifications/ui/notifications-pages.test.tsx @@ -28,9 +28,9 @@ function render(scenario: "candidate" | "employer", element: React.ReactElement) } describe("notification pages", () => { - it("name the cabinet and carry the single h1", () => { + it("carry the single h1; the candidate shell names its cabinet next to the wordmark", () => { const candidate = render("candidate", ); - expect(candidate).toContain("Кабинет кандидата"); + expect(candidate).not.toContain("Кабинет кандидата"); expect(candidate.match(/

    ); expect(employer).toContain("Кабинет работодателя"); diff --git a/frontend/src/pages/notifications/ui/notifications-pages.tsx b/frontend/src/pages/notifications/ui/notifications-pages.tsx index 64f5ff8..8242f95 100644 --- a/frontend/src/pages/notifications/ui/notifications-pages.tsx +++ b/frontend/src/pages/notifications/ui/notifications-pages.tsx @@ -6,7 +6,7 @@ const lead = export function CandidateNotificationsPage() { return ( - + ); diff --git a/frontend/src/pages/privacy/ui/privacy-page.module.css b/frontend/src/pages/privacy/ui/privacy-page.module.css index e60281c..26065e8 100644 --- a/frontend/src/pages/privacy/ui/privacy-page.module.css +++ b/frontend/src/pages/privacy/ui/privacy-page.module.css @@ -6,15 +6,15 @@ } .note { - margin: 0.75rem 0 0; + margin: var(--space-3) 0 0; color: var(--color-text-secondary); - font-size: 0.925rem; - line-height: 1.55; + font-size: var(--font-size-s); + line-height: var(--line-height-body); } .organization-columns section { min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); @@ -22,7 +22,8 @@ .organization-columns h3 { margin: 0 0 var(--space-3); - font-size: 1rem; + color: var(--color-text-strong); + font-size: var(--font-size-m); } .organization-list, @@ -59,7 +60,13 @@ .history-list time, .history-list span { color: var(--color-text-secondary); - font-size: 0.9rem; + font-size: var(--font-size-s); +} + +.organization-list time, +.history-list time { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; } .history-list li { @@ -82,21 +89,68 @@ margin: 0; } -.error { - margin-block-start: var(--space-3); - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-danger); - background: var(--color-surface); +.notice-text { color: var(--color-text); } -.message { - margin-block-start: var(--space-3); - color: var(--color-text-secondary); +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +/* In-page contents as filter chips; on a phone the row scrolls sideways. */ +.contents { + min-width: 0; +} + +.contents ul { + display: flex; + gap: var(--space-2); + margin: 0; + padding: 0 0 var(--space-1); + overflow-x: auto; + list-style: none; + scrollbar-width: none; +} + +.contents-link { + display: inline-flex; + align-items: center; + min-height: 2.25rem; + padding: 0 var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-pill); + color: var(--color-text); + font-family: var(--font-mono); + font-size: var(--font-size-s); + white-space: nowrap; + text-decoration: none; + background: var(--color-surface); + transition: border-color var(--duration-fast) var(--easing-standard); +} + +.contents-link:hover { + border-color: var(--color-border-strong); +} + +.anchor { + display: grid; + gap: var(--space-7); + min-width: 0; + scroll-margin-block-start: var(--space-4); } @media (width < 48rem) { .organization-columns { grid-template-columns: minmax(0, 1fr); } + + /* On a phone the two lists are plain blocks: a card around a nested empty + * state would leave its text a narrow column. */ + .organization-columns section { + padding: 0; + border: 0; + background: none; + } } diff --git a/frontend/src/pages/privacy/ui/privacy-page.tsx b/frontend/src/pages/privacy/ui/privacy-page.tsx index 338622a..06540ee 100644 --- a/frontend/src/pages/privacy/ui/privacy-page.tsx +++ b/frontend/src/pages/privacy/ui/privacy-page.tsx @@ -61,6 +61,7 @@ import { ErrorState, ForbiddenState, LoadingState, + Notice, Page, Section, } from "../../../shared/ui"; @@ -68,6 +69,16 @@ import { candidateViewQueryKeys } from "../../../entities/candidate-view"; import styles from "./privacy-page.module.css"; const pageSize = 100; + +/** In-page contents: each settings block has an anchor. */ +const privacySections = [ + { id: "privacy-consents", label: "Согласия" }, + { id: "privacy-publication", label: "Публикация" }, + { id: "privacy-search", label: "Статус поиска" }, + { id: "privacy-preview", label: "Предпросмотр" }, + { id: "privacy-companies", label: "Компании" }, + { id: "privacy-history", label: "История" }, +] as const; const noOrganizations: ReadonlySet = new Set(); const privateQueryOptions = { gcTime: 0, @@ -302,14 +313,18 @@ export function OrganizationVisibility({

    {contactAccessAfterVisibilityChange}

    {actionError ? ( -
    - {actionError} +
    + +

    {actionError}

    +
    ) : null} {actionMessage ? ( -

    - {actionMessage} -

    +
    + +

    {actionMessage}

    +
    +
    ) : null} ); @@ -801,7 +816,7 @@ export function PrivacyPage() { if (session.isError) { return ( - + void session.refetch()} @@ -815,14 +830,14 @@ export function PrivacyPage() { if (session.isPending) return ; if (session.data?.account.scenario !== "candidate") { return ( - + ); } if (privateAccessLost) { return ( - + + void settingsQuery.refetch()} @@ -846,26 +861,38 @@ export function PrivacyPage() { return ( - {canShowConsentManagement ? ( - <> + +
    + {canShowConsentManagement ? ( + <> +
    + + + ) : (
    - - - ) : ( -
    - -
    - )} + description="Очищаем прежнюю приватную историю перед загрузкой текущего аккаунта." + > + +
    + )} +
    {c2State === "checking" ? (
    ) : null} - { - if (actor) setDraftState({ actorId: actor.account.id, value }); - }} - onSave={() => void savePublication()} - onReload={() => void reloadPublicationSettings()} - onOpenConsent={openConsentBlock} - /> - - void setSearchStatus(value)} - /> - -
    - void previewQuery.refetch()} +
    + { + if (actor) setDraftState({ actorId: actor.account.id, value }); + }} + onSave={() => void savePublication()} + onReload={() => void reloadPublicationSettings()} + onOpenConsent={openConsentBlock} /> -
    +
    - void accessHistory.fetchNextPage()} - hiddenOrganizations={hiddenOrganizations} - hiddenLoading={hiddenOrganizationsQuery.isPending} - hiddenError={hiddenOrganizationsQuery.error} - hiddenHasMore={Boolean(hiddenOrganizationsQuery.hasNextPage)} - hiddenFetching={hiddenOrganizationsQuery.isFetchingNextPage} - onLoadHidden={() => void hiddenOrganizationsQuery.fetchNextPage()} - pendingAction={pendingAction} - actionError={feedbackScope === "organization" ? actionError : null} - actionMessage={feedbackScope === "organization" ? actionMessage : null} - onHide={hideFromOrganization} - onUnhide={unhideOrganizationForCandidate} - /> + - void privacyHistory.fetchNextPage()} - /> +
    +
    + void previewQuery.refetch()} + /> +
    +
    - void accessHistory.fetchNextPage()} - /> +
    + void accessHistory.fetchNextPage()} + hiddenOrganizations={hiddenOrganizations} + hiddenLoading={hiddenOrganizationsQuery.isPending} + hiddenError={hiddenOrganizationsQuery.error} + hiddenHasMore={Boolean(hiddenOrganizationsQuery.hasNextPage)} + hiddenFetching={hiddenOrganizationsQuery.isFetchingNextPage} + onLoadHidden={() => void hiddenOrganizationsQuery.fetchNextPage()} + pendingAction={pendingAction} + actionError={feedbackScope === "organization" ? actionError : null} + actionMessage={feedbackScope === "organization" ? actionMessage : null} + onHide={hideFromOrganization} + onUnhide={unhideOrganizationForCandidate} + /> +
    + +
    + void privacyHistory.fetchNextPage()} + /> + + void accessHistory.fetchNextPage()} + /> +

    Можно запросить оценку специалистом до первого теста или после отзыва согласия на автоматическую оценку. Запрос не включает согласие обратно.

    - - Запросить ручную оценку - +
    + + Запросить ручную оценку + +
    ); diff --git a/frontend/src/pages/profile/ui/profile-page.tsx b/frontend/src/pages/profile/ui/profile-page.tsx index e7b8f12..3f42898 100644 --- a/frontend/src/pages/profile/ui/profile-page.tsx +++ b/frontend/src/pages/profile/ui/profile-page.tsx @@ -5,7 +5,6 @@ export function ProfilePage() { return ( diff --git a/frontend/src/pages/questionnaire/ui/questionnaire-page.tsx b/frontend/src/pages/questionnaire/ui/questionnaire-page.tsx index 4a481b9..9e4fbb3 100644 --- a/frontend/src/pages/questionnaire/ui/questionnaire-page.tsx +++ b/frontend/src/pages/questionnaire/ui/questionnaire-page.tsx @@ -5,7 +5,6 @@ export function QuestionnairePage() { return ( diff --git a/frontend/src/pages/support-cases/ui/support-cases-pages.module.css b/frontend/src/pages/support-cases/ui/support-cases-pages.module.css index 12e91bc..5f1ff5c 100644 --- a/frontend/src/pages/support-cases/ui/support-cases-pages.module.css +++ b/frontend/src/pages/support-cases/ui/support-cases-pages.module.css @@ -20,7 +20,7 @@ .event, .decision { min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); @@ -39,17 +39,10 @@ .event-heading h3, .decision h3 { margin: 0; + color: var(--color-text-strong); font-size: var(--font-size-l); } -.card-heading > span { - padding: var(--space-1) var(--space-2); - border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-pill); - font-size: var(--font-size-s); - font-weight: var(--font-weight-bold); -} - .case-card p, .event p, .decision p { @@ -65,6 +58,12 @@ font-size: var(--font-size-s); } +.date, +.event-heading time { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; +} + .more { margin-top: var(--space-4); } @@ -104,10 +103,6 @@ } @media (width <= 40rem) { - .actions > * { - width: 100%; - } - .facts { grid-template-columns: minmax(0, 1fr); gap: var(--space-1); diff --git a/frontend/src/pages/support-cases/ui/support-cases-pages.tsx b/frontend/src/pages/support-cases/ui/support-cases-pages.tsx index 981b0a4..feb539d 100644 --- a/frontend/src/pages/support-cases/ui/support-cases-pages.tsx +++ b/frontend/src/pages/support-cases/ui/support-cases-pages.tsx @@ -26,7 +26,7 @@ import { getMySupportCase, listMySupportCases, } from "../../../shared/api/endpoints/support/support"; -import type { Session, SupportCase } from "../../../shared/api/schemas"; +import type { Session, SupportCase, SupportCaseStatus } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config"; import { Button, @@ -37,11 +37,23 @@ import { LoadingState, Page, Section, + Tag, TextLink, + type TagTone, } from "../../../shared/ui"; import styles from "./support-cases-pages.module.css"; const supportCasePageSize = 20; + +// The label states the status; the tone only marks the one that waits for the candidate. +const supportCaseStatusTones: Readonly> = { + submitted: "neutral", + in_review: "neutral", + waiting_for_user: "accent", + waiting_expert: "neutral", + resolved: "success", + closed: "neutral", +}; const caseIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; function isCaseAccessError(error: unknown): error is ApiRequestError { @@ -204,9 +216,7 @@ export function SupportCasesPage() { return ( @@ -302,7 +312,9 @@ function SupportCaseSummaryCard({

    {supportCase.number}

    - {supportCaseStatusLabels[supportCase.status]} + + {supportCaseStatusLabels[supportCase.status]} +

    {supportCaseTypeLabels[supportCase.type]}

    {supportTargetDescription(supportCase.response_target)}

    diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx b/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx index d385a2e..059164f 100644 --- a/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx +++ b/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx @@ -1,7 +1,7 @@ import type { Ref } from "react"; import type { AssessmentResult } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config/paths"; -import { TextLink } from "../../../shared/ui"; +import { Mono, TextLink } from "../../../shared/ui"; import { describeAssessmentResult } from "../../../entities/assessment"; import styles from "./assessment-history.module.css"; @@ -23,7 +23,9 @@ export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHi const view = describeAssessmentResult(item, timeZone ? { timeZone } : {}); return (
  • -

    {view.kindLabel}

    +

    + {view.kindLabel} · {view.decidedDay} +

    {view.title}

    {view.summary.text}

    diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history.module.css b/frontend/src/widgets/assessment-history/ui/assessment-history.module.css index 63b35f0..aea3256 100644 --- a/frontend/src/widgets/assessment-history/ui/assessment-history.module.css +++ b/frontend/src/widgets/assessment-history/ui/assessment-history.module.css @@ -10,22 +10,60 @@ font-size: var(--font-size-s); } +/* A timeline: the results hang on a circuit trace, newest first. */ .list { + position: relative; display: grid; gap: var(--space-4); margin: 0; - padding: 0; + padding: 0 0 0 var(--space-5); list-style: none; } +.list::before { + position: absolute; + top: var(--space-5); + bottom: var(--space-5); + left: 0.25rem; + width: var(--line-thin); + content: ""; + background: var(--color-divider); +} + .item { + position: relative; display: grid; gap: var(--space-3); min-width: 0; - padding: var(--space-4); + padding: var(--space-5); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); + transition: border-color var(--duration-fast) var(--easing-standard); +} + +.item:hover { + border-color: var(--color-border-hover); +} + +.item::before { + position: absolute; + top: var(--space-5); + left: calc(-1 * var(--space-5) + 0.25rem - 0.25rem + 0.5px); + width: 0.5rem; + height: 0.5rem; + border: var(--line-thin) solid var(--color-accent); + border-radius: 50%; + content: ""; + background: var(--color-canvas); +} + +.item:first-child::before { + background: var(--color-accent); +} + +.more { + display: flex; } .item p { @@ -35,6 +73,7 @@ .kind { color: var(--color-text-secondary); + font-family: var(--font-mono); font-size: var(--font-size-xs); letter-spacing: var(--letter-spacing-label); text-transform: uppercase; @@ -42,6 +81,7 @@ .title { margin: 0; + color: var(--color-text-strong); font-size: var(--font-size-l); line-height: var(--line-height-snug); overflow-wrap: anywhere; @@ -76,7 +116,7 @@ @media (width < 42rem) { .item { - padding: var(--space-3); + padding: var(--space-4); } } diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history.tsx b/frontend/src/widgets/assessment-history/ui/assessment-history.tsx index aa8acfe..cf8cab7 100644 --- a/frontend/src/widgets/assessment-history/ui/assessment-history.tsx +++ b/frontend/src/widgets/assessment-history/ui/assessment-history.tsx @@ -9,6 +9,7 @@ import { ErrorState, ForbiddenState, LoadingState, + Skeleton, } from "../../../shared/ui"; import { isAssessmentAccessLoss, @@ -79,7 +80,14 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps /> ); } - if (history.isPending) return ; + if (history.isPending) { + return ( +
    + + +
    + ); + } if (history.isError && !history.data) { return ( void loadMore()} /> ) : history.hasNextPage ? ( - +
    + +
    ) : null}
  • ); diff --git a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css index 0ecedbd..430b3f1 100644 --- a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css +++ b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css @@ -3,32 +3,55 @@ gap: var(--space-6); } -/* The next step is the one dominant block of the home screen. */ +/* The next step is the one dominant block of the home screen: a panel with + * the circuit trace drawn behind its right half. */ .card { - display: grid; - gap: var(--space-3); - padding: var(--space-5); - border: var(--line-strong) solid var(--color-border-strong); - border-radius: var(--radius-l); - background: var(--color-surface); + position: relative; + overflow: hidden; + isolation: isolate; +} + +.decor { + position: absolute; + z-index: -1; + top: 50%; + right: calc(-1 * var(--space-6)); + width: min(28rem, 70%); + height: auto; + opacity: 0.55; + transform: translateY(-50%); +} + +@media (width < 48rem) { + .decor { + top: auto; + bottom: calc(-1 * var(--space-6)); + opacity: 0.3; + transform: none; + } } .card-eyebrow { color: var(--color-accent); + font-family: var(--font-mono); font-size: var(--font-size-xs); - font-weight: var(--font-weight-bold); + font-weight: var(--font-weight-medium); letter-spacing: var(--letter-spacing-label); text-transform: uppercase; } .card-title { - font-size: var(--font-size-xl); - font-weight: var(--font-weight-bold); - line-height: var(--line-height-snug); + max-width: 36rem; + color: var(--color-text-strong); + font-size: var(--font-size-title); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-display); + line-height: 1.2; } .card-text { - max-width: 44rem; + max-width: 40rem; + color: var(--color-text); font-size: var(--font-size-m); line-height: var(--line-height-body); } @@ -68,19 +91,26 @@ list-style: none; } -.standing, .link { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: center; + justify-content: space-between; min-width: 0; - padding: var(--space-4); + padding: var(--space-3) var(--space-4); border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-m); background: var(--color-surface); + transition: border-color var(--duration-fast) var(--easing-standard); +} + +.link:hover { + border-color: var(--color-border-hover); } .standing-title { - margin-bottom: var(--space-3); font-size: var(--font-size-m); - font-weight: var(--font-weight-bold); } .facts { @@ -108,16 +138,10 @@ overflow-wrap: anywhere; } -.link { - display: flex; - flex-wrap: wrap; - gap: var(--space-2) var(--space-4); - align-items: center; - justify-content: space-between; -} - .link-label { - font-weight: var(--font-weight-bold); + color: var(--color-text-strong); + font-family: var(--font-mono); + font-weight: var(--font-weight-medium); } .link-status { diff --git a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx index cdf79a2..d5977d4 100644 --- a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx +++ b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx @@ -11,12 +11,16 @@ import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/ide import { paths } from "../../../shared/config"; import { ButtonLink, + Card, + CircuitTrace, EmptyState, ErrorState, ForbiddenState, isAccessDenied, LoadingState, Section, + Skeleton, + Tag, TextLink, TrustLevel, } from "../../../shared/ui"; @@ -109,7 +113,8 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) { // produced a result, showing "consents" would contradict the result blocks. const showSavedStep = !journey.hasResults; return ( -
    + +

    Следующий шаг

    {view.title} @@ -135,7 +140,7 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) { : null}

    ) : null} -

    + ); } @@ -155,34 +160,40 @@ function Standings({ journey }: { journey: CandidateJourney }) { ) : (
      {journey.standings.map((standing) => ( -
    • -

      - {specializationLabels[standing.specialization]} -

      -
      -
      Заявлено (самооценка)
      -
      - -
      -
      Подтвержденная категория
      -
      - {standing.confirmedGrade ? ( +
    • + +

      + + {standing.confirmedGrade + ? `${specializationLabels[standing.specialization]} · ${gradeLabels[standing.confirmedGrade]}` + : specializationLabels[standing.specialization]} + +

      +
      +
      Заявлено (самооценка)
      +
      - ) : ( - - )} -
      -
      +
    • +
      Подтвержденная категория
      +
      + {standing.confirmedGrade ? ( + + ) : ( + + )} +
      +
      +
    • ))}
    @@ -291,7 +302,12 @@ export function CandidateNextStep() { ); } if (state.status === "pending") { - return ; + return ( +
    + + +
    + ); } if (state.status === "error") { if (isAccessDenied(state.error)) return ; diff --git a/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css b/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css index 72d0d85..a91e56e 100644 --- a/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css +++ b/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css @@ -100,3 +100,23 @@ padding: 0; } } + +/* A strip that hides tabs fades at that edge, so the cut tab reads as "more + * to scroll". The fade is a mask, so the strip keeps its own background. */ +.list[data-fade-end] { + mask-image: linear-gradient(to right, #000 calc(100% - 3rem), transparent); +} + +.list[data-fade-start] { + mask-image: linear-gradient(to left, #000 calc(100% - 3rem), transparent); +} + +.list[data-fade-start][data-fade-end] { + mask-image: linear-gradient( + to right, + transparent, + #000 3rem, + #000 calc(100% - 3rem), + transparent + ); +} diff --git a/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx b/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx index ef5fff8..d32099d 100644 --- a/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx +++ b/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useState, type RefObject } from "react"; import { Outlet, useLocation } from "react-router-dom"; import { paths } from "../../../shared/config"; import { HeaderPlate, MainRegion, NavItem, SkipLink, Wordmark } from "../../../shared/ui"; @@ -13,7 +13,7 @@ const navigation = [ { to: paths.candidate.invitations, label: "Приглашения", end: false }, { to: paths.candidate.notifications, label: "Уведомления", end: false }, { to: paths.candidate.privacy, label: "Приватность", end: false }, - { to: paths.support, label: "Поддержка", end: false }, + { to: paths.candidate.supportCases, label: "Поддержка", end: false }, ] as const; /** @@ -35,6 +35,38 @@ function useCurrentTabInView() { return listRef; } +type ScrollEdges = { start: boolean; end: boolean }; + +/** + * Whether the tab strip hides tabs before or after the visible part. The + * shell fades that edge, so a cut tab reads as "scroll for more". + */ +function useScrollEdges(listRef: RefObject): ScrollEdges { + const [edges, setEdges] = useState({ start: false, end: false }); + + useEffect(() => { + const list = listRef.current; + if (!list) return; + const update = () => { + const start = list.scrollLeft > 1; + const end = list.scrollLeft + list.clientWidth < list.scrollWidth - 1; + setEdges((current) => + current.start === start && current.end === end ? current : { start, end }, + ); + }; + update(); + list.addEventListener("scroll", update, { passive: true }); + const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update); + observer?.observe(list); + return () => { + list.removeEventListener("scroll", update); + observer?.disconnect(); + }; + }, [listRef]); + + return edges; +} + /** * Candidate cabinet layout, designed for phones first. On a phone the * section tabs form a bar at the bottom of the screen, within thumb reach; @@ -43,6 +75,7 @@ function useCurrentTabInView() { */ export function CandidateShell() { const listRef = useCurrentTabInView(); + const edges = useScrollEdges(listRef); return (
    @@ -51,7 +84,12 @@ export function CandidateShell() {