feat(frontend): redesign the candidate cabinet with step-by-step profile and questionnaire forms

This commit is contained in:
shira committed 2026-10-10 09:50:27 +03:00
1 parent 15590d127c
commit c836d02ea3
77 files changed
+4976 -1185

No files matched your search

+3 -3
View File
@@ -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. 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. `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. 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 ## Candidate visibility tests
+3 -3
View File
@@ -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/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) содержат только синтетические данные. `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 не меняются. Изолированный почтовый 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. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
## Тесты видимости кандидата ## Тесты видимости кандидата
+32
View File
@@ -131,11 +131,18 @@ async function grantC3(page: Page): Promise<void> {
async function saveAssessmentQuestionnaire(page: Page): Promise<void> { async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
await page.goto("/candidate/questionnaire"); await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); 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.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.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByRole("checkbox", { name: "Python", 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("checkbox", { name: "Удаленно", exact: true }).check();
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
const response = page.waitForResponse( const response = page.waitForResponse(
(item) => (item) =>
item.request().method() === "PUT" && 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; const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot;
expect(firstExpressSnapshot.current_item?.id).toBeTruthy(); 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 navigateInApp(page, `/candidate/assessment/${realAttempt.id}`);
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0); await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0);
+13
View File
@@ -159,6 +159,13 @@ test.describe("candidate home with the real backend", () => {
await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click(); await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click();
await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible(); await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible();
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат"); 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( const profileSaved = page.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && 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 page.getByRole("link", { name: "Заполнить анкету", exact: true }).first().click();
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); 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.getByLabel("Моя оценка уровня").selectOption("middle");
await page.getByRole("checkbox", { name: "Python", 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("checkbox", { name: "Удаленно", exact: true }).check();
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
const questionnaireSaved = page.waitForResponse( const questionnaireSaved = page.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && response.request().method() === "PUT" &&
+7
View File
@@ -606,11 +606,18 @@ async function grantC3(page: Page): Promise<void> {
async function saveAssessmentQuestionnaire(page: Page): Promise<void> { async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
await page.goto("/candidate/questionnaire"); await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); 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.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.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByRole("checkbox", { name: "Python", 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("checkbox", { name: "Удаленно", exact: true }).check();
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
const response = page.waitForResponse( const response = page.waitForResponse(
(item) => (item) =>
item.request().method() === "PUT" && item.request().method() === "PUT" &&
+9
View File
@@ -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. // Two declared specializations in the profile, none confirmed by a test.
await page.goto("/candidate/profile"); await page.goto("/candidate/profile");
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат"); 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.getByRole("button", { name: "Добавить специализацию" }).click(); await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByLabel("Специализация").nth(0).selectOption("backend"); await page.getByLabel("Специализация").nth(0).selectOption("backend");
await page.getByLabel("Специализация").nth(1).selectOption("network_engineer"); await page.getByLabel("Специализация").nth(1).selectOption("network_engineer");
await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle"); await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle");
await page.getByLabel("Моя оценка уровня").nth(1).selectOption("junior"); 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")); const profileSaved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile"));
await page.getByRole("button", { name: "Сохранить профиль" }).click(); await page.getByRole("button", { name: "Сохранить профиль" }).click();
expect((await profileSaved).status()).toBe(200); expect((await profileSaved).status()).toBe(200);
+56 -5
View File
@@ -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<void> {
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<void> {
await page.getByRole("button", { name: `Изменить: ${step}` }).click();
await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused();
}
async function openReview(page: Page): Promise<void> {
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<void> { async function saveProfile(page: Page, expectedStatus = 200): Promise<void> {
await openReview(page);
const responsePromise = page.waitForResponse( const responsePromise = page.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && response.request().method() === "PUT" &&
@@ -182,29 +211,47 @@ test.describe("candidate profile", () => {
await page.getByLabel("Телефон").fill("+79990000000"); await page.getByLabel("Телефон").fill("+79990000000");
await page.getByLabel("Telegram").fill("@candidate_123"); 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();
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(0).fill("Первая компания");
await page.getByLabel("Компания").nth(1).fill("Вторая компания"); await page.getByLabel("Компания").nth(1).fill("Вторая компания");
await page.getByLabel("Специализация").nth(0).selectOption("backend"); await experienceSpecialization.nth(0).selectOption("backend");
await page.getByLabel("Специализация").nth(1).selectOption("frontend"); await experienceSpecialization.nth(1).selectOption("frontend");
await page.getByLabel("Начало работы").nth(0).fill("2024-01"); await page.getByLabel("Начало работы").nth(0).fill("2024-01");
await page.getByLabel("Окончание работы").nth(0).fill("2024-12"); await page.getByLabel("Окончание работы").nth(0).fill("2024-12");
await page.getByLabel("Начало работы").nth(1).fill("2024-06"); await page.getByLabel("Начало работы").nth(1).fill("2024-06");
await page.getByLabel("Окончание работы").nth(1).fill("2025-01"); 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("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check();
await page.getByRole("button", { name: "Добавить специализацию" }).click(); await nextStep(page, "Навыки");
await page.getByLabel("Специализация").nth(2).selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByRole("button", { name: "Добавить навык" }).click(); await page.getByRole("button", { name: "Добавить навык" }).click();
await page.getByLabel("Навык 1", { exact: true }).fill("Go"); await page.getByLabel("Навык 1", { exact: true }).fill("Go");
await page.getByRole("button", { name: "Добавить гибкий навык" }).click(); await page.getByRole("button", { name: "Добавить гибкий навык" }).click();
await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация"); await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация");
await nextStep(page, "Условия");
await page.getByLabel("Желаемое место работы").fill("Москва"); await page.getByLabel("Желаемое место работы").fill("Москва");
await page.getByLabel("Готовность к переезду").selectOption("true"); await page.getByLabel("Готовность к переезду").selectOption("true");
await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000"); await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000");
await page.getByLabel("Сумма до или после налога").selectOption("gross"); 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); const pausedSave = await pauseProfileSave(page);
try { try {
@@ -226,6 +273,7 @@ test.describe("candidate profile", () => {
).toBeVisible(); ).toBeVisible();
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible(); await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
await editStep(page, "опыт", "Опыт");
await expect( await expect(
page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/), page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/),
).toBeVisible(); ).toBeVisible();
@@ -287,9 +335,11 @@ test.describe("candidate profile", () => {
await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click(); await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click();
await latestRead; await latestRead;
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName);
await editStep(page, "контакты", "Контакты");
await page.getByLabel("Имя и фамилия").fill(staleName); await page.getByLabel("Имя и фамилия").fill(staleName);
await saveProfile(page); await saveProfile(page);
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
await editStep(page, "контакты", "Контакты");
await expectResponsiveKeyboardFlow(page); await expectResponsiveKeyboardFlow(page);
await page.reload(); await page.reload();
@@ -303,6 +353,7 @@ test.describe("candidate profile", () => {
const firstAccount = await registerCandidate(page); const firstAccount = await registerCandidate(page);
const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`; const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`;
await page.getByLabel("Имя и фамилия").fill(firstProfileName); await page.getByLabel("Имя и фамилия").fill(firstProfileName);
await openReview(page);
const pausedSave = await pauseProfileSave(page); const pausedSave = await pauseProfileSave(page);
try { try {
+63 -11
View File
@@ -170,6 +170,30 @@ async function saveFromKeyboard(page: Page, expectedStatus: number): Promise<voi
expect((await responsePromise).status()).toBe(expectedStatus); expect((await responsePromise).status()).toBe(expectedStatus);
} }
// The questionnaire is a form in steps. "Далее" checks the visible step and
// moves the focus to the heading of the next one.
async function nextStep(page: Page, heading: string): Promise<void> {
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<void> {
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<void> {
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<Page> { async function createSecondSession(browser: Browser, email: string): Promise<Page> {
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const page = await context.newPage(); const page = await context.newPage();
@@ -228,25 +252,44 @@ test.describe("candidate questionnaire", () => {
expect(initial.version).toBe(0); expect(initial.version).toBe(0);
const specialization = page.getByLabel("Специализация", { exact: true }); const specialization = page.getByLabel("Специализация", { exact: true });
await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible();
await specialization.selectOption("ds_ml"); await specialization.selectOption("ds_ml");
await expect(page.getByText("Проверка: в разработке")).toBeVisible(); await expect(page.getByText("Проверка: в разработке")).toBeVisible();
await expect( await expect(
page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."), page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."),
).toBeVisible(); ).toBeVisible();
await expect(page.getByRole("button", { name: /проверку/i })).toHaveCount(0); 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 page.getByLabel("Моя оценка уровня").selectOption("senior");
await nextStep(page, "Формат работы");
await page.getByLabel("Удаленно").check(); 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 saveFromKeyboard(page, 200);
await expect( await expect(
page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/), page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/),
).toBeVisible(); ).toBeVisible();
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible(); await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await editStep(page, "направления", "Направления");
await specialization.selectOption("backend"); await specialization.selectOption("backend");
await nextStep(page, "Уровень и опыт");
await page.getByLabel("Моя оценка уровня").selectOption("junior"); await page.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByLabel("Стек технологий").fill("Go"); await page.getByLabel("Стек технологий").fill("Go");
await page.getByRole("button", { name: "Добавить технологию" }).click(); await page.getByRole("button", { name: "Добавить технологию" }).click();
await nextStep(page, "Формат работы");
await nextStep(page, "Проверка и сохранение");
const backendSave = page.waitForResponse( const backendSave = page.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && response.request().method() === "PUT" &&
@@ -267,9 +310,13 @@ test.describe("candidate questionnaire", () => {
]); ]);
await expect(page.getByText(/Анкета сохранена/)).toBeVisible(); await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
await page.reload(); 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("Специализация", { exact: true })).toHaveValue("backend");
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("junior"); 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.getByLabel("Стек технологий")).toHaveValue("");
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible(); await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await page.screenshot({ await page.screenshot({
@@ -280,7 +327,10 @@ test.describe("candidate questionnaire", () => {
const secondPage = await createSecondSession(browser, email); const secondPage = await createSecondSession(browser, email);
try { try {
await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await nextStep(secondPage, "Уровень и опыт");
await secondPage.getByLabel("Моя оценка уровня").selectOption("senior"); await secondPage.getByLabel("Моя оценка уровня").selectOption("senior");
await nextStep(secondPage, "Формат работы");
await nextStep(secondPage, "Проверка и сохранение");
const concurrentSave = secondPage.waitForResponse( const concurrentSave = secondPage.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && response.request().method() === "PUT" &&
@@ -289,8 +339,11 @@ test.describe("candidate questionnaire", () => {
await secondPage.getByRole("button", { name: "Сохранить анкету" }).click(); await secondPage.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await concurrentSave).status()).toBe(200); expect((await concurrentSave).status()).toBe(200);
await nextStep(page, "Уровень и опыт");
await nextStep(page, "Формат работы");
await page.getByLabel("Удаленно").uncheck(); await page.getByLabel("Удаленно").uncheck();
await page.getByLabel("В офисе").check(); await page.getByLabel("В офисе").check();
await nextStep(page, "Проверка и сохранение");
const staleSave = page.waitForResponse( const staleSave = page.waitForResponse(
(response) => (response) =>
response.request().method() === "PUT" && response.request().method() === "PUT" &&
@@ -319,6 +372,7 @@ test.describe("candidate questionnaire", () => {
await expect(secondPage.getByLabel("В офисе")).toBeChecked(); await expect(secondPage.getByLabel("В офисе")).toBeChecked();
await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked(); await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked();
await editStep(page, "направления", "Направления");
await checkResponsiveLayout(page); await checkResponsiveLayout(page);
} finally { } finally {
await secondPage.context().close(); await secondPage.context().close();
@@ -361,9 +415,7 @@ test.describe("candidate questionnaire", () => {
); );
await registerVerifiedCandidate(page); await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
await page.route("**/api/v1/me/questionnaire", async (route) => { await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "PUT") { if (route.request().method() === "PUT") {
await fulfillProblem(route, 403, "forbidden"); await fulfillProblem(route, 403, "forbidden");
@@ -393,9 +445,7 @@ test.describe("candidate questionnaire", () => {
); );
await registerVerifiedCandidate(page); await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let rejectSessionRefresh = false; let rejectSessionRefresh = false;
await page.route("**/api/v1/identity/sessions/current", async (route) => { await page.route("**/api/v1/identity/sessions/current", async (route) => {
if (rejectSessionRefresh) { if (rejectSessionRefresh) {
@@ -455,9 +505,7 @@ test.describe("candidate questionnaire", () => {
} }
await registerVerifiedCandidate(page); await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml"); await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let releaseOldResponse: () => void = () => undefined; let releaseOldResponse: () => void = () => undefined;
let markOldRequestHeld: () => void = () => undefined; let markOldRequestHeld: () => void = () => undefined;
@@ -517,7 +565,11 @@ test.describe("candidate questionnaire", () => {
expect((await oldSaveResponse).status()).toBe(200); expect((await oldSaveResponse).status()).toBe(200);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue(""); await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
await expect(page.getByLabel("Моя оценка уровня")).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); await expect(page.getByRole("button", { name: "Сохраняем анкету..." })).toHaveCount(0);
} finally { } finally {
cleanupStarted = true; cleanupStarted = true;
@@ -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 { .root {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-inline-start: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-canvas); background: var(--color-surface);
} }
.root[data-express="true"] { .root[data-express="true"] {
border-inline-start-style: dashed; border-style: dashed;
border-color: var(--color-border-hover);
} }
.root p { .root p {
@@ -24,7 +26,8 @@
} }
.kind { .kind {
color: var(--color-text-secondary); color: var(--color-accent);
font-family: var(--font-mono);
font-size: var(--font-size-xs); font-size: var(--font-size-xs);
letter-spacing: var(--letter-spacing-label); letter-spacing: var(--letter-spacing-label);
text-transform: uppercase; text-transform: uppercase;
@@ -32,6 +35,7 @@
.title { .title {
margin: 0; margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-xl); font-size: var(--font-size-xl);
line-height: var(--line-height-snug); line-height: var(--line-height-snug);
overflow-wrap: anywhere; overflow-wrap: anywhere;
@@ -47,17 +51,12 @@
display: none; 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 { .summary {
font-size: var(--font-size-m); color: var(--color-text-strong);
font-weight: var(--font-weight-bold); font-family: var(--font-mono);
font-size: 1.125rem;
font-weight: var(--font-weight-medium);
line-height: var(--line-height-snug);
} }
.demo { .demo {
@@ -87,6 +86,13 @@
overflow-wrap: anywhere; 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 { .block {
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-3);
@@ -119,6 +125,6 @@
@media (width < 42rem) { @media (width < 42rem) {
.root { .root {
padding: var(--space-3); padding: var(--space-4);
} }
} }
@@ -1,7 +1,7 @@
import { useId, type ReactNode } from "react"; import { useId, type ReactNode } from "react";
import type { AssessmentResult } from "../../../shared/api/schemas"; import type { AssessmentResult } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths"; 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 { describeAssessmentResult } from "../model/result-presentation";
import styles from "./assessment-result-view.module.css"; import styles from "./assessment-result-view.module.css";
@@ -54,9 +54,11 @@ export function AssessmentResultView({
{view.title} {view.title}
</Heading> </Heading>
<p className={styles.badges}> <p className={styles.badges}>
{view.isExpress ? <span className={styles.badge}>Демонстрация</span> : null} {view.isExpress ? <Tag tone="accent">Демонстрация</Tag> : null}
{!view.isExpress && view.isProvisional ? ( {!view.isExpress && view.isProvisional ? (
<span className={styles.badge}>Предварительный результат</span> <Tag tone="neutral" dot>
Предварительный результат
</Tag>
) : null} ) : null}
</p> </p>
</header> </header>
@@ -72,7 +74,7 @@ export function AssessmentResultView({
</> </>
) : null} ) : null}
<dl className={styles.facts}> <dl className={`${styles.facts} ${styles["facts-main"]}`}>
{view.facts.map((fact) => ( {view.facts.map((fact) => (
<div key={fact.label}> <div key={fact.label}>
<dt>{fact.label}</dt> <dt>{fact.label}</dt>
@@ -1,16 +1,17 @@
.form { .form {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
align-content: start;
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-strong) solid var(--color-accent); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
} }
.title { .title {
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
} }
.fieldset { .fieldset {
@@ -71,9 +72,9 @@
min-height: 2.75rem; min-height: 2.75rem;
min-width: 0; min-width: 0;
padding: var(--space-2) var(--space-3); 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); border-radius: var(--radius-s);
background: var(--color-surface); background: var(--color-canvas);
line-height: var(--line-height-body); line-height: var(--line-height-body);
cursor: pointer; cursor: pointer;
} }
@@ -91,18 +92,24 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.option:has(input:checked) {
border-color: var(--color-accent);
background: var(--color-accent-tint);
}
.option:has(input:focus-visible) { .option:has(input:focus-visible) {
outline: var(--focus-ring-width) solid var(--color-focus-ring); outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset); outline-offset: var(--focus-ring-offset);
} }
.alert { .alert {
padding: var(--space-3); padding: var(--space-3) var(--space-4);
border: var(--line-strong) solid var(--color-danger); border: var(--line-thin) solid var(--color-danger);
border-radius: var(--radius-s); border-radius: var(--radius-s);
background: var(--color-surface);
color: var(--color-text); color: var(--color-text);
line-height: var(--line-height-body); line-height: var(--line-height-body);
background:
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
} }
.alert:focus-visible { .alert:focus-visible {
@@ -4,49 +4,116 @@
min-width: 0; min-width: 0;
} }
/* The answer sits directly in the item panel: no second frame around it. */
.fields, .fields,
.code-lines { .code-lines {
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-3);
min-width: 0; min-width: 0;
margin: 0; margin: 0;
padding: var(--space-4); padding: 0;
border: var(--line-thin) solid var(--color-divider); border: 0;
border-radius: var(--radius-m);
} }
.legend, .legend,
.code-lines legend { .code-lines legend {
padding: 0 var(--space-2); float: left;
font-weight: var(--font-weight-bold); 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, .options,
.practice { .practice {
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-2);
min-width: 0; 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, .option,
.code-line { .code-line {
display: flex; display: flex;
align-items: flex-start;
gap: var(--space-3); gap: var(--space-3);
align-items: flex-start;
min-width: 0; min-width: 0;
padding: var(--space-3); padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); border-radius: var(--radius-s);
background: var(--color-canvas);
cursor: pointer; 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, .option input,
.code-line input { .code-line input {
flex: 0 0 auto; flex: 0 0 auto;
width: 1.2rem; margin-block-start: 0.2rem;
height: 1.2rem; }
margin-block-start: 0.15rem;
accent-color: var(--color-action); .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 { .field {
@@ -61,15 +128,14 @@
.field textarea { .field textarea {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); 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); font-weight: var(--font-weight-regular);
} }
.field input {
font-family: var(--font-mono);
}
.field textarea { .field textarea {
resize: vertical; resize: vertical;
font-family: var(--font-mono); font-family: var(--font-mono);
@@ -77,13 +143,6 @@
overflow-wrap: anywhere; 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 { .hint {
margin: 0; margin: 0;
color: var(--color-text-secondary); color: var(--color-text-secondary);
@@ -109,6 +168,7 @@
padding: var(--space-3); padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); border-radius: var(--radius-s);
background: var(--color-canvas);
} }
.order-actions, .order-actions,
@@ -119,16 +179,6 @@
align-items: center; 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 { .line-number {
flex: 0 0 2.5rem; flex: 0 0 2.5rem;
color: var(--color-text-secondary); color: var(--color-text-secondary);
@@ -171,10 +221,6 @@
} }
@media (width < 42rem) { @media (width < 42rem) {
.fields {
padding: var(--space-3);
}
.order-item { .order-item {
align-items: flex-start; align-items: flex-start;
} }
@@ -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 type { AssessmentItem } from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui"; import { Button } from "../../../shared/ui";
import type { AnswerDraft } from "../model/answer-draft"; import type { AnswerDraft } from "../model/answer-draft";
@@ -42,8 +42,33 @@ export function AnswerForm({
onSubmit(draft); 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<HTMLFormElement>) {
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<HTMLInputElement>(
`input[name="answer-${item.id}"]`,
)[Number(event.key) - 1];
if (!option) return;
event.preventDefault();
option.focus();
option.click();
}
return ( return (
<form className={styles.form} onSubmit={submit}> <form className={styles.form} onSubmit={submit} onKeyDown={handleKeyDown}>
<fieldset <fieldset
className={styles.fields} className={styles.fields}
disabled={frozen} disabled={frozen}
@@ -51,6 +76,12 @@ export function AnswerForm({
> >
<legend className={styles.legend}>Ваш ответ</legend> <legend className={styles.legend}>Ваш ответ</legend>
<AnswerFields item={item} draft={draft} setDraft={setDraft} /> <AnswerFields item={item} draft={draft} setDraft={setDraft} />
{item.content.format === "choice" ? (
<p className={styles.keys}>
<kbd>1</kbd>-<kbd>{Math.min(item.content.options.length, 9)}</kbd> выбирают вариант,{" "}
<kbd>Enter</kbd> отправляет ответ.
</p>
) : null}
</fieldset> </fieldset>
{errorMessage ? ( {errorMessage ? (
<p className={styles.error} id={errorId} role="alert"> <p className={styles.error} id={errorId} role="alert">
@@ -86,10 +117,10 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
const selected = draft.format === "choice" ? draft.optionIds : []; const selected = draft.format === "choice" ? draft.optionIds : [];
return ( return (
<div className={styles.options}> <div className={styles.options}>
{content.options.map((option) => { {content.options.map((option, index) => {
const checked = selected.includes(option.id); const checked = selected.includes(option.id);
return ( return (
<label className={styles.option} key={option.id}> <label className={styles.option} key={option.id} data-checked={checked || undefined}>
<input <input
type={content.multiple ? "checkbox" : "radio"} type={content.multiple ? "checkbox" : "radio"}
name={`answer-${item.id}`} name={`answer-${item.id}`}
@@ -104,7 +135,12 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
setDraft({ format: "choice", optionIds }); setDraft({ format: "choice", optionIds });
}} }}
/> />
<span>{option.text}</span> {index < 9 ? (
<kbd className={styles.keycap} aria-hidden="true">
{index + 1}
</kbd>
) : null}
<span className={styles["option-text"]}>{option.text}</span>
</label> </label>
); );
})} })}
@@ -24,16 +24,22 @@
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-3);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-4) var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
} }
.confirmation {
border-color: var(--color-danger);
}
.record-title { .record-title {
overflow-wrap: anywhere; color: var(--color-text-strong);
font-family: var(--font-mono);
font-size: var(--font-size-m); font-size: var(--font-size-m);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
} }
.organization-snapshot { .organization-snapshot {
@@ -57,33 +63,45 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.facts .mono {
font-family: var(--font-mono);
font-size: var(--font-size-s);
font-variant-numeric: tabular-nums;
}
.empty-purpose, .empty-purpose,
.notice, .notice,
.status-message,
.action-error { .action-error {
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.notice { .empty-purpose {
padding: var(--space-3); color: var(--color-text-secondary);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
} }
.status-message { /* Inline notes in the shape of the Notice primitive: a nested surface with
padding: var(--space-3); * a hairline and the accent stripe of the state. */
.notice {
padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-left: var(--line-strong) solid var(--color-accent); border-left: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-s);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
background: var(--color-canvas); background: var(--color-canvas);
} }
.action-error { .action-error {
padding: var(--space-3); border-radius: var(--radius-s);
border-left: var(--line-strong) solid var(--color-danger);
background: var(--color-canvas);
} }
.action-error button { .action-error:focus-visible {
margin-left: var(--space-2); outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.notice-text {
color: var(--color-text);
} }
.actions { .actions {
@@ -128,6 +146,7 @@
.consent-text { .consent-text {
max-height: 24rem; max-height: 24rem;
color: var(--color-text);
min-width: 0; min-width: 0;
overflow: auto; overflow: auto;
padding: var(--space-3); padding: var(--space-3);
@@ -20,7 +20,15 @@ import type {
ConsentSettingsRevokePurpose, ConsentSettingsRevokePurpose,
} from "../../../shared/api/schemas"; } from "../../../shared/api/schemas";
import { ApiRequestError } from "../../../shared/api"; import { ApiRequestError } from "../../../shared/api";
import { Button, EmptyState, ErrorState, LoadingState, Section } from "../../../shared/ui"; import {
Button,
EmptyState,
ErrorState,
LoadingState,
Notice,
Section,
Tag,
} from "../../../shared/ui";
import { import {
consentPurposeDetails, consentPurposeDetails,
consentSourceLabels, consentSourceLabels,
@@ -118,15 +126,19 @@ function ConsentRecordView({ record }: { record: ConsentRecord }) {
) : null} ) : null}
<dl className={styles.facts}> <dl className={styles.facts}>
<dt>Состояние</dt> <dt>Состояние</dt>
<dd>{consentStateLabels[record.state]}</dd> <dd>
<Tag tone={record.state === "active" ? "success" : "neutral"} dot>
{consentStateLabels[record.state]}
</Tag>
</dd>
<dt>Выдано</dt> <dt>Выдано</dt>
<dd>{formatConsentDate(record.granted_at)}</dd> <dd className={styles.mono}>{formatConsentDate(record.granted_at)}</dd>
<dt>Источник</dt> <dt>Источник</dt>
<dd>{consentSourceLabels[record.source]}</dd> <dd>{consentSourceLabels[record.source]}</dd>
{record.revoked_at ? ( {record.revoked_at ? (
<> <>
<dt>Отозвано</dt> <dt>Отозвано</dt>
<dd>{formatConsentDate(record.revoked_at)}</dd> <dd className={styles.mono}>{formatConsentDate(record.revoked_at)}</dd>
</> </>
) : null} ) : null}
{record.revocation_source ? ( {record.revocation_source ? (
@@ -556,9 +568,11 @@ export function ConsentManagement({
return ( return (
<div className={styles.root}> <div className={styles.root}>
{statusMessage ? ( {statusMessage ? (
<p className={styles["status-message"]} role="status" aria-live="polite"> <div role="status" aria-live="polite">
{statusMessage} <Notice tone="success">
</p> <p className={styles["notice-text"]}>{statusMessage}</p>
</Notice>
</div>
) : null} ) : null}
{actionError ? ( {actionError ? (
<div <div
@@ -568,12 +582,16 @@ export function ConsentManagement({
aria-live="assertive" aria-live="assertive"
tabIndex={-1} tabIndex={-1}
> >
{actionError} <Notice tone="danger">
<p className={styles["notice-text"]}>{actionError}</p>
</Notice>
</div> </div>
) : null} ) : null}
{history.isError && history.data ? ( {history.isError && history.data ? (
<div className={styles["action-error"]} role="alert"> <div className={styles["action-error"]} role="alert">
Не удалось обновить историю. Показаны последние загруженные данные. <Notice
tone="danger"
action={
<Button <Button
variant="quiet" variant="quiet"
isBusy={history.isRefetching} isBusy={history.isRefetching}
@@ -581,6 +599,12 @@ export function ConsentManagement({
> >
Обновить список Обновить список
</Button> </Button>
}
>
<p className={styles["notice-text"]}>
Не удалось обновить историю. Показаны последние загруженные данные.
</p>
</Notice>
</div> </div>
) : null} ) : null}
{!canMutate ? ( {!canMutate ? (
@@ -669,11 +693,13 @@ export function ConsentManagement({
<p className={styles["empty-purpose"]}>{emptyMessage}</p> <p className={styles["empty-purpose"]}>{emptyMessage}</p>
)} )}
{canRevoke && action && !isConfirmingPurpose ? ( {canRevoke && action && !isConfirmingPurpose ? (
<div className={styles.actions}>
<Button variant="secondary" onClick={() => beginConfirmation(action)}> <Button variant="secondary" onClick={() => beginConfirmation(action)}>
{purpose === "c1" {purpose === "c1"
? "Отозвать C1 и запросить удаление" ? "Отозвать C1 и запросить удаление"
: `Отозвать C${purpose.slice(1)}`} : `Отозвать C${purpose.slice(1)}`}
</Button> </Button>
</div>
) : null} ) : null}
{canRevoke && action && isConfirmingPurpose ? ( {canRevoke && action && isConfirmingPurpose ? (
<ActionConfirmation <ActionConfirmation
@@ -5,28 +5,35 @@
.intro { .intro {
max-width: 68ch; max-width: 68ch;
margin: 0 0 1.25rem; margin: 0 0 var(--space-5);
color: var(--color-text-muted); color: var(--color-text-secondary);
line-height: 1.65; line-height: var(--line-height-body);
} }
/* The form is one card of the system. */
.form { .form {
display: grid; display: grid;
gap: 1.25rem; gap: var(--space-5);
max-width: 52rem; max-width: 52rem;
padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
} }
.context { .context {
min-width: 0; min-width: 0;
padding: 1rem; margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-s);
background: var(--color-canvas);
} }
.context legend { .context legend {
padding: 0 0.35rem; padding: 0 0.35rem;
color: var(--color-text-strong); color: var(--color-text-strong);
font-weight: 650; font-weight: var(--font-weight-bold);
} }
.checkbox { .checkbox {
@@ -50,7 +57,7 @@
.field label { .field label {
color: var(--color-text-strong); color: var(--color-text-strong);
font-weight: 650; font-weight: var(--font-weight-bold);
} }
.field textarea { .field textarea {
@@ -59,14 +66,12 @@
min-width: 0; min-width: 0;
max-width: 100%; max-width: 100%;
min-height: 12rem; min-height: 12rem;
padding: 0.85rem;
resize: vertical; resize: vertical;
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); border-radius: var(--radius-s);
color: var(--color-text); color: var(--color-text);
background: var(--color-surface); background: var(--color-canvas);
font: inherit; line-height: var(--line-height-body);
line-height: 1.55;
} }
.field textarea:focus-visible, .field textarea:focus-visible,
@@ -81,17 +86,20 @@
.hint { .hint {
margin: 0; margin: 0;
color: var(--color-text-muted); color: var(--color-text-secondary);
font-size: 0.92rem; font-size: var(--font-size-s);
line-height: 1.5; line-height: var(--line-height-body);
} }
/* An error in the shape of the danger Notice: a nested surface with a red
* hairline and a faint red wash. */
.error { .error {
padding: 0.85rem 1rem; padding: var(--space-3) var(--space-4);
border-inline-start: var(--line-strong) solid var(--color-danger); border: var(--line-thin) solid var(--color-danger);
border-radius: var(--radius-s); border-radius: var(--radius-s);
color: var(--color-text); color: var(--color-text);
background: var(--color-surface); background:
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
} }
.error:focus { .error:focus {
@@ -107,11 +115,11 @@
} }
@media (width <= 40rem) { @media (width <= 40rem) {
.form {
padding: var(--space-4);
}
.actions > * { .actions > * {
max-width: 100%; max-width: 100%;
} }
.actions button {
width: 100%;
}
} }
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { profileStepOfField } from "./profile-steps";
describe("profile steps", () => {
it("opens the step that owns a client or server issue", () => {
expect(profileStepOfField("fullName")).toBe("contacts");
expect(profileStepOfField("contacts.phone")).toBe("contacts");
expect(profileStepOfField("roles.1.self_assessed_grade")).toBe("roles");
expect(profileStepOfField("experience.2.ended_on")).toBe("experience");
expect(profileStepOfField("experience.overlaps")).toBe("experience");
expect(profileStepOfField("stack.0.tag")).toBe("skills");
expect(profileStepOfField("softSkills.3.skill")).toBe("skills");
expect(profileStepOfField("terms.salaryMinimum.amount")).toBe("terms");
expect(profileStepOfField("form")).toBe("review");
});
});
@@ -0,0 +1,26 @@
/** Steps of the profile form, in order. */
export type ProfileStepId = "contacts" | "roles" | "experience" | "skills" | "terms" | "review";
/**
* The step that owns a profile form field, so a client or server issue opens
* the step where it can be fixed. General and unknown fields go to review.
*/
export function profileStepOfField(field: string): ProfileStepId {
const root = field.split(".")[0] ?? "";
switch (root) {
case "fullName":
case "contacts":
return "contacts";
case "roles":
return "roles";
case "experience":
return "experience";
case "stack":
case "softSkills":
return "skills";
case "terms":
return "terms";
default:
return "review";
}
}
@@ -1,61 +1,90 @@
.root { /* Phone first: one column; from 1024px the form and a side note. */
.layout {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
align-items: start;
min-width: 0; min-width: 0;
} }
.root > section { @media (width >= 64rem) {
min-width: 0; .layout {
grid-template-columns: minmax(0, 1fr) 18rem;
} }
.server-step, .aside {
.form-error, position: sticky;
.conflict, top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4));
.continuation { }
min-width: 0; }
margin: 0 0 var(--space-4);
padding: var(--space-4); .panel {
border: var(--line-thin) solid var(--color-divider); gap: var(--space-5);
border-radius: var(--radius-m); }
background: var(--color-surface);
overflow-wrap: anywhere; .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 { .server-step {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s);
} }
.form-error, .server-step strong {
.conflict { color: var(--color-text);
border-width: var(--line-strong); font-family: var(--font-mono);
border-color: var(--color-danger);
}
.form-error {
font-weight: var(--font-weight-medium); font-weight: var(--font-weight-medium);
} }
.conflict h2 { .notice-title {
margin: 0 0 var(--space-2); margin-bottom: var(--space-1);
font-size: var(--font-size-l); color: var(--color-danger);
font-size: var(--font-size-m);
} }
.conflict p, .notice-text {
.continuation p { color: var(--color-text);
margin: 0 0 var(--space-3); }
.aside {
min-width: 0;
}
.aside-title {
color: var(--color-text-strong);
font-size: var(--font-size-m);
}
.aside-text,
.aside-note {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
.continuation { .aside-note {
display: flex; padding-top: var(--space-3);
flex-wrap: wrap; border-top: var(--line-thin) solid var(--color-divider);
gap: var(--space-3);
align-items: center;
justify-content: space-between;
margin: var(--space-5) 0 0;
} }
.continuation p { .legend {
flex: 1 1 16rem; display: grid;
gap: var(--space-2);
margin: 0; margin: 0;
padding: 0;
list-style: none;
}
.loading {
display: grid;
gap: var(--space-4);
} }
@@ -25,10 +25,13 @@ import { paths } from "../../../shared/config";
import { import {
Button, Button,
ButtonLink, ButtonLink,
Card,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Section, Notice,
Skeleton,
TrustLevel,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { ProfileForm } from "./profile-form"; import { ProfileForm } from "./profile-form";
import styles from "./edit-profile.module.css"; import styles from "./edit-profile.module.css";
@@ -62,6 +65,15 @@ function ProfileAccessDenied({ error }: { error: unknown }) {
); );
} }
function EditorLoading({ label }: { label: string }) {
return (
<div className={styles.loading}>
<LoadingState label={label} />
<Skeleton shape="card" lines={4} />
</div>
);
}
export function EditProfile() { export function EditProfile() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const profile = useGetMyProfile({ const profile = useGetMyProfile({
@@ -92,7 +104,7 @@ export function EditProfile() {
}, [profileAccessError, queryClient, sessionAccessError]); }, [profileAccessError, queryClient, sessionAccessError]);
if (profile.isPending && !profile.data) { if (profile.isPending && !profile.data) {
return <LoadingState label="Загружаем профиль кандидата..." />; return <EditorLoading label="Загружаем профиль кандидата..." />;
} }
if (profileAccessError) { if (profileAccessError) {
return <ProfileAccessDenied error={profileAccessError} />; return <ProfileAccessDenied error={profileAccessError} />;
@@ -130,7 +142,7 @@ export function EditProfile() {
/> />
); );
} }
return <LoadingState label="Проверяем текущий вход..." />; return <EditorLoading label="Проверяем текущий вход..." />;
} }
if (session.data.account.scenario !== "candidate") { if (session.data.account.scenario !== "candidate") {
return ( return (
@@ -294,26 +306,23 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
const continuationLabel = savedStep ? stepLabel(savedStep) : null; const continuationLabel = savedStep ? stepLabel(savedStep) : null;
return ( return (
<div className={styles.root}> <div className={styles.layout}>
<Section <Card as="section" tone="panel" labelledBy="profile-title" className={styles.panel}>
title="Личные сведения" <header className={styles["panel-header"]}>
description="Заполните только то, что готовы указать. Профиль сохраняется на сервере и не требует резюме или внешнего аккаунта." <h2 id="profile-title" className={styles["panel-title"]}>
> Личные сведения
</h2>
{currentStep ? ( {currentStep ? (
<p className={styles["server-step"]}> <p className={styles["server-step"]}>
Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>. Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>.
</p> </p>
) : null} ) : null}
</header>
{conflict ? ( {conflict ? (
<div className={styles.conflict} role="alert" aria-labelledby="profile-conflict-title"> <div role="alert" aria-labelledby="profile-conflict-title">
<h2 id="profile-conflict-title">Профиль обновлен в другом окне</h2> <Notice
<p> tone="danger"
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не action={
выполняются. При замене черновика данные из этой формы будут удалены.
</p>
{latestLoadError ? (
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
) : null}
<Button <Button
variant="secondary" variant="secondary"
isBusy={profileQuery.isRefetching} isBusy={profileQuery.isRefetching}
@@ -324,16 +333,35 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
? "Загружаем текущую версию..." ? "Загружаем текущую версию..."
: "Заменить черновик актуальной версией"} : "Заменить черновик актуальной версией"}
</Button> </Button>
}
>
<h3 id="profile-conflict-title" className={styles["notice-title"]}>
Профиль обновлен в другом окне
</h3>
<p>
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не
выполняются. При замене черновика данные из этой формы будут удалены.
</p>
{latestLoadError ? (
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
) : null}
</Notice>
</div> </div>
) : null} ) : null}
{forbidden ? ( {forbidden ? (
<div className={styles["form-error"]} role="alert"> <div role="alert">
<Notice tone="danger">
<p className={styles["notice-text"]}>
Профиль больше недоступен. Данные формы останутся до ухода со страницы. Профиль больше недоступен. Данные формы останутся до ухода со страницы.
</p>
</Notice>
</div> </div>
) : null} ) : null}
{formError ? ( {formError ? (
<div className={styles["form-error"]} role="alert"> <div role="alert">
{formError} <Notice tone="danger">
<p className={styles["notice-text"]}>{formError}</p>
</Notice>
</div> </div>
) : null} ) : null}
<ProfileForm <ProfileForm
@@ -345,18 +373,50 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
onSubmit={() => void handleSubmit()} onSubmit={() => void handleSubmit()}
/> />
{savedStep && continuation ? ( {savedStep && continuation ? (
<div className={styles.continuation} role="status"> <div role="status">
<p>Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.</p> <Notice
{continuation !== paths.candidate.profile ? ( tone="success"
action={
continuation !== paths.candidate.profile ? (
<ButtonLink to={continuation} variant="secondary"> <ButtonLink to={continuation} variant="secondary">
Открыть сохраненный шаг Открыть сохраненный шаг
</ButtonLink> </ButtonLink>
) : ( ) : null
}
>
<p className={styles["notice-text"]}>
Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.
</p>
{continuation === paths.candidate.profile ? (
<p>Серверный шаг остается «Профиль».</p> <p>Серверный шаг остается «Профиль».</p>
)} ) : null}
</Notice>
</div> </div>
) : null} ) : null}
</Section> </Card>
<aside className={styles.aside} aria-labelledby="profile-aside-title">
<Card tone="raised">
<h2 id="profile-aside-title" className={styles["aside-title"]}>
Кто что видит
</h2>
<p className={styles["aside-text"]}>
Профиль сохраняется на сервере и не требует резюме или внешнего аккаунта. Имя и контакты
компании получают только после вашего согласия на конкретное приглашение.
</p>
<ul className={styles.legend}>
<li>
<TrustLevel level="claimed" label="Заявлено вами" />
</li>
<li>
<TrustLevel level="confirmed" label="Подтверждено тестом" />
</li>
</ul>
<p className={styles["aside-note"]}>
Черновик живет только на этой странице: он не записывается в браузерное хранилище и
отправляется целиком на последнем шаге.
</p>
</Card>
</aside>
</div> </div>
); );
} }
@@ -0,0 +1,140 @@
/* Phone first. The same rules live in the questionnaire 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);
}
@@ -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 questionnaire feature;
* it belongs in shared/ui once both forms settle (see the frontend README).
*/
export type { FormStep };
type FormProgressProps<TId extends string> = {
label: string;
steps: readonly FormStep<TId>[];
index: number;
};
/** The Stepper of the form; on a phone only the markers and the count stay. */
export function FormProgress<TId extends string>({ label, steps, index }: FormProgressProps<TId>) {
return (
<div className={styles.progress}>
<Stepper label={label} steps={buildSteps(steps, index)} />
</div>
);
}
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 (
<section className={styles.step} hidden={!active} aria-labelledby={headingId}>
<header className={styles.header}>
<h3 id={headingId} ref={headingRef} tabIndex={-1} className={styles.title}>
<VisuallyHidden>{`Шаг ${position} из ${total}. `}</VisuallyHidden>
{step.label}
</h3>
{description ? <div className={styles.description}>{description}</div> : null}
</header>
<div className={styles.body}>{children}</div>
</section>
);
}
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 (
<div className={styles.footer}>
<div className={styles["footer-back"]}>{back}</div>
<div className={styles["footer-forward"]}>{children}</div>
</div>
);
}
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 (
<section className={styles.review} aria-labelledby={headingId}>
<div className={styles["review-header"]}>
<h4 id={headingId} className={styles["review-title"]}>
{title}
</h4>
<button
type="button"
className={styles.edit}
disabled={disabled}
aria-label={`Изменить: ${editLabel}`}
onClick={onEdit}
>
Изменить
</button>
</div>
{children}
</section>
);
}
@@ -1,12 +1,12 @@
.form { .form {
display: grid; display: grid;
gap: var(--space-6); gap: var(--space-5);
min-width: 0; min-width: 0;
} }
.editor-fields { .editor-fields {
display: grid; display: grid;
gap: var(--space-6); gap: var(--space-5);
min-width: 0; min-width: 0;
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -24,53 +24,25 @@
.issue-summary { .issue-summary {
min-width: 0; min-width: 0;
padding: var(--space-4); border-radius: var(--radius-s);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-m);
background: var(--color-surface);
} }
.issue-summary h2, .issue-list {
.categories h2 { display: grid;
gap: var(--space-1);
margin: 0; margin: 0;
font-size: var(--font-size-l);
}
.issue-summary ul,
.categories ul {
margin: var(--space-3) 0 0;
padding-left: var(--space-5); padding-left: var(--space-5);
} }
.group { .issue-step {
display: grid; color: var(--color-text);
gap: var(--space-4); font-weight: var(--font-weight-medium);
min-width: 0;
margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.group legend {
max-width: 100%;
padding-inline: var(--space-2);
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.group-description,
.hint,
.categories p {
margin: 0;
color: var(--color-text-secondary);
line-height: var(--line-height-body);
} }
.field { .field {
display: grid; display: grid;
gap: var(--space-2); gap: var(--space-2);
align-content: start;
min-width: 0; min-width: 0;
} }
@@ -81,17 +53,17 @@
.field input, .field input,
.field select, .field select,
.field textarea { .field textarea {
box-sizing: border-box;
width: 100%; width: 100%;
min-width: 0; min-width: 0;
max-width: 100%; max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); }
color: var(--color-text);
background: var(--color-surface); .field input[type="number"],
font: inherit; .field input[type="month"],
.field input[type="tel"] {
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
} }
.field textarea { .field textarea {
@@ -101,28 +73,9 @@
.field input[aria-invalid="true"], .field input[aria-invalid="true"],
.field select[aria-invalid="true"], .field select[aria-invalid="true"],
.field textarea[aria-invalid="true"] { .field textarea[aria-invalid="true"] {
border-width: var(--line-strong);
border-color: var(--color-danger); border-color: var(--color-danger);
} }
.overlap input {
width: 1.25rem;
height: 1.25rem;
margin: 0.125rem 0 0;
}
.overlap input:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.field input:focus-visible,
.field select:focus-visible,
.field textarea:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.hint, .hint,
.error, .error,
.claim-status { .claim-status {
@@ -130,26 +83,37 @@
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
.hint {
color: var(--color-text-secondary);
}
.error { .error {
margin: 0; margin: 0;
color: var(--color-text); color: var(--color-danger);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-bold);
} }
.claim-status { .claim-status {
justify-self: start;
padding: 0 var(--space-2);
border-radius: var(--radius-pill);
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-family: var(--font-mono);
font-size: var(--font-size-xs);
background: var(--color-surface-tint);
} }
/* A suggestion from a document: a quiet nested note under the field. */
.suggestion { .suggestion {
min-width: 0; min-width: 0;
padding: var(--space-2) var(--space-3); padding: var(--space-2) var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent); border: var(--line-thin) solid var(--color-divider);
background: var(--color-canvas); border-radius: var(--radius-s);
background: var(--color-surface-tint);
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.suggestion summary { .suggestion summary {
cursor: pointer;
font-size: var(--font-size-s); font-size: var(--font-size-s);
font-weight: var(--font-weight-medium); font-weight: var(--font-weight-medium);
} }
@@ -161,22 +125,24 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
/* A repeated row (a role, a workplace): a nested surface inside the panel. */
.item { .item {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-s);
background: var(--color-canvas);
} }
.item-header, .item-header,
.item-actions, .item-actions,
.list-row, .list-row,
.actions { .add-row {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-3); gap: var(--space-2) var(--space-3);
align-items: center; align-items: center;
min-width: 0; min-width: 0;
} }
@@ -185,16 +151,17 @@
justify-content: space-between; justify-content: space-between;
} }
.item-header h3, .item-header h4,
.list h3, .list h4,
.overlap-list h3 { .overlap-list h4,
margin: 0; .categories h4 {
color: var(--color-text-strong);
font-size: var(--font-size-m); font-size: var(--font-size-m);
} }
.grid { .grid {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: minmax(0, 1fr);
gap: var(--space-4); gap: var(--space-4);
min-width: 0; min-width: 0;
} }
@@ -206,6 +173,11 @@
min-width: 0; min-width: 0;
} }
.list + .list {
padding-top: var(--space-4);
border-top: var(--line-thin) solid var(--color-divider);
}
.list-row { .list-row {
align-items: flex-end; align-items: flex-end;
} }
@@ -220,11 +192,20 @@
gap: var(--space-3); gap: var(--space-3);
align-items: start; align-items: start;
min-width: 0; min-width: 0;
padding: var(--space-3); padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); border-radius: var(--radius-s);
} }
.overlap:has(input:checked) {
border-color: var(--color-accent);
background: var(--color-accent-tint);
}
.overlap input {
margin-top: 0.2em;
}
.overlap label, .overlap label,
.overlap p { .overlap p {
margin: 0; margin: 0;
@@ -237,40 +218,107 @@
gap: var(--space-2); gap: var(--space-2);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) dashed var(--color-border-hover);
border-radius: var(--radius-m); border-radius: var(--radius-s);
} }
.actions { .categories p {
justify-content: space-between; color: var(--color-text-secondary);
padding-top: var(--space-2); font-size: var(--font-size-s);
} }
.actions > :first-child { .category-list,
flex: 1 1 12rem; .review-tags {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: center;
margin: 0;
padding: 0;
list-style: none;
} }
@media (width < 48rem) { .category-list li {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: center;
}
.review {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.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,
.review-meta {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.review-facts dd {
min-width: 0;
overflow-wrap: anywhere;
}
.review-list {
display: grid;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.review-list li {
display: grid;
gap: 0.125rem;
min-width: 0;
}
.review-strong {
color: var(--color-text-strong);
font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
}
.review-empty {
color: var(--color-text-muted);
font-size: var(--font-size-s);
}
.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;
}
.salary .review-meta {
font-family: var(--font-text);
font-weight: var(--font-weight-regular);
}
@media (width >= 48rem) {
.grid { .grid {
grid-template-columns: minmax(0, 1fr); grid-template-columns: repeat(2, minmax(0, 1fr));
}
} }
@media (width < 30rem) { .review-facts > div {
.group { grid-template-columns: 9rem minmax(0, 1fr);
padding: var(--space-3); align-items: baseline;
}
.item {
padding: var(--space-3);
}
.actions {
align-items: stretch;
flex-direction: column;
}
.item-actions {
width: 100%;
} }
} }
@@ -113,4 +113,27 @@ describe("ProfileForm", () => {
); );
expect(unconfirmedText).not.toContain("подтверждена ранее"); expect(unconfirmedText).not.toContain("подтверждена ранее");
}); });
it("walks six steps and keeps the save action on the last one", () => {
const html = renderToString(
<ProfileForm
draft={toCandidateProfileDraft(emptyProfile)}
issues={[]}
isSaving={false}
savingState="idle"
onDraftChange={vi.fn()}
onSubmit={vi.fn()}
/>,
);
expect(html).toContain("Шаг 1 из 6");
for (const step of ["Контакты", "Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
expect(html).toContain(step);
}
expect(html.match(/<section[^>]*hidden=""/g)).toHaveLength(5);
expect(html).toContain(">Далее<");
expect(html).not.toContain("Сохранить профиль");
// An unsaved profile has no shortcut to the review step.
expect(html).not.toContain("К проверке и сохранению");
});
}); });
@@ -1,9 +1,10 @@
import { useId, useRef, type FormEvent, type ReactNode } from "react"; import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import { import {
addExperience, addExperience,
addRole, addRole,
addSoftSkill, addSoftSkill,
addStack, addStack,
buildCandidateProfileUpdate,
moveExperience, moveExperience,
removeExperience, removeExperience,
removeItem, removeItem,
@@ -19,9 +20,27 @@ import {
type ProfileFormIssue, type ProfileFormIssue,
} from "../../../entities/candidate"; } from "../../../entities/candidate";
import type { CandidateProfile } from "../../../shared/api/schemas"; import type { CandidateProfile } from "../../../shared/api/schemas";
import { Button, SavingStatus } from "../../../shared/ui"; import { Button, Mono, Notice, SavingStatus, Tag, TrustLevel } from "../../../shared/ui";
import { profileStepOfField, type ProfileStepId } from "../model/profile-steps";
import {
FormProgress,
FormStepFooter,
FormStepPanel,
ReviewBlock,
type FormStep,
} from "./form-steps";
import { useFormSteps } from "./use-form-steps";
import styles from "./profile-form.module.css"; import styles from "./profile-form.module.css";
const profileSteps: readonly FormStep<ProfileStepId>[] = [
{ id: "contacts", label: "Контакты" },
{ id: "roles", label: "Роли" },
{ id: "experience", label: "Опыт" },
{ id: "skills", label: "Навыки" },
{ id: "terms", label: "Условия" },
{ id: "review", label: "Проверка" },
];
type Specialization = CandidateProfile["roles"][number]["specialization"]; type Specialization = CandidateProfile["roles"][number]["specialization"];
type Grade = NonNullable<CandidateProfile["roles"][number]["self_assessed_grade"]>; type Grade = NonNullable<CandidateProfile["roles"][number]["self_assessed_grade"]>;
@@ -121,6 +140,46 @@ function describedBy(
return values || undefined; return values || undefined;
} }
const fieldLabels: Readonly<Record<string, string>> = {
fullName: "имя и фамилия",
"contacts.email": "контактный email",
"contacts.phone": "телефон",
"contacts.telegram": "Telegram",
"terms.location": "место работы",
"terms.relocation": "переезд",
"terms.salaryMinimum.amount": "минимальная зарплата",
"terms.salaryMinimum.tax_basis": "до или после налога",
};
/** The field named in an issue of the summary, when it has a short name. */
function fieldLabel(field: string): string | null {
if (fieldLabels[field]) return fieldLabels[field];
const row = /^(experience|roles|stack|softSkills)\.(\d+)/.exec(field);
if (!row) return null;
const position = Number(row[2]) + 1;
switch (row[1]) {
case "experience":
return `место работы ${position}`;
case "roles":
return `роль ${position}`;
case "stack":
return `навык ${position}`;
default:
return `гибкий навык ${position}`;
}
}
/** One line per field and message: a schema error can repeat for a field. */
function uniqueIssues(issues: readonly ProfileFormIssue[]): ProfileFormIssue[] {
const seen = new Set<string>();
return issues.filter((item) => {
const key = `${item.field}\u0000${item.message}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function SourceLabel({ status }: { status: "confirmed" | "extracted" | "unknown" }) { function SourceLabel({ status }: { status: "confirmed" | "extracted" | "unknown" }) {
if (status === "extracted") if (status === "extracted")
return <span className={styles["claim-status"]}>Нужно проверить</span>; return <span className={styles["claim-status"]}>Нужно проверить</span>;
@@ -140,38 +199,106 @@ export function ProfileForm({
const rowSequence = useRef(0); const rowSequence = useRef(0);
const newRowId = (kind: string) => `${kind}-draft-${++rowSequence.current}`; const newRowId = (kind: string) => `${kind}-draft-${++rowSequence.current}`;
const fieldId = (field: string) => `${prefix}-${field.replaceAll(".", "-")}`; const fieldId = (field: string) => `${prefix}-${field.replaceAll(".", "-")}`;
const issue = (field: string) => errorFor(issues, field); const issueSummary = useRef<HTMLDivElement>(null);
const setDraft = (next: CandidateProfileDraft) => onDraftChange(next); const steps = useFormSteps(profileSteps);
const { goTo } = steps;
const [stepIssues, setStepIssues] = useState<ProfileFormIssue[]>([]);
const shownIssues = issues.length > 0 ? issues : stepIssues;
const listedIssues = uniqueIssues(shownIssues);
const issue = (field: string) => errorFor(shownIssues, field);
const setDraft = (next: CandidateProfileDraft) => {
setStepIssues([]);
onDraftChange(next);
};
// 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(profileStepOfField(first.field));
}
useEffect(() => {
if (shownIssues.length > 0) issueSummary.current?.focus();
}, [shownIssues]);
function goForward() {
const step = steps.current.id;
const found = buildCandidateProfileUpdate(draft).issues.filter(
(item) => profileStepOfField(item.field) === step,
);
if (found.length > 0) {
setStepIssues(found);
return;
}
setStepIssues([]);
steps.next();
}
function handleSubmit(event: FormEvent<HTMLFormElement>) { function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
if (!steps.isLast) {
goForward();
return;
}
event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus(); event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
onSubmit(); onSubmit();
} }
const stepLabel = (field: string) =>
profileSteps.find((step) => step.id === profileStepOfField(field))?.label ?? "";
const panel = (id: ProfileStepId) => {
const position = profileSteps.findIndex((step) => step.id === id);
return {
step: profileSteps[position] as FormStep<ProfileStepId>,
position: position + 1,
total: profileSteps.length,
active: steps.current.id === id,
headingRef: steps.headingRef(id),
};
};
const overlaps = reviewExperienceOverlaps(draft); const overlaps = reviewExperienceOverlaps(draft);
return ( return (
<form className={styles.form} onSubmit={handleSubmit} noValidate> <form className={styles.form} onSubmit={handleSubmit} noValidate>
{issues.length > 0 ? ( <FormProgress label="Шаги профиля" steps={profileSteps} index={steps.index} />
{shownIssues.length > 0 ? (
<div <div
className={styles["issue-summary"]} className={styles["issue-summary"]}
ref={issueSummary}
role="alert" role="alert"
aria-labelledby={`${prefix}-issues-title`} aria-labelledby={`${prefix}-issues-title`}
tabIndex={-1}
> >
<h2 id={`${prefix}-issues-title`}>Проверьте профиль</h2> <Notice
<ul> tone="danger"
{issues.map((item, index) => ( title={<span id={`${prefix}-issues-title`}>Проверьте профиль</span>}
<li key={`${item.field}-${index}`}>{item.message}</li> >
<ul className={styles["issue-list"]}>
{listedIssues.map((item, index) => (
<li key={`${item.field}-${index}`}>
<span className={styles["issue-step"]}>
{stepLabel(item.field)}
{fieldLabel(item.field) ? `, ${fieldLabel(item.field)}` : ""}:
</span>{" "}
{item.message}
</li>
))} ))}
</ul> </ul>
</Notice>
</div> </div>
) : null} ) : null}
<fieldset className={styles["editor-fields"]} disabled={isSaving}> <fieldset className={styles["editor-fields"]} disabled={isSaving}>
<legend className={styles["editor-legend"]}>Данные профиля</legend> <legend className={styles["editor-legend"]}>Данные профиля</legend>
<fieldset className={styles.group}> <FormStepPanel
<legend>Имя и контакты</legend> {...panel("contacts")}
description="Заполните только то, что готовы указать. Компании увидят контакты только после вашего отдельного согласия."
>
<div className={styles.grid}>
<Field <Field
id={fieldId("fullName")} id={fieldId("fullName")}
label="Имя и фамилия" label="Имя и фамилия"
@@ -291,21 +418,141 @@ export function ProfileForm({
...draft, ...draft,
contacts: { contacts: {
...draft.contacts, ...draft.contacts,
telegram: updateFieldDraft(draft.contacts.telegram, event.currentTarget.value), telegram: updateFieldDraft(
draft.contacts.telegram,
event.currentTarget.value,
),
}, },
}) })
} }
/> />
<SourceLabel status={draft.contacts.telegram.status} /> <SourceLabel status={draft.contacts.telegram.status} />
</Field> </Field>
</fieldset> </div>
</FormStepPanel>
<fieldset className={styles.group}> <FormStepPanel
<legend>Опыт работы</legend> {...panel("roles")}
<p className={styles["group-description"]}> description="Самооценка остается заявлением кандидата. Подтвержденная категория появляется только после оценки."
Укажите специализацию и месяцы работы. Пустая дата окончания означает, что работа >
продолжается. {draft.roles.map((item, index) => {
</p> const base = `roles.${index}`;
const specializationId = fieldId(`${base}.specialization`);
const gradeId = fieldId(`${base}.self_assessed_grade`);
return (
<div className={styles.item} key={item.id}>
<div className={styles["item-header"]}>
<h4>Роль {index + 1}</h4>
<Button
variant="quiet"
aria-label={`Удалить роль ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeItem(draft, "roles", item.id))}
>
Удалить
</Button>
</div>
<div className={styles.grid}>
<Field
id={specializationId}
label="Специализация"
error={issue(`${base}.specialization`)}
suggestion={item.source}
>
<select
id={specializationId}
value={item.specialization}
aria-invalid={Boolean(issue(`${base}.specialization`))}
aria-describedby={describedBy(
specializationId,
issue(`${base}.specialization`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
specialization: event.currentTarget.value as Specialization | "",
}),
)
}
>
<option value="">Выберите специализацию</option>
{specializations.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
<Field
id={gradeId}
label="Моя оценка уровня"
error={issue(`${base}.self_assessed_grade`)}
suggestion={item.source}
>
<select
id={gradeId}
value={item.self_assessed_grade ?? ""}
aria-invalid={Boolean(issue(`${base}.self_assessed_grade`))}
aria-describedby={describedBy(
gradeId,
issue(`${base}.self_assessed_grade`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
self_assessed_grade: (event.currentTarget.value ||
null) as Grade | null,
}),
)
}
>
<option value="">Не указывать</option>
{grades.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
</div>
</div>
);
})}
<div className={styles["add-row"]}>
<Button
variant="secondary"
disabled={draft.roles.length >= 9 || isSaving}
onClick={() => setDraft(addRole(draft, newRowId("role")))}
>
Добавить специализацию
</Button>
</div>
<section className={styles.categories} aria-labelledby={`${prefix}-categories-title`}>
<h4 id={`${prefix}-categories-title`}>Подтвержденные категории</h4>
<p>Эти результаты устанавливает оценка. Их нельзя изменить в профиле.</p>
{draft.confirmedCategories.length > 0 ? (
<ul className={styles["category-list"]}>
{draft.confirmedCategories.map((category) => (
<li key={`${category.specialization}-${category.grade}-${category.attempt_id}`}>
<Tag tone="grade">
{`${specializationLabel(category.specialization)} · ${gradeLabel(category.grade)}`}
</Tag>
<TrustLevel level="confirmed" label="Подтверждено тестом" />
</li>
))}
</ul>
) : (
<p>Подтвержденных категорий пока нет.</p>
)}
</section>
</FormStepPanel>
<FormStepPanel
{...panel("experience")}
description="Укажите специализацию и месяцы работы. Пустая дата окончания означает, что работа продолжается."
>
{draft.experience.map((item, index) => { {draft.experience.map((item, index) => {
const base = `experience.${index}`; const base = `experience.${index}`;
const specialId = fieldId(`${base}.specialization`); const specialId = fieldId(`${base}.specialization`);
@@ -320,7 +567,7 @@ export function ProfileForm({
aria-labelledby={`${prefix}-experience-${index}-title`} aria-labelledby={`${prefix}-experience-${index}-title`}
> >
<div className={styles["item-header"]}> <div className={styles["item-header"]}>
<h3 id={`${prefix}-experience-${index}-title`}>Место работы {index + 1}</h3> <h4 id={`${prefix}-experience-${index}-title`}>Место работы {index + 1}</h4>
<div className={styles["item-actions"]}> <div className={styles["item-actions"]}>
<Button <Button
variant="quiet" variant="quiet"
@@ -489,7 +736,7 @@ export function ProfileForm({
</Button> </Button>
{overlaps.length > 0 ? ( {overlaps.length > 0 ? (
<div className={styles["overlap-list"]}> <div className={styles["overlap-list"]}>
<h3>Параллельные периоды</h3> <h4>Параллельные периоды</h4>
<p>Совпадающие месяцы нужно подтвердить отдельно для каждой пары мест работы.</p> <p>Совпадающие месяцы нужно подтвердить отдельно для каждой пары мест работы.</p>
{overlaps.map((overlap) => { {overlaps.map((overlap) => {
const id = `${prefix}-overlap-${overlap.key.replace(":", "-")}`; const id = `${prefix}-overlap-${overlap.key.replace(":", "-")}`;
@@ -537,109 +784,14 @@ export function ProfileForm({
</ErrorText> </ErrorText>
</div> </div>
) : null} ) : null}
</fieldset> </FormStepPanel>
<fieldset className={styles.group}> <FormStepPanel
<legend>Специализация и навыки</legend> {...panel("skills")}
<p className={styles["group-description"]}> description="Технологии и гибкие навыки по одному в строке. Пустые строки не сохраняются."
Самооценка остается заявлением кандидата. Подтвержденная категория появляется только
после оценки.
</p>
{draft.roles.map((item, index) => {
const base = `roles.${index}`;
const specializationId = fieldId(`${base}.specialization`);
const gradeId = fieldId(`${base}.self_assessed_grade`);
return (
<div className={styles.item} key={item.id}>
<div className={styles["item-header"]}>
<h3>Роль {index + 1}</h3>
<Button
variant="quiet"
aria-label={`Удалить роль ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeItem(draft, "roles", item.id))}
> >
Удалить
</Button>
</div>
<div className={styles.grid}>
<Field
id={specializationId}
label="Специализация"
error={issue(`${base}.specialization`)}
suggestion={item.source}
>
<select
id={specializationId}
value={item.specialization}
aria-invalid={Boolean(issue(`${base}.specialization`))}
aria-describedby={describedBy(
specializationId,
issue(`${base}.specialization`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
specialization: event.currentTarget.value as Specialization | "",
}),
)
}
>
<option value="">Выберите специализацию</option>
{specializations.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
<Field
id={gradeId}
label="Моя оценка уровня"
error={issue(`${base}.self_assessed_grade`)}
suggestion={item.source}
>
<select
id={gradeId}
value={item.self_assessed_grade ?? ""}
aria-invalid={Boolean(issue(`${base}.self_assessed_grade`))}
aria-describedby={describedBy(
gradeId,
issue(`${base}.self_assessed_grade`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
self_assessed_grade: (event.currentTarget.value ||
null) as Grade | null,
}),
)
}
>
<option value="">Не указывать</option>
{grades.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
</div>
</div>
);
})}
<Button
variant="secondary"
disabled={draft.roles.length >= 9 || isSaving}
onClick={() => setDraft(addRole(draft, newRowId("role")))}
>
Добавить специализацию
</Button>
<div className={styles.list}> <div className={styles.list}>
<h3>Технологии и инструменты</h3> <h4>Технологии и инструменты</h4>
{draft.stack.map((item, index) => { {draft.stack.map((item, index) => {
const field = `stack.${index}.tag`; const field = `stack.${index}.tag`;
const id = fieldId(field); const id = fieldId(field);
@@ -685,7 +837,7 @@ export function ProfileForm({
</div> </div>
<div className={styles.list}> <div className={styles.list}>
<h3>Гибкие навыки</h3> <h4>Гибкие навыки</h4>
{draft.softSkills.map((item, index) => { {draft.softSkills.map((item, index) => {
const field = `softSkills.${index}.skill`; const field = `softSkills.${index}.skill`;
const id = fieldId(field); const id = fieldId(field);
@@ -731,10 +883,12 @@ export function ProfileForm({
Добавить гибкий навык Добавить гибкий навык
</Button> </Button>
</div> </div>
</fieldset> </FormStepPanel>
<fieldset className={styles.group}> <FormStepPanel
<legend>Условия работы</legend> {...panel("terms")}
description="Все условия необязательны. Зарплата указывается в рублях в месяц."
>
<Field <Field
id={fieldId("terms.location")} id={fieldId("terms.location")}
label="Желаемое место работы" label="Желаемое место работы"
@@ -857,39 +1011,246 @@ export function ProfileForm({
</select> </select>
</Field> </Field>
</div> </div>
</FormStepPanel>
<FormStepPanel
{...panel("review")}
description="Проверьте сведения перед сохранением. Сервер получит профиль целиком."
>
<ProfileReview draft={draft} disabled={isSaving} onEdit={(id) => goTo(id)} />
</FormStepPanel>
</fieldset> </fieldset>
<section className={styles.categories} aria-labelledby={`${prefix}-categories-title`}> <FormStepFooter
<h2 id={`${prefix}-categories-title`}>Подтвержденные категории</h2> back={
<p>Эти результаты устанавливает оценка. Их нельзя изменить в профиле.</p> steps.isFirst ? null : (
{draft.confirmedCategories.length > 0 ? ( <Button variant="secondary" disabled={isSaving} onClick={steps.back}>
<ul> Назад
{draft.confirmedCategories.map((category) => ( </Button>
<li key={`${category.specialization}-${category.grade}-${category.attempt_id}`}> )
{specializations.find((option) => option.value === category.specialization) }
?.label ?? category.specialization} >
,{" "} {steps.isLast ? (
{grades.find((option) => option.value === category.grade)?.label ?? <>
category.grade}
</li>
))}
</ul>
) : (
<p>Подтвержденных категорий пока нет.</p>
)}
</section>
</fieldset>
<div className={styles.actions}>
<SavingStatus state={savingState} /> <SavingStatus state={savingState} />
<Button type="submit" isBusy={isSaving}> <Button type="submit" isBusy={isSaving}>
{isSaving ? "Сохраняем профиль..." : "Сохранить профиль"} {isSaving ? "Сохраняем профиль..." : "Сохранить профиль"}
</Button> </Button>
</div> </>
) : (
<>
{draft.expectedVersion > 0 ? (
<Button variant="quiet" disabled={isSaving} onClick={() => goTo("review")}>
К проверке и сохранению
</Button>
) : null}
<Button type="submit" disabled={isSaving}>
Далее
</Button>
</>
)}
</FormStepFooter>
</form> </form>
); );
} }
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 ? (
<span className={styles["review-empty"]}>не указано</span>
) : (
<>{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 (
<div className={styles.review}>
<ReviewBlock
title="Контакты"
editLabel="контакты"
disabled={disabled}
onEdit={() => onEdit("contacts")}
>
<dl className={styles["review-facts"]}>
<div>
<dt>Имя</dt>
<dd>
<ReviewValue>{draft.fullName.value.trim()}</ReviewValue>
</dd>
</div>
<div>
<dt>Email</dt>
<dd>
<ReviewValue>{draft.contacts.email.value.trim()}</ReviewValue>
</dd>
</div>
<div>
<dt>Телефон</dt>
<dd>
<ReviewValue>
{draft.contacts.phone.value.trim() ? (
<Mono>{draft.contacts.phone.value.trim()}</Mono>
) : (
""
)}
</ReviewValue>
</dd>
</div>
<div>
<dt>Telegram</dt>
<dd>
<ReviewValue>{draft.contacts.telegram.value.trim()}</ReviewValue>
</dd>
</div>
</dl>
</ReviewBlock>
<ReviewBlock title="Роли" editLabel="роли" disabled={disabled} onEdit={() => onEdit("roles")}>
{draft.roles.length > 0 ? (
<ul className={styles["review-tags"]}>
{draft.roles.map((role) => (
<li key={role.id}>
<Tag tone="grade">
{`${specializationLabel(role.specialization)} · ${gradeLabel(role.self_assessed_grade)}`}
</Tag>
</li>
))}
<li>
<TrustLevel level="claimed" label="Самооценка" />
</li>
</ul>
) : (
<p className={styles["review-empty"]}>Роли не добавлены.</p>
)}
</ReviewBlock>
<ReviewBlock
title="Опыт"
editLabel="опыт"
disabled={disabled}
onEdit={() => onEdit("experience")}
>
{draft.experience.length > 0 ? (
<ol className={styles["review-list"]}>
{draft.experience.map((item) => (
<li key={item.id}>
<span className={styles["review-strong"]}>
{item.employer_name?.trim() || "Компания не указана"}
</span>
<span className={styles["review-meta"]}>
{specializationLabel(item.specialization)},{" "}
<Mono>
{item.started_on || "?"} — {item.ended_on || "сейчас"}
</Mono>
</span>
</li>
))}
</ol>
) : (
<p className={styles["review-empty"]}>Места работы не добавлены.</p>
)}
{overlaps > 0 ? (
<p className={styles["review-meta"]}>
Пересекающихся пар периодов: <Mono>{overlaps}</Mono>.
</p>
) : null}
</ReviewBlock>
<ReviewBlock
title="Навыки"
editLabel="навыки"
disabled={disabled}
onEdit={() => onEdit("skills")}
>
{stack.length > 0 || softSkills.length > 0 ? (
<ul className={styles["review-tags"]}>
{stack.map((item) => (
<li key={item.id}>
<Tag tone="stack">{item.tag.trim()}</Tag>
</li>
))}
{softSkills.map((item) => (
<li key={item.id}>
<Tag tone="neutral">{item.skill.trim()}</Tag>
</li>
))}
</ul>
) : (
<p className={styles["review-empty"]}>Навыки не добавлены.</p>
)}
</ReviewBlock>
<ReviewBlock
title="Условия"
editLabel="условия"
disabled={disabled}
onEdit={() => onEdit("terms")}
>
<dl className={styles["review-facts"]}>
<div>
<dt>Место работы</dt>
<dd>
<ReviewValue>{draft.terms.location.value.trim()}</ReviewValue>
</dd>
</div>
<div>
<dt>Переезд</dt>
<dd>
<ReviewValue>
{draft.terms.relocation.value === null
? ""
: draft.terms.relocation.value
? "готов(а)"
: "не готов(а)"}
</ReviewValue>
</dd>
</div>
<div>
<dt>Зарплата</dt>
<dd>
<ReviewValue>
{salary.amount.trim() && Number.isFinite(salaryAmount) ? (
<span className={styles.salary}>
от {moneyFormat.format(salaryAmount)} ₽
{salary.tax_basis ? (
<span className={styles["review-meta"]}>
{" "}
{salary.tax_basis === "gross" ? "до налога" : "на руки"}
</span>
) : null}
</span>
) : (
""
)}
</ReviewValue>
</dd>
</div>
</dl>
</ReviewBlock>
</div>
);
}
function formatPeriod(period: { started_on: string; ended_on: string | null }): string { function formatPeriod(period: { started_on: string; ended_on: string | null }): string {
return `${period.started_on} - ${period.ended_on ?? "сейчас"}`; return `${period.started_on} - ${period.ended_on ?? "сейчас"}`;
} }
@@ -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<TId extends string> = { 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<TId extends string>(steps: readonly FormStep<TId>[]) {
const [index, setIndex] = useState(0);
const headings = useRef(new Map<TId, HTMLHeadingElement | null>());
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<TId>,
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);
},
};
}
@@ -14,6 +14,7 @@ import {
removeQuestionnaireSpecialization, removeQuestionnaireSpecialization,
toQuestionnaireDraft, toQuestionnaireDraft,
toggleQuestionnaireWorkFormat, toggleQuestionnaireWorkFormat,
questionnaireStepOfField,
} from "./questionnaire-form"; } from "./questionnaire-form";
const catalog: SpecializationCatalog = { 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");
});
});
@@ -359,3 +359,18 @@ export function mapQuestionnaireServerErrors(
message: "Сервер не принял это значение. Проверьте выбор и повторите сохранение.", 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";
}
@@ -1,72 +1,90 @@
.root { /* Phone first: one column; from 1024px the form and a side note. */
.layout {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
align-items: start;
min-width: 0; min-width: 0;
} }
.root > section { @media (width >= 64rem) {
min-width: 0; .layout {
grid-template-columns: minmax(0, 1fr) 18rem;
} }
.server-step, .aside {
.warning, position: sticky;
.form-error, top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4));
.conflict, }
.continuation { }
min-width: 0;
margin: 0 0 var(--space-4); .panel {
padding: var(--space-4); gap: var(--space-5);
border: var(--line-thin) solid var(--color-divider); }
border-radius: var(--radius-m);
background: var(--color-surface); .panel-header {
overflow-wrap: anywhere; 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 { .server-step {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s);
} }
.warning, .server-step strong {
.form-error, color: var(--color-text);
.conflict { font-family: var(--font-mono);
border-width: var(--line-strong); font-weight: var(--font-weight-medium);
border-color: var(--color-danger);
} }
.warning, .notice-title {
.conflict { margin-bottom: var(--space-1);
display: grid; color: var(--color-danger);
gap: var(--space-3); font-size: var(--font-size-m);
} }
.warning p, .notice-text {
.conflict p, color: var(--color-text);
.continuation p {
margin: 0;
line-height: var(--line-height-body);
} }
.conflict h2 { .aside {
margin: 0;
font-size: var(--font-size-l);
}
.conflict-actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
min-width: 0; min-width: 0;
} }
.continuation { .aside-title {
display: flex; color: var(--color-text-strong);
flex-wrap: wrap; font-size: var(--font-size-m);
gap: var(--space-3);
align-items: center;
justify-content: space-between;
margin: var(--space-5) 0 0;
} }
.continuation p { .aside-text,
flex: 1 1 16rem; .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);
} }
@@ -29,10 +29,14 @@ import { paths } from "../../../shared/config";
import { import {
Button, Button,
ButtonLink, ButtonLink,
Card,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Section, Mono,
Notice,
Skeleton,
TrustLevel,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { import {
buildCandidateQuestionnaireUpdate, buildCandidateQuestionnaireUpdate,
@@ -84,6 +88,15 @@ function actorMatches(queryClient: ReturnType<typeof useQueryClient>, actor: Ses
); );
} }
function EditorLoading({ label }: { label: string }) {
return (
<div className={styles.loading}>
<LoadingState label={label} />
<Skeleton shape="card" lines={4} />
</div>
);
}
export function FillQuestionnaire() { export function FillQuestionnaire() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const session = useGetCurrentSession(); const session = useGetCurrentSession();
@@ -161,7 +174,7 @@ export function FillQuestionnaire() {
); );
} }
if (session.isPending || !session.data) { if (session.isPending || !session.data) {
return <LoadingState label="Проверяем вход и загружаем анкету..." />; return <EditorLoading label="Проверяем вход и загружаем анкету..." />;
} }
if (session.data.account.scenario !== "candidate") { if (session.data.account.scenario !== "candidate") {
return ( return (
@@ -181,7 +194,7 @@ export function FillQuestionnaire() {
); );
} }
if (questionnaire.isPending && !questionnaire.data) { if (questionnaire.isPending && !questionnaire.data) {
return <LoadingState label="Загружаем сохраненные ответы..." />; return <EditorLoading label="Загружаем сохраненные ответы..." />;
} }
if (questionnaireAccessError) { if (questionnaireAccessError) {
return ( return (
@@ -204,7 +217,7 @@ export function FillQuestionnaire() {
); );
} }
if (catalog.isPending && !catalog.data) { if (catalog.isPending && !catalog.data) {
return <LoadingState label="Загружаем каталог специализаций..." />; return <EditorLoading label="Загружаем каталог специализаций..." />;
} }
if (!catalog.data) { if (!catalog.data) {
return ( return (
@@ -444,49 +457,52 @@ function QuestionnaireEditor({
savedStep === "candidate_assessment" ? paths.candidate.assessment : null; savedStep === "candidate_assessment" ? paths.candidate.assessment : null;
return ( return (
<div className={styles.root}> <div className={styles.layout}>
<Section <Card as="section" tone="panel" labelledBy="questionnaire-title" className={styles.panel}>
title="Ответы кандидата" <header className={styles["panel-header"]}>
description="Выберите специализации, укажите самооценку и подходящие форматы работы. Эти ответы не подтверждают грейд и не требуют ФСП." <h2 id="questionnaire-title" className={styles["panel-title"]}>
> Ответы кандидата
</h2>
{currentStep ? ( {currentStep ? (
<p className={styles["server-step"]}> <p className={styles["server-step"]}>
Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>. Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>.
</p> </p>
) : null} ) : null}
</header>
{catalogUnavailable ? ( {catalogUnavailable ? (
<div className={styles.warning} role="alert"> <div role="alert">
<p>Не удалось обновить каталог. Показаны последние загруженные сведения.</p> <Notice
tone="danger"
title="Не удалось обновить каталог"
action={
<Button <Button
variant="secondary" variant="secondary"
isBusy={catalogQuery.isRefetching} isBusy={catalogQuery.isRefetching}
onClick={() => void catalogQuery.refetch()} onClick={() => void catalogQuery.refetch()}
> >
{catalogQuery.isRefetching ? "Обновляем каталог..." : "Повторить загрузку каталога"} {catalogQuery.isRefetching
? "Обновляем каталог..."
: "Повторить загрузку каталога"}
</Button> </Button>
}
>
<p>Показаны последние загруженные сведения.</p>
</Notice>
</div> </div>
) : null} ) : null}
{formError ? ( {formError ? (
<div className={styles["form-error"]} role="alert"> <div role="alert">
{formError} <Notice tone="danger">
<p className={styles["notice-text"]}>{formError}</p>
</Notice>
</div> </div>
) : null} ) : null}
{conflict ? ( {conflict ? (
<div <div role="alert" aria-labelledby="questionnaire-conflict-title">
className={styles.conflict} <Notice
role="alert" tone="danger"
aria-labelledby="questionnaire-conflict-title" action={
> <>
<h2 id="questionnaire-conflict-title">Анкета изменилась в другом окне</h2>
<p>
Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие ответы
оставить. Перезапись отправит весь черновик поверх актуальной анкеты.
</p>
{latestLoadError ? (
<p>Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.</p>
) : null}
{latest ? <p>Последняя прочитанная серверная версия: {latest.version}.</p> : null}
<div className={styles["conflict-actions"]}>
<Button <Button
variant="primary" variant="primary"
isBusy={saveState === "saving" || questionnaire.isRefetching} isBusy={saveState === "saving" || questionnaire.isRefetching}
@@ -500,7 +516,9 @@ function QuestionnaireEditor({
isBusy={questionnaire.isRefetching} isBusy={questionnaire.isRefetching}
onClick={() => void refreshLatest()} onClick={() => void refreshLatest()}
> >
{questionnaire.isRefetching ? "Загружаем ответы..." : "Загрузить актуальные ответы"} {questionnaire.isRefetching
? "Загружаем ответы..."
: "Загрузить актуальные ответы"}
</Button> </Button>
<Button <Button
variant="quiet" variant="quiet"
@@ -510,10 +528,28 @@ function QuestionnaireEditor({
> >
Заменить черновик актуальными ответами Заменить черновик актуальными ответами
</Button> </Button>
</div> </>
}
>
<h3 id="questionnaire-conflict-title" className={styles["notice-title"]}>
Анкета изменилась в другом окне
</h3>
<p>
Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие
ответы оставить. Перезапись отправит весь черновик поверх актуальной анкеты.
</p>
{latestLoadError ? (
<p>Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.</p>
) : null}
{latest ? (
<p>
Последняя прочитанная серверная версия: <Mono>{latest.version}</Mono>.
</p>
) : null}
<p id="questionnaire-conflict-discard-hint"> <p id="questionnaire-conflict-discard-hint">
Замена удалит введенные в этой форме изменения. Замена удалит введенные в этой форме изменения.
</p> </p>
</Notice>
</div> </div>
) : null} ) : null}
<QuestionnaireForm <QuestionnaireForm
@@ -529,19 +565,48 @@ function QuestionnaireEditor({
onSubmit={() => void submit()} onSubmit={() => void submit()}
/> />
{saveState === "saved" ? ( {saveState === "saved" ? (
<div className={styles.continuation} role="status"> <div role="status">
<p> <Notice
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "} tone="success"
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}. action={
</p> onboardingDestination ? (
{onboardingDestination ? (
<ButtonLink to={onboardingDestination} variant="secondary"> <ButtonLink to={onboardingDestination} variant="secondary">
Перейти к следующему шагу Перейти к следующему шагу
</ButtonLink> </ButtonLink>
) : null} ) : null
}
>
<p className={styles["notice-text"]}>
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "}
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}.
</p>
</Notice>
</div> </div>
) : null} ) : null}
</Section> </Card>
<aside className={styles.aside} aria-labelledby="questionnaire-aside-title">
<Card tone="raised">
<h2 id="questionnaire-aside-title" className={styles["aside-title"]}>
Заявлено и подтверждено
</h2>
<p className={styles["aside-text"]}>
Анкета хранит самооценку: уровень, на который вы претендуете. Подтвержденную категорию
присваивает только результат теста. Привязка ФСП не нужна.
</p>
<ul className={styles.legend}>
<li>
<TrustLevel level="claimed" label="Самооценка из анкеты" />
</li>
<li>
<TrustLevel level="confirmed" label="Категория после теста" />
</li>
</ul>
<p className={styles["aside-note"]}>
Черновик живет только на этой странице и не записывается в браузерное хранилище.
Сохраненные ответы можно изменить в любой момент.
</p>
</Card>
</aside>
</div> </div>
); );
} }
@@ -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);
}
@@ -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<TId extends string> = {
label: string;
steps: readonly FormStep<TId>[];
index: number;
};
/** The Stepper of the form; on a phone only the markers and the count stay. */
export function FormProgress<TId extends string>({ label, steps, index }: FormProgressProps<TId>) {
return (
<div className={styles.progress}>
<Stepper label={label} steps={buildSteps(steps, index)} />
</div>
);
}
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 (
<section className={styles.step} hidden={!active} aria-labelledby={headingId}>
<header className={styles.header}>
<h3 id={headingId} ref={headingRef} tabIndex={-1} className={styles.title}>
<VisuallyHidden>{`Шаг ${position} из ${total}. `}</VisuallyHidden>
{step.label}
</h3>
{description ? <div className={styles.description}>{description}</div> : null}
</header>
<div className={styles.body}>{children}</div>
</section>
);
}
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 (
<div className={styles.footer}>
<div className={styles["footer-back"]}>{back}</div>
<div className={styles["footer-forward"]}>{children}</div>
</div>
);
}
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 (
<section className={styles.review} aria-labelledby={headingId}>
<div className={styles["review-header"]}>
<h4 id={headingId} className={styles["review-title"]}>
{title}
</h4>
<button
type="button"
className={styles.edit}
disabled={disabled}
aria-label={`Изменить: ${editLabel}`}
onClick={onEdit}
>
Изменить
</button>
</div>
{children}
</section>
);
}
@@ -1,12 +1,12 @@
.form { .form {
display: grid; display: grid;
gap: var(--space-6); gap: var(--space-5);
min-width: 0; min-width: 0;
} }
.editor-fields { .editor-fields {
display: grid; display: grid;
gap: var(--space-6); gap: var(--space-5);
min-width: 0; min-width: 0;
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -24,53 +24,85 @@
.issue-summary { .issue-summary {
min-width: 0; min-width: 0;
padding: var(--space-4); border-radius: var(--radius-s);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-m);
background: var(--color-surface);
} }
.issue-summary:focus { .issue-list {
outline: var(--line-strong) solid var(--color-focus-ring); display: grid;
outline-offset: 2px; gap: var(--space-1);
}
.issue-summary h2 {
margin: 0; margin: 0;
font-size: var(--font-size-l);
}
.issue-summary ul {
margin: var(--space-3) 0 0;
padding-left: var(--space-5); padding-left: var(--space-5);
} }
.group, .issue-step {
.specialization, color: var(--color-text);
.option-group { font-weight: var(--font-weight-medium);
}
/* A row of the form: a nested surface with a mono index in the legend. */
.row {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
min-width: 0; min-width: 0;
margin: 0; margin: 0;
padding: var(--space-4); padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-s);
background: var(--color-canvas);
} }
.group legend, /* A legend cannot be a grid item; floating it puts it inside the row. */
.specialization legend, .row-legend {
.option-group legend { display: flex;
max-width: 100%; float: left;
padding-inline: var(--space-2); gap: var(--space-2);
font-size: var(--font-size-l); align-items: baseline;
font-weight: var(--font-weight-bold); 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; overflow-wrap: anywhere;
} }
.hint, .row-legend > span:first-child {
.availability p { 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; margin: 0;
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
@@ -86,68 +118,68 @@
.field input, .field input,
.field select { .field select {
box-sizing: border-box;
width: 100%; width: 100%;
min-width: 0; min-width: 0;
max-width: 100%; max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); }
color: var(--color-text);
background: var(--color-surface); .number {
font: inherit; font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
} }
.error { .error {
margin: 0; margin: 0;
color: var(--color-text); color: var(--color-danger);
font-size: var(--font-size-s); font-size: var(--font-size-s);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-bold);
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
.availability { /* Checkbox choices as capsules: the whole capsule is the click target. */
display: grid; .choice-list {
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 {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-3) var(--space-5);
min-width: 0;
}
.check-item {
display: flex;
gap: var(--space-2); gap: var(--space-2);
align-items: flex-start;
min-width: 0; min-width: 0;
line-height: var(--line-height-body);
overflow-wrap: anywhere;
} }
.check-item input { .choice {
width: 1.25rem; display: inline-flex;
height: 1.25rem; gap: var(--space-2);
margin: 0.125rem 0 0; align-items: center;
flex: 0 0 auto; 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 { .month-grid {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: minmax(0, 1fr);
gap: var(--space-4); gap: var(--space-4);
min-width: 0; min-width: 0;
} }
@@ -164,20 +196,13 @@
flex: 1 1 15rem; 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 input[aria-invalid="true"],
.field select[aria-invalid="true"] { .field select[aria-invalid="true"] {
border-width: var(--line-strong);
border-color: var(--color-danger); border-color: var(--color-danger);
} }
.tag-list { .tag-list,
.review-tags {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-2); gap: var(--space-2);
@@ -186,54 +211,94 @@
list-style: none; list-style: none;
} }
.tag { .review-tags li {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-2); 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 { .tag-remove {
display: flex; display: inline-grid;
flex-wrap: wrap; place-items: center;
gap: var(--space-3); width: 1.5rem;
align-items: center; height: 1.5rem;
justify-content: space-between; margin-inline: var(--space-1) calc(-1 * var(--space-2));
min-width: 0; border: 0;
border-radius: 50%;
color: var(--color-text-secondary);
font-size: 1rem;
line-height: 1;
background: none;
cursor: pointer;
} }
.actions > .hint { .tag-remove:hover {
flex: 1 1 18rem; color: var(--color-text-strong);
background: var(--color-surface-tint-hover);
} }
.form-error { .form-error {
margin: 0; margin: 0;
padding: var(--space-3); color: var(--color-danger);
border-inline-start: var(--line-strong) solid var(--color-danger);
background: var(--color-canvas);
line-height: var(--line-height-body); 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 { .month-grid {
grid-template-columns: minmax(0, 1fr); grid-template-columns: repeat(2, minmax(0, 1fr));
}
} }
@media (width < 30rem) { .review-facts > div {
.group, grid-template-columns: 9rem minmax(0, 1fr);
.specialization, align-items: baseline;
.option-group {
padding: var(--space-3);
}
.actions {
align-items: stretch;
flex-direction: column;
} }
} }
@@ -112,4 +112,17 @@ describe("questionnaire form", () => {
expect(markup).toContain('value="senior" selected=""'); expect(markup).toContain('value="senior" selected=""');
expect(markup).not.toMatch(/<button\b[^>]*>[^<]*(?:Перейти|Начать) проверку/); expect(markup).not.toMatch(/<button\b[^>]*>[^<]*(?:Перейти|Начать) проверку/);
}); });
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(/<li[^>]*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(/<section[^>]*hidden=""/g)).toHaveLength(3);
expect(markup).toContain("Моя оценка уровня");
expect(markup).toContain(">Далее<");
expect(markup).not.toContain("Сохранить анкету");
});
}); });
@@ -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 { import {
addQuestionnaireSpecialization, addQuestionnaireSpecialization,
addQuestionnaireStackTag, addQuestionnaireStackTag,
buildCandidateQuestionnaireUpdate,
changeQuestionnaireSpecialization, changeQuestionnaireSpecialization,
patchQuestionnaireSpecialization, patchQuestionnaireSpecialization,
questionnaireStepOfField,
removeQuestionnaireSpecialization, removeQuestionnaireSpecialization,
removeQuestionnaireStackTag, removeQuestionnaireStackTag,
toggleQuestionnaireWorkFormat, toggleQuestionnaireWorkFormat,
type QuestionnaireDraft, type QuestionnaireDraft,
type QuestionnaireFormIssue, type QuestionnaireFormIssue,
type QuestionnaireSpecializationDraft, type QuestionnaireSpecializationDraft,
type QuestionnaireStepId,
} from "../model/questionnaire-form"; } from "../model/questionnaire-form";
import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization"; import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization";
import type { import type {
@@ -18,7 +21,15 @@ import type {
TaskLanguage, TaskLanguage,
WorkFormat, WorkFormat,
} from "../../../shared/api/schemas"; } 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"; import styles from "./questionnaire-form.module.css";
const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [ const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [
@@ -32,6 +43,13 @@ const taskLanguageLabels: Record<TaskLanguage, string> = {
go: "Go", go: "Go",
}; };
const questionnaireSteps: readonly FormStep<QuestionnaireStepId>[] = [
{ id: "specializations", label: "Направления" },
{ id: "details", label: "Уровень и опыт" },
{ id: "work", label: "Формат работы" },
{ id: "review", label: "Проверка и сохранение" },
];
type QuestionnaireFormProps = { type QuestionnaireFormProps = {
draft: QuestionnaireDraft; draft: QuestionnaireDraft;
catalog: SpecializationCatalog; 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 (
<fieldset className={styles.row}>
<legend className={styles["row-legend"]}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono> Специализация {index + 1}
</legend>
<Field
id={selectionId}
label="Специализация"
hint="Выберите направление из актуального каталога. При смене выбора самооценка, языки заданий, стек и опыт для этой строки будут очищены."
error={error}
>
<select
id={selectionId}
value={item.specialization}
aria-invalid={Boolean(error)}
aria-describedby={describeIds(selectionId, true, Boolean(error))}
onChange={(event) =>
onDraftChange(
changeQuestionnaireSpecialization(
draft,
item.id,
event.currentTarget.value as SpecializationCode | "",
),
)
}
>
<option value="">Выберите специализацию</option>
{item.specialization && !selectedOption ? (
<option value={item.specialization}>
{item.specialization} (нет в текущем каталоге)
</option>
) : null}
{catalog.directions.map((direction) => (
<optgroup key={direction.code} label={direction.title}>
{direction.specializations.map((option) => (
<option
key={option.code}
value={option.code}
disabled={selectedElsewhere.has(option.code)}
>
{option.title}
</option>
))}
</optgroup>
))}
</select>
</Field>
{selectedOption ? (
<div role="status">
{selectedOption.test_availability.status === "in_development" ? (
<Notice tone="neutral" title="Проверка: в разработке">
<p>Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.</p>
{selectedOption.test_availability.note ? (
<p>{selectedOption.test_availability.note}</p>
) : null}
</Notice>
) : selectedOption.test_availability.grades.length > 0 ? (
<Notice tone="info">
<p>
Проверка опубликована для уровней:{" "}
{selectedOption.test_availability.grades
.map((grade) => findGradeTitle(catalog, grade))
.join(", ")}
.
</p>
</Notice>
) : (
<Notice tone="neutral">
<p>Сейчас нет опубликованных уровней проверки для этой специализации.</p>
</Notice>
)}
</div>
) : null}
{draft.specializations.length > 1 ? (
<div className={styles["row-actions"]}>
<Button
variant="quiet"
disabled={disabled}
onClick={() => onDraftChange(removeQuestionnaireSpecialization(draft, item.id))}
aria-label={`Удалить специализацию ${index + 1}`}
>
Удалить специализацию
</Button>
</div>
) : null}
</fieldset>
);
}
function StackTags({ function StackTags({
draft, draft,
item, item,
@@ -123,7 +275,8 @@ function StackTags({
<div className={styles.field}> <div className={styles.field}>
<label htmlFor={inputId}>Стек технологий</label> <label htmlFor={inputId}>Стек технологий</label>
<p className={styles.hint} id={helpId}> <p className={styles.hint} id={helpId}>
Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки. Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки. Enter
добавляет технологию.
</p> </p>
<div className={styles["stack-input"]}> <div className={styles["stack-input"]}>
<input <input
@@ -154,16 +307,19 @@ function StackTags({
{item.stack.length > 0 ? ( {item.stack.length > 0 ? (
<ul className={styles["tag-list"]} aria-label={`Технологии по специализации ${index + 1}`}> <ul className={styles["tag-list"]} aria-label={`Технологии по специализации ${index + 1}`}>
{item.stack.map((tag) => ( {item.stack.map((tag) => (
<li className={styles.tag} key={`${tag}-${index}`}> <li key={`${tag}-${index}`}>
<span>{tag}</span> <Tag tone="stack">
<Button {tag}
variant="quiet" <button
type="button"
className={styles["tag-remove"]}
disabled={disabled} disabled={disabled}
aria-label={`Удалить технологию ${tag}`} aria-label={`Удалить технологию ${tag}`}
onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))} onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))}
> >
Удалить <span aria-hidden="true">×</span>
</Button> </button>
</Tag>
</li> </li>
))} ))}
</ul> </ul>
@@ -173,7 +329,8 @@ function StackTags({
); );
} }
function SpecializationCard({ /** Step 2: self-assessment, task languages, stack, and experience of one row. */
function SpecializationDetails({
draft, draft,
item, item,
index, index,
@@ -183,34 +340,18 @@ function SpecializationCard({
prefix, prefix,
onDraftChange, onDraftChange,
onIssue, onIssue,
}: { }: RowProps) {
draft: QuestionnaireDraft;
item: QuestionnaireSpecializationDraft;
index: number;
catalog: SpecializationCatalog;
issues: readonly QuestionnaireFormIssue[];
disabled: boolean;
prefix: string;
onDraftChange: (draft: QuestionnaireDraft) => void;
onIssue: (issue: QuestionnaireFormIssue) => void;
}) {
const cardId = `${prefix}-specialization-${index}`; const cardId = `${prefix}-specialization-${index}`;
const selectionId = `${cardId}-selection`;
const gradeId = `${cardId}-grade`; const gradeId = `${cardId}-grade`;
const experienceToggleId = `${cardId}-experience-enabled`; const experienceToggleId = `${cardId}-experience-enabled`;
const commercialId = `${cardId}-commercial-months`; const commercialId = `${cardId}-commercial-months`;
const academicId = `${cardId}-academic-months`; const academicId = `${cardId}-academic-months`;
const taskLanguagesId = `${cardId}-task-languages`; const taskLanguagesId = `${cardId}-task-languages`;
const selectedOption = findSpecializationOption(catalog, item.specialization); 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 gradeField = `specializations.${index}.selfAssessedGrade`;
const languagesField = `specializations.${index}.taskLanguages`; const languagesField = `specializations.${index}.taskLanguages`;
const commercialField = `specializations.${index}.commercialMonths`;
const academicField = `specializations.${index}.academicMonths`;
const stackError = issues.find((issue) => const stackError = issues.find((issue) =>
issue.field.startsWith(`specializations.${index}.stack`), issue.field.startsWith(`specializations.${index}.stack`),
)?.message; )?.message;
@@ -228,83 +369,14 @@ function SpecializationCard({
} }
return ( return (
<fieldset className={styles.specialization}> <fieldset className={styles.row}>
<legend>Специализация {index + 1}</legend> <legend className={styles["row-legend"]}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono> {specializationTitle(catalog, item)}
</legend>
<p className={styles.hint}> <p className={styles.hint}>
Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет
только результат проверки. только результат проверки.
</p> </p>
<Field
id={selectionId}
label="Специализация"
hint="Выберите направление из актуального каталога. При смене выбора самооценка, языки заданий, стек и опыт для этой строки будут очищены."
error={issueFor(issues, specialtyField)}
>
<select
id={selectionId}
value={item.specialization}
aria-invalid={Boolean(issueFor(issues, specialtyField))}
aria-describedby={describeIds(
selectionId,
true,
Boolean(issueFor(issues, specialtyField)),
)}
onChange={(event) =>
onDraftChange(
changeQuestionnaireSpecialization(
draft,
item.id,
event.currentTarget.value as SpecializationCode | "",
),
)
}
>
<option value="">Выберите специализацию</option>
{item.specialization && !selectedOption ? (
<option value={item.specialization}>
{item.specialization} (нет в текущем каталоге)
</option>
) : null}
{catalog.directions.map((direction) => (
<optgroup key={direction.code} label={direction.title}>
{direction.specializations.map((option) => (
<option
key={option.code}
value={option.code}
disabled={selectedElsewhere.has(option.code)}
>
{option.title}
</option>
))}
</optgroup>
))}
</select>
</Field>
{selectedOption ? (
<div className={styles.availability} role="status">
{selectedOption.test_availability.status === "in_development" ? (
<>
<p className={styles["availability-title"]}>Проверка: в разработке</p>
<p>Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.</p>
{selectedOption.test_availability.note ? (
<p>{selectedOption.test_availability.note}</p>
) : null}
</>
) : selectedOption.test_availability.grades.length > 0 ? (
<p>
Проверка опубликована для уровней:{" "}
{selectedOption.test_availability.grades
.map((grade) => findGradeTitle(catalog, grade))
.join(", ")}
.
</p>
) : (
<p>Сейчас нет опубликованных уровней проверки для этой специализации.</p>
)}
</div>
) : null}
<Field <Field
id={gradeId} id={gradeId}
label="Моя оценка уровня" label="Моя оценка уровня"
@@ -341,14 +413,14 @@ function SpecializationCard({
Этот выбор относится к языку заданий проверки, а не к вашему стеку технологий. Этот выбор относится к языку заданий проверки, а не к вашему стеку технологий.
</p> </p>
{!selectedOption ? ( {!selectedOption ? (
<p>Сначала выберите специализацию.</p> <p className={styles.hint}>Сначала выберите специализацию.</p>
) : shownLanguages.length > 0 ? ( ) : shownLanguages.length > 0 ? (
<div className={styles["check-list"]}> <div className={styles["choice-list"]}>
{shownLanguages.map((language) => { {shownLanguages.map((language) => {
const isOld = oldLanguages.includes(language); const isOld = oldLanguages.includes(language);
const languageId = `${taskLanguagesId}-${language}`; const languageId = `${taskLanguagesId}-${language}`;
return ( return (
<label className={styles["check-item"]} htmlFor={languageId} key={language}> <label className={styles.choice} htmlFor={languageId} key={language}>
<input <input
id={languageId} id={languageId}
type="checkbox" type="checkbox"
@@ -370,7 +442,9 @@ function SpecializationCard({
})} })}
</div> </div>
) : ( ) : (
<p>Для этой специализации сейчас не предлагаются варианты языка заданий.</p> <p className={styles.hint}>
Для этой специализации сейчас не предлагаются варианты языка заданий.
</p>
)} )}
<ErrorText id={`${taskLanguagesId}-error`}>{issueFor(issues, languagesField)}</ErrorText> <ErrorText id={`${taskLanguagesId}-error`}>{issueFor(issues, languagesField)}</ErrorText>
</fieldset> </fieldset>
@@ -388,7 +462,7 @@ function SpecializationCard({
<fieldset className={styles["option-group"]}> <fieldset className={styles["option-group"]}>
<legend>Опыт в этой специализации</legend> <legend>Опыт в этой специализации</legend>
<label className={styles["check-item"]} htmlFor={experienceToggleId}> <label className={styles.choice} htmlFor={experienceToggleId}>
<input <input
id={experienceToggleId} id={experienceToggleId}
type="checkbox" type="checkbox"
@@ -410,10 +484,11 @@ function SpecializationCard({
id={commercialId} id={commercialId}
label="Коммерческий опыт, месяцев" label="Коммерческий опыт, месяцев"
hint="Допустимое значение: от 0 до 600." hint="Допустимое значение: от 0 до 600."
error={issueFor(issues, `specializations.${index}.commercialMonths`)} error={issueFor(issues, commercialField)}
> >
<input <input
id={commercialId} id={commercialId}
className={styles.number}
type="number" type="number"
min={0} min={0}
max={600} max={600}
@@ -421,13 +496,11 @@ function SpecializationCard({
inputMode="numeric" inputMode="numeric"
value={item.commercialMonths} value={item.commercialMonths}
disabled={!selectedOption} disabled={!selectedOption}
aria-invalid={Boolean( aria-invalid={Boolean(issueFor(issues, commercialField))}
issueFor(issues, `specializations.${index}.commercialMonths`),
)}
aria-describedby={describeIds( aria-describedby={describeIds(
commercialId, commercialId,
true, true,
Boolean(issueFor(issues, `specializations.${index}.commercialMonths`)), Boolean(issueFor(issues, commercialField)),
)} )}
onChange={(event) => onChange={(event) =>
onDraftChange( onDraftChange(
@@ -442,10 +515,11 @@ function SpecializationCard({
id={academicId} id={academicId}
label="Учебный и академический опыт, месяцев" label="Учебный и академический опыт, месяцев"
hint="Допустимое значение: от 0 до 600." hint="Допустимое значение: от 0 до 600."
error={issueFor(issues, `specializations.${index}.academicMonths`)} error={issueFor(issues, academicField)}
> >
<input <input
id={academicId} id={academicId}
className={styles.number}
type="number" type="number"
min={0} min={0}
max={600} max={600}
@@ -453,11 +527,11 @@ function SpecializationCard({
inputMode="numeric" inputMode="numeric"
value={item.academicMonths} value={item.academicMonths}
disabled={!selectedOption} disabled={!selectedOption}
aria-invalid={Boolean(issueFor(issues, `specializations.${index}.academicMonths`))} aria-invalid={Boolean(issueFor(issues, academicField))}
aria-describedby={describeIds( aria-describedby={describeIds(
academicId, academicId,
true, true,
Boolean(issueFor(issues, `specializations.${index}.academicMonths`)), Boolean(issueFor(issues, academicField)),
)} )}
onChange={(event) => onChange={(event) =>
onDraftChange( onDraftChange(
@@ -473,21 +547,138 @@ function SpecializationCard({
<p className={styles.hint}>Можно оставить без указания.</p> <p className={styles.hint}>Можно оставить без указания.</p>
)} )}
</fieldset> </fieldset>
{draft.specializations.length > 1 ? (
<Button
variant="quiet"
disabled={disabled}
onClick={() => onDraftChange(removeQuestionnaireSpecialization(draft, item.id))}
aria-label={`Удалить специализацию ${index + 1}`}
>
Удалить специализацию
</Button>
) : null}
</fieldset> </fieldset>
); );
} }
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 (
<div className={styles.review}>
<ReviewBlock
title="Направления"
editLabel="направления"
disabled={disabled}
onEdit={() => onEdit("specializations")}
>
{chosen.length > 0 ? (
<ul className={styles["review-tags"]}>
{chosen.map((item) => {
const option = findSpecializationOption(catalog, item.specialization);
return (
<li key={item.id}>
<Tag tone="grade">{specializationTitle(catalog, item)}</Tag>
{option?.test_availability.status === "in_development" ? (
<Tag tone="neutral">тест готовится</Tag>
) : null}
</li>
);
})}
</ul>
) : (
<p className={styles.hint}>Ни одна специализация не выбрана.</p>
)}
</ReviewBlock>
<ReviewBlock
title="Уровень и опыт"
editLabel="уровень и опыт"
disabled={disabled}
onEdit={() => onEdit("details")}
>
{chosen.length > 0 ? (
<ul className={styles["review-list"]}>
{chosen.map((item) => (
<li key={item.id} className={styles["review-row"]}>
<span className={styles["review-name"]}>
<Tag tone="grade">
{`${specializationTitle(catalog, item)} · ${
item.selfAssessedGrade
? findGradeTitle(catalog, item.selfAssessedGrade)
: "уровень не выбран"
}`}
</Tag>
<TrustLevel level="claimed" label="Самооценка" />
</span>
<dl className={styles["review-facts"]}>
<div>
<dt>Язык заданий</dt>
<dd>
{item.taskLanguages.length > 0
? item.taskLanguages.map((code) => taskLanguageLabels[code]).join(", ")
: "не выбран"}
</dd>
</div>
<div>
<dt>Стек</dt>
<dd>
{item.stack.length > 0 ? (
<span className={styles["review-tags"]}>
{item.stack.map((tag) => (
<Tag key={tag} tone="stack">
{tag}
</Tag>
))}
</span>
) : (
"не указан"
)}
</dd>
</div>
<div>
<dt>Опыт, месяцев</dt>
<dd>
{item.hasExperience ? (
<>
коммерческий <Mono>{item.commercialMonths || "?"}</Mono>, учебный{" "}
<Mono>{item.academicMonths || "?"}</Mono>
</>
) : (
"не указан"
)}
</dd>
</div>
</dl>
</li>
))}
</ul>
) : (
<p className={styles.hint}>Появится после выбора специализации.</p>
)}
</ReviewBlock>
<ReviewBlock
title="Формат работы"
editLabel="формат работы"
disabled={disabled}
onEdit={() => onEdit("work")}
>
{draft.workFormats.length > 0 ? (
<p className={styles["review-tags"]}>
{workFormats
.filter((format) => draft.workFormats.includes(format.value))
.map((format) => (
<Tag key={format.value} tone="neutral">
{format.label.toLowerCase()}
</Tag>
))}
</p>
) : (
<p className={styles.hint}>Формат не выбран.</p>
)}
</ReviewBlock>
</div>
);
}
export function QuestionnaireForm({ export function QuestionnaireForm({
draft, draft,
catalog, catalog,
@@ -503,23 +694,73 @@ export function QuestionnaireForm({
const prefix = `questionnaire-${useId().replaceAll(":", "")}`; const prefix = `questionnaire-${useId().replaceAll(":", "")}`;
const rowSequence = useRef(0); const rowSequence = useRef(0);
const issueSummary = useRef<HTMLDivElement>(null); const issueSummary = useRef<HTMLDivElement>(null);
const steps = useFormSteps(questionnaireSteps);
const [stepIssues, setStepIssues] = useState<QuestionnaireFormIssue[]>([]);
const shownIssues = issues.length > 0 ? issues : stepIssues;
const formDisabled = isSaving || isForbidden; 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(() => { useEffect(() => {
if (issues.length > 0) issueSummary.current?.focus(); if (shownIssues.length > 0) issueSummary.current?.focus();
}, [issues.length]); }, [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<HTMLFormElement>) { function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); 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<HTMLButtonElement>('button[type="submit"]')?.focus(); else event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
onSubmit(); 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<QuestionnaireStepId>,
position: position + 1,
total,
active: steps.current.id === id,
headingRef: steps.headingRef(id),
};
};
return ( return (
<form className={styles.form} onSubmit={handleSubmit} noValidate> <form className={styles.form} onSubmit={handleSubmit} noValidate>
{issues.length > 0 ? ( <FormProgress label="Шаги анкеты" steps={questionnaireSteps} index={steps.index} />
{shownIssues.length > 0 ? (
<div <div
className={styles["issue-summary"]} className={styles["issue-summary"]}
ref={issueSummary} ref={issueSummary}
@@ -527,46 +768,51 @@ export function QuestionnaireForm({
aria-labelledby={`${prefix}-issues-title`} aria-labelledby={`${prefix}-issues-title`}
tabIndex={-1} tabIndex={-1}
> >
<h2 id={`${prefix}-issues-title`}>Проверьте анкету</h2> <Notice tone="danger" title={<span id={`${prefix}-issues-title`}>Проверьте анкету</span>}>
<ul> <ul className={styles["issue-list"]}>
{issues.map((item, index) => ( {shownIssues.map((item, index) => (
<li key={`${item.field}-${index}`}>{item.message}</li> <li key={`${item.field}-${index}`}>
<span className={styles["issue-step"]}>{stepLabel(item.field)}:</span>{" "}
{item.message}
</li>
))} ))}
</ul> </ul>
</Notice>
</div> </div>
) : null} ) : null}
<fieldset className={styles["editor-fields"]} disabled={formDisabled}> <fieldset className={styles["editor-fields"]} disabled={formDisabled}>
<legend className={styles["visually-hidden"]}>Ответы анкеты</legend> <legend className={styles["visually-hidden"]}>Ответы анкеты</legend>
<fieldset className={styles.group}>
<legend>Специализации</legend> <FormStepPanel
<p className={styles.hint}> {...panel("specializations")}
Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой. description="Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой."
</p> >
{draft.specializations.map((item, index) => ( {draft.specializations.map((item, index) => (
<SpecializationCard <SpecializationChoice
key={item.id} key={item.id}
draft={draft} draft={draft}
item={item} item={item}
index={index} index={index}
catalog={catalog} catalog={catalog}
issues={issues} issues={shownIssues}
disabled={formDisabled} disabled={formDisabled}
prefix={prefix} prefix={prefix}
onDraftChange={onDraftChange} onDraftChange={changeDraft}
onIssue={onIssue} onIssue={onIssue}
/> />
))} ))}
<ErrorText id={`${prefix}-specializations-error`}> <ErrorText id={`${prefix}-specializations-error`}>
{issueFor(issues, "specializations")} {issueFor(shownIssues, "specializations")}
</ErrorText> </ErrorText>
<div className={styles["add-row"]}>
<Button <Button
variant="secondary" variant="secondary"
disabled={formDisabled || draft.specializations.length >= 2} disabled={formDisabled || draft.specializations.length >= 2}
aria-describedby={`${prefix}-specialization-limit`} aria-describedby={`${prefix}-specialization-limit`}
onClick={() => { onClick={() => {
const id = `${prefix}-row-${++rowSequence.current}`; const id = `${prefix}-row-${++rowSequence.current}`;
onDraftChange(addQuestionnaireSpecialization(draft, id)); changeDraft(addQuestionnaireSpecialization(draft, id));
}} }}
> >
Добавить специализацию Добавить специализацию
@@ -574,24 +820,46 @@ export function QuestionnaireForm({
<p className={styles.hint} id={`${prefix}-specialization-limit`}> <p className={styles.hint} id={`${prefix}-specialization-limit`}>
Можно указать не больше двух специализаций. Можно указать не больше двух специализаций.
</p> </p>
</fieldset> </div>
</FormStepPanel>
<fieldset className={styles.group}> <FormStepPanel
{...panel("details")}
description="Для каждой выбранной специализации: уровень, на который вы претендуете, язык заданий проверки, стек и опыт."
>
{draft.specializations.map((item, index) => (
<SpecializationDetails
key={item.id}
draft={draft}
item={item}
index={index}
catalog={catalog}
issues={shownIssues}
disabled={formDisabled}
prefix={prefix}
onDraftChange={changeDraft}
onIssue={onIssue}
/>
))}
</FormStepPanel>
<FormStepPanel
{...panel("work")}
description="Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю."
>
<fieldset className={styles["option-group"]}>
<legend>Подходящий формат работы</legend> <legend>Подходящий формат работы</legend>
<p className={styles.hint}> <div className={styles["choice-list"]}>
Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю.
</p>
<div className={styles["check-list"]}>
{workFormats.map((format) => { {workFormats.map((format) => {
const id = `${prefix}-format-${format.value}`; const id = `${prefix}-format-${format.value}`;
return ( return (
<label className={styles["check-item"]} htmlFor={id} key={format.value}> <label className={styles.choice} htmlFor={id} key={format.value}>
<input <input
id={id} id={id}
type="checkbox" type="checkbox"
checked={draft.workFormats.includes(format.value)} checked={draft.workFormats.includes(format.value)}
onChange={() => onChange={() =>
onDraftChange(toggleQuestionnaireWorkFormat(draft, format.value)) changeDraft(toggleQuestionnaireWorkFormat(draft, format.value))
} }
/> />
<span>{format.label}</span> <span>{format.label}</span>
@@ -600,9 +868,22 @@ export function QuestionnaireForm({
})} })}
</div> </div>
<ErrorText id={`${prefix}-work-formats-error`}> <ErrorText id={`${prefix}-work-formats-error`}>
{issueFor(issues, "workFormats")} {issueFor(shownIssues, "workFormats")}
</ErrorText> </ErrorText>
</fieldset> </fieldset>
</FormStepPanel>
<FormStepPanel
{...panel("review")}
description="Проверьте ответы перед сохранением. Сервер получит анкету целиком."
>
<ReviewSummary
draft={draft}
catalog={catalog}
disabled={formDisabled}
onEdit={(id) => goTo(id)}
/>
</FormStepPanel>
</fieldset> </fieldset>
{generalIssue ? ( {generalIssue ? (
@@ -611,11 +892,16 @@ export function QuestionnaireForm({
</p> </p>
) : null} ) : null}
<div className={styles.actions}> <FormStepFooter
<p className={styles.hint}> back={
Сохраненные ответы можно изменить. Данные черновика не записываются в браузерное steps.isFirst ? null : (
хранилище. <Button variant="secondary" disabled={isSaving} onClick={steps.back}>
</p> Назад
</Button>
)
}
>
{steps.isLast ? (
<Button <Button
type="submit" type="submit"
isBusy={isSaving} isBusy={isSaving}
@@ -628,7 +914,19 @@ export function QuestionnaireForm({
? "Повторить сохранение" ? "Повторить сохранение"
: "Сохранить анкету"} : "Сохранить анкету"}
</Button> </Button>
</div> ) : (
<>
{draft.expectedVersion > 0 ? (
<Button variant="quiet" disabled={formDisabled} onClick={() => goTo("review")}>
К проверке и сохранению
</Button>
) : null}
<Button type="submit" disabled={formDisabled}>
Далее
</Button>
</>
)}
</FormStepFooter>
</form> </form>
); );
} }
@@ -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<TId extends string> = { 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<TId extends string>(steps: readonly FormStep<TId>[]) {
const [index, setIndex] = useState(0);
const headings = useRef(new Map<TId, HTMLHeadingElement | null>());
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<TId>,
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);
},
};
}
@@ -18,16 +18,16 @@
.item { .item {
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); 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] { .item[data-unread] {
border-color: var(--color-border-strong); border-color: var(--color-border-hover);
border-inline-start-width: var(--space-2);
} }
.item article { .item article {
@@ -44,27 +44,25 @@
.meta { .meta {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-2) var(--space-4); gap: var(--space-2) var(--space-3);
align-items: baseline; align-items: center;
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-xs); font-size: var(--font-size-xs);
} }
.kind { .kind {
font-family: var(--font-mono);
letter-spacing: var(--letter-spacing-label); letter-spacing: var(--letter-spacing-label);
text-transform: uppercase; text-transform: uppercase;
} }
.unread { .meta time {
color: var(--color-text); font-family: var(--font-mono);
font-weight: var(--font-weight-bold); font-variant-numeric: tabular-nums;
}
.read {
font-weight: var(--font-weight-regular);
} }
.title { .title {
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
line-height: var(--line-height-snug); line-height: var(--line-height-snug);
} }
@@ -102,6 +100,6 @@
@media (width < 42rem) { @media (width < 42rem) {
.item { .item {
padding: var(--space-3); padding: var(--space-4);
} }
} }
@@ -15,12 +15,15 @@ import {
import type { Notification, NotificationList, Session } from "../../../shared/api/schemas"; import type { Notification, NotificationList, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths"; import { paths } from "../../../shared/config/paths";
import { import {
AttentionDot,
Button, Button,
ButtonLink, ButtonLink,
EmptyState, EmptyState,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Skeleton,
Tag,
TextLink, TextLink,
VisuallyHidden, VisuallyHidden,
} from "../../../shared/ui"; } from "../../../shared/ui";
@@ -243,7 +246,14 @@ export function NotificationInbox({ scope }: NotificationInboxProps) {
/> />
); );
} }
if (list.isPending || !list.data) return <LoadingState label="Загружаем уведомления..." />; if (list.isPending || !list.data) {
return (
<div className={styles.root}>
<LoadingState label="Загружаем уведомления..." />
<Skeleton shape="card" lines={2} />
</div>
);
}
const items = list.data.pages.flatMap((page) => page.items); const items = list.data.pages.flatMap((page) => page.items);
if (items.length === 0) { if (items.length === 0) {
@@ -326,11 +336,10 @@ function NotificationItem({
<li className={styles.item} data-unread={unread || undefined}> <li className={styles.item} data-unread={unread || undefined}>
<article aria-labelledby={headingId}> <article aria-labelledby={headingId}>
<p className={styles.meta}> <p className={styles.meta}>
{unread ? <AttentionDot label="Новое" /> : null}
<span className={styles.kind}>{notificationKindLabel(item.kind)}</span> <span className={styles.kind}>{notificationKindLabel(item.kind)}</span>
<time dateTime={item.delivered_at}>{formatDeliveredAt(item.delivered_at)}</time> <time dateTime={item.delivered_at}>{formatDeliveredAt(item.delivered_at)}</time>
<span className={unread ? styles.unread : styles.read}> <Tag tone={unread ? "accent" : "neutral"}>{unread ? "Не прочитано" : "Прочитано"}</Tag>
{unread ? "Не прочитано" : "Прочитано"}
</span>
</p> </p>
<h2 id={headingId} className={styles.title} tabIndex={-1} ref={registerHeading}> <h2 id={headingId} className={styles.title} tabIndex={-1} ref={registerHeading}>
{title} {title}
@@ -37,8 +37,8 @@
} }
.choice input:focus-visible { .choice input:focus-visible {
outline: var(--line-strong) solid var(--color-accent); outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: 2px; outline-offset: var(--focus-ring-offset);
} }
.help, .help,
@@ -60,16 +60,24 @@
font-weight: var(--font-weight-bold); 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, .notice,
.message, .message,
.error { .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-inline-start: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-s);
background: var(--color-canvas); background: var(--color-canvas);
} }
.message {
border-inline-start-color: var(--color-success);
}
.error { .error {
border-inline-start-color: var(--color-danger); border-color: var(--color-danger);
} }
.step { .step {
@@ -78,7 +86,8 @@
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); 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. */ /* The state is stated in text; the stronger edge only repeats it for sighted users. */
@@ -92,7 +101,8 @@
.step-title { .step-title {
margin: 0; margin: 0;
font-size: 1rem; color: var(--color-text-strong);
font-size: var(--font-size-m);
} }
.step-text { .step-text {
@@ -104,8 +114,10 @@
display: grid; display: grid;
gap: var(--space-2); gap: var(--space-2);
min-width: 0; 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-inline-start: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-s);
background: var(--color-canvas); background: var(--color-canvas);
} }
@@ -17,11 +17,16 @@
color: var(--color-text); color: var(--color-text);
} }
/* The form is one card of the system. */
.form { .form {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
max-width: 52rem; max-width: 52rem;
min-width: 0; 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 { .field {
@@ -40,13 +45,9 @@
width: 100%; width: 100%;
min-width: 0; min-width: 0;
max-width: 100%; max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text); color: var(--color-text);
background: var(--color-surface); background-color: var(--color-canvas);
font: inherit;
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
@@ -65,10 +66,13 @@
font-size: var(--font-size-s); font-size: var(--font-size-s);
} }
/* An error in the shape of the danger Notice. */
.error { .error {
padding: var(--space-3); padding: var(--space-3) var(--space-4);
border-inline-start: var(--line-strong) solid var(--color-danger); border: var(--line-thin) solid var(--color-danger);
background: var(--color-surface); border-radius: var(--radius-s);
background:
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
} }
.error:focus { .error:focus {
@@ -84,7 +88,7 @@
} }
@media (width <= 40rem) { @media (width <= 40rem) {
.actions > :first-child { .form {
width: 100%; padding: var(--space-4);
} }
} }
@@ -1,16 +1,17 @@
.form { .form {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
align-content: start;
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
} }
.title { .title {
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
} }
.fieldset { .fieldset {
@@ -44,9 +45,9 @@
min-height: 2.75rem; min-height: 2.75rem;
min-width: 0; min-width: 0;
padding: var(--space-2) var(--space-3); 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); border-radius: var(--radius-s);
background: var(--color-surface); background: var(--color-canvas);
line-height: var(--line-height-body); line-height: var(--line-height-body);
cursor: pointer; cursor: pointer;
} }
@@ -64,6 +65,11 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.option:has(input:checked) {
border-color: var(--color-accent);
background: var(--color-accent-tint);
}
.option:has(input:focus-visible) { .option:has(input:focus-visible) {
outline: var(--focus-ring-width) solid var(--color-focus-ring); outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset); outline-offset: var(--focus-ring-offset);
@@ -80,7 +86,7 @@
width: 100%; width: 100%;
min-width: 0; min-width: 0;
padding: var(--space-3); 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); border-radius: var(--radius-s);
background: var(--color-surface); background: var(--color-surface);
color: var(--color-text); color: var(--color-text);
@@ -99,12 +105,13 @@
} }
.alert { .alert {
padding: var(--space-3); padding: var(--space-3) var(--space-4);
border: var(--line-strong) solid var(--color-danger); border: var(--line-thin) solid var(--color-danger);
border-radius: var(--radius-s); border-radius: var(--radius-s);
background: var(--color-surface);
color: var(--color-text); color: var(--color-text);
line-height: var(--line-height-body); line-height: var(--line-height-body);
background:
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
} }
.alert:focus-visible { .alert:focus-visible {
@@ -11,6 +11,7 @@ import {
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Page, Page,
Skeleton,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { import {
AssessmentActorGate, AssessmentActorGate,
@@ -29,7 +30,7 @@ const attemptIdPattern =
export function AssessmentResultPage() { export function AssessmentResultPage() {
const { attemptId = "" } = useParams(); const { attemptId = "" } = useParams();
return ( return (
<Page title="Результат проверки" eyebrow="Кабинет кандидата" width="wide"> <Page title="Результат проверки" width="wide">
<AssessmentActorGate> <AssessmentActorGate>
{({ actor, queryClient }) => ( {({ actor, queryClient }) => (
<StoredResult <StoredResult
@@ -98,7 +99,14 @@ function StoredResult({
</> </>
); );
} }
if (result.isPending) return <LoadingState label="Загружаем сохраненный результат..." />; if (result.isPending) {
return (
<div className={styles.layout}>
<LoadingState label="Загружаем сохраненный результат..." />
<Skeleton shape="card" lines={5} />
</div>
);
}
if (!result.data) { if (!result.data) {
return ( return (
<> <>
@@ -7,7 +7,6 @@ export function AssessmentResultsPage() {
return ( return (
<Page <Page
title="Результаты проверок" title="Результаты проверок"
eyebrow="Кабинет кандидата"
lead="Решения сервера по завершенным проверкам. Неудачная попытка не понижает действующую категорию." lead="Решения сервера по завершенным проверкам. Неудачная попытка не понижает действующую категорию."
> >
<AssessmentActorGate> <AssessmentActorGate>
@@ -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");
});
});
@@ -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}`;
}
@@ -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<string, string>();
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");
});
});
@@ -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<Storage, "getItem" | "setItem" | "removeItem">;
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<string, unknown>;
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<ExpressStartEntry, "storedAt">,
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.
}
}
@@ -1,73 +1,246 @@
/* The test-taking screen: one narrow reading column with a focus strip. */
.layout { .layout {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
max-width: 52rem;
min-width: 0; 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 { .meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s); 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, .resume,
.finalize, .finalize {
.info, gap: var(--space-4);
.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);
} }
.resume p, .resume p,
.finalize p, .finalize p {
.info p {
margin: 0; 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 { .item {
gap: var(--space-4); display: grid;
border-color: var(--color-border-strong); 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 { .item-heading {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-2);
align-items: baseline; align-items: baseline;
justify-content: space-between; justify-content: space-between;
gap: var(--space-2);
} }
.item-heading h2, .item-heading h3 {
.result h2 { color: var(--color-text-strong);
margin: 0;
font-size: var(--font-size-l); 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); color: var(--color-text-secondary);
font-size: var(--font-size-s); font-size: var(--font-size-s);
} }
.item-counter > span:first-child {
color: var(--color-text-strong);
font-size: var(--font-size-l);
}
.prompt { .prompt {
margin: 0; margin: 0;
color: var(--color-text);
font-size: 1.0625rem;
line-height: var(--line-height-body);
white-space: pre-wrap; white-space: pre-wrap;
overflow-wrap: anywhere; overflow-wrap: anywhere;
line-height: var(--line-height-body);
} }
.info { .info {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s);
} }
.error { .notice-text {
margin: 0; color: var(--color-text);
color: var(--color-danger);
} }
.result { .result {
@@ -86,21 +259,29 @@
flex-wrap: wrap; flex-wrap: wrap;
} }
@media (width < 42rem) {
.resume,
.finalize,
.info,
.item {
padding: var(--space-3);
}
}
.result-heading { .result-heading {
margin: 0; margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
} }
.result-heading:focus {
outline: none;
}
.result-heading:focus-visible { .result-heading:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring); outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset); 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;
}
}
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query"; 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 { ApiRequestError } from "../../../shared/api";
import { import {
finalizeMyAssessmentAttempt, finalizeMyAssessmentAttempt,
@@ -20,11 +20,14 @@ import { paths } from "../../../shared/config/paths";
import { import {
Button, Button,
ButtonLink, ButtonLink,
Card,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Mono,
Notice,
Page, Page,
Section, Skeleton,
VisuallyHidden, VisuallyHidden,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { import {
@@ -38,6 +41,7 @@ import {
parseAssessmentAttemptResponse, parseAssessmentAttemptResponse,
removeAssessmentQueries, removeAssessmentQueries,
removeAssessmentQueriesForSessionChange, removeAssessmentQueriesForSessionChange,
specializationLabels,
useAssessmentAttempt, useAssessmentAttempt,
useAssessmentResult, useAssessmentResult,
} from "../../../entities/assessment"; } from "../../../entities/assessment";
@@ -55,6 +59,8 @@ import {
useAssessmentSignals, useAssessmentSignals,
useSignalNoticeGate, useSignalNoticeGate,
} from "../../../features/assessment-signals"; } 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"; import attemptStyles from "./assessment-attempt-page.module.css";
type PendingFinalize = { key: string; body: AssessmentFinalization }; type PendingFinalize = { key: string; body: AssessmentFinalization };
@@ -69,7 +75,16 @@ function isTerminal(attempt: AssessmentAttempt): boolean {
function attemptName(attempt: AssessmentAttempt): string { function attemptName(attempt: AssessmentAttempt): string {
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск"; 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 { function answerErrorMessage(error: unknown): string {
@@ -144,6 +159,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
const [answerBusy, setAnswerBusy] = useState(false); const [answerBusy, setAnswerBusy] = useState(false);
const [answerError, setAnswerError] = useState<string | null>(null); const [answerError, setAnswerError] = useState<string | null>(null);
const [answerNeedsReview, setAnswerNeedsReview] = useState(false); 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<PendingFinalize | null>(null); const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
const [finalizeBusy, setFinalizeBusy] = useState(false); const [finalizeBusy, setFinalizeBusy] = useState(false);
const [pageError, setPageError] = useState<string | null>(null); const [pageError, setPageError] = useState<string | null>(null);
@@ -198,6 +218,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
resultQuery.isError, 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<boolean> { async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const key = getGetCurrentSessionQueryKey(); const key = getGetCurrentSessionQueryKey();
const captured = queryClient.getQueryData<Session>(key); const captured = queryClient.getQueryData<Session>(key);
@@ -312,6 +340,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
setAnswerBusy(true); setAnswerBusy(true);
setAnswerError(null); setAnswerError(null);
setAnswerNeedsReview(false); setAnswerNeedsReview(false);
setAnswerSaved(false);
try { try {
const outcome = await submitPendingAnswerCommand( const outcome = await submitPendingAnswerCommand(
command, command,
@@ -335,6 +364,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
setPendingAnswer(null); setPendingAnswer(null);
setAnswerError(null); setAnswerError(null);
setAnswerNeedsReview(false); setAnswerNeedsReview(false);
setAnswerSaved(true);
setWorkReady(true); setWorkReady(true);
} catch (error: unknown) { } catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return; if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
@@ -435,7 +465,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) { if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<ForbiddenState <ForbiddenState
error={session.error} error={session.error}
title="Попытка недоступна" title="Попытка недоступна"
@@ -447,21 +477,21 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
} }
if (session.isPending || !actor) { if (session.isPending || !actor) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<LoadingState label="Проверяем вход..." /> <LoadingState label="Проверяем вход..." />
</Page> </Page>
); );
} }
if (!actorReady) { if (!actorReady) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<LoadingState label="Подтверждаем текущий вход..." /> <LoadingState label="Подтверждаем текущий вход..." />
</Page> </Page>
); );
} }
if (!attemptId) { if (!attemptId) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<ErrorState <ErrorState
error={new Error("The attempt identifier is missing.")} error={new Error("The attempt identifier is missing.")}
title="Не удалось открыть попытку" title="Не удалось открыть попытку"
@@ -471,7 +501,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
} }
if (attemptQuery.isPending && !attempt) { if (attemptQuery.isPending && !attempt) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<LoadingState label="Загружаем сохраненную попытку..." /> <LoadingState label="Загружаем сохраненную попытку..." />
</Page> </Page>
); );
@@ -479,7 +509,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
if (attemptQuery.isError || !attempt) { if (attemptQuery.isError || !attempt) {
if (isAccessLoss(attemptQuery.error)) { if (isAccessLoss(attemptQuery.error)) {
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<ForbiddenState <ForbiddenState
error={attemptQuery.error} error={attemptQuery.error}
title="Попытка недоступна" title="Попытка недоступна"
@@ -490,7 +520,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
); );
} }
return ( return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата"> <Page title="Попытка проверки">
<ErrorState <ErrorState
error={attemptQuery.error} error={attemptQuery.error}
isRetrying={attemptQuery.isRefetching} isRetrying={attemptQuery.isRefetching}
@@ -516,10 +546,23 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
)); ));
const terminal = isTerminal(attempt); const terminal = isTerminal(attempt);
const saveState: AnswerSaveState = answerBusy
? "saving"
: pendingAnswer
? "unconfirmed"
: answerError
? "failed"
: answerSaved
? "saved"
: "idle";
const deadline = new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(attempt.expires_at));
return ( return (
<Page <Page
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"} title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
eyebrow="Кабинет кандидата"
lead={ lead={
attempt.kind === "demo_express" attempt.kind === "demo_express"
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд." ? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
@@ -528,44 +571,67 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
width="wide" width="wide"
> >
<div className={attemptStyles.layout}> <div className={attemptStyles.layout}>
<Section <section className={attemptStyles.session} aria-labelledby="attempt-title">
title={attemptName(attempt)} <header className={attemptStyles["session-header"]}>
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`} <h2 id="attempt-title" className={attemptStyles["session-title"]}>
> {attemptName(attempt)}
<div className={attemptStyles.meta}> </h2>
<span> <p className={attemptStyles.meta}>
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items} {methodLabel(attempt.mode) !== attemptName(attempt)
</span> ? `${methodLabel(attempt.mode)}. `
<span> : ""}
Срок до:{" "} Сервер хранит состояние и результат попытки. Срок до <Mono>{deadline}</Mono>
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
new Date(attempt.expires_at),
)}
</span>
{attempt.sessions ? ( {attempt.sessions ? (
<span> <>
Сеанс {attempt.sessions.used} из {attempt.sessions.max} , сеанс <Mono>{attempt.sessions.used}</Mono> из{" "}
</span> <Mono>{attempt.sessions.max}</Mono>
</>
) : null}
.
</p>
</header>
{!terminal ? (
<AttemptFocusBar
label={attemptTag(attempt)}
answered={attempt.progress.answered_items}
total={attempt.progress.max_items}
expiresAt={attempt.expires_at}
saveState={saveState}
running={workReady}
/>
) : null}
{resumedExpress && attempt.kind === "demo_express" && !terminal ? (
<Notice tone="info" title="Незавершенная демонстрация продолжена">
<p>
Это тот же запуск: время идет с момента его начала, ответы сохранены на сервере.
</p>
</Notice>
) : null} ) : null}
</div>
{pageError ? ( {pageError ? (
<p className={attemptStyles.error} role="alert"> <div role="alert">
{pageError} <Notice tone="danger">
</p> <p className={attemptStyles["notice-text"]}>{pageError}</p>
</Notice>
</div>
) : null} ) : null}
{!workReady && !terminal ? ( {!workReady && !terminal ? (
<div className={attemptStyles.resume}> <Card tone="raised" className={attemptStyles.resume}>
<p> <p>
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
меняются, а ответ не отправляется повторно автоматически. меняются, а ответ не отправляется повторно автоматически.
</p> </p>
{signalNotice.checkError ? ( {signalNotice.checkError ? (
<p className={attemptStyles.error} role="alert"> <div role="alert">
{signalNotice.checkError} <Notice tone="danger">
</p> <p className={attemptStyles["notice-text"]}>{signalNotice.checkError}</p>
</Notice>
</div>
) : null} ) : null}
<div className={attemptStyles.actions}>
<Button <Button
isBusy={resumeBusy} isBusy={resumeBusy}
onClick={() => onClick={() =>
@@ -581,14 +647,23 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
: "Начать или продолжить"} : "Начать или продолжить"}
</Button> </Button>
</div> </div>
</Card>
) : null} ) : null}
{workReady && pendingAnswerNeedsReplay && !terminal ? ( {workReady && pendingAnswerNeedsReplay && !terminal ? (
<div className={attemptStyles.info} role="status"> <div role="status">
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p> <Notice
tone="neutral"
action={
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}> <Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"} {answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
</Button> </Button>
}
>
<p className={attemptStyles["notice-text"]}>
Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.
</p>
</Notice>
</div> </div>
) : null} ) : null}
@@ -598,10 +673,15 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? ( (!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
<article className={attemptStyles.item} aria-labelledby="assessment-item-title"> <article className={attemptStyles.item} aria-labelledby="assessment-item-title">
<div className={attemptStyles["item-heading"]}> <div className={attemptStyles["item-heading"]}>
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2> <h3 id="assessment-item-title">Задание {currentItem.sequence}</h3>
<span> <span className={attemptStyles["item-counter"]} aria-hidden="true">
{currentItem.sequence} из {attempt.progress.max_items} <Mono strong>{String(currentItem.sequence).padStart(2, "0")}</Mono>
<span>/</span>
<Mono>{String(attempt.progress.max_items).padStart(2, "0")}</Mono>
</span> </span>
<VisuallyHidden>
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
</VisuallyHidden>
</div> </div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p> <p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<AnswerForm <AnswerForm
@@ -623,10 +703,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
) : null} ) : null}
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? ( {workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
<p className={attemptStyles.info} role="status"> <div role="status">
<Notice tone="info">
<p className={attemptStyles["notice-text"]}>
Решение передано на проверку. Результат появится после ответа сервера; страница Решение передано на проверку. Результат появится после ответа сервера; страница
обновляет статус автоматически. обновляет статус автоматически.
</p> </p>
</Notice>
</div>
) : null} ) : null}
{workReady && {workReady &&
@@ -635,10 +719,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
canFinalize && canFinalize &&
!terminal && !terminal &&
!pendingAnswerNeedsReplay ? ( !pendingAnswerNeedsReplay ? (
<div className={attemptStyles.finalize}> <Card tone="raised" className={attemptStyles.finalize}>
<p> <p>
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения. Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
</p> </p>
<div className={attemptStyles.actions}>
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}> <Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
{finalizeBusy {finalizeBusy
? "Запрашиваем решение..." ? "Запрашиваем решение..."
@@ -647,6 +732,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
: "Завершить проверку"} : "Завершить проверку"}
</Button> </Button>
</div> </div>
</Card>
) : null} ) : null}
{workReady && {workReady &&
@@ -655,8 +741,10 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
!canFinalize && !canFinalize &&
!terminal && !terminal &&
!pendingAnswerNeedsReplay ? ( !pendingAnswerNeedsReplay ? (
<div className={attemptStyles.info} role="status"> <div role="status">
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p> <Notice
tone="neutral"
action={
<Button <Button
variant="secondary" variant="secondary"
isBusy={attemptQuery.isRefetching} isBusy={attemptQuery.isRefetching}
@@ -664,11 +752,17 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
> >
Обновить попытку Обновить попытку
</Button> </Button>
}
>
<p className={attemptStyles["notice-text"]}>
Сервер не вернул следующее задание. Обновите состояние попытки.
</p>
</Notice>
</div> </div>
) : null} ) : null}
{terminal ? <ResultView resultQuery={resultQuery} /> : null} {terminal ? <ResultView resultQuery={resultQuery} /> : null}
</Section> </section>
<div className={attemptStyles["back-link"]}> <div className={attemptStyles["back-link"]}>
<ButtonLink variant="secondary" to={paths.candidate.assessment}> <ButtonLink variant="secondary" to={paths.candidate.assessment}>
К доступным проверкам К доступным проверкам
@@ -682,7 +776,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) { function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
if (resultQuery.isPending && !resultQuery.data) { if (resultQuery.isPending && !resultQuery.data) {
return <LoadingState label="Загружаем сохраненный результат..." />; return (
<div className={attemptStyles.result}>
<LoadingState label="Загружаем сохраненный результат..." />
<Skeleton shape="card" lines={4} />
</div>
);
} }
if (!resultQuery.data) { if (!resultQuery.data) {
return ( return (
@@ -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<string, string>();
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<string | null> = [];
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<string | null> = [];
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<string | null> = [];
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();
});
});
@@ -4,8 +4,16 @@ import type {
SpecializationCode, SpecializationCode,
TaskLanguage, TaskLanguage,
} from "../../../shared/api/schemas"; } 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 { 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 }; export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
@@ -47,3 +55,72 @@ export function submitPendingAttempt(command: PendingCreate, csrfToken: string)
{ headers: { "X-CSRF-Token": csrfToken } }, { headers: { "X-CSRF-Token": csrfToken } },
).then((response) => parseAssessmentAttemptResponse(response, 201)); ).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<Storage, "getItem" | "setItem" | "removeItem"> | 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;
}
}
}
@@ -1,12 +1,64 @@
/* Phone first: one column; from 1024px the full check and the express run
* side by side. */
.layout { .layout {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
align-items: start;
min-width: 0; 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 { .controls {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: minmax(0, 1fr);
gap: var(--space-3); gap: var(--space-3);
} }
@@ -20,108 +72,123 @@
.field select { .field select {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong); border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s); font-weight: var(--font-weight-regular);
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;
} }
.language-note, .language-note,
.language-availability { .language-availability {
margin: 0; margin: 0;
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s);
} }
.language-note { .language-note strong {
padding: var(--space-3); color: var(--color-text);
border-inline-start: var(--line-strong) solid var(--color-divider); font-family: var(--font-mono);
} }
.language-availability { .language-availability {
max-width: 72ch; max-width: 72ch;
font-size: var(--font-size-s);
} }
.availability, /* The chosen level: a nested surface with its category tag and status. */
.express { .availability {
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-4);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-s);
background: var(--color-canvas);
} }
.availability p, .availability p {
.express p {
margin: 0; margin: 0;
} }
.status-row { .status-row {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: space-between;
gap: var(--space-2); gap: var(--space-2);
align-items: center;
justify-content: space-between;
} }
.status-row [data-state="available"] { /* Policy limits as small readouts with mono values. */
font-weight: var(--font-weight-bold);
}
.limits { .limits {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3); gap: var(--space-2);
margin: 0; margin: 0;
} }
.limits div { .limits div {
display: grid;
gap: var(--space-1);
min-width: 0; min-width: 0;
padding: var(--space-3); padding: var(--space-3);
background: var(--color-canvas); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s); border-radius: var(--radius-xs);
background: var(--color-surface);
} }
.limits dt { .limits dt {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: var(--font-size-s); font-size: var(--font-size-xs);
} }
.limits dd { .limits dd {
margin: var(--space-1) 0 0; margin: 0;
font-weight: var(--font-weight-bold); color: var(--color-text-strong);
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.express p, .actions {
.pending { 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); 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 { .pending {
margin: 0; margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
} }
.error { .notice-text {
margin: 0; color: var(--color-text);
color: var(--color-danger); }
@media (width >= 48rem) {
.controls {
grid-template-columns: repeat(2, minmax(0, 1fr));
} }
@media (width < 42rem) {
.controls,
.limits { .limits {
grid-template-columns: minmax(0, 1fr); grid-template-columns: repeat(4, minmax(0, 1fr));
}
.availability,
.express {
padding: var(--space-3);
} }
} }
@@ -18,12 +18,17 @@ import { paths } from "../../../shared/config/paths";
import { import {
Button, Button,
ButtonLink, ButtonLink,
Card,
EmptyState, EmptyState,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Mono,
Notice,
Page, Page,
Section, Skeleton,
Tag,
type TagTone,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { import {
assessmentSessionMatches, assessmentSessionMatches,
@@ -46,7 +51,9 @@ import {
} from "../../../features/assessment-signals"; } from "../../../features/assessment-signals";
import { import {
buildRootAttemptCreate, buildRootAttemptCreate,
ExpressRunElsewhereError,
preservePendingCreate, preservePendingCreate,
startExpressRun,
submitPendingAttempt, submitPendingAttempt,
type PendingCreate, type PendingCreate,
} from "./assessment-page.model"; } 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 { function formatDate(value: string): string {
return new Intl.DateTimeFormat("ru-RU", { return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium", dateStyle: "medium",
@@ -197,6 +217,7 @@ export function AssessmentPage() {
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null); const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
const [createBusy, setCreateBusy] = useState(false); const [createBusy, setCreateBusy] = useState(false);
const [formError, setFormError] = useState<string | null>(null); const [formError, setFormError] = useState<string | null>(null);
const [expressNote, setExpressNote] = useState<string | null>(null);
const [c3Required, setC3Required] = useState(false); const [c3Required, setC3Required] = useState(false);
const [accessDenied, setAccessDenied] = useState(false); const [accessDenied, setAccessDenied] = useState(false);
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null); const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
@@ -370,13 +391,73 @@ export function AssessmentPage() {
void signalNotice.guard(() => void startAttempt(body)); 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 = () => { const handleStartExpress = () => {
void startAttempt({ kind: "demo_express" }); void startExpress();
}; };
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) { if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return ( return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата"> <Page title="Проверка знаний">
<ForbiddenState <ForbiddenState
error={session.error} error={session.error}
title="Проверка недоступна" title="Проверка недоступна"
@@ -388,33 +469,41 @@ export function AssessmentPage() {
} }
if (session.isPending || !actor) { if (session.isPending || !actor) {
return ( return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата"> <Page title="Проверка знаний">
<LoadingState label="Проверяем вход..." /> <LoadingState label="Проверяем вход..." />
</Page> </Page>
); );
} }
if (!actorReady) { if (!actorReady) {
return ( return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата"> <Page title="Проверка знаний">
<LoadingState label="Подтверждаем текущий вход..." /> <LoadingState label="Подтверждаем текущий вход..." />
</Page> </Page>
); );
} }
const statusTag = grade ? gradeStatusTag(grade) : null;
return ( return (
<Page <Page
title="Проверка знаний" title="Проверка знаний"
eyebrow="Кабинет кандидата"
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения." lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide" width="wide"
> >
<div className={styles.layout}> <div className={styles.layout}>
<Section <Card as="section" tone="panel" labelledBy="assessment-full-title" className={styles.main}>
title="Доступность проверки" <header className={styles["block-header"]}>
description="Состояние и ограничения загружаются с сервера." <p className={styles.kicker}>Полная проверка</p>
> <h2 id="assessment-full-title" className={styles["block-title"]}>
Доступность проверки
</h2>
<p className={styles["block-lead"]}>Состояние и ограничения загружаются с сервера.</p>
</header>
{(availability.isPending && !availability.data) || {(availability.isPending && !availability.data) ||
(questionnaire.isPending && !questionnaire.data) ? ( (questionnaire.isPending && !questionnaire.data) ? (
<div className={styles.loading}>
<LoadingState label="Загружаем доступность и сохраненные ответы..." /> <LoadingState label="Загружаем доступность и сохраненные ответы..." />
<Skeleton lines={4} />
</div>
) : !data || !questionnaire.data ? ( ) : !data || !questionnaire.data ? (
<ErrorState <ErrorState
error={!data ? availability.error : questionnaire.error} error={!data ? availability.error : questionnaire.error}
@@ -485,22 +574,19 @@ export function AssessmentPage() {
опубликованы ли подходящие задания. опубликованы ли подходящие задания.
</p> </p>
) : null} ) : null}
{specialization && grade ? ( {specialization && grade && statusTag ? (
<div className={styles.availability}> <div className={styles.availability}>
<div className={styles["status-row"]}> <div className={styles["status-row"]}>
<strong>{gradeLabels[grade.grade]}</strong> <Tag tone="grade">
<span data-state={grade.status}> {`${specializationLabels[specialization.specialization]} · ${gradeLabels[grade.grade]}`}
{grade.status === "available" </Tag>
? "Доступна" <Tag tone={statusTag.tone} dot>
: grade.status === "active_attempt" {statusTag.label}
? "Есть попытка" </Tag>
: grade.status === "cooldown"
? "Пауза"
: "Банк не готов"}
</span>
</div> </div>
<p>{gradeStatusDescription(grade)}</p> <p>{gradeStatusDescription(grade)}</p>
<AssessmentPolicyParameters grade={grade} /> <AssessmentPolicyParameters grade={grade} />
<div className={styles.actions}>
{activeAttemptId && grade.status === "active_attempt" ? ( {activeAttemptId && grade.status === "active_attempt" ? (
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}> <ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
Продолжить текущую попытку Продолжить текущую попытку
@@ -508,7 +594,7 @@ export function AssessmentPage() {
) : grade.status === "available" ? ( ) : grade.status === "available" ? (
<Button <Button
isBusy={createBusy} isBusy={createBusy}
disabled={!taskLanguageReady} disabled={!taskLanguageReady || pendingCreate?.body.kind === "demo_express"}
onClick={() => { onClick={() => {
if (taskLanguageReady) handleStartReal(); if (taskLanguageReady) handleStartReal();
}} }}
@@ -517,49 +603,76 @@ export function AssessmentPage() {
</Button> </Button>
) : null} ) : null}
</div> </div>
</div>
) : null} ) : null}
{pendingCreate ? ( {pendingCreate && pendingCreate.body.kind !== "demo_express" ? (
<p className={styles.pending} role="status"> <p className={styles.pending} role="status">
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
ее с тем же ключом. ее с тем же ключом.
</p> </p>
) : null} ) : null}
{formError ? ( {formError ? (
<p className={styles.error} role="alert"> <div role="alert">
{formError}{" "} <Notice
{c3Required ? ( tone="danger"
action={
c3Required ? (
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink> <ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
) : null} ) : null
</p> }
>
<p className={styles["notice-text"]}>{formError}</p>
</Notice>
</div>
) : null} ) : null}
</> </>
)} )}
<SignalNoticeSummary /> <SignalNoticeSummary />
{signalNotice.checkError ? ( {signalNotice.checkError ? (
<p className={styles.error} role="alert"> <div role="alert">
{signalNotice.checkError} <Notice tone="danger">
</p> <p className={styles["notice-text"]}>{signalNotice.checkError}</p>
</Notice>
</div>
) : null} ) : null}
</Section> </Card>
<Section <aside className={styles.aside} aria-labelledby="assessment-express-title">
title="Демонстрационный экспресс-запуск" <Card tone="raised" className={styles.express}>
description="Отдельный учебный режим для знакомства с заданиями." <p className={styles.kicker}>Учебный режим</p>
> <h2 id="assessment-express-title" className={styles["block-title"]}>
<div className={styles.express}> Демонстрационный экспресс-запуск
<p> </h2>
<p className={styles.duration}>
<Mono strong>3-5</Mono> <span>минут</span>
</p>
<p className={styles["block-lead"]}>
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
и не влияет на доступность полной проверки. и не влияет на доступность полной проверки.
</p> </p>
<p className={styles["express-note"]}>
Незавершенный запуск этой вкладки продолжается той же кнопкой.
</p>
<Button <Button
isBusy={createBusy} isBusy={createBusy}
disabled={Boolean(pendingCreate)} disabled={Boolean(pendingCreate) && pendingCreate?.body.kind !== "demo_express"}
onClick={handleStartExpress} onClick={handleStartExpress}
> >
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"} {createBusy
? "Создаем запуск..."
: pendingCreate?.body.kind === "demo_express"
? "Повторить начало демонстрации"
: "Начать демонстрацию"}
</Button> </Button>
{expressNote ? (
<div role="status">
<Notice tone="neutral">
<p className={styles["notice-text"]}>{expressNote}</p>
</Notice>
</div> </div>
</Section> ) : null}
</Card>
</aside>
</div> </div>
<SignalNoticeDialog {...signalNotice.dialog} /> <SignalNoticeDialog {...signalNotice.dialog} />
</Page> </Page>
@@ -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<Record<AnswerSaveState, string>> = {
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 (
<div className={styles["focus-bar"]}>
<div className={styles["focus-name"]}>
<Tag tone="grade">{label}</Tag>
</div>
<div className={styles["focus-progress"]}>
<p className={styles["focus-count"]}>
Отвечено <Mono strong>{answered}</Mono> из <Mono>{total}</Mono>
</p>
<div
className={styles.track}
role="progressbar"
aria-label="Отвеченные задания"
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={answered}
aria-valuetext={`Отвечено ${answered} из ${total}`}
>
<span className={styles.fill} style={{ width: `${share}%` }} />
</div>
</div>
<div className={styles["focus-timer"]} data-urgent={urgent || undefined}>
<span className={styles["timer-label"]}>До конца</span>
<span role="timer" aria-label={describeTimeLeft(left)} className={styles.timer}>
{formatTimeLeft(left)}
</span>
</div>
<p className={styles["save-state"]} data-state={saveState} role="status">
<span className={styles["save-mark"]} aria-hidden="true" />
{saveLabels[saveState]}
</p>
</div>
);
}
@@ -8,7 +8,16 @@ import { assessmentResultSummary } from "../../../entities/assessment";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas"; import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config"; 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 { CandidateNextStep } from "../../../widgets/candidate-next-step";
import styles from "./candidate-home-page.module.css"; import styles from "./candidate-home-page.module.css";
@@ -36,7 +45,7 @@ function searchStatusText(search: VisibilitySummary["searchStatus"]): string {
function VisibilityFacts({ settings }: { settings: PrivacySettings }) { function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
const visibility = summarizeVisibility(settings); const visibility = summarizeVisibility(settings);
return ( return (
<> <Card tone="raised">
<dl className={styles.facts}> <dl className={styles.facts}>
<dt>Карточка для компаний</dt> <dt>Карточка для компаний</dt>
<dd> <dd>
@@ -55,12 +64,12 @@ function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
<dt>Статус поиска</dt> <dt>Статус поиска</dt>
<dd>{searchStatusText(visibility.searchStatus)}</dd> <dd>{searchStatusText(visibility.searchStatus)}</dd>
</dl> </dl>
<div> <div className={styles.links}>
<ButtonLink to={paths.candidate.privacy} variant="secondary"> <ButtonLink to={paths.candidate.privacy} variant="secondary">
Настроить видимость и согласия Настроить видимость и согласия
</ButtonLink> </ButtonLink>
</div> </div>
</> </Card>
); );
} }
@@ -84,17 +93,19 @@ function LatestResult({ page }: { page: AssessmentResultHistoryPage }) {
if (!latest) return null; if (!latest) return null;
const summary = assessmentResultSummary(latest); const summary = assessmentResultSummary(latest);
return ( return (
<> <Card tone="raised">
<p className={styles["result-text"]}>{summary.text}</p> <p className={styles["result-text"]}>{summary.text}</p>
{summary.reason ? <p className={styles.reason}>{summary.reason}</p> : null} {summary.reason ? <p className={styles.reason}>{summary.reason}</p> : null}
<p className={styles.reason}>Решение сохранено: {formatDate(latest.decided_at)}</p> <p className={styles.reason}>
Решение сохранено: <Mono>{formatDate(latest.decided_at)}</Mono>
</p>
<div className={styles.links}> <div className={styles.links}>
<TextLink to={paths.candidate.result(latest.attempt_id)}> <TextLink to={paths.candidate.result(latest.attempt_id)}>
Открыть разбор результата Открыть разбор результата
</TextLink> </TextLink>
<TextLink to={paths.candidate.results}>История результатов</TextLink> <TextLink to={paths.candidate.results}>История результатов</TextLink>
</div> </div>
</> </Card>
); );
} }
@@ -134,7 +145,6 @@ export function CandidateHomePage() {
return ( return (
<Page <Page
title="Главная" title="Главная"
eyebrow="Кабинет кандидата"
lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом." lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом."
width="wide" width="wide"
> >
@@ -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",
);
});
});
@@ -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<CandidateInvitation, "state" | "response_deadline_at">,
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<CandidateInvitation, "state" | "response_deadline_at">,
serverNowMs: number,
): boolean {
return invitation.state === "delivered" && isAnswerable(invitation, serverNowMs);
}
@@ -32,15 +32,20 @@ import type {
import { paths } from "../../../shared/config"; import { paths } from "../../../shared/config";
import { import {
ButtonLink, ButtonLink,
Card,
EmptyState, EmptyState,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
isAccessDenied, isAccessDenied,
LoadingState, LoadingState,
Notice,
Page, Page,
Section, Section,
Skeleton,
Tag,
TextLink, TextLink,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { invitationTagTone } from "../model/status-tone";
import { InvitationTermsArticle } from "../../../widgets/invitation-preview"; import { InvitationTermsArticle } from "../../../widgets/invitation-preview";
import styles from "./candidate-invitations.module.css"; import styles from "./candidate-invitations.module.css";
@@ -183,16 +188,18 @@ function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerS
onFailure={(failure) => onFailure("accept", failure)} onFailure={(failure) => onFailure("accept", failure)}
/> />
) : ( ) : (
<div className={styles["no-offer"]}> <Card tone="raised" className={styles["no-offer"]}>
<h3 className={styles.subtitle}>Принять приглашение нельзя</h3> <h3 className={styles.subtitle}>Принять приглашение нельзя</h3>
<p className={styles.text}> <p className={styles.text}>
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в
профиль, чтобы принять приглашение. профиль, чтобы принять приглашение.
</p> </p>
<div className={styles.actions}>
<ButtonLink to={paths.candidate.profile} variant="secondary"> <ButtonLink to={paths.candidate.profile} variant="secondary">
Открыть профиль Открыть профиль
</ButtonLink> </ButtonLink>
</div> </div>
</Card>
)} )}
<DeclineInvitationForm <DeclineInvitationForm
key={invitation.id} key={invitation.id}
@@ -221,31 +228,47 @@ function InvitationContent({
}: InvitationContentProps) { }: InvitationContentProps) {
return ( return (
<> <>
<Section title="Компания и срок"> <Card
as="section"
tone="raised"
labelledBy="invitation-company-title"
className={styles.summary}
>
<div className={styles["summary-head"]}>
<div className={styles["card-company"]}>
<span className={styles["card-label"]}>Компания и срок</span>
<h2 id="invitation-company-title" className={styles["summary-title"]}>
{invitation.organization.name}
</h2>
</div>
<span data-state={invitation.state}>
<Tag tone={invitationTagTone(invitation, serverNow)} dot>
{candidateStatusLabel(invitation, serverNow)}
</Tag>
</span>
</div>
<dl className={styles.facts}> <dl className={styles.facts}>
<div className={styles.fact}> <div className={styles.fact}>
<dt>Компания</dt> <dt>Роль</dt>
<dd>{invitation.organization.name}</dd> <dd className={styles["card-role"]}>{invitation.terms.role_title}</dd>
</div>
<div className={styles.fact}>
<dt>Состояние</dt>
<dd data-state={invitation.state}>{candidateStatusLabel(invitation, serverNow)}</dd>
</div> </div>
<div className={styles.fact}> <div className={styles.fact}>
<dt>Срок ответа</dt> <dt>Срок ответа</dt>
<dd data-term="deadline"> <dd data-term="deadline" className={styles.mono}>
<time dateTime={invitation.response_deadline_at}> <time dateTime={invitation.response_deadline_at}>
{`До ${formatServerMoment(invitation.response_deadline_at)}`} {`До ${formatServerMoment(invitation.response_deadline_at)}`}
</time> </time>
</dd> </dd>
</div> </div>
</dl> </dl>
</Section> </Card>
{notice ? ( {notice ? (
<p className={styles.notice} role="status"> <div role="status">
{notice} <Notice tone="info">
</p> <p className={styles.text}>{notice}</p>
</Notice>
</div>
) : null} ) : null}
<Section title="Условия приглашения"> <Section title="Условия приглашения">
@@ -330,14 +353,13 @@ export function CandidateInvitationPage() {
const serverNow = useServerNow(); const serverNow = useServerNow();
return ( return (
<Page <Page title="Приглашение" width="wide">
title="Приглашение"
eyebrow="Кабинет кандидата"
lead={invitation ? candidateStatusLabel(invitation, serverNow) : undefined}
>
{!validId ? <NotFoundState /> : null} {!validId ? <NotFoundState /> : null}
{validId && accountId !== "" && detail.isPending ? ( {validId && accountId !== "" && detail.isPending ? (
<>
<LoadingState label="Открываем приглашение..." /> <LoadingState label="Открываем приглашение..." />
<Skeleton shape="card" lines={4} />
</>
) : null} ) : null}
{validId && detail.isError ? ( {validId && detail.isError ? (
isMissing(detail.error) ? ( isMissing(detail.error) ? (
@@ -11,6 +11,7 @@ import {
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { paths } from "../../../shared/config"; import { paths } from "../../../shared/config";
import { import {
AttentionDot,
Button, Button,
EmptyState, EmptyState,
ErrorState, ErrorState,
@@ -18,7 +19,10 @@ import {
isAccessDenied, isAccessDenied,
LoadingState, LoadingState,
Page, Page,
Skeleton,
Tag,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { invitationTagTone, isNewInvitation } from "../model/status-tone";
import styles from "./candidate-invitations.module.css"; import styles from "./candidate-invitations.module.css";
const lead = const lead =
@@ -45,9 +49,12 @@ export function CandidateInvitationsPage() {
const serverNow = useServerNow(); const serverNow = useServerNow();
return ( return (
<Page title="Приглашения" eyebrow="Кабинет кандидата" lead={lead}> <Page title="Приглашения" lead={lead} width="wide">
{inbox.isPending && accountId !== "" ? ( {inbox.isPending && accountId !== "" ? (
<>
<LoadingState label="Загружаем приглашения..." /> <LoadingState label="Загружаем приглашения..." />
<Skeleton shape="card" lines={3} />
</>
) : null} ) : null}
{inbox.isError ? ( {inbox.isError ? (
isAccessDenied(inbox.error) ? ( isAccessDenied(inbox.error) ? (
@@ -77,20 +84,25 @@ export function CandidateInvitationsPage() {
{items.map((item) => ( {items.map((item) => (
<li key={item.id}> <li key={item.id}>
<Link className={styles.card} to={paths.candidate.invitation(item.id)}> <Link className={styles.card} to={paths.candidate.invitation(item.id)}>
<span className={styles["card-head"]}>
<span className={styles["card-company"]}> <span className={styles["card-company"]}>
<span className={styles["card-label"]}>Компания</span> <span className={styles["card-label"]}>Компания</span>
<span className={styles["card-title"]}>{item.organization.name}</span> <span className={styles["card-title"]}>
{isNewInvitation(item, serverNow) ? (
<AttentionDot label="Новое приглашение" />
) : null}
{item.organization.name}
</span>
</span>
<Tag tone={invitationTagTone(item, serverNow)}>
{candidateStatusLabel(item, serverNow)}
</Tag>
</span> </span>
<span className={styles["card-role"]}>{item.role_title}</span> <span className={styles["card-role"]}>{item.role_title}</span>
<span className={styles.salary}>{formatSalaryRange(item.salary)}</span>
<span className={styles["card-facts"]}> <span className={styles["card-facts"]}>
<span>{formatSalaryRange(item.salary)}</span>
<span>
{`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`} {`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
</span> </span>
</span>
<span className={styles["card-status"]} data-state={item.state}>
{candidateStatusLabel(item, serverNow)}
</span>
</Link> </Link>
</li> </li>
))} ))}
@@ -17,19 +17,68 @@
.card { .card {
display: grid; display: grid;
gap: var(--space-2); gap: var(--space-3);
align-content: start;
min-width: 0; min-width: 0;
min-height: 2.75rem; min-height: 2.75rem;
padding: var(--space-4); height: 100%;
padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
color: var(--color-text); color: var(--color-text);
text-decoration: none; text-decoration: none;
transition: border-color var(--duration-fast) var(--easing-standard);
} }
.card:hover { .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 { .card:focus-visible {
@@ -44,20 +93,28 @@
.card-label { .card-label {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-family: var(--font-mono);
font-size: var(--font-size-xs); font-size: var(--font-size-xs);
letter-spacing: var(--letter-spacing-label); letter-spacing: var(--letter-spacing-label);
text-transform: uppercase; text-transform: uppercase;
} }
.card-title { .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-size: var(--font-size-l);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
} }
.card-role { .card-role {
overflow-wrap: anywhere; color: var(--color-text);
font-family: var(--font-mono);
font-weight: var(--font-weight-medium); font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
} }
.card-facts { .card-facts {
@@ -67,14 +124,6 @@
font-size: var(--font-size-s); 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 { .more {
display: flex; display: flex;
justify-content: center; justify-content: center;
@@ -87,6 +136,12 @@
margin: 0; margin: 0;
} }
@media (width >= 48rem) {
.facts {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.fact { .fact {
display: grid; display: grid;
gap: var(--space-1); gap: var(--space-1);
@@ -104,13 +159,13 @@
} }
.section-title { .section-title {
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
} }
.subtitle { .subtitle {
color: var(--color-text-strong);
font-size: var(--font-size-m); font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
} }
.text { .text {
@@ -119,29 +174,21 @@
overflow-wrap: anywhere; 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 { .decisions {
display: grid; display: grid;
gap: var(--space-5); gap: var(--space-5);
align-items: start;
min-width: 0; min-width: 0;
} }
@media (width >= 64rem) {
.decisions {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.no-offer { .no-offer {
display: grid; align-content: start;
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);
} }
.grant { .grant {
@@ -166,3 +213,9 @@
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
} }
} }
@media (width >= 80rem) {
.list {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@@ -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);
}
@@ -2,7 +2,45 @@ import { Navigate } from "react-router-dom";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { getOnboardingDestination } from "../../../entities/session"; import { getOnboardingDestination } from "../../../entities/session";
import { paths } from "../../../shared/config"; 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() { export function CandidateOnboardingPage() {
const session = useGetCurrentSession(); const session = useGetCurrentSession();
@@ -32,20 +70,57 @@ export function CandidateOnboardingPage() {
return <Navigate to={destination} replace />; return <Navigate to={destination} replace />;
} }
const currentIndex = accountSteps.findIndex((item) => item.id === step);
return ( return (
<Page title="Первые шаги" eyebrow="Кабинет кандидата"> <Page
<Section title="Первые шаги"
title="Согласия" lead="Четыре шага до подтвержденной категории. Состояние шага хранится на сервере, поэтому его можно продолжить с любого устройства."
description="Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации." width="wide"
> >
<p> <Card as="section" tone="panel" labelledBy="onboarding-progress-title">
Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие <h2 id="onboarding-progress-title" className={styles["panel-title"]}>
отдельно. Шаги аккаунта
</p> </h2>
<Stepper label="Шаги аккаунта кандидата" steps={buildSteps(accountSteps, currentIndex)} />
<ol className={styles.steps}>
{accountSteps.map((item, index) => {
const isCurrent = index === currentIndex;
return (
<li
key={item.id}
className={styles.step}
data-current={isCurrent || undefined}
aria-labelledby={`onboarding-step-${item.id}`}
>
<div className={styles["step-head"]}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono>
<h3 id={`onboarding-step-${item.id}`} className={styles["step-title"]}>
{item.label}
</h3>
{isCurrent ? (
<Tag tone="accent" dot>
сейчас
</Tag>
) : null}
</div>
<p className={styles["step-text"]}>{item.text}</p>
{isCurrent ? (
<div className={styles.action}>
<ButtonLink to={paths.candidate.privacy}> <ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности Открыть согласия и настройки приватности
</ButtonLink> </ButtonLink>
</Section> </div>
) : null}
</li>
);
})}
</ol>
<p className={styles.note}>
Сохраненный шаг хранит сервер. Профиль, анкета и тест открываются из меню кабинета и
сохраняются независимо от него. Привязка ФСП ID и резюме для этого пути не нужны.
</p>
</Card>
</Page> </Page>
); );
} }
@@ -28,9 +28,9 @@ function render(scenario: "candidate" | "employer", element: React.ReactElement)
} }
describe("notification pages", () => { 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", <CandidateNotificationsPage />); const candidate = render("candidate", <CandidateNotificationsPage />);
expect(candidate).toContain("Кабинет кандидата"); expect(candidate).not.toContain("Кабинет кандидата");
expect(candidate.match(/<h1/g)).toHaveLength(1); expect(candidate.match(/<h1/g)).toHaveLength(1);
const employer = render("employer", <EmployerNotificationsPage />); const employer = render("employer", <EmployerNotificationsPage />);
expect(employer).toContain("Кабинет работодателя"); expect(employer).toContain("Кабинет работодателя");
@@ -6,7 +6,7 @@ const lead =
export function CandidateNotificationsPage() { export function CandidateNotificationsPage() {
return ( return (
<Page title="Уведомления" eyebrow="Кабинет кандидата" lead={lead}> <Page title="Уведомления" lead={lead}>
<NotificationInbox scope={{ kind: "candidate" }} /> <NotificationInbox scope={{ kind: "candidate" }} />
</Page> </Page>
); );
@@ -6,15 +6,15 @@
} }
.note { .note {
margin: 0.75rem 0 0; margin: var(--space-3) 0 0;
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: 0.925rem; font-size: var(--font-size-s);
line-height: 1.55; line-height: var(--line-height-body);
} }
.organization-columns section { .organization-columns section {
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
@@ -22,7 +22,8 @@
.organization-columns h3 { .organization-columns h3 {
margin: 0 0 var(--space-3); margin: 0 0 var(--space-3);
font-size: 1rem; color: var(--color-text-strong);
font-size: var(--font-size-m);
} }
.organization-list, .organization-list,
@@ -59,7 +60,13 @@
.history-list time, .history-list time,
.history-list span { .history-list span {
color: var(--color-text-secondary); 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 { .history-list li {
@@ -82,21 +89,68 @@
margin: 0; margin: 0;
} }
.error { .notice-text {
margin-block-start: var(--space-3);
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-danger);
background: var(--color-surface);
color: var(--color-text); color: var(--color-text);
} }
.message { .actions {
margin-block-start: var(--space-3); display: flex;
color: var(--color-text-secondary); 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) { @media (width < 48rem) {
.organization-columns { .organization-columns {
grid-template-columns: minmax(0, 1fr); 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;
}
} }
+49 -10
View File
@@ -61,6 +61,7 @@ import {
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Notice,
Page, Page,
Section, Section,
} from "../../../shared/ui"; } from "../../../shared/ui";
@@ -68,6 +69,16 @@ import { candidateViewQueryKeys } from "../../../entities/candidate-view";
import styles from "./privacy-page.module.css"; import styles from "./privacy-page.module.css";
const pageSize = 100; 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<string> = new Set(); const noOrganizations: ReadonlySet<string> = new Set();
const privateQueryOptions = { const privateQueryOptions = {
gcTime: 0, gcTime: 0,
@@ -302,14 +313,18 @@ export function OrganizationVisibility({
</div> </div>
<p className={styles.note}>{contactAccessAfterVisibilityChange}</p> <p className={styles.note}>{contactAccessAfterVisibilityChange}</p>
{actionError ? ( {actionError ? (
<div className={styles.error} role="alert"> <div role="alert">
{actionError} <Notice tone="danger">
<p className={styles["notice-text"]}>{actionError}</p>
</Notice>
</div> </div>
) : null} ) : null}
{actionMessage ? ( {actionMessage ? (
<p className={styles.message} role="status"> <div role="status">
{actionMessage} <Notice tone="success">
</p> <p className={styles["notice-text"]}>{actionMessage}</p>
</Notice>
</div>
) : null} ) : null}
</Section> </Section>
); );
@@ -801,7 +816,7 @@ export function PrivacyPage() {
if (session.isError) { if (session.isError) {
return ( return (
<Page title="Настройки приватности" eyebrow="Кабинет кандидата"> <Page title="Настройки приватности">
<ErrorState <ErrorState
error={session.error} error={session.error}
onRetry={() => void session.refetch()} onRetry={() => void session.refetch()}
@@ -815,14 +830,14 @@ export function PrivacyPage() {
if (session.isPending) return <LoadingState label="Проверяем доступ к приватным настройкам..." />; if (session.isPending) return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
if (session.data?.account.scenario !== "candidate") { if (session.data?.account.scenario !== "candidate") {
return ( return (
<Page title="Настройки приватности" eyebrow="Кабинет кандидата"> <Page title="Настройки приватности">
<ForbiddenState title="Настройки доступны только кандидату" /> <ForbiddenState title="Настройки доступны только кандидату" />
</Page> </Page>
); );
} }
if (privateAccessLost) { if (privateAccessLost) {
return ( return (
<Page title="Настройки приватности" eyebrow="Кабинет кандидата"> <Page title="Настройки приватности">
<ForbiddenState <ForbiddenState
title="Доступ к приватным данным потерян" title="Доступ к приватным данным потерян"
description="Сеанс или права доступа изменились. Приватные данные очищены из текущего экрана; проверьте сессию и откройте страницу снова." description="Сеанс или права доступа изменились. Приватные данные очищены из текущего экрана; проверьте сессию и откройте страницу снова."
@@ -832,7 +847,7 @@ export function PrivacyPage() {
} }
if (settingsQuery.isError) { if (settingsQuery.isError) {
return ( return (
<Page title="Настройки приватности" eyebrow="Кабинет кандидата"> <Page title="Настройки приватности">
<ErrorState <ErrorState
error={settingsQuery.error} error={settingsQuery.error}
onRetry={() => void settingsQuery.refetch()} onRetry={() => void settingsQuery.refetch()}
@@ -846,10 +861,21 @@ export function PrivacyPage() {
return ( return (
<Page <Page
title="Настройки приватности" title="Настройки приватности"
eyebrow="Кабинет кандидата"
width="wide" width="wide"
lead="Согласие, публикация карточки, статус поиска и скрытие от компаний - отдельные настройки. Ни одно действие не включает другое автоматически." lead="Согласие, публикация карточки, статус поиска и скрытие от компаний - отдельные настройки. Ни одно действие не включает другое автоматически."
> >
<nav className={styles.contents} aria-label="Разделы настроек приватности">
<ul>
{privacySections.map((section) => (
<li key={section.id}>
<a href={`#${section.id}`} className={styles["contents-link"]}>
{section.label}
</a>
</li>
))}
</ul>
</nav>
<div id="privacy-consents" className={styles.anchor}>
{canShowConsentManagement ? ( {canShowConsentManagement ? (
<> <>
<Section <Section
@@ -866,6 +892,7 @@ export function PrivacyPage() {
<LoadingState label="Подготавливаем историю согласий..." /> <LoadingState label="Подготавливаем историю согласий..." />
</Section> </Section>
)} )}
</div>
{c2State === "checking" ? ( {c2State === "checking" ? (
<Section <Section
@@ -900,6 +927,7 @@ export function PrivacyPage() {
</Section> </Section>
) : null} ) : null}
<div id="privacy-publication" className={styles.anchor}>
<PublicationControls <PublicationControls
settings={settings} settings={settings}
c2State={c2State} c2State={c2State}
@@ -918,7 +946,9 @@ export function PrivacyPage() {
onReload={() => void reloadPublicationSettings()} onReload={() => void reloadPublicationSettings()}
onOpenConsent={openConsentBlock} onOpenConsent={openConsentBlock}
/> />
</div>
<div id="privacy-search" className={styles.anchor}>
<SearchStatusControl <SearchStatusControl
settings={settings} settings={settings}
isSaving={pendingAction !== null || settingsQuery.isFetching} isSaving={pendingAction !== null || settingsQuery.isFetching}
@@ -926,7 +956,9 @@ export function PrivacyPage() {
error={feedbackScope === "search" ? actionError : null} error={feedbackScope === "search" ? actionError : null}
onSetStatus={(value) => void setSearchStatus(value)} onSetStatus={(value) => void setSearchStatus(value)}
/> />
</div>
<div id="privacy-preview" className={styles.anchor}>
<Section <Section
title="Предварительный просмотр карточки" title="Предварительный просмотр карточки"
description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации." description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации."
@@ -938,7 +970,9 @@ export function PrivacyPage() {
onRetry={() => void previewQuery.refetch()} onRetry={() => void previewQuery.refetch()}
/> />
</Section> </Section>
</div>
<div id="privacy-companies" className={styles.anchor}>
<OrganizationVisibility <OrganizationVisibility
accessRecords={accessRecords} accessRecords={accessRecords}
accessLoading={accessHistory.isPending} accessLoading={accessHistory.isPending}
@@ -958,7 +992,9 @@ export function PrivacyPage() {
onHide={hideFromOrganization} onHide={hideFromOrganization}
onUnhide={unhideOrganizationForCandidate} onUnhide={unhideOrganizationForCandidate}
/> />
</div>
<div id="privacy-history" className={styles.anchor}>
<PrivacyHistory <PrivacyHistory
events={privacyEvents} events={privacyEvents}
isLoading={privacyHistory.isPending} isLoading={privacyHistory.isPending}
@@ -977,15 +1013,18 @@ export function PrivacyPage() {
isFetching={accessHistory.isFetchingNextPage} isFetching={accessHistory.isFetchingNextPage}
onLoad={() => void accessHistory.fetchNextPage()} onLoad={() => void accessHistory.fetchNextPage()}
/> />
</div>
<Section title="Ручная оценка"> <Section title="Ручная оценка">
<p> <p>
Можно запросить оценку специалистом до первого теста или после отзыва согласия на Можно запросить оценку специалистом до первого теста или после отзыва согласия на
автоматическую оценку. Запрос не включает согласие обратно. автоматическую оценку. Запрос не включает согласие обратно.
</p> </p>
<div className={styles.actions}>
<ButtonLink to={paths.candidate.supportManual} variant="secondary"> <ButtonLink to={paths.candidate.supportManual} variant="secondary">
Запросить ручную оценку Запросить ручную оценку
</ButtonLink> </ButtonLink>
</div>
</Section> </Section>
</Page> </Page>
); );
@@ -5,7 +5,6 @@ export function ProfilePage() {
return ( return (
<Page <Page
title="Профиль" title="Профиль"
eyebrow="Кабинет кандидата"
lead="Управляйте своими сведениями и проверяйте, какие данные подтверждены оценкой." lead="Управляйте своими сведениями и проверяйте, какие данные подтверждены оценкой."
width="wide" width="wide"
> >
@@ -5,7 +5,6 @@ export function QuestionnairePage() {
return ( return (
<Page <Page
title="Анкета" title="Анкета"
eyebrow="Кабинет кандидата"
lead="Укажите специализации и условия поиска. Самооценка не становится подтвержденной категорией." lead="Укажите специализации и условия поиска. Самооценка не становится подтвержденной категорией."
width="wide" width="wide"
> >
@@ -20,7 +20,7 @@
.event, .event,
.decision { .decision {
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
@@ -39,17 +39,10 @@
.event-heading h3, .event-heading h3,
.decision h3 { .decision h3 {
margin: 0; margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-l); 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, .case-card p,
.event p, .event p,
.decision p { .decision p {
@@ -65,6 +58,12 @@
font-size: var(--font-size-s); font-size: var(--font-size-s);
} }
.date,
.event-heading time {
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
}
.more { .more {
margin-top: var(--space-4); margin-top: var(--space-4);
} }
@@ -104,10 +103,6 @@
} }
@media (width <= 40rem) { @media (width <= 40rem) {
.actions > * {
width: 100%;
}
.facts { .facts {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-1); gap: var(--space-1);
@@ -26,7 +26,7 @@ import {
getMySupportCase, getMySupportCase,
listMySupportCases, listMySupportCases,
} from "../../../shared/api/endpoints/support/support"; } 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 { paths } from "../../../shared/config";
import { import {
Button, Button,
@@ -37,11 +37,23 @@ import {
LoadingState, LoadingState,
Page, Page,
Section, Section,
Tag,
TextLink, TextLink,
type TagTone,
} from "../../../shared/ui"; } from "../../../shared/ui";
import styles from "./support-cases-pages.module.css"; import styles from "./support-cases-pages.module.css";
const supportCasePageSize = 20; const supportCasePageSize = 20;
// The label states the status; the tone only marks the one that waits for the candidate.
const supportCaseStatusTones: Readonly<Record<SupportCaseStatus, TagTone>> = {
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; 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 { function isCaseAccessError(error: unknown): error is ApiRequestError {
@@ -204,9 +216,7 @@ export function SupportCasesPage() {
return ( return (
<Page <Page
title="Мои обращения" title="Мои обращения"
eyebrow={ eyebrow={actor.account.scenario === "candidate" ? undefined : "Кабинет работодателя"}
actor.account.scenario === "candidate" ? "Кабинет кандидата" : "Кабинет работодателя"
}
lead="Здесь хранятся обращения этого аккаунта и ответы поддержки." lead="Здесь хранятся обращения этого аккаунта и ответы поддержки."
width="wide" width="wide"
> >
@@ -302,7 +312,9 @@ function SupportCaseSummaryCard({
<h3> <h3>
<TextLink to={href}>{supportCase.number}</TextLink> <TextLink to={href}>{supportCase.number}</TextLink>
</h3> </h3>
<span>{supportCaseStatusLabels[supportCase.status]}</span> <Tag tone={supportCaseStatusTones[supportCase.status]}>
{supportCaseStatusLabels[supportCase.status]}
</Tag>
</div> </div>
<p>{supportCaseTypeLabels[supportCase.type]}</p> <p>{supportCaseTypeLabels[supportCase.type]}</p>
<p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p> <p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p>
@@ -1,7 +1,7 @@
import type { Ref } from "react"; import type { Ref } from "react";
import type { AssessmentResult } from "../../../shared/api/schemas"; import type { AssessmentResult } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths"; import { paths } from "../../../shared/config/paths";
import { TextLink } from "../../../shared/ui"; import { Mono, TextLink } from "../../../shared/ui";
import { describeAssessmentResult } from "../../../entities/assessment"; import { describeAssessmentResult } from "../../../entities/assessment";
import styles from "./assessment-history.module.css"; import styles from "./assessment-history.module.css";
@@ -23,7 +23,9 @@ export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHi
const view = describeAssessmentResult(item, timeZone ? { timeZone } : {}); const view = describeAssessmentResult(item, timeZone ? { timeZone } : {});
return ( return (
<li key={item.attempt_id} className={styles.item}> <li key={item.attempt_id} className={styles.item}>
<p className={styles.kind}>{view.kindLabel}</p> <p className={styles.kind}>
{view.kindLabel} · <Mono>{view.decidedDay}</Mono>
</p>
<h2 className={styles.title}>{view.title}</h2> <h2 className={styles.title}>{view.title}</h2>
<p className={styles.summary}>{view.summary.text}</p> <p className={styles.summary}>{view.summary.text}</p>
<dl className={styles.facts}> <dl className={styles.facts}>
@@ -10,22 +10,60 @@
font-size: var(--font-size-s); font-size: var(--font-size-s);
} }
/* A timeline: the results hang on a circuit trace, newest first. */
.list { .list {
position: relative;
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
margin: 0; margin: 0;
padding: 0; padding: 0 0 0 var(--space-5);
list-style: none; 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 { .item {
position: relative;
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-3);
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); 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 { .item p {
@@ -35,6 +73,7 @@
.kind { .kind {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-family: var(--font-mono);
font-size: var(--font-size-xs); font-size: var(--font-size-xs);
letter-spacing: var(--letter-spacing-label); letter-spacing: var(--letter-spacing-label);
text-transform: uppercase; text-transform: uppercase;
@@ -42,6 +81,7 @@
.title { .title {
margin: 0; margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-l); font-size: var(--font-size-l);
line-height: var(--line-height-snug); line-height: var(--line-height-snug);
overflow-wrap: anywhere; overflow-wrap: anywhere;
@@ -76,7 +116,7 @@
@media (width < 42rem) { @media (width < 42rem) {
.item { .item {
padding: var(--space-3); padding: var(--space-4);
} }
} }
@@ -9,6 +9,7 @@ import {
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
LoadingState, LoadingState,
Skeleton,
} from "../../../shared/ui"; } from "../../../shared/ui";
import { import {
isAssessmentAccessLoss, isAssessmentAccessLoss,
@@ -79,7 +80,14 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps
/> />
); );
} }
if (history.isPending) return <LoadingState label="Загружаем историю результатов..." />; if (history.isPending) {
return (
<div className={styles.root}>
<LoadingState label="Загружаем историю результатов..." />
<Skeleton shape="card" lines={3} />
</div>
);
}
if (history.isError && !history.data) { if (history.isError && !history.data) {
return ( return (
<ErrorState <ErrorState
@@ -128,6 +136,7 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps
onRetry={() => void loadMore()} onRetry={() => void loadMore()}
/> />
) : history.hasNextPage ? ( ) : history.hasNextPage ? (
<div className={styles.more}>
<Button <Button
variant="secondary" variant="secondary"
isBusy={history.isFetchingNextPage} isBusy={history.isFetchingNextPage}
@@ -135,6 +144,7 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps
> >
{history.isFetchingNextPage ? "Загружаем..." : "Показать еще"} {history.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
</Button> </Button>
</div>
) : null} ) : null}
</div> </div>
); );
@@ -3,32 +3,55 @@
gap: var(--space-6); 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 { .card {
display: grid; position: relative;
gap: var(--space-3); overflow: hidden;
padding: var(--space-5); isolation: isolate;
border: var(--line-strong) solid var(--color-border-strong); }
border-radius: var(--radius-l);
background: var(--color-surface); .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 { .card-eyebrow {
color: var(--color-accent); color: var(--color-accent);
font-family: var(--font-mono);
font-size: var(--font-size-xs); font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-medium);
letter-spacing: var(--letter-spacing-label); letter-spacing: var(--letter-spacing-label);
text-transform: uppercase; text-transform: uppercase;
} }
.card-title { .card-title {
font-size: var(--font-size-xl); max-width: 36rem;
font-weight: var(--font-weight-bold); color: var(--color-text-strong);
line-height: var(--line-height-snug); font-size: var(--font-size-title);
font-weight: var(--font-weight-medium);
letter-spacing: var(--letter-spacing-display);
line-height: 1.2;
} }
.card-text { .card-text {
max-width: 44rem; max-width: 40rem;
color: var(--color-text);
font-size: var(--font-size-m); font-size: var(--font-size-m);
line-height: var(--line-height-body); line-height: var(--line-height-body);
} }
@@ -68,19 +91,26 @@
list-style: none; list-style: none;
} }
.standing,
.link { .link {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: center;
justify-content: space-between;
min-width: 0; min-width: 0;
padding: var(--space-4); padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-divider); border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m); border-radius: var(--radius-m);
background: var(--color-surface); background: var(--color-surface);
transition: border-color var(--duration-fast) var(--easing-standard);
}
.link:hover {
border-color: var(--color-border-hover);
} }
.standing-title { .standing-title {
margin-bottom: var(--space-3);
font-size: var(--font-size-m); font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
} }
.facts { .facts {
@@ -108,16 +138,10 @@
overflow-wrap: anywhere; 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 { .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 { .link-status {
@@ -11,12 +11,16 @@ import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/ide
import { paths } from "../../../shared/config"; import { paths } from "../../../shared/config";
import { import {
ButtonLink, ButtonLink,
Card,
CircuitTrace,
EmptyState, EmptyState,
ErrorState, ErrorState,
ForbiddenState, ForbiddenState,
isAccessDenied, isAccessDenied,
LoadingState, LoadingState,
Section, Section,
Skeleton,
Tag,
TextLink, TextLink,
TrustLevel, TrustLevel,
} from "../../../shared/ui"; } from "../../../shared/ui";
@@ -109,7 +113,8 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) {
// produced a result, showing "consents" would contradict the result blocks. // produced a result, showing "consents" would contradict the result blocks.
const showSavedStep = !journey.hasResults; const showSavedStep = !journey.hasResults;
return ( return (
<section className={styles.card} aria-labelledby="next-step-title"> <Card as="section" tone="panel" labelledBy="next-step-title" className={styles.card}>
<CircuitTrace className={styles.decor} />
<p className={styles["card-eyebrow"]}>Следующий шаг</p> <p className={styles["card-eyebrow"]}>Следующий шаг</p>
<h2 id="next-step-title" className={styles["card-title"]}> <h2 id="next-step-title" className={styles["card-title"]}>
{view.title} {view.title}
@@ -135,7 +140,7 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) {
: null} : null}
</p> </p>
) : null} ) : null}
</section> </Card>
); );
} }
@@ -155,9 +160,14 @@ function Standings({ journey }: { journey: CandidateJourney }) {
) : ( ) : (
<ul className={styles.standings}> <ul className={styles.standings}>
{journey.standings.map((standing) => ( {journey.standings.map((standing) => (
<li key={standing.specialization} className={styles.standing}> <li key={standing.specialization}>
<h3 className={styles["standing-title"]}> <Card tone="raised" labelledBy={`standing-${standing.specialization}`}>
{specializationLabels[standing.specialization]} <h3 id={`standing-${standing.specialization}`} className={styles["standing-title"]}>
<Tag tone="grade">
{standing.confirmedGrade
? `${specializationLabels[standing.specialization]} · ${gradeLabels[standing.confirmedGrade]}`
: specializationLabels[standing.specialization]}
</Tag>
</h3> </h3>
<dl className={styles.facts}> <dl className={styles.facts}>
<dt>Заявлено (самооценка)</dt> <dt>Заявлено (самооценка)</dt>
@@ -183,6 +193,7 @@ function Standings({ journey }: { journey: CandidateJourney }) {
)} )}
</dd> </dd>
</dl> </dl>
</Card>
</li> </li>
))} ))}
</ul> </ul>
@@ -291,7 +302,12 @@ export function CandidateNextStep() {
); );
} }
if (state.status === "pending") { if (state.status === "pending") {
return <LoadingState label="Определяем следующий шаг..." />; return (
<div className={styles.root}>
<LoadingState label="Определяем следующий шаг..." />
<Skeleton shape="card" lines={3} />
</div>
);
} }
if (state.status === "error") { if (state.status === "error") {
if (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />; if (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />;
@@ -100,3 +100,23 @@
padding: 0; 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
);
}
@@ -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 { Outlet, useLocation } from "react-router-dom";
import { paths } from "../../../shared/config"; import { paths } from "../../../shared/config";
import { HeaderPlate, MainRegion, NavItem, SkipLink, Wordmark } from "../../../shared/ui"; 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.invitations, label: "Приглашения", end: false },
{ to: paths.candidate.notifications, label: "Уведомления", end: false }, { to: paths.candidate.notifications, label: "Уведомления", end: false },
{ to: paths.candidate.privacy, 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; ] as const;
/** /**
@@ -35,6 +35,38 @@ function useCurrentTabInView() {
return listRef; 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<HTMLUListElement | null>): ScrollEdges {
const [edges, setEdges] = useState<ScrollEdges>({ 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 * 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; * section tabs form a bar at the bottom of the screen, within thumb reach;
@@ -43,6 +75,7 @@ function useCurrentTabInView() {
*/ */
export function CandidateShell() { export function CandidateShell() {
const listRef = useCurrentTabInView(); const listRef = useCurrentTabInView();
const edges = useScrollEdges(listRef);
return ( return (
<div className={styles.shell}> <div className={styles.shell}>
@@ -51,7 +84,12 @@ export function CandidateShell() {
<HeaderPlate className={styles.plate}> <HeaderPlate className={styles.plate}>
<Wordmark to={paths.candidate.root} context="Кабинет кандидата" /> <Wordmark to={paths.candidate.root} context="Кабинет кандидата" />
<nav className={styles.nav} aria-label="Разделы кабинета кандидата"> <nav className={styles.nav} aria-label="Разделы кабинета кандидата">
<ul ref={listRef} className={styles.list}> <ul
ref={listRef}
className={styles.list}
data-fade-start={edges.start || undefined}
data-fade-end={edges.end || undefined}
>
{navigation.map((item) => ( {navigation.map((item) => (
<li key={item.to}> <li key={item.to}>
<NavItem to={item.to} end={item.end}> <NavItem to={item.to} end={item.end}>