feat(frontend): redesign the candidate cabinet with step-by-step profile and questionnaire forms
This commit is contained in:
1 parent
15590d127c
commit
c836d02ea3
77 files changed
+5409
-1618
No files matched your search
+3
-3
@@ -83,7 +83,7 @@ In the same mode, the runner invokes `/consent-fixture` from the test backend im
|
||||
|
||||
The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser.
|
||||
|
||||
`frontend/e2e/profile-edit.spec.ts` fills the manual profile at 360px after real registration, acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
|
||||
`frontend/e2e/profile-edit.spec.ts` walks the steps of the manual profile at 360px after real registration ("Далее" with the focus on the heading, a step blocked until overlapping periods are confirmed, "Назад" without losing data), acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
|
||||
|
||||
`frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data.
|
||||
|
||||
@@ -453,9 +453,9 @@ Unit tests (`make -C backend test`) check the profile rules without a database:
|
||||
|
||||
The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged.
|
||||
|
||||
`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled.
|
||||
`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario walks the questionnaire steps (step validation, the focus on the heading, "Назад" and "Изменить" without losing answers) and covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled.
|
||||
|
||||
`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training, offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration.
|
||||
`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration.
|
||||
|
||||
## Candidate visibility tests
|
||||
|
||||
|
||||
+3
-3
@@ -83,7 +83,7 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
|
||||
|
||||
Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется.
|
||||
|
||||
`frontend/e2e/profile-edit.spec.ts` заполняет ручной профиль на 360 px после реальной регистрации, подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
|
||||
`frontend/e2e/profile-edit.spec.ts` проходит шаги ручного профиля на 360 px после реальной регистрации (переход "Далее" с фокусом на заголовке, блокировка шага без подтверждения пересечения, "Назад" без потери данных), подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
|
||||
|
||||
`frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные.
|
||||
|
||||
@@ -453,9 +453,9 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются.
|
||||
|
||||
`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается.
|
||||
`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проходит шаги анкеты (проверка шага, фокус на заголовке, "Назад" и "Изменить" без потери ответов) и проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается.
|
||||
|
||||
`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим, отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
|
||||
`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
|
||||
|
||||
## Тесты видимости кандидата
|
||||
|
||||
|
||||
@@ -131,11 +131,18 @@ async function grantC3(page: Page): Promise<void> {
|
||||
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/questionnaire");
|
||||
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
|
||||
// The questionnaire is a form in steps; "Далее" moves the focus to the next heading.
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused();
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("junior");
|
||||
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
@@ -369,6 +376,31 @@ test("candidate can review, resume, and finish separate assessment modes", async
|
||||
const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot;
|
||||
expect(firstExpressSnapshot.current_item?.id).toBeTruthy();
|
||||
|
||||
// An unfinished express run is resumed: after a full reload of the
|
||||
// assessment page, a new start answers 409, and the page replays the start
|
||||
// with the key stored in this tab, which returns the stored 201 of the run.
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible();
|
||||
const expressStarts: { status: number; key: string | null }[] = [];
|
||||
const recordExpressStart = (response: Response) => {
|
||||
if (
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts"
|
||||
) {
|
||||
expressStarts.push({
|
||||
status: response.status(),
|
||||
key: response.request().headers()["idempotency-key"] ?? null,
|
||||
});
|
||||
}
|
||||
};
|
||||
page.on("response", recordExpressStart);
|
||||
await page.getByRole("button", { name: "Начать демонстрацию" }).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`));
|
||||
await expect(page.getByText("Незавершенная демонстрация продолжена")).toBeVisible();
|
||||
page.off("response", recordExpressStart);
|
||||
expect(expressStarts.map((start) => start.status)).toEqual([409, 201]);
|
||||
expect(expressStarts[0]?.key).not.toBe(expressStarts[1]?.key);
|
||||
|
||||
await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`);
|
||||
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0);
|
||||
|
||||
@@ -159,6 +159,13 @@ test.describe("candidate home with the real backend", () => {
|
||||
await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click();
|
||||
await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible();
|
||||
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат");
|
||||
// The profile is a form in steps: walk to the review step, then save.
|
||||
for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
|
||||
).toBeFocused();
|
||||
}
|
||||
const profileSaved = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
@@ -173,9 +180,15 @@ test.describe("candidate home with the real backend", () => {
|
||||
await page.getByRole("link", { name: "Заполнить анкету", exact: true }).first().click();
|
||||
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused();
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("middle");
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
|
||||
const questionnaireSaved = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
|
||||
@@ -606,11 +606,18 @@ async function grantC3(page: Page): Promise<void> {
|
||||
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/questionnaire");
|
||||
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
|
||||
// The questionnaire is a form in steps; "Далее" moves the focus to the next heading.
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused();
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("junior");
|
||||
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
|
||||
@@ -394,12 +394,21 @@ test.describe("candidate without a confirmed grade with the real backend", () =>
|
||||
// Two declared specializations in the profile, none confirmed by a test.
|
||||
await page.goto("/candidate/profile");
|
||||
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат");
|
||||
// The profile is a form in steps: roles are the second step.
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Роли$/ })).toBeFocused();
|
||||
await page.getByRole("button", { name: "Добавить специализацию" }).click();
|
||||
await page.getByRole("button", { name: "Добавить специализацию" }).click();
|
||||
await page.getByLabel("Специализация").nth(0).selectOption("backend");
|
||||
await page.getByLabel("Специализация").nth(1).selectOption("network_engineer");
|
||||
await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle");
|
||||
await page.getByLabel("Моя оценка уровня").nth(1).selectOption("junior");
|
||||
for (const heading of ["Опыт", "Навыки", "Условия", "Проверка"]) {
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
|
||||
).toBeFocused();
|
||||
}
|
||||
const profileSaved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile"));
|
||||
await page.getByRole("button", { name: "Сохранить профиль" }).click();
|
||||
expect((await profileSaved).status()).toBe(200);
|
||||
|
||||
@@ -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> {
|
||||
await openReview(page);
|
||||
const responsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
@@ -182,29 +211,47 @@ test.describe("candidate profile", () => {
|
||||
await page.getByLabel("Телефон").fill("+79990000000");
|
||||
await page.getByLabel("Telegram").fill("@candidate_123");
|
||||
|
||||
await expect(page.getByText("Шаг 1 из 6", { exact: true })).toBeVisible();
|
||||
await nextStep(page, "Роли");
|
||||
await page.getByRole("button", { name: "Добавить специализацию" }).click();
|
||||
await page.getByLabel("Специализация").selectOption("backend");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
|
||||
await nextStep(page, "Опыт");
|
||||
await page.getByRole("button", { name: "Добавить место работы" }).click();
|
||||
await page.getByRole("button", { name: "Добавить место работы" }).click();
|
||||
const experienceSpecialization = page.getByLabel("Специализация").filter({ visible: true });
|
||||
await page.getByLabel("Компания").nth(0).fill("Первая компания");
|
||||
await page.getByLabel("Компания").nth(1).fill("Вторая компания");
|
||||
await page.getByLabel("Специализация").nth(0).selectOption("backend");
|
||||
await page.getByLabel("Специализация").nth(1).selectOption("frontend");
|
||||
await experienceSpecialization.nth(0).selectOption("backend");
|
||||
await experienceSpecialization.nth(1).selectOption("frontend");
|
||||
await page.getByLabel("Начало работы").nth(0).fill("2024-01");
|
||||
await page.getByLabel("Окончание работы").nth(0).fill("2024-12");
|
||||
await page.getByLabel("Начало работы").nth(1).fill("2024-06");
|
||||
await page.getByLabel("Окончание работы").nth(1).fill("2025-01");
|
||||
// The overlapping periods block the step until they are confirmed.
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "действительно шли параллельно" }),
|
||||
).toBeFocused();
|
||||
await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check();
|
||||
|
||||
await page.getByRole("button", { name: "Добавить специализацию" }).click();
|
||||
await page.getByLabel("Специализация").nth(2).selectOption("backend");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await nextStep(page, "Навыки");
|
||||
await page.getByRole("button", { name: "Добавить навык" }).click();
|
||||
await page.getByLabel("Навык 1", { exact: true }).fill("Go");
|
||||
await page.getByRole("button", { name: "Добавить гибкий навык" }).click();
|
||||
await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация");
|
||||
await nextStep(page, "Условия");
|
||||
await page.getByLabel("Желаемое место работы").fill("Москва");
|
||||
await page.getByLabel("Готовность к переезду").selectOption("true");
|
||||
await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000");
|
||||
await page.getByLabel("Сумма до или после налога").selectOption("gross");
|
||||
await nextStep(page, "Проверка");
|
||||
// Back keeps the entered data.
|
||||
await page.getByRole("button", { name: "Назад", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Условия$/ })).toBeFocused();
|
||||
await expect(page.getByLabel("Желаемое место работы")).toHaveValue("Москва");
|
||||
await nextStep(page, "Проверка");
|
||||
|
||||
const pausedSave = await pauseProfileSave(page);
|
||||
try {
|
||||
@@ -226,6 +273,7 @@ test.describe("candidate profile", () => {
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
|
||||
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
|
||||
await editStep(page, "опыт", "Опыт");
|
||||
await expect(
|
||||
page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/),
|
||||
).toBeVisible();
|
||||
@@ -287,9 +335,11 @@ test.describe("candidate profile", () => {
|
||||
await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click();
|
||||
await latestRead;
|
||||
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName);
|
||||
await editStep(page, "контакты", "Контакты");
|
||||
await page.getByLabel("Имя и фамилия").fill(staleName);
|
||||
await saveProfile(page);
|
||||
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
|
||||
await editStep(page, "контакты", "Контакты");
|
||||
await expectResponsiveKeyboardFlow(page);
|
||||
|
||||
await page.reload();
|
||||
@@ -303,6 +353,7 @@ test.describe("candidate profile", () => {
|
||||
const firstAccount = await registerCandidate(page);
|
||||
const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`;
|
||||
await page.getByLabel("Имя и фамилия").fill(firstProfileName);
|
||||
await openReview(page);
|
||||
|
||||
const pausedSave = await pauseProfileSave(page);
|
||||
try {
|
||||
|
||||
@@ -170,6 +170,30 @@ async function saveFromKeyboard(page: Page, expectedStatus: number): Promise<voi
|
||||
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> {
|
||||
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
||||
const page = await context.newPage();
|
||||
@@ -228,25 +252,44 @@ test.describe("candidate questionnaire", () => {
|
||||
expect(initial.version).toBe(0);
|
||||
|
||||
const specialization = page.getByLabel("Специализация", { exact: true });
|
||||
await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible();
|
||||
await specialization.selectOption("ds_ml");
|
||||
await expect(page.getByText("Проверка: в разработке")).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /проверку/i })).toHaveCount(0);
|
||||
// A step with a missing answer does not let the form move on.
|
||||
await nextStep(page, "Уровень и опыт");
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "Укажите свою оценку уровня." }),
|
||||
).toBeFocused();
|
||||
await expect(page.getByLabel("Моя оценка уровня")).toHaveAttribute("aria-invalid", "true");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await nextStep(page, "Формат работы");
|
||||
await page.getByLabel("Удаленно").check();
|
||||
await nextStep(page, "Проверка и сохранение");
|
||||
// Going back keeps what was entered.
|
||||
await page.getByRole("button", { name: "Назад", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused();
|
||||
await expect(page.getByLabel("Удаленно")).toBeChecked();
|
||||
await nextStep(page, "Проверка и сохранение");
|
||||
await saveFromKeyboard(page, 200);
|
||||
await expect(
|
||||
page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
|
||||
|
||||
await editStep(page, "направления", "Направления");
|
||||
await specialization.selectOption("backend");
|
||||
await nextStep(page, "Уровень и опыт");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("junior");
|
||||
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
|
||||
await page.getByLabel("Стек технологий").fill("Go");
|
||||
await page.getByRole("button", { name: "Добавить технологию" }).click();
|
||||
await nextStep(page, "Формат работы");
|
||||
await nextStep(page, "Проверка и сохранение");
|
||||
const backendSave = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
@@ -267,9 +310,13 @@ test.describe("candidate questionnaire", () => {
|
||||
]);
|
||||
await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
|
||||
await page.reload();
|
||||
// A reload restores the server record and opens the first step.
|
||||
await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("backend");
|
||||
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("junior");
|
||||
await expect(page.getByRole("checkbox", { name: "Go", exact: true })).toBeChecked();
|
||||
await expect(
|
||||
page.getByRole("checkbox", { name: "Go", exact: true, includeHidden: true }),
|
||||
).toBeChecked();
|
||||
await expect(page.getByLabel("Стек технологий")).toHaveValue("");
|
||||
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
|
||||
await page.screenshot({
|
||||
@@ -280,7 +327,10 @@ test.describe("candidate questionnaire", () => {
|
||||
const secondPage = await createSecondSession(browser, email);
|
||||
try {
|
||||
await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
|
||||
await nextStep(secondPage, "Уровень и опыт");
|
||||
await secondPage.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await nextStep(secondPage, "Формат работы");
|
||||
await nextStep(secondPage, "Проверка и сохранение");
|
||||
const concurrentSave = secondPage.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
@@ -289,8 +339,11 @@ test.describe("candidate questionnaire", () => {
|
||||
await secondPage.getByRole("button", { name: "Сохранить анкету" }).click();
|
||||
expect((await concurrentSave).status()).toBe(200);
|
||||
|
||||
await nextStep(page, "Уровень и опыт");
|
||||
await nextStep(page, "Формат работы");
|
||||
await page.getByLabel("Удаленно").uncheck();
|
||||
await page.getByLabel("В офисе").check();
|
||||
await nextStep(page, "Проверка и сохранение");
|
||||
const staleSave = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PUT" &&
|
||||
@@ -319,6 +372,7 @@ test.describe("candidate questionnaire", () => {
|
||||
await expect(secondPage.getByLabel("В офисе")).toBeChecked();
|
||||
await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked();
|
||||
|
||||
await editStep(page, "направления", "Направления");
|
||||
await checkResponsiveLayout(page);
|
||||
} finally {
|
||||
await secondPage.context().close();
|
||||
@@ -361,9 +415,7 @@ test.describe("candidate questionnaire", () => {
|
||||
);
|
||||
|
||||
await registerVerifiedCandidate(page);
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await page.getByLabel("Удаленно").check();
|
||||
await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
|
||||
await page.route("**/api/v1/me/questionnaire", async (route) => {
|
||||
if (route.request().method() === "PUT") {
|
||||
await fulfillProblem(route, 403, "forbidden");
|
||||
@@ -393,9 +445,7 @@ test.describe("candidate questionnaire", () => {
|
||||
);
|
||||
|
||||
await registerVerifiedCandidate(page);
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await page.getByLabel("Удаленно").check();
|
||||
await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
|
||||
let rejectSessionRefresh = false;
|
||||
await page.route("**/api/v1/identity/sessions/current", async (route) => {
|
||||
if (rejectSessionRefresh) {
|
||||
@@ -455,9 +505,7 @@ test.describe("candidate questionnaire", () => {
|
||||
}
|
||||
|
||||
await registerVerifiedCandidate(page);
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("senior");
|
||||
await page.getByLabel("Удаленно").check();
|
||||
await fillAnswers(page, { specialization: "ds_ml", grade: "senior", formats: ["Удаленно"] });
|
||||
|
||||
let releaseOldResponse: () => void = () => undefined;
|
||||
let markOldRequestHeld: () => void = () => undefined;
|
||||
@@ -517,7 +565,11 @@ test.describe("candidate questionnaire", () => {
|
||||
expect((await oldSaveResponse).status()).toBe(200);
|
||||
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
|
||||
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("");
|
||||
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toBeEnabled();
|
||||
// The new account's editor opens at its first step and is not saving:
|
||||
// the fields and the step action are enabled.
|
||||
await expect(page.getByText("Шаг 1 из 4", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("Специализация", { exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("button", { name: "Далее", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("button", { name: "Сохраняем анкету..." })).toHaveCount(0);
|
||||
} finally {
|
||||
cleanupStarted = true;
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
/* A card of the system; a demonstration run has a dashed boundary, so it is
|
||||
* never mistaken for a qualification result. */
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-canvas);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.root[data-express="true"] {
|
||||
border-inline-start-style: dashed;
|
||||
border-style: dashed;
|
||||
border-color: var(--color-border-hover);
|
||||
}
|
||||
|
||||
.root p {
|
||||
@@ -24,7 +26,8 @@
|
||||
}
|
||||
|
||||
.kind {
|
||||
color: var(--color-text-secondary);
|
||||
color: var(--color-accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
@@ -32,6 +35,7 @@
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-xl);
|
||||
line-height: var(--line-height-snug);
|
||||
overflow-wrap: anywhere;
|
||||
@@ -47,17 +51,12 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
.badge {
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.summary {
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 1.125rem;
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: var(--line-height-snug);
|
||||
}
|
||||
|
||||
.demo {
|
||||
@@ -87,6 +86,13 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* The decision facts as small readouts on nested surfaces. */
|
||||
.facts-main > div {
|
||||
padding: var(--space-3);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.block {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
@@ -119,6 +125,6 @@
|
||||
|
||||
@media (width < 42rem) {
|
||||
.root {
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useId, type ReactNode } from "react";
|
||||
import type { AssessmentResult } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import { ButtonLink, Mono } from "../../../shared/ui";
|
||||
import { ButtonLink, Mono, Tag } from "../../../shared/ui";
|
||||
import { describeAssessmentResult } from "../model/result-presentation";
|
||||
import styles from "./assessment-result-view.module.css";
|
||||
|
||||
@@ -54,9 +54,11 @@ export function AssessmentResultView({
|
||||
{view.title}
|
||||
</Heading>
|
||||
<p className={styles.badges}>
|
||||
{view.isExpress ? <span className={styles.badge}>Демонстрация</span> : null}
|
||||
{view.isExpress ? <Tag tone="accent">Демонстрация</Tag> : null}
|
||||
{!view.isExpress && view.isProvisional ? (
|
||||
<span className={styles.badge}>Предварительный результат</span>
|
||||
<Tag tone="neutral" dot>
|
||||
Предварительный результат
|
||||
</Tag>
|
||||
) : null}
|
||||
</p>
|
||||
</header>
|
||||
@@ -72,7 +74,7 @@ export function AssessmentResultView({
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<dl className={styles.facts}>
|
||||
<dl className={`${styles.facts} ${styles["facts-main"]}`}>
|
||||
{view.facts.map((fact) => (
|
||||
<div key={fact.label}>
|
||||
<dt>{fact.label}</dt>
|
||||
|
||||
+15
-8
@@ -1,16 +1,17 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-accent);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.fieldset {
|
||||
@@ -71,9 +72,9 @@
|
||||
min-height: 2.75rem;
|
||||
min-width: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -91,18 +92,24 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.option:has(input:checked) {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent-tint);
|
||||
}
|
||||
|
||||
.option:has(input:focus-visible) {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-danger);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
line-height: var(--line-height-body);
|
||||
background:
|
||||
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
|
||||
}
|
||||
|
||||
.alert:focus-visible {
|
||||
|
||||
@@ -4,49 +4,116 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* The answer sits directly in the item panel: no second frame around it. */
|
||||
.fields,
|
||||
.code-lines {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.legend,
|
||||
.code-lines legend {
|
||||
padding: 0 var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
float: left;
|
||||
width: 100%;
|
||||
margin-bottom: var(--space-1);
|
||||
padding: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.options,
|
||||
.practice {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* An option is a nested surface; a keycap gives its keyboard digit. The
|
||||
* chosen option gets the accent border and tint and its native mark. */
|
||||
.option,
|
||||
.code-line {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-3);
|
||||
align-items: flex-start;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color var(--duration-fast) var(--easing-standard),
|
||||
background-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.code-line {
|
||||
align-items: baseline;
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.option:hover,
|
||||
.code-line:hover {
|
||||
border-color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.option[data-checked],
|
||||
.code-line:has(input:checked) {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent-tint);
|
||||
}
|
||||
|
||||
.option:has(input:focus-visible) {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.option input,
|
||||
.code-line input {
|
||||
flex: 0 0 auto;
|
||||
width: 1.2rem;
|
||||
height: 1.2rem;
|
||||
margin-block-start: 0.15rem;
|
||||
accent-color: var(--color-action);
|
||||
margin-block-start: 0.2rem;
|
||||
}
|
||||
|
||||
.option-text {
|
||||
min-width: 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.keycap,
|
||||
.keys kbd {
|
||||
display: inline-grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
min-width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
padding: 0 var(--space-1);
|
||||
border: var(--line-thin) solid var(--color-border-hover);
|
||||
border-radius: var(--radius-xs);
|
||||
color: var(--color-text-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
background: var(--color-surface-elevated);
|
||||
}
|
||||
|
||||
.keys {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.keys kbd {
|
||||
display: inline-flex;
|
||||
min-width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
vertical-align: 0.05em;
|
||||
}
|
||||
|
||||
.field {
|
||||
@@ -61,15 +128,14 @@
|
||||
.field textarea {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
font-weight: var(--font-weight-regular);
|
||||
}
|
||||
|
||||
.field input {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
font-family: var(--font-mono);
|
||||
@@ -77,13 +143,6 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.field :is(input, select, textarea):focus-visible,
|
||||
.option input:focus-visible,
|
||||
.code-line input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
@@ -109,6 +168,7 @@
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.order-actions,
|
||||
@@ -119,16 +179,6 @@
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.code-lines {
|
||||
padding-inline: var(--space-3);
|
||||
}
|
||||
|
||||
.code-line {
|
||||
align-items: baseline;
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.line-number {
|
||||
flex: 0 0 2.5rem;
|
||||
color: var(--color-text-secondary);
|
||||
@@ -171,10 +221,6 @@
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.fields {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.order-item {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { useId, useState, type FormEvent, type KeyboardEvent } from "react";
|
||||
import type { AssessmentItem } from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import type { AnswerDraft } from "../model/answer-draft";
|
||||
@@ -42,8 +42,33 @@ export function AnswerForm({
|
||||
onSubmit(draft);
|
||||
}
|
||||
|
||||
// Keyboard first: digits 1-9 pick an option of a choice item, and Enter on
|
||||
// an option sends the answer like Enter in a text field. Text fields keep
|
||||
// their digits; modifier keys are left to the browser and assistive tools.
|
||||
function handleKeyDown(event: KeyboardEvent<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 (
|
||||
<form className={styles.form} onSubmit={submit}>
|
||||
<form className={styles.form} onSubmit={submit} onKeyDown={handleKeyDown}>
|
||||
<fieldset
|
||||
className={styles.fields}
|
||||
disabled={frozen}
|
||||
@@ -51,6 +76,12 @@ export function AnswerForm({
|
||||
>
|
||||
<legend className={styles.legend}>Ваш ответ</legend>
|
||||
<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>
|
||||
{errorMessage ? (
|
||||
<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 : [];
|
||||
return (
|
||||
<div className={styles.options}>
|
||||
{content.options.map((option) => {
|
||||
{content.options.map((option, index) => {
|
||||
const checked = selected.includes(option.id);
|
||||
return (
|
||||
<label className={styles.option} key={option.id}>
|
||||
<label className={styles.option} key={option.id} data-checked={checked || undefined}>
|
||||
<input
|
||||
type={content.multiple ? "checkbox" : "radio"}
|
||||
name={`answer-${item.id}`}
|
||||
@@ -104,7 +135,12 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
|
||||
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>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -24,16 +24,22 @@
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-4) var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.confirmation {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.record-title {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
font-weight: var(--font-weight-medium);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.organization-snapshot {
|
||||
@@ -57,33 +63,45 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.facts .mono {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-s);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.empty-purpose,
|
||||
.notice,
|
||||
.status-message,
|
||||
.action-error {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
.empty-purpose {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.status-message {
|
||||
padding: var(--space-3);
|
||||
/* Inline notes in the shape of the Notice primitive: a nested surface with
|
||||
* 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-radius: var(--radius-s);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.action-error {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-canvas);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.action-error button {
|
||||
margin-left: var(--space-2);
|
||||
.action-error:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.actions {
|
||||
@@ -128,6 +146,7 @@
|
||||
|
||||
.consent-text {
|
||||
max-height: 24rem;
|
||||
color: var(--color-text);
|
||||
min-width: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-3);
|
||||
|
||||
@@ -20,7 +20,15 @@ import type {
|
||||
ConsentSettingsRevokePurpose,
|
||||
} from "../../../shared/api/schemas";
|
||||
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 {
|
||||
consentPurposeDetails,
|
||||
consentSourceLabels,
|
||||
@@ -118,15 +126,19 @@ function ConsentRecordView({ record }: { record: ConsentRecord }) {
|
||||
) : null}
|
||||
<dl className={styles.facts}>
|
||||
<dt>Состояние</dt>
|
||||
<dd>{consentStateLabels[record.state]}</dd>
|
||||
<dd>
|
||||
<Tag tone={record.state === "active" ? "success" : "neutral"} dot>
|
||||
{consentStateLabels[record.state]}
|
||||
</Tag>
|
||||
</dd>
|
||||
<dt>Выдано</dt>
|
||||
<dd>{formatConsentDate(record.granted_at)}</dd>
|
||||
<dd className={styles.mono}>{formatConsentDate(record.granted_at)}</dd>
|
||||
<dt>Источник</dt>
|
||||
<dd>{consentSourceLabels[record.source]}</dd>
|
||||
{record.revoked_at ? (
|
||||
<>
|
||||
<dt>Отозвано</dt>
|
||||
<dd>{formatConsentDate(record.revoked_at)}</dd>
|
||||
<dd className={styles.mono}>{formatConsentDate(record.revoked_at)}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{record.revocation_source ? (
|
||||
@@ -556,9 +568,11 @@ export function ConsentManagement({
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
{statusMessage ? (
|
||||
<p className={styles["status-message"]} role="status" aria-live="polite">
|
||||
{statusMessage}
|
||||
</p>
|
||||
<div role="status" aria-live="polite">
|
||||
<Notice tone="success">
|
||||
<p className={styles["notice-text"]}>{statusMessage}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{actionError ? (
|
||||
<div
|
||||
@@ -568,19 +582,29 @@ export function ConsentManagement({
|
||||
aria-live="assertive"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{actionError}
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>{actionError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{history.isError && history.data ? (
|
||||
<div className={styles["action-error"]} role="alert">
|
||||
Не удалось обновить историю. Показаны последние загруженные данные.
|
||||
<Button
|
||||
variant="quiet"
|
||||
isBusy={history.isRefetching}
|
||||
onClick={() => void history.refetch()}
|
||||
<Notice
|
||||
tone="danger"
|
||||
action={
|
||||
<Button
|
||||
variant="quiet"
|
||||
isBusy={history.isRefetching}
|
||||
onClick={() => void history.refetch()}
|
||||
>
|
||||
Обновить список
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Обновить список
|
||||
</Button>
|
||||
<p className={styles["notice-text"]}>
|
||||
Не удалось обновить историю. Показаны последние загруженные данные.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{!canMutate ? (
|
||||
@@ -669,11 +693,13 @@ export function ConsentManagement({
|
||||
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
|
||||
)}
|
||||
{canRevoke && action && !isConfirmingPurpose ? (
|
||||
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
|
||||
{purpose === "c1"
|
||||
? "Отозвать C1 и запросить удаление"
|
||||
: `Отозвать C${purpose.slice(1)}`}
|
||||
</Button>
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
|
||||
{purpose === "c1"
|
||||
? "Отозвать C1 и запросить удаление"
|
||||
: `Отозвать C${purpose.slice(1)}`}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{canRevoke && action && isConfirmingPurpose ? (
|
||||
<ActionConfirmation
|
||||
|
||||
@@ -5,28 +5,35 @@
|
||||
|
||||
.intro {
|
||||
max-width: 68ch;
|
||||
margin: 0 0 1.25rem;
|
||||
color: var(--color-text-muted);
|
||||
line-height: 1.65;
|
||||
margin: 0 0 var(--space-5);
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
/* The form is one card of the system. */
|
||||
.form {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
gap: var(--space-5);
|
||||
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 {
|
||||
min-width: 0;
|
||||
padding: 1rem;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.context legend {
|
||||
padding: 0 0.35rem;
|
||||
color: var(--color-text-strong);
|
||||
font-weight: 650;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
@@ -50,7 +57,7 @@
|
||||
|
||||
.field label {
|
||||
color: var(--color-text-strong);
|
||||
font-weight: 650;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
@@ -59,14 +66,12 @@
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 12rem;
|
||||
padding: 0.85rem;
|
||||
resize: vertical;
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
line-height: 1.55;
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.field textarea:focus-visible,
|
||||
@@ -81,17 +86,20 @@
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.5;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
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 {
|
||||
padding: 0.85rem 1rem;
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-danger);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
background:
|
||||
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
|
||||
}
|
||||
|
||||
.error:focus {
|
||||
@@ -107,11 +115,11 @@
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.form {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.actions > * {
|
||||
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;
|
||||
gap: var(--space-5);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.root > section {
|
||||
min-width: 0;
|
||||
@media (width >= 64rem) {
|
||||
.layout {
|
||||
grid-template-columns: minmax(0, 1fr) 18rem;
|
||||
}
|
||||
|
||||
.aside {
|
||||
position: sticky;
|
||||
top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4));
|
||||
}
|
||||
}
|
||||
|
||||
.server-step,
|
||||
.form-error,
|
||||
.conflict,
|
||||
.continuation {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
overflow-wrap: anywhere;
|
||||
.panel {
|
||||
gap: var(--space-5);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.server-step {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.form-error,
|
||||
.conflict {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.form-error {
|
||||
.server-step strong {
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.conflict h2 {
|
||||
margin: 0 0 var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
.notice-title {
|
||||
margin-bottom: var(--space-1);
|
||||
color: var(--color-danger);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.conflict p,
|
||||
.continuation p {
|
||||
margin: 0 0 var(--space-3);
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
|
||||
.continuation {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: var(--space-5) 0 0;
|
||||
.aside-note {
|
||||
padding-top: var(--space-3);
|
||||
border-top: var(--line-thin) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.continuation p {
|
||||
flex: 1 1 16rem;
|
||||
.legend {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
@@ -25,10 +25,13 @@ import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
Card,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
Notice,
|
||||
Skeleton,
|
||||
TrustLevel,
|
||||
} from "../../../shared/ui";
|
||||
import { ProfileForm } from "./profile-form";
|
||||
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() {
|
||||
const queryClient = useQueryClient();
|
||||
const profile = useGetMyProfile({
|
||||
@@ -92,7 +104,7 @@ export function EditProfile() {
|
||||
}, [profileAccessError, queryClient, sessionAccessError]);
|
||||
|
||||
if (profile.isPending && !profile.data) {
|
||||
return <LoadingState label="Загружаем профиль кандидата..." />;
|
||||
return <EditorLoading label="Загружаем профиль кандидата..." />;
|
||||
}
|
||||
if (profileAccessError) {
|
||||
return <ProfileAccessDenied error={profileAccessError} />;
|
||||
@@ -130,7 +142,7 @@ export function EditProfile() {
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <LoadingState label="Проверяем текущий вход..." />;
|
||||
return <EditorLoading label="Проверяем текущий вход..." />;
|
||||
}
|
||||
if (session.data.account.scenario !== "candidate") {
|
||||
return (
|
||||
@@ -294,46 +306,62 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
|
||||
const continuationLabel = savedStep ? stepLabel(savedStep) : null;
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section
|
||||
title="Личные сведения"
|
||||
description="Заполните только то, что готовы указать. Профиль сохраняется на сервере и не требует резюме или внешнего аккаунта."
|
||||
>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
) : null}
|
||||
{conflict ? (
|
||||
<div className={styles.conflict} role="alert" aria-labelledby="profile-conflict-title">
|
||||
<h2 id="profile-conflict-title">Профиль обновлен в другом окне</h2>
|
||||
<p>
|
||||
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не
|
||||
выполняются. При замене черновика данные из этой формы будут удалены.
|
||||
<div className={styles.layout}>
|
||||
<Card as="section" tone="panel" labelledBy="profile-title" className={styles.panel}>
|
||||
<header className={styles["panel-header"]}>
|
||||
<h2 id="profile-title" className={styles["panel-title"]}>
|
||||
Личные сведения
|
||||
</h2>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
{latestLoadError ? (
|
||||
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
|
||||
) : null}
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={profileQuery.isRefetching}
|
||||
aria-describedby="profile-conflict-title"
|
||||
onClick={() => void loadCurrentVersion()}
|
||||
) : null}
|
||||
</header>
|
||||
{conflict ? (
|
||||
<div role="alert" aria-labelledby="profile-conflict-title">
|
||||
<Notice
|
||||
tone="danger"
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={profileQuery.isRefetching}
|
||||
aria-describedby="profile-conflict-title"
|
||||
onClick={() => void loadCurrentVersion()}
|
||||
>
|
||||
{profileQuery.isRefetching
|
||||
? "Загружаем текущую версию..."
|
||||
: "Заменить черновик актуальной версией"}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{profileQuery.isRefetching
|
||||
? "Загружаем текущую версию..."
|
||||
: "Заменить черновик актуальной версией"}
|
||||
</Button>
|
||||
<h3 id="profile-conflict-title" className={styles["notice-title"]}>
|
||||
Профиль обновлен в другом окне
|
||||
</h3>
|
||||
<p>
|
||||
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не
|
||||
выполняются. При замене черновика данные из этой формы будут удалены.
|
||||
</p>
|
||||
{latestLoadError ? (
|
||||
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
|
||||
) : null}
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{forbidden ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
Профиль больше недоступен. Данные формы останутся до ухода со страницы.
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>
|
||||
Профиль больше недоступен. Данные формы останутся до ухода со страницы.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
{formError}
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>{formError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
<ProfileForm
|
||||
@@ -345,18 +373,50 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
|
||||
onSubmit={() => void handleSubmit()}
|
||||
/>
|
||||
{savedStep && continuation ? (
|
||||
<div className={styles.continuation} role="status">
|
||||
<p>Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.</p>
|
||||
{continuation !== paths.candidate.profile ? (
|
||||
<ButtonLink to={continuation} variant="secondary">
|
||||
Открыть сохраненный шаг
|
||||
</ButtonLink>
|
||||
) : (
|
||||
<p>Серверный шаг остается «Профиль».</p>
|
||||
)}
|
||||
<div role="status">
|
||||
<Notice
|
||||
tone="success"
|
||||
action={
|
||||
continuation !== paths.candidate.profile ? (
|
||||
<ButtonLink to={continuation} variant="secondary">
|
||||
Открыть сохраненный шаг
|
||||
</ButtonLink>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<p className={styles["notice-text"]}>
|
||||
Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.
|
||||
</p>
|
||||
{continuation === paths.candidate.profile ? (
|
||||
<p>Серверный шаг остается «Профиль».</p>
|
||||
) : null}
|
||||
</Notice>
|
||||
</div>
|
||||
) : 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>
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.editor-fields {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
@@ -24,53 +24,25 @@
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.issue-summary h2,
|
||||
.categories h2 {
|
||||
.issue-list {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul,
|
||||
.categories ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.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);
|
||||
.issue-step {
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@@ -81,17 +53,17 @@
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.field input[type="number"],
|
||||
.field input[type="month"],
|
||||
.field input[type="tel"] {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
@@ -101,28 +73,9 @@
|
||||
.field input[aria-invalid="true"],
|
||||
.field select[aria-invalid="true"],
|
||||
.field textarea[aria-invalid="true"] {
|
||||
border-width: var(--line-strong);
|
||||
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,
|
||||
.error,
|
||||
.claim-status {
|
||||
@@ -130,26 +83,37 @@
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
color: var(--color-danger);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.claim-status {
|
||||
justify-self: start;
|
||||
padding: 0 var(--space-2);
|
||||
border-radius: var(--radius-pill);
|
||||
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 {
|
||||
min-width: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface-tint);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.suggestion summary {
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
@@ -161,22 +125,24 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* A repeated row (a role, a workplace): a nested surface inside the panel. */
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.item-header,
|
||||
.item-actions,
|
||||
.list-row,
|
||||
.actions {
|
||||
.add-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
gap: var(--space-2) var(--space-3);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -185,16 +151,17 @@
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.item-header h3,
|
||||
.list h3,
|
||||
.overlap-list h3 {
|
||||
margin: 0;
|
||||
.item-header h4,
|
||||
.list h4,
|
||||
.overlap-list h4,
|
||||
.categories h4 {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -206,6 +173,11 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.list + .list {
|
||||
padding-top: var(--space-4);
|
||||
border-top: var(--line-thin) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.list-row {
|
||||
align-items: flex-end;
|
||||
}
|
||||
@@ -220,11 +192,20 @@
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.overlap:has(input:checked) {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent-tint);
|
||||
}
|
||||
|
||||
.overlap input {
|
||||
margin-top: 0.2em;
|
||||
}
|
||||
|
||||
.overlap label,
|
||||
.overlap p {
|
||||
margin: 0;
|
||||
@@ -237,40 +218,107 @@
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border: var(--line-thin) dashed var(--color-border-hover);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.actions {
|
||||
justify-content: space-between;
|
||||
padding-top: var(--space-2);
|
||||
.categories p {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.actions > :first-child {
|
||||
flex: 1 1 12rem;
|
||||
.category-list,
|
||||
.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-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.actions {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
width: 100%;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.review-facts > div {
|
||||
grid-template-columns: 9rem minmax(0, 1fr);
|
||||
align-items: baseline;
|
||||
}
|
||||
}
|
||||
@@ -113,4 +113,27 @@ describe("ProfileForm", () => {
|
||||
);
|
||||
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("К проверке и сохранению");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
toQuestionnaireDraft,
|
||||
toggleQuestionnaireWorkFormat,
|
||||
questionnaireStepOfField,
|
||||
} from "./questionnaire-form";
|
||||
|
||||
const catalog: SpecializationCatalog = {
|
||||
@@ -272,3 +273,17 @@ describe("questionnaire form model", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("questionnaire steps", () => {
|
||||
it("opens the step that owns a client or server issue", () => {
|
||||
expect(questionnaireStepOfField("specializations")).toBe("specializations");
|
||||
expect(questionnaireStepOfField("specializations.1.specialization")).toBe("specializations");
|
||||
expect(questionnaireStepOfField("specializations.0.selfAssessedGrade")).toBe("details");
|
||||
expect(questionnaireStepOfField("specializations.0.stack.3")).toBe("details");
|
||||
expect(questionnaireStepOfField("specializations.1")).toBe("details");
|
||||
expect(questionnaireStepOfField("workFormats")).toBe("work");
|
||||
expect(questionnaireStepOfField("work_context.work_formats")).toBe("work");
|
||||
expect(questionnaireStepOfField("form")).toBe("review");
|
||||
expect(questionnaireStepOfField("expected_version")).toBe("review");
|
||||
});
|
||||
});
|
||||
@@ -359,3 +359,18 @@ export function mapQuestionnaireServerErrors(
|
||||
message: "Сервер не принял это значение. Проверьте выбор и повторите сохранение.",
|
||||
}));
|
||||
}
|
||||
|
||||
/** Steps of the questionnaire form, in order. */
|
||||
export type QuestionnaireStepId = "specializations" | "details" | "work" | "review";
|
||||
|
||||
/**
|
||||
* The step that owns a form field, so a client or server issue opens the step
|
||||
* where it can be fixed. Unknown fields and general issues belong to review.
|
||||
*/
|
||||
export function questionnaireStepOfField(field: string): QuestionnaireStepId {
|
||||
if (field === "specializations") return "specializations";
|
||||
const row = /^specializations\.\d+(?:\.(\w+))?/.exec(field);
|
||||
if (row) return row[1] === "specialization" ? "specializations" : "details";
|
||||
if (field === "workFormats" || field.startsWith("work_context")) return "work";
|
||||
return "review";
|
||||
}
|
||||
@@ -1,72 +1,90 @@
|
||||
.root {
|
||||
/* Phone first: one column; from 1024px the form and a side note. */
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.root > section {
|
||||
min-width: 0;
|
||||
@media (width >= 64rem) {
|
||||
.layout {
|
||||
grid-template-columns: minmax(0, 1fr) 18rem;
|
||||
}
|
||||
|
||||
.aside {
|
||||
position: sticky;
|
||||
top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4));
|
||||
}
|
||||
}
|
||||
|
||||
.server-step,
|
||||
.warning,
|
||||
.form-error,
|
||||
.conflict,
|
||||
.continuation {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
overflow-wrap: anywhere;
|
||||
.panel {
|
||||
gap: var(--space-5);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.server-step {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.warning,
|
||||
.form-error,
|
||||
.conflict {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
.server-step strong {
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.warning,
|
||||
.conflict {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
.notice-title {
|
||||
margin-bottom: var(--space-1);
|
||||
color: var(--color-danger);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.warning p,
|
||||
.conflict p,
|
||||
.continuation p {
|
||||
margin: 0;
|
||||
line-height: var(--line-height-body);
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.conflict h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.conflict-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
.aside {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.continuation {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: var(--space-5) 0 0;
|
||||
.aside-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.continuation p {
|
||||
flex: 1 1 16rem;
|
||||
.aside-text,
|
||||
.aside-note {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.aside-note {
|
||||
padding-top: var(--space-3);
|
||||
border-top: var(--line-thin) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.legend {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
@@ -29,10 +29,14 @@ import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
Card,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
Mono,
|
||||
Notice,
|
||||
Skeleton,
|
||||
TrustLevel,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
buildCandidateQuestionnaireUpdate,
|
||||
@@ -84,6 +88,15 @@ function actorMatches(queryClient: ReturnType<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() {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession();
|
||||
@@ -161,7 +174,7 @@ export function FillQuestionnaire() {
|
||||
);
|
||||
}
|
||||
if (session.isPending || !session.data) {
|
||||
return <LoadingState label="Проверяем вход и загружаем анкету..." />;
|
||||
return <EditorLoading label="Проверяем вход и загружаем анкету..." />;
|
||||
}
|
||||
if (session.data.account.scenario !== "candidate") {
|
||||
return (
|
||||
@@ -181,7 +194,7 @@ export function FillQuestionnaire() {
|
||||
);
|
||||
}
|
||||
if (questionnaire.isPending && !questionnaire.data) {
|
||||
return <LoadingState label="Загружаем сохраненные ответы..." />;
|
||||
return <EditorLoading label="Загружаем сохраненные ответы..." />;
|
||||
}
|
||||
if (questionnaireAccessError) {
|
||||
return (
|
||||
@@ -204,7 +217,7 @@ export function FillQuestionnaire() {
|
||||
);
|
||||
}
|
||||
if (catalog.isPending && !catalog.data) {
|
||||
return <LoadingState label="Загружаем каталог специализаций..." />;
|
||||
return <EditorLoading label="Загружаем каталог специализаций..." />;
|
||||
}
|
||||
if (!catalog.data) {
|
||||
return (
|
||||
@@ -444,76 +457,99 @@ function QuestionnaireEditor({
|
||||
savedStep === "candidate_assessment" ? paths.candidate.assessment : null;
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section
|
||||
title="Ответы кандидата"
|
||||
description="Выберите специализации, укажите самооценку и подходящие форматы работы. Эти ответы не подтверждают грейд и не требуют ФСП."
|
||||
>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
) : null}
|
||||
<div className={styles.layout}>
|
||||
<Card as="section" tone="panel" labelledBy="questionnaire-title" className={styles.panel}>
|
||||
<header className={styles["panel-header"]}>
|
||||
<h2 id="questionnaire-title" className={styles["panel-title"]}>
|
||||
Ответы кандидата
|
||||
</h2>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
) : null}
|
||||
</header>
|
||||
{catalogUnavailable ? (
|
||||
<div className={styles.warning} role="alert">
|
||||
<p>Не удалось обновить каталог. Показаны последние загруженные сведения.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={catalogQuery.isRefetching}
|
||||
onClick={() => void catalogQuery.refetch()}
|
||||
<div role="alert">
|
||||
<Notice
|
||||
tone="danger"
|
||||
title="Не удалось обновить каталог"
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={catalogQuery.isRefetching}
|
||||
onClick={() => void catalogQuery.refetch()}
|
||||
>
|
||||
{catalogQuery.isRefetching
|
||||
? "Обновляем каталог..."
|
||||
: "Повторить загрузку каталога"}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{catalogQuery.isRefetching ? "Обновляем каталог..." : "Повторить загрузку каталога"}
|
||||
</Button>
|
||||
<p>Показаны последние загруженные сведения.</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
{formError}
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>{formError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{conflict ? (
|
||||
<div
|
||||
className={styles.conflict}
|
||||
role="alert"
|
||||
aria-labelledby="questionnaire-conflict-title"
|
||||
>
|
||||
<h2 id="questionnaire-conflict-title">Анкета изменилась в другом окне</h2>
|
||||
<p>
|
||||
Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие ответы
|
||||
оставить. Перезапись отправит весь черновик поверх актуальной анкеты.
|
||||
</p>
|
||||
{latestLoadError ? (
|
||||
<p>Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.</p>
|
||||
) : null}
|
||||
{latest ? <p>Последняя прочитанная серверная версия: {latest.version}.</p> : null}
|
||||
<div className={styles["conflict-actions"]}>
|
||||
<Button
|
||||
variant="primary"
|
||||
isBusy={saveState === "saving" || questionnaire.isRefetching}
|
||||
disabled={!latest || latestLoadError}
|
||||
onClick={() => void submit(latest?.version ?? draft.expectedVersion)}
|
||||
>
|
||||
Записать этот черновик поверх актуальной анкеты
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={questionnaire.isRefetching}
|
||||
onClick={() => void refreshLatest()}
|
||||
>
|
||||
{questionnaire.isRefetching ? "Загружаем ответы..." : "Загрузить актуальные ответы"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={!latest || questionnaire.isRefetching || saveState === "saving"}
|
||||
onClick={loadLatestAndDiscardDraft}
|
||||
aria-describedby="questionnaire-conflict-discard-hint"
|
||||
>
|
||||
Заменить черновик актуальными ответами
|
||||
</Button>
|
||||
</div>
|
||||
<p id="questionnaire-conflict-discard-hint">
|
||||
Замена удалит введенные в этой форме изменения.
|
||||
</p>
|
||||
<div role="alert" aria-labelledby="questionnaire-conflict-title">
|
||||
<Notice
|
||||
tone="danger"
|
||||
action={
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
isBusy={saveState === "saving" || questionnaire.isRefetching}
|
||||
disabled={!latest || latestLoadError}
|
||||
onClick={() => void submit(latest?.version ?? draft.expectedVersion)}
|
||||
>
|
||||
Записать этот черновик поверх актуальной анкеты
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={questionnaire.isRefetching}
|
||||
onClick={() => void refreshLatest()}
|
||||
>
|
||||
{questionnaire.isRefetching
|
||||
? "Загружаем ответы..."
|
||||
: "Загрузить актуальные ответы"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={!latest || questionnaire.isRefetching || saveState === "saving"}
|
||||
onClick={loadLatestAndDiscardDraft}
|
||||
aria-describedby="questionnaire-conflict-discard-hint"
|
||||
>
|
||||
Заменить черновик актуальными ответами
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<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>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
<QuestionnaireForm
|
||||
@@ -529,19 +565,48 @@ function QuestionnaireEditor({
|
||||
onSubmit={() => void submit()}
|
||||
/>
|
||||
{saveState === "saved" ? (
|
||||
<div className={styles.continuation} role="status">
|
||||
<p>
|
||||
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "}
|
||||
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}.
|
||||
</p>
|
||||
{onboardingDestination ? (
|
||||
<ButtonLink to={onboardingDestination} variant="secondary">
|
||||
Перейти к следующему шагу
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
<div role="status">
|
||||
<Notice
|
||||
tone="success"
|
||||
action={
|
||||
onboardingDestination ? (
|
||||
<ButtonLink to={onboardingDestination} variant="secondary">
|
||||
Перейти к следующему шагу
|
||||
</ButtonLink>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<p className={styles["notice-text"]}>
|
||||
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "}
|
||||
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : 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>
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.editor-fields {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
@@ -24,53 +24,85 @@
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.issue-summary:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.issue-summary h2 {
|
||||
.issue-list {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group,
|
||||
.specialization,
|
||||
.option-group {
|
||||
.issue-step {
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
/* A row of the form: a nested surface with a mono index in the legend. */
|
||||
.row {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.group legend,
|
||||
.specialization legend,
|
||||
.option-group legend {
|
||||
max-width: 100%;
|
||||
padding-inline: var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
/* A legend cannot be a grid item; floating it puts it inside the row. */
|
||||
.row-legend {
|
||||
display: flex;
|
||||
float: left;
|
||||
gap: var(--space-2);
|
||||
align-items: baseline;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-medium);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.availability p {
|
||||
.row-legend > span:first-child {
|
||||
color: var(--color-accent);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.add-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.option-group {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.option-group legend {
|
||||
float: left;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
@@ -86,68 +118,68 @@
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.number {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
color: var(--color-danger);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.availability {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.availability-title {
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.check-list {
|
||||
/* Checkbox choices as capsules: the whole capsule is the click target. */
|
||||
.choice-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3) var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.check-item {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
align-items: flex-start;
|
||||
min-width: 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.check-item input {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
margin: 0.125rem 0 0;
|
||||
flex: 0 0 auto;
|
||||
.choice {
|
||||
display: inline-flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
min-height: var(--control-height);
|
||||
padding: var(--space-2) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-snug);
|
||||
overflow-wrap: anywhere;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color var(--duration-fast) var(--easing-standard),
|
||||
background-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.choice:hover {
|
||||
border-color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.choice:has(input:checked) {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent-tint);
|
||||
}
|
||||
|
||||
.choice:has(input:disabled) {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.month-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -164,20 +196,13 @@
|
||||
flex: 1 1 15rem;
|
||||
}
|
||||
|
||||
.field input:focus-visible,
|
||||
.field select:focus-visible,
|
||||
.check-item input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field input[aria-invalid="true"],
|
||||
.field select[aria-invalid="true"] {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.tag-list {
|
||||
.tag-list,
|
||||
.review-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
@@ -186,54 +211,94 @@
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.tag {
|
||||
.review-tags li {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
max-width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
.tag-remove {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
margin-inline: var(--space-1) calc(-1 * var(--space-2));
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.actions > .hint {
|
||||
flex: 1 1 18rem;
|
||||
.tag-remove:hover {
|
||||
color: var(--color-text-strong);
|
||||
background: var(--color-surface-tint-hover);
|
||||
}
|
||||
|
||||
.form-error {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-canvas);
|
||||
color: var(--color-danger);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.review {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.review-list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.review-row {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.review-name {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.review-facts {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.review-facts > div {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.review-facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.review-facts dd {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.month-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.group,
|
||||
.specialization,
|
||||
.option-group {
|
||||
padding: var(--space-3);
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.actions {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
.review-facts > div {
|
||||
grid-template-columns: 9rem minmax(0, 1fr);
|
||||
align-items: baseline;
|
||||
}
|
||||
}
|
||||
@@ -112,4 +112,17 @@ describe("questionnaire form", () => {
|
||||
expect(markup).toContain('value="senior" selected=""');
|
||||
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 {
|
||||
addQuestionnaireSpecialization,
|
||||
addQuestionnaireStackTag,
|
||||
buildCandidateQuestionnaireUpdate,
|
||||
changeQuestionnaireSpecialization,
|
||||
patchQuestionnaireSpecialization,
|
||||
questionnaireStepOfField,
|
||||
removeQuestionnaireSpecialization,
|
||||
removeQuestionnaireStackTag,
|
||||
toggleQuestionnaireWorkFormat,
|
||||
type QuestionnaireDraft,
|
||||
type QuestionnaireFormIssue,
|
||||
type QuestionnaireSpecializationDraft,
|
||||
type QuestionnaireStepId,
|
||||
} from "../model/questionnaire-form";
|
||||
import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization";
|
||||
import type {
|
||||
@@ -18,7 +21,15 @@ import type {
|
||||
TaskLanguage,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import { Button, Mono, Notice, Tag, TrustLevel } from "../../../shared/ui";
|
||||
import {
|
||||
FormProgress,
|
||||
FormStepFooter,
|
||||
FormStepPanel,
|
||||
ReviewBlock,
|
||||
type FormStep,
|
||||
} from "./form-steps";
|
||||
import { useFormSteps } from "./use-form-steps";
|
||||
import styles from "./questionnaire-form.module.css";
|
||||
|
||||
const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [
|
||||
@@ -32,6 +43,13 @@ const taskLanguageLabels: Record<TaskLanguage, string> = {
|
||||
go: "Go",
|
||||
};
|
||||
|
||||
const questionnaireSteps: readonly FormStep<QuestionnaireStepId>[] = [
|
||||
{ id: "specializations", label: "Направления" },
|
||||
{ id: "details", label: "Уровень и опыт" },
|
||||
{ id: "work", label: "Формат работы" },
|
||||
{ id: "review", label: "Проверка и сохранение" },
|
||||
];
|
||||
|
||||
type QuestionnaireFormProps = {
|
||||
draft: QuestionnaireDraft;
|
||||
catalog: SpecializationCatalog;
|
||||
@@ -89,6 +107,140 @@ function Field({
|
||||
);
|
||||
}
|
||||
|
||||
function specializationTitle(
|
||||
catalog: SpecializationCatalog,
|
||||
item: QuestionnaireSpecializationDraft,
|
||||
) {
|
||||
if (!item.specialization) return "Специализация не выбрана";
|
||||
return findSpecializationOption(catalog, item.specialization)?.title ?? item.specialization;
|
||||
}
|
||||
|
||||
type RowProps = {
|
||||
draft: QuestionnaireDraft;
|
||||
item: QuestionnaireSpecializationDraft;
|
||||
index: number;
|
||||
catalog: SpecializationCatalog;
|
||||
issues: readonly QuestionnaireFormIssue[];
|
||||
disabled: boolean;
|
||||
prefix: string;
|
||||
onDraftChange: (draft: QuestionnaireDraft) => void;
|
||||
onIssue: (issue: QuestionnaireFormIssue) => void;
|
||||
};
|
||||
|
||||
/** Step 1: the specialization of one row and what the catalog offers for it. */
|
||||
function SpecializationChoice({
|
||||
draft,
|
||||
item,
|
||||
index,
|
||||
catalog,
|
||||
issues,
|
||||
disabled,
|
||||
prefix,
|
||||
onDraftChange,
|
||||
}: RowProps) {
|
||||
const cardId = `${prefix}-specialization-${index}`;
|
||||
const selectionId = `${cardId}-selection`;
|
||||
const selectedOption = findSpecializationOption(catalog, item.specialization);
|
||||
const selectedElsewhere = new Set(
|
||||
draft.specializations
|
||||
.filter((candidate) => candidate.id !== item.id)
|
||||
.map((candidate) => candidate.specialization)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const specialtyField = `specializations.${index}.specialization`;
|
||||
const error = issueFor(issues, specialtyField);
|
||||
|
||||
return (
|
||||
<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({
|
||||
draft,
|
||||
item,
|
||||
@@ -123,7 +275,8 @@ function StackTags({
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={inputId}>Стек технологий</label>
|
||||
<p className={styles.hint} id={helpId}>
|
||||
Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки.
|
||||
Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки. Enter
|
||||
добавляет технологию.
|
||||
</p>
|
||||
<div className={styles["stack-input"]}>
|
||||
<input
|
||||
@@ -154,16 +307,19 @@ function StackTags({
|
||||
{item.stack.length > 0 ? (
|
||||
<ul className={styles["tag-list"]} aria-label={`Технологии по специализации ${index + 1}`}>
|
||||
{item.stack.map((tag) => (
|
||||
<li className={styles.tag} key={`${tag}-${index}`}>
|
||||
<span>{tag}</span>
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={disabled}
|
||||
aria-label={`Удалить технологию ${tag}`}
|
||||
onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
<li key={`${tag}-${index}`}>
|
||||
<Tag tone="stack">
|
||||
{tag}
|
||||
<button
|
||||
type="button"
|
||||
className={styles["tag-remove"]}
|
||||
disabled={disabled}
|
||||
aria-label={`Удалить технологию ${tag}`}
|
||||
onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))}
|
||||
>
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</Tag>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -173,7 +329,8 @@ function StackTags({
|
||||
);
|
||||
}
|
||||
|
||||
function SpecializationCard({
|
||||
/** Step 2: self-assessment, task languages, stack, and experience of one row. */
|
||||
function SpecializationDetails({
|
||||
draft,
|
||||
item,
|
||||
index,
|
||||
@@ -183,34 +340,18 @@ function SpecializationCard({
|
||||
prefix,
|
||||
onDraftChange,
|
||||
onIssue,
|
||||
}: {
|
||||
draft: QuestionnaireDraft;
|
||||
item: QuestionnaireSpecializationDraft;
|
||||
index: number;
|
||||
catalog: SpecializationCatalog;
|
||||
issues: readonly QuestionnaireFormIssue[];
|
||||
disabled: boolean;
|
||||
prefix: string;
|
||||
onDraftChange: (draft: QuestionnaireDraft) => void;
|
||||
onIssue: (issue: QuestionnaireFormIssue) => void;
|
||||
}) {
|
||||
}: RowProps) {
|
||||
const cardId = `${prefix}-specialization-${index}`;
|
||||
const selectionId = `${cardId}-selection`;
|
||||
const gradeId = `${cardId}-grade`;
|
||||
const experienceToggleId = `${cardId}-experience-enabled`;
|
||||
const commercialId = `${cardId}-commercial-months`;
|
||||
const academicId = `${cardId}-academic-months`;
|
||||
const taskLanguagesId = `${cardId}-task-languages`;
|
||||
const selectedOption = findSpecializationOption(catalog, item.specialization);
|
||||
const selectedElsewhere = new Set(
|
||||
draft.specializations
|
||||
.filter((candidate) => candidate.id !== item.id)
|
||||
.map((candidate) => candidate.specialization)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const specialtyField = `specializations.${index}.specialization`;
|
||||
const gradeField = `specializations.${index}.selfAssessedGrade`;
|
||||
const languagesField = `specializations.${index}.taskLanguages`;
|
||||
const commercialField = `specializations.${index}.commercialMonths`;
|
||||
const academicField = `specializations.${index}.academicMonths`;
|
||||
const stackError = issues.find((issue) =>
|
||||
issue.field.startsWith(`specializations.${index}.stack`),
|
||||
)?.message;
|
||||
@@ -228,83 +369,14 @@ function SpecializationCard({
|
||||
}
|
||||
|
||||
return (
|
||||
<fieldset className={styles.specialization}>
|
||||
<legend>Специализация {index + 1}</legend>
|
||||
<fieldset className={styles.row}>
|
||||
<legend className={styles["row-legend"]}>
|
||||
<Mono>{String(index + 1).padStart(2, "0")}</Mono> {specializationTitle(catalog, item)}
|
||||
</legend>
|
||||
<p className={styles.hint}>
|
||||
Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет
|
||||
только результат проверки.
|
||||
</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
|
||||
id={gradeId}
|
||||
label="Моя оценка уровня"
|
||||
@@ -341,14 +413,14 @@ function SpecializationCard({
|
||||
Этот выбор относится к языку заданий проверки, а не к вашему стеку технологий.
|
||||
</p>
|
||||
{!selectedOption ? (
|
||||
<p>Сначала выберите специализацию.</p>
|
||||
<p className={styles.hint}>Сначала выберите специализацию.</p>
|
||||
) : shownLanguages.length > 0 ? (
|
||||
<div className={styles["check-list"]}>
|
||||
<div className={styles["choice-list"]}>
|
||||
{shownLanguages.map((language) => {
|
||||
const isOld = oldLanguages.includes(language);
|
||||
const languageId = `${taskLanguagesId}-${language}`;
|
||||
return (
|
||||
<label className={styles["check-item"]} htmlFor={languageId} key={language}>
|
||||
<label className={styles.choice} htmlFor={languageId} key={language}>
|
||||
<input
|
||||
id={languageId}
|
||||
type="checkbox"
|
||||
@@ -370,7 +442,9 @@ function SpecializationCard({
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p>Для этой специализации сейчас не предлагаются варианты языка заданий.</p>
|
||||
<p className={styles.hint}>
|
||||
Для этой специализации сейчас не предлагаются варианты языка заданий.
|
||||
</p>
|
||||
)}
|
||||
<ErrorText id={`${taskLanguagesId}-error`}>{issueFor(issues, languagesField)}</ErrorText>
|
||||
</fieldset>
|
||||
@@ -388,7 +462,7 @@ function SpecializationCard({
|
||||
|
||||
<fieldset className={styles["option-group"]}>
|
||||
<legend>Опыт в этой специализации</legend>
|
||||
<label className={styles["check-item"]} htmlFor={experienceToggleId}>
|
||||
<label className={styles.choice} htmlFor={experienceToggleId}>
|
||||
<input
|
||||
id={experienceToggleId}
|
||||
type="checkbox"
|
||||
@@ -410,10 +484,11 @@ function SpecializationCard({
|
||||
id={commercialId}
|
||||
label="Коммерческий опыт, месяцев"
|
||||
hint="Допустимое значение: от 0 до 600."
|
||||
error={issueFor(issues, `specializations.${index}.commercialMonths`)}
|
||||
error={issueFor(issues, commercialField)}
|
||||
>
|
||||
<input
|
||||
id={commercialId}
|
||||
className={styles.number}
|
||||
type="number"
|
||||
min={0}
|
||||
max={600}
|
||||
@@ -421,13 +496,11 @@ function SpecializationCard({
|
||||
inputMode="numeric"
|
||||
value={item.commercialMonths}
|
||||
disabled={!selectedOption}
|
||||
aria-invalid={Boolean(
|
||||
issueFor(issues, `specializations.${index}.commercialMonths`),
|
||||
)}
|
||||
aria-invalid={Boolean(issueFor(issues, commercialField))}
|
||||
aria-describedby={describeIds(
|
||||
commercialId,
|
||||
true,
|
||||
Boolean(issueFor(issues, `specializations.${index}.commercialMonths`)),
|
||||
Boolean(issueFor(issues, commercialField)),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
@@ -442,10 +515,11 @@ function SpecializationCard({
|
||||
id={academicId}
|
||||
label="Учебный и академический опыт, месяцев"
|
||||
hint="Допустимое значение: от 0 до 600."
|
||||
error={issueFor(issues, `specializations.${index}.academicMonths`)}
|
||||
error={issueFor(issues, academicField)}
|
||||
>
|
||||
<input
|
||||
id={academicId}
|
||||
className={styles.number}
|
||||
type="number"
|
||||
min={0}
|
||||
max={600}
|
||||
@@ -453,11 +527,11 @@ function SpecializationCard({
|
||||
inputMode="numeric"
|
||||
value={item.academicMonths}
|
||||
disabled={!selectedOption}
|
||||
aria-invalid={Boolean(issueFor(issues, `specializations.${index}.academicMonths`))}
|
||||
aria-invalid={Boolean(issueFor(issues, academicField))}
|
||||
aria-describedby={describeIds(
|
||||
academicId,
|
||||
true,
|
||||
Boolean(issueFor(issues, `specializations.${index}.academicMonths`)),
|
||||
Boolean(issueFor(issues, academicField)),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
@@ -473,21 +547,138 @@ function SpecializationCard({
|
||||
<p className={styles.hint}>Можно оставить без указания.</p>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{draft.specializations.length > 1 ? (
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={disabled}
|
||||
onClick={() => onDraftChange(removeQuestionnaireSpecialization(draft, item.id))}
|
||||
aria-label={`Удалить специализацию ${index + 1}`}
|
||||
>
|
||||
Удалить специализацию
|
||||
</Button>
|
||||
) : null}
|
||||
</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({
|
||||
draft,
|
||||
catalog,
|
||||
@@ -503,23 +694,73 @@ export function QuestionnaireForm({
|
||||
const prefix = `questionnaire-${useId().replaceAll(":", "")}`;
|
||||
const rowSequence = useRef(0);
|
||||
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 generalIssue = issueFor(issues, "form");
|
||||
const generalIssue = issueFor(shownIssues, "form");
|
||||
const { goTo } = steps;
|
||||
|
||||
// Issues from a save (client or server) open the first step that owns one.
|
||||
const [seenIssues, setSeenIssues] = useState(issues);
|
||||
if (seenIssues !== issues) {
|
||||
setSeenIssues(issues);
|
||||
const first = issues[0];
|
||||
if (first) steps.show(questionnaireStepOfField(first.field));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (issues.length > 0) issueSummary.current?.focus();
|
||||
}, [issues.length]);
|
||||
if (shownIssues.length > 0) issueSummary.current?.focus();
|
||||
}, [shownIssues]);
|
||||
|
||||
function changeDraft(next: QuestionnaireDraft) {
|
||||
setStepIssues([]);
|
||||
onDraftChange(next);
|
||||
}
|
||||
|
||||
function goForward() {
|
||||
const step = steps.current.id;
|
||||
const found = buildCandidateQuestionnaireUpdate(draft, catalog).issues.filter(
|
||||
(issue) => questionnaireStepOfField(issue.field) === step,
|
||||
);
|
||||
if (found.length > 0) {
|
||||
setStepIssues(found);
|
||||
return;
|
||||
}
|
||||
setStepIssues([]);
|
||||
steps.next();
|
||||
}
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
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();
|
||||
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 (
|
||||
<form className={styles.form} onSubmit={handleSubmit} noValidate>
|
||||
{issues.length > 0 ? (
|
||||
<FormProgress label="Шаги анкеты" steps={questionnaireSteps} index={steps.index} />
|
||||
|
||||
{shownIssues.length > 0 ? (
|
||||
<div
|
||||
className={styles["issue-summary"]}
|
||||
ref={issueSummary}
|
||||
@@ -527,82 +768,122 @@ export function QuestionnaireForm({
|
||||
aria-labelledby={`${prefix}-issues-title`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h2 id={`${prefix}-issues-title`}>Проверьте анкету</h2>
|
||||
<ul>
|
||||
{issues.map((item, index) => (
|
||||
<li key={`${item.field}-${index}`}>{item.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
<Notice tone="danger" title={<span id={`${prefix}-issues-title`}>Проверьте анкету</span>}>
|
||||
<ul className={styles["issue-list"]}>
|
||||
{shownIssues.map((item, index) => (
|
||||
<li key={`${item.field}-${index}`}>
|
||||
<span className={styles["issue-step"]}>{stepLabel(item.field)}:</span>{" "}
|
||||
{item.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<fieldset className={styles["editor-fields"]} disabled={formDisabled}>
|
||||
<legend className={styles["visually-hidden"]}>Ответы анкеты</legend>
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Специализации</legend>
|
||||
<p className={styles.hint}>
|
||||
Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой.
|
||||
</p>
|
||||
|
||||
<FormStepPanel
|
||||
{...panel("specializations")}
|
||||
description="Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой."
|
||||
>
|
||||
{draft.specializations.map((item, index) => (
|
||||
<SpecializationCard
|
||||
<SpecializationChoice
|
||||
key={item.id}
|
||||
draft={draft}
|
||||
item={item}
|
||||
index={index}
|
||||
catalog={catalog}
|
||||
issues={issues}
|
||||
issues={shownIssues}
|
||||
disabled={formDisabled}
|
||||
prefix={prefix}
|
||||
onDraftChange={onDraftChange}
|
||||
onDraftChange={changeDraft}
|
||||
onIssue={onIssue}
|
||||
/>
|
||||
))}
|
||||
<ErrorText id={`${prefix}-specializations-error`}>
|
||||
{issueFor(issues, "specializations")}
|
||||
{issueFor(shownIssues, "specializations")}
|
||||
</ErrorText>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={formDisabled || draft.specializations.length >= 2}
|
||||
aria-describedby={`${prefix}-specialization-limit`}
|
||||
onClick={() => {
|
||||
const id = `${prefix}-row-${++rowSequence.current}`;
|
||||
onDraftChange(addQuestionnaireSpecialization(draft, id));
|
||||
}}
|
||||
>
|
||||
Добавить специализацию
|
||||
</Button>
|
||||
<p className={styles.hint} id={`${prefix}-specialization-limit`}>
|
||||
Можно указать не больше двух специализаций.
|
||||
</p>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Подходящий формат работы</legend>
|
||||
<p className={styles.hint}>
|
||||
Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю.
|
||||
</p>
|
||||
<div className={styles["check-list"]}>
|
||||
{workFormats.map((format) => {
|
||||
const id = `${prefix}-format-${format.value}`;
|
||||
return (
|
||||
<label className={styles["check-item"]} htmlFor={id} key={format.value}>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
checked={draft.workFormats.includes(format.value)}
|
||||
onChange={() =>
|
||||
onDraftChange(toggleQuestionnaireWorkFormat(draft, format.value))
|
||||
}
|
||||
/>
|
||||
<span>{format.label}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<div className={styles["add-row"]}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={formDisabled || draft.specializations.length >= 2}
|
||||
aria-describedby={`${prefix}-specialization-limit`}
|
||||
onClick={() => {
|
||||
const id = `${prefix}-row-${++rowSequence.current}`;
|
||||
changeDraft(addQuestionnaireSpecialization(draft, id));
|
||||
}}
|
||||
>
|
||||
Добавить специализацию
|
||||
</Button>
|
||||
<p className={styles.hint} id={`${prefix}-specialization-limit`}>
|
||||
Можно указать не больше двух специализаций.
|
||||
</p>
|
||||
</div>
|
||||
<ErrorText id={`${prefix}-work-formats-error`}>
|
||||
{issueFor(issues, "workFormats")}
|
||||
</ErrorText>
|
||||
</fieldset>
|
||||
</FormStepPanel>
|
||||
|
||||
<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>
|
||||
<div className={styles["choice-list"]}>
|
||||
{workFormats.map((format) => {
|
||||
const id = `${prefix}-format-${format.value}`;
|
||||
return (
|
||||
<label className={styles.choice} htmlFor={id} key={format.value}>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
checked={draft.workFormats.includes(format.value)}
|
||||
onChange={() =>
|
||||
changeDraft(toggleQuestionnaireWorkFormat(draft, format.value))
|
||||
}
|
||||
/>
|
||||
<span>{format.label}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<ErrorText id={`${prefix}-work-formats-error`}>
|
||||
{issueFor(shownIssues, "workFormats")}
|
||||
</ErrorText>
|
||||
</fieldset>
|
||||
</FormStepPanel>
|
||||
|
||||
<FormStepPanel
|
||||
{...panel("review")}
|
||||
description="Проверьте ответы перед сохранением. Сервер получит анкету целиком."
|
||||
>
|
||||
<ReviewSummary
|
||||
draft={draft}
|
||||
catalog={catalog}
|
||||
disabled={formDisabled}
|
||||
onEdit={(id) => goTo(id)}
|
||||
/>
|
||||
</FormStepPanel>
|
||||
</fieldset>
|
||||
|
||||
{generalIssue ? (
|
||||
@@ -611,24 +892,41 @@ export function QuestionnaireForm({
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<p className={styles.hint}>
|
||||
Сохраненные ответы можно изменить. Данные черновика не записываются в браузерное
|
||||
хранилище.
|
||||
</p>
|
||||
<Button
|
||||
type="submit"
|
||||
isBusy={isSaving}
|
||||
disabled={isForbidden || isConflict}
|
||||
aria-disabled={isForbidden || isConflict || undefined}
|
||||
>
|
||||
{isSaving
|
||||
? "Сохраняем анкету..."
|
||||
: canRetry
|
||||
? "Повторить сохранение"
|
||||
: "Сохранить анкету"}
|
||||
</Button>
|
||||
</div>
|
||||
<FormStepFooter
|
||||
back={
|
||||
steps.isFirst ? null : (
|
||||
<Button variant="secondary" disabled={isSaving} onClick={steps.back}>
|
||||
Назад
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
>
|
||||
{steps.isLast ? (
|
||||
<Button
|
||||
type="submit"
|
||||
isBusy={isSaving}
|
||||
disabled={isForbidden || isConflict}
|
||||
aria-disabled={isForbidden || isConflict || undefined}
|
||||
>
|
||||
{isSaving
|
||||
? "Сохраняем анкету..."
|
||||
: canRetry
|
||||
? "Повторить сохранение"
|
||||
: "Сохранить анкету"}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{draft.expectedVersion > 0 ? (
|
||||
<Button variant="quiet" disabled={formDisabled} onClick={() => goTo("review")}>
|
||||
К проверке и сохранению
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="submit" disabled={formDisabled}>
|
||||
Далее
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</FormStepFooter>
|
||||
</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 {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
/* Unread is a heavier edge and the word "Не прочитано", never color alone. */
|
||||
/* Unread is the red dot, a stronger hairline, and the words "Не прочитано";
|
||||
* never color alone. */
|
||||
.item[data-unread] {
|
||||
border-color: var(--color-border-strong);
|
||||
border-inline-start-width: var(--space-2);
|
||||
border-color: var(--color-border-hover);
|
||||
}
|
||||
|
||||
.item article {
|
||||
@@ -44,27 +44,25 @@
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: baseline;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
align-items: center;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.kind {
|
||||
font-family: var(--font-mono);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.unread {
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.read {
|
||||
font-weight: var(--font-weight-regular);
|
||||
.meta time {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
line-height: var(--line-height-snug);
|
||||
}
|
||||
@@ -102,6 +100,6 @@
|
||||
|
||||
@media (width < 42rem) {
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
@@ -15,12 +15,15 @@ import {
|
||||
import type { Notification, NotificationList, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
AttentionDot,
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Skeleton,
|
||||
Tag,
|
||||
TextLink,
|
||||
VisuallyHidden,
|
||||
} from "../../../shared/ui";
|
||||
@@ -243,7 +246,14 @@ export function NotificationInbox({ scope }: NotificationInboxProps) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (list.isPending || !list.data) return <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);
|
||||
if (items.length === 0) {
|
||||
@@ -326,11 +336,10 @@ function NotificationItem({
|
||||
<li className={styles.item} data-unread={unread || undefined}>
|
||||
<article aria-labelledby={headingId}>
|
||||
<p className={styles.meta}>
|
||||
{unread ? <AttentionDot label="Новое" /> : null}
|
||||
<span className={styles.kind}>{notificationKindLabel(item.kind)}</span>
|
||||
<time dateTime={item.delivered_at}>{formatDeliveredAt(item.delivered_at)}</time>
|
||||
<span className={unread ? styles.unread : styles.read}>
|
||||
{unread ? "Не прочитано" : "Прочитано"}
|
||||
</span>
|
||||
<Tag tone={unread ? "accent" : "neutral"}>{unread ? "Не прочитано" : "Прочитано"}</Tag>
|
||||
</p>
|
||||
<h2 id={headingId} className={styles.title} tabIndex={-1} ref={registerHeading}>
|
||||
{title}
|
||||
|
||||
@@ -37,8 +37,8 @@
|
||||
}
|
||||
|
||||
.choice input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.help,
|
||||
@@ -60,16 +60,24 @@
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
/* Notes in the shape of the Notice primitive: a nested surface, a hairline,
|
||||
* and the accent stripe of the state. */
|
||||
.notice,
|
||||
.message,
|
||||
.error {
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.message {
|
||||
border-inline-start-color: var(--color-success);
|
||||
}
|
||||
|
||||
.error {
|
||||
border-inline-start-color: var(--color-danger);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.step {
|
||||
@@ -78,7 +86,8 @@
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
/* The state is stated in text; the stronger edge only repeats it for sighted users. */
|
||||
@@ -92,7 +101,8 @@
|
||||
|
||||
.step-title {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.step-text {
|
||||
@@ -104,8 +114,10 @@
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
|
||||
+14
-10
@@ -17,11 +17,16 @@
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* The form is one card of the system. */
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
max-width: 52rem;
|
||||
min-width: 0;
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.field {
|
||||
@@ -40,13 +45,9 @@
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
background-color: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
@@ -65,10 +66,13 @@
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
/* An error in the shape of the danger Notice. */
|
||||
.error {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-danger);
|
||||
border-radius: var(--radius-s);
|
||||
background:
|
||||
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
|
||||
}
|
||||
|
||||
.error:focus {
|
||||
@@ -84,7 +88,7 @@
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > :first-child {
|
||||
width: 100%;
|
||||
.form {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.fieldset {
|
||||
@@ -44,9 +45,9 @@
|
||||
min-height: 2.75rem;
|
||||
min-width: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -64,6 +65,11 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.option:has(input:checked) {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent-tint);
|
||||
}
|
||||
|
||||
.option:has(input:focus-visible) {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
@@ -80,7 +86,7 @@
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-border-strong);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
@@ -99,12 +105,13 @@
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-danger);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
line-height: var(--line-height-body);
|
||||
background:
|
||||
linear-gradient(var(--color-danger-wash), var(--color-danger-wash)), var(--color-canvas);
|
||||
}
|
||||
|
||||
.alert:focus-visible {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
AssessmentActorGate,
|
||||
@@ -29,7 +30,7 @@ const attemptIdPattern =
|
||||
export function AssessmentResultPage() {
|
||||
const { attemptId = "" } = useParams();
|
||||
return (
|
||||
<Page title="Результат проверки" eyebrow="Кабинет кандидата" width="wide">
|
||||
<Page title="Результат проверки" width="wide">
|
||||
<AssessmentActorGate>
|
||||
{({ actor, queryClient }) => (
|
||||
<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) {
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -7,7 +7,6 @@ export function AssessmentResultsPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Результаты проверок"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Решения сервера по завершенным проверкам. Неудачная попытка не понижает действующую категорию."
|
||||
>
|
||||
<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 {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
max-width: 52rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.session {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.session-header {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.session-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
/* Focus strip: name, progress, timer, and save state. It stays in view
|
||||
* under the header on wider screens. */
|
||||
.focus-bar {
|
||||
display: grid;
|
||||
grid-template-areas:
|
||||
"name timer"
|
||||
"progress progress"
|
||||
"save save";
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: var(--space-3) var(--space-4);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
@media (width >= 43.75rem) {
|
||||
.focus-bar {
|
||||
position: sticky;
|
||||
z-index: 5;
|
||||
top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-2));
|
||||
grid-template-areas:
|
||||
"name progress timer"
|
||||
"save save save";
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
}
|
||||
}
|
||||
|
||||
.focus-name {
|
||||
grid-area: name;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.focus-progress {
|
||||
display: grid;
|
||||
grid-area: progress;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.focus-count {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.track {
|
||||
height: 0.375rem;
|
||||
border-radius: var(--radius-pill);
|
||||
overflow: hidden;
|
||||
background: var(--color-surface-elevated);
|
||||
}
|
||||
|
||||
.fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--color-inverse);
|
||||
transition: width var(--duration-slow) var(--easing-emphasized);
|
||||
}
|
||||
|
||||
.focus-timer {
|
||||
display: grid;
|
||||
grid-area: timer;
|
||||
justify-items: end;
|
||||
}
|
||||
|
||||
.timer-label {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.timer {
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 1.375rem;
|
||||
font-weight: var(--font-weight-bold);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
/* The last minute: the digits turn to the error color and a word says so. */
|
||||
.focus-timer[data-urgent] .timer {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.focus-timer[data-urgent] .timer-label::after {
|
||||
content: " · последняя минута";
|
||||
}
|
||||
|
||||
.save-state {
|
||||
display: flex;
|
||||
grid-area: save;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
padding-top: var(--space-2);
|
||||
border-top: var(--line-thin) solid var(--color-divider);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
/* The mark differs in shape per state: ring, spinner arc, filled dot, cross. */
|
||||
.save-mark {
|
||||
flex: none;
|
||||
width: 0.625rem;
|
||||
height: 0.625rem;
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.save-state[data-state="saving"] .save-mark {
|
||||
border-color: var(--color-accent);
|
||||
border-right-color: transparent;
|
||||
animation: spin 0.9s linear infinite;
|
||||
}
|
||||
|
||||
.save-state[data-state="saved"] {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.save-state[data-state="saved"] .save-mark {
|
||||
border-color: var(--color-success);
|
||||
background: var(--color-success);
|
||||
}
|
||||
|
||||
.save-state[data-state="unconfirmed"],
|
||||
.save-state[data-state="failed"] {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.save-state[data-state="unconfirmed"] .save-mark,
|
||||
.save-state[data-state="failed"] .save-mark {
|
||||
border-radius: var(--radius-xs);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
.finalize {
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.resume p,
|
||||
.finalize p,
|
||||
.info p {
|
||||
.finalize p {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
/* The item: the one panel the eye rests on. */
|
||||
.item {
|
||||
gap: var(--space-4);
|
||||
border-color: var(--color-border-strong);
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-border-hover);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.item-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.item-heading h2,
|
||||
.result h2 {
|
||||
margin: 0;
|
||||
.item-heading h3 {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.item-heading span {
|
||||
.item-counter {
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
align-items: baseline;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.item-counter > span:first-child {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.prompt {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
font-size: 1.0625rem;
|
||||
line-height: var(--line-height-body);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.info {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.result {
|
||||
@@ -86,21 +259,29 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.result-heading {
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.result-heading:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.result-heading:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
@media (width < 43.75rem) {
|
||||
.item {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.save-state[data-state="saving"] .save-mark {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useLocation, useParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
finalizeMyAssessmentAttempt,
|
||||
@@ -20,11 +20,14 @@ import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
Card,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Mono,
|
||||
Notice,
|
||||
Page,
|
||||
Section,
|
||||
Skeleton,
|
||||
VisuallyHidden,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
@@ -38,6 +41,7 @@ import {
|
||||
parseAssessmentAttemptResponse,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
specializationLabels,
|
||||
useAssessmentAttempt,
|
||||
useAssessmentResult,
|
||||
} from "../../../entities/assessment";
|
||||
@@ -55,6 +59,8 @@ import {
|
||||
useAssessmentSignals,
|
||||
useSignalNoticeGate,
|
||||
} from "../../../features/assessment-signals";
|
||||
import { forgetExpressStart } from "../model/express-start";
|
||||
import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar";
|
||||
import attemptStyles from "./assessment-attempt-page.module.css";
|
||||
|
||||
type PendingFinalize = { key: string; body: AssessmentFinalization };
|
||||
@@ -69,7 +75,16 @@ function isTerminal(attempt: AssessmentAttempt): boolean {
|
||||
|
||||
function attemptName(attempt: AssessmentAttempt): string {
|
||||
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
|
||||
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
|
||||
return `${attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
|
||||
}
|
||||
|
||||
function attemptTag(attempt: AssessmentAttempt): string {
|
||||
if (attempt.kind === "demo_express") return "Демонстрация";
|
||||
const parts = [
|
||||
attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка",
|
||||
attempt.target_grade ? gradeLabels[attempt.target_grade] : null,
|
||||
];
|
||||
return parts.filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
function answerErrorMessage(error: unknown): string {
|
||||
@@ -144,6 +159,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
const [answerBusy, setAnswerBusy] = useState(false);
|
||||
const [answerError, setAnswerError] = useState<string | null>(null);
|
||||
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
|
||||
const [answerSaved, setAnswerSaved] = useState(false);
|
||||
const location = useLocation();
|
||||
const resumedExpress = Boolean(
|
||||
(location.state as { expressResumed?: boolean } | null)?.expressResumed,
|
||||
);
|
||||
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
|
||||
const [finalizeBusy, setFinalizeBusy] = useState(false);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
@@ -198,6 +218,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
resultQuery.isError,
|
||||
]);
|
||||
|
||||
// A finished or expired express run cannot be resumed; its start key goes.
|
||||
const expressFinishedId =
|
||||
attempt && attempt.kind === "demo_express" && isTerminal(attempt) ? attempt.id : null;
|
||||
const actorId = actor?.account.id ?? null;
|
||||
useEffect(() => {
|
||||
if (expressFinishedId && actorId) forgetExpressStart(actorId, expressFinishedId);
|
||||
}, [actorId, expressFinishedId]);
|
||||
|
||||
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
|
||||
const key = getGetCurrentSessionQueryKey();
|
||||
const captured = queryClient.getQueryData<Session>(key);
|
||||
@@ -312,6 +340,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
setAnswerBusy(true);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
setAnswerSaved(false);
|
||||
try {
|
||||
const outcome = await submitPendingAnswerCommand(
|
||||
command,
|
||||
@@ -335,6 +364,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
setPendingAnswer(null);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
setAnswerSaved(true);
|
||||
setWorkReady(true);
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
@@ -435,7 +465,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Попытка недоступна"
|
||||
@@ -447,21 +477,21 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!attemptId) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<ErrorState
|
||||
error={new Error("The attempt identifier is missing.")}
|
||||
title="Не удалось открыть попытку"
|
||||
@@ -471,7 +501,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
}
|
||||
if (attemptQuery.isPending && !attempt) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<LoadingState label="Загружаем сохраненную попытку..." />
|
||||
</Page>
|
||||
);
|
||||
@@ -479,7 +509,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
if (attemptQuery.isError || !attempt) {
|
||||
if (isAccessLoss(attemptQuery.error)) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<ForbiddenState
|
||||
error={attemptQuery.error}
|
||||
title="Попытка недоступна"
|
||||
@@ -490,7 +520,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<Page title="Попытка проверки">
|
||||
<ErrorState
|
||||
error={attemptQuery.error}
|
||||
isRetrying={attemptQuery.isRefetching}
|
||||
@@ -516,10 +546,23 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
));
|
||||
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 (
|
||||
<Page
|
||||
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead={
|
||||
attempt.kind === "demo_express"
|
||||
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
|
||||
@@ -528,67 +571,99 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
width="wide"
|
||||
>
|
||||
<div className={attemptStyles.layout}>
|
||||
<Section
|
||||
title={attemptName(attempt)}
|
||||
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`}
|
||||
>
|
||||
<div className={attemptStyles.meta}>
|
||||
<span>
|
||||
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items}
|
||||
</span>
|
||||
<span>
|
||||
Срок до:{" "}
|
||||
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
|
||||
new Date(attempt.expires_at),
|
||||
)}
|
||||
</span>
|
||||
{attempt.sessions ? (
|
||||
<span>
|
||||
Сеанс {attempt.sessions.used} из {attempt.sessions.max}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<section className={attemptStyles.session} aria-labelledby="attempt-title">
|
||||
<header className={attemptStyles["session-header"]}>
|
||||
<h2 id="attempt-title" className={attemptStyles["session-title"]}>
|
||||
{attemptName(attempt)}
|
||||
</h2>
|
||||
<p className={attemptStyles.meta}>
|
||||
{methodLabel(attempt.mode) !== attemptName(attempt)
|
||||
? `${methodLabel(attempt.mode)}. `
|
||||
: ""}
|
||||
Сервер хранит состояние и результат попытки. Срок до <Mono>{deadline}</Mono>
|
||||
{attempt.sessions ? (
|
||||
<>
|
||||
, сеанс <Mono>{attempt.sessions.used}</Mono> из{" "}
|
||||
<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}
|
||||
|
||||
{pageError ? (
|
||||
<p className={attemptStyles.error} role="alert">
|
||||
{pageError}
|
||||
</p>
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={attemptStyles["notice-text"]}>{pageError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!workReady && !terminal ? (
|
||||
<div className={attemptStyles.resume}>
|
||||
<Card tone="raised" className={attemptStyles.resume}>
|
||||
<p>
|
||||
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
|
||||
меняются, а ответ не отправляется повторно автоматически.
|
||||
</p>
|
||||
{signalNotice.checkError ? (
|
||||
<p className={attemptStyles.error} role="alert">
|
||||
{signalNotice.checkError}
|
||||
</p>
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={attemptStyles["notice-text"]}>{signalNotice.checkError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
<Button
|
||||
isBusy={resumeBusy}
|
||||
onClick={() =>
|
||||
void (collectsSignals
|
||||
? signalNotice.guard(() => void resumeWork())
|
||||
: resumeWork())
|
||||
}
|
||||
>
|
||||
{resumeBusy
|
||||
? "Проверяем попытку..."
|
||||
: pendingResume
|
||||
? "Повторить продолжение"
|
||||
: "Начать или продолжить"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className={attemptStyles.actions}>
|
||||
<Button
|
||||
isBusy={resumeBusy}
|
||||
onClick={() =>
|
||||
void (collectsSignals
|
||||
? signalNotice.guard(() => void resumeWork())
|
||||
: resumeWork())
|
||||
}
|
||||
>
|
||||
{resumeBusy
|
||||
? "Проверяем попытку..."
|
||||
: pendingResume
|
||||
? "Повторить продолжение"
|
||||
: "Начать или продолжить"}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{workReady && pendingAnswerNeedsReplay && !terminal ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
|
||||
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
|
||||
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
|
||||
</Button>
|
||||
<div role="status">
|
||||
<Notice
|
||||
tone="neutral"
|
||||
action={
|
||||
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
|
||||
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<p className={attemptStyles["notice-text"]}>
|
||||
Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -598,10 +673,15 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
|
||||
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
|
||||
<div className={attemptStyles["item-heading"]}>
|
||||
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2>
|
||||
<span>
|
||||
{currentItem.sequence} из {attempt.progress.max_items}
|
||||
<h3 id="assessment-item-title">Задание {currentItem.sequence}</h3>
|
||||
<span className={attemptStyles["item-counter"]} aria-hidden="true">
|
||||
<Mono strong>{String(currentItem.sequence).padStart(2, "0")}</Mono>
|
||||
<span>/</span>
|
||||
<Mono>{String(attempt.progress.max_items).padStart(2, "0")}</Mono>
|
||||
</span>
|
||||
<VisuallyHidden>
|
||||
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
|
||||
</VisuallyHidden>
|
||||
</div>
|
||||
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
|
||||
<AnswerForm
|
||||
@@ -623,10 +703,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
) : null}
|
||||
|
||||
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
|
||||
<p className={attemptStyles.info} role="status">
|
||||
Решение передано на проверку. Результат появится после ответа сервера; страница
|
||||
обновляет статус автоматически.
|
||||
</p>
|
||||
<div role="status">
|
||||
<Notice tone="info">
|
||||
<p className={attemptStyles["notice-text"]}>
|
||||
Решение передано на проверку. Результат появится после ответа сервера; страница
|
||||
обновляет статус автоматически.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
@@ -635,18 +719,20 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.finalize}>
|
||||
<Card tone="raised" className={attemptStyles.finalize}>
|
||||
<p>
|
||||
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
|
||||
</p>
|
||||
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
|
||||
{finalizeBusy
|
||||
? "Запрашиваем решение..."
|
||||
: pendingFinalize
|
||||
? "Повторить завершение"
|
||||
: "Завершить проверку"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className={attemptStyles.actions}>
|
||||
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
|
||||
{finalizeBusy
|
||||
? "Запрашиваем решение..."
|
||||
: pendingFinalize
|
||||
? "Повторить завершение"
|
||||
: "Завершить проверку"}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
@@ -655,20 +741,28 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
!canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={attemptQuery.isRefetching}
|
||||
onClick={() => void attemptQuery.refetch()}
|
||||
<div role="status">
|
||||
<Notice
|
||||
tone="neutral"
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={attemptQuery.isRefetching}
|
||||
onClick={() => void attemptQuery.refetch()}
|
||||
>
|
||||
Обновить попытку
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Обновить попытку
|
||||
</Button>
|
||||
<p className={attemptStyles["notice-text"]}>
|
||||
Сервер не вернул следующее задание. Обновите состояние попытки.
|
||||
</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
|
||||
</Section>
|
||||
</section>
|
||||
<div className={attemptStyles["back-link"]}>
|
||||
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
|
||||
К доступным проверкам
|
||||
@@ -682,7 +776,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
|
||||
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
|
||||
if (resultQuery.isPending && !resultQuery.data) {
|
||||
return <LoadingState label="Загружаем сохраненный результат..." />;
|
||||
return (
|
||||
<div className={attemptStyles.result}>
|
||||
<LoadingState label="Загружаем сохраненный результат..." />
|
||||
<Skeleton shape="card" lines={4} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!resultQuery.data) {
|
||||
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,
|
||||
TaskLanguage,
|
||||
} from "../../../shared/api/schemas";
|
||||
import type { AssessmentAttempt } from "../../../shared/api/schemas";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import { parseAssessmentAttemptResponse } from "../../../entities/assessment";
|
||||
import { isOutcomeAmbiguous, parseAssessmentAttemptResponse } from "../../../entities/assessment";
|
||||
import {
|
||||
beginExpressStart,
|
||||
forgetExpressStart,
|
||||
recordExpressRun,
|
||||
settleRefusedExpressStart,
|
||||
} from "../model/express-start";
|
||||
|
||||
export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
|
||||
|
||||
@@ -47,3 +55,72 @@ export function submitPendingAttempt(command: PendingCreate, csrfToken: string)
|
||||
{ headers: { "X-CSRF-Token": csrfToken } },
|
||||
).then((response) => parseAssessmentAttemptResponse(response, 201));
|
||||
}
|
||||
|
||||
/** 409 to an express start while another express run is active. */
|
||||
export function isActiveExpressConflict(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 409 &&
|
||||
error.code === "state_conflict" &&
|
||||
!error.fieldErrors.some((field) => field.code === "consent_required")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* An express run is active, but this tab does not know the key that started
|
||||
* it (another browser, a closed tab, or blocked storage). It ends by itself
|
||||
* within five minutes.
|
||||
*/
|
||||
export class ExpressRunElsewhereError extends Error {
|
||||
constructor(cause: unknown) {
|
||||
super("An express run is active, and its start key is not stored in this tab.", { cause });
|
||||
this.name = "ExpressRunElsewhereError";
|
||||
}
|
||||
}
|
||||
|
||||
type ExpressStartOptions = {
|
||||
accountId: string;
|
||||
csrfToken: string;
|
||||
/** Key of a start of this page whose outcome is not known yet. */
|
||||
pendingKey: string | null;
|
||||
newKey: () => string;
|
||||
/** Called with the key before the request, so a retry repeats it. */
|
||||
onKey?: (key: string) => void;
|
||||
store?: Pick<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 {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
.layout {
|
||||
grid-template-columns: minmax(0, 1fr) 20rem;
|
||||
}
|
||||
|
||||
.aside {
|
||||
position: sticky;
|
||||
top: calc(var(--header-height) + var(--chrome-inset) * 2 + var(--space-4));
|
||||
}
|
||||
}
|
||||
|
||||
.main {
|
||||
gap: var(--space-5);
|
||||
}
|
||||
|
||||
.aside {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.block-header {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.kicker {
|
||||
color: var(--color-accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.block-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.block-lead {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
@@ -20,108 +72,123 @@
|
||||
.field select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.field select:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
font-weight: var(--font-weight-regular);
|
||||
}
|
||||
|
||||
.language-note,
|
||||
.language-availability {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.language-note {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-divider);
|
||||
.language-note strong {
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.language-availability {
|
||||
max-width: 72ch;
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express {
|
||||
/* The chosen level: a nested surface with its category tag and status. */
|
||||
.availability {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.availability p,
|
||||
.express p {
|
||||
.availability p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.status-row [data-state="available"] {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
/* Policy limits as small readouts with mono values. */
|
||||
.limits {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.limits div {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-canvas);
|
||||
border-radius: var(--radius-s);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.limits dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.limits dd {
|
||||
margin: var(--space-1) 0 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.express p,
|
||||
.pending {
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.express {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.duration {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
align-items: baseline;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.duration > span:first-child {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-title);
|
||||
}
|
||||
|
||||
.express-note {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.pending {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.controls,
|
||||
@media (width >= 48rem) {
|
||||
.controls {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.limits {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express {
|
||||
padding: var(--space-3);
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,17 @@ import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
Card,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Mono,
|
||||
Notice,
|
||||
Page,
|
||||
Section,
|
||||
Skeleton,
|
||||
Tag,
|
||||
type TagTone,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
assessmentSessionMatches,
|
||||
@@ -46,7 +51,9 @@ import {
|
||||
} from "../../../features/assessment-signals";
|
||||
import {
|
||||
buildRootAttemptCreate,
|
||||
ExpressRunElsewhereError,
|
||||
preservePendingCreate,
|
||||
startExpressRun,
|
||||
submitPendingAttempt,
|
||||
type PendingCreate,
|
||||
} from "./assessment-page.model";
|
||||
@@ -78,6 +85,19 @@ function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
|
||||
}
|
||||
}
|
||||
|
||||
function gradeStatusTag(grade: AssessmentGradeAvailability): { label: string; tone: TagTone } {
|
||||
switch (grade.status) {
|
||||
case "available":
|
||||
return { label: "Доступна", tone: "success" };
|
||||
case "active_attempt":
|
||||
return { label: "Есть попытка", tone: "accent" };
|
||||
case "cooldown":
|
||||
return { label: "Пауза", tone: "neutral" };
|
||||
case "insufficient_bank":
|
||||
return { label: "Банк не готов", tone: "neutral" };
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "medium",
|
||||
@@ -197,6 +217,7 @@ export function AssessmentPage() {
|
||||
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
|
||||
const [createBusy, setCreateBusy] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [expressNote, setExpressNote] = useState<string | null>(null);
|
||||
const [c3Required, setC3Required] = useState(false);
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
@@ -370,13 +391,73 @@ export function AssessmentPage() {
|
||||
void signalNotice.guard(() => void startAttempt(body));
|
||||
};
|
||||
|
||||
async function startExpress() {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
|
||||
return;
|
||||
requestInFlight.current = true;
|
||||
setCreateBusy(true);
|
||||
setFormError(null);
|
||||
setExpressNote(null);
|
||||
setC3Required(false);
|
||||
try {
|
||||
const { attempt, resumed } = await startExpressRun({
|
||||
accountId: actor.account.id,
|
||||
csrfToken: actor.csrf_token,
|
||||
pendingKey: pendingCreate?.body.kind === "demo_express" ? pendingCreate.key : null,
|
||||
newKey: newIdempotencyKey,
|
||||
onKey: (key) => setPendingCreate({ key, body: { kind: "demo_express" } }),
|
||||
});
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setPendingCreate(null);
|
||||
navigate(paths.candidate.assessmentAttempt(attempt.id), {
|
||||
state: resumed ? { expressResumed: true } : null,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
const refreshed = await refreshSessionForActor(actor);
|
||||
if (refreshed) {
|
||||
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
return;
|
||||
}
|
||||
if (error instanceof ExpressRunElsewhereError) {
|
||||
setPendingCreate(null);
|
||||
setExpressNote(
|
||||
"Незавершенная демонстрация открыта в другой вкладке или браузере. Продолжите ее там или подождите: она закончится сама не позже чем через 5 минут после начала.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (isOutcomeAmbiguous(error)) {
|
||||
setExpressNote(
|
||||
"Не удалось подтвердить начало демонстрации. Повторная отправка использует тот же ключ.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setPendingCreate(null);
|
||||
setExpressNote("Сервер не начал демонстрацию. Обновите страницу и повторите действие.");
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setCreateBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleStartExpress = () => {
|
||||
void startAttempt({ kind: "demo_express" });
|
||||
void startExpress();
|
||||
};
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<Page title="Проверка знаний">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Проверка недоступна"
|
||||
@@ -388,33 +469,41 @@ export function AssessmentPage() {
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<Page title="Проверка знаний">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<Page title="Проверка знаний">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
const statusTag = grade ? gradeStatusTag(grade) : null;
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Проверка знаний"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<Section
|
||||
title="Доступность проверки"
|
||||
description="Состояние и ограничения загружаются с сервера."
|
||||
>
|
||||
<Card as="section" tone="panel" labelledBy="assessment-full-title" className={styles.main}>
|
||||
<header className={styles["block-header"]}>
|
||||
<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) ||
|
||||
(questionnaire.isPending && !questionnaire.data) ? (
|
||||
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
|
||||
<div className={styles.loading}>
|
||||
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
|
||||
<Skeleton lines={4} />
|
||||
</div>
|
||||
) : !data || !questionnaire.data ? (
|
||||
<ErrorState
|
||||
error={!data ? availability.error : questionnaire.error}
|
||||
@@ -485,81 +574,105 @@ export function AssessmentPage() {
|
||||
опубликованы ли подходящие задания.
|
||||
</p>
|
||||
) : null}
|
||||
{specialization && grade ? (
|
||||
{specialization && grade && statusTag ? (
|
||||
<div className={styles.availability}>
|
||||
<div className={styles["status-row"]}>
|
||||
<strong>{gradeLabels[grade.grade]}</strong>
|
||||
<span data-state={grade.status}>
|
||||
{grade.status === "available"
|
||||
? "Доступна"
|
||||
: grade.status === "active_attempt"
|
||||
? "Есть попытка"
|
||||
: grade.status === "cooldown"
|
||||
? "Пауза"
|
||||
: "Банк не готов"}
|
||||
</span>
|
||||
<Tag tone="grade">
|
||||
{`${specializationLabels[specialization.specialization]} · ${gradeLabels[grade.grade]}`}
|
||||
</Tag>
|
||||
<Tag tone={statusTag.tone} dot>
|
||||
{statusTag.label}
|
||||
</Tag>
|
||||
</div>
|
||||
<p>{gradeStatusDescription(grade)}</p>
|
||||
<AssessmentPolicyParameters grade={grade} />
|
||||
{activeAttemptId && grade.status === "active_attempt" ? (
|
||||
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
|
||||
Продолжить текущую попытку
|
||||
</ButtonLink>
|
||||
) : grade.status === "available" ? (
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={!taskLanguageReady}
|
||||
onClick={() => {
|
||||
if (taskLanguageReady) handleStartReal();
|
||||
}}
|
||||
>
|
||||
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
|
||||
</Button>
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
{activeAttemptId && grade.status === "active_attempt" ? (
|
||||
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
|
||||
Продолжить текущую попытку
|
||||
</ButtonLink>
|
||||
) : grade.status === "available" ? (
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={!taskLanguageReady || pendingCreate?.body.kind === "demo_express"}
|
||||
onClick={() => {
|
||||
if (taskLanguageReady) handleStartReal();
|
||||
}}
|
||||
>
|
||||
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{pendingCreate ? (
|
||||
{pendingCreate && pendingCreate.body.kind !== "demo_express" ? (
|
||||
<p className={styles.pending} role="status">
|
||||
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
|
||||
ее с тем же ключом.
|
||||
</p>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<p className={styles.error} role="alert">
|
||||
{formError}{" "}
|
||||
{c3Required ? (
|
||||
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
|
||||
) : null}
|
||||
</p>
|
||||
<div role="alert">
|
||||
<Notice
|
||||
tone="danger"
|
||||
action={
|
||||
c3Required ? (
|
||||
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<p className={styles["notice-text"]}>{formError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<SignalNoticeSummary />
|
||||
{signalNotice.checkError ? (
|
||||
<p className={styles.error} role="alert">
|
||||
{signalNotice.checkError}
|
||||
</p>
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>{signalNotice.checkError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
</Card>
|
||||
|
||||
<Section
|
||||
title="Демонстрационный экспресс-запуск"
|
||||
description="Отдельный учебный режим для знакомства с заданиями."
|
||||
>
|
||||
<div className={styles.express}>
|
||||
<p>
|
||||
<aside className={styles.aside} aria-labelledby="assessment-express-title">
|
||||
<Card tone="raised" className={styles.express}>
|
||||
<p className={styles.kicker}>Учебный режим</p>
|
||||
<h2 id="assessment-express-title" className={styles["block-title"]}>
|
||||
Демонстрационный экспресс-запуск
|
||||
</h2>
|
||||
<p className={styles.duration}>
|
||||
<Mono strong>3-5</Mono> <span>минут</span>
|
||||
</p>
|
||||
<p className={styles["block-lead"]}>
|
||||
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
|
||||
и не влияет на доступность полной проверки.
|
||||
</p>
|
||||
<p className={styles["express-note"]}>
|
||||
Незавершенный запуск этой вкладки продолжается той же кнопкой.
|
||||
</p>
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
disabled={Boolean(pendingCreate) && pendingCreate?.body.kind !== "demo_express"}
|
||||
onClick={handleStartExpress}
|
||||
>
|
||||
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
|
||||
{createBusy
|
||||
? "Создаем запуск..."
|
||||
: pendingCreate?.body.kind === "demo_express"
|
||||
? "Повторить начало демонстрации"
|
||||
: "Начать демонстрацию"}
|
||||
</Button>
|
||||
</div>
|
||||
</Section>
|
||||
{expressNote ? (
|
||||
<div role="status">
|
||||
<Notice tone="neutral">
|
||||
<p className={styles["notice-text"]}>{expressNote}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
</Card>
|
||||
</aside>
|
||||
</div>
|
||||
<SignalNoticeDialog {...signalNotice.dialog} />
|
||||
</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 type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, EmptyState, Page, QueryView, Section, TextLink } from "../../../shared/ui";
|
||||
import {
|
||||
ButtonLink,
|
||||
Card,
|
||||
EmptyState,
|
||||
Mono,
|
||||
Page,
|
||||
QueryView,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import { CandidateNextStep } from "../../../widgets/candidate-next-step";
|
||||
import styles from "./candidate-home-page.module.css";
|
||||
|
||||
@@ -36,7 +45,7 @@ function searchStatusText(search: VisibilitySummary["searchStatus"]): string {
|
||||
function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
|
||||
const visibility = summarizeVisibility(settings);
|
||||
return (
|
||||
<>
|
||||
<Card tone="raised">
|
||||
<dl className={styles.facts}>
|
||||
<dt>Карточка для компаний</dt>
|
||||
<dd>
|
||||
@@ -55,12 +64,12 @@ function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
|
||||
<dt>Статус поиска</dt>
|
||||
<dd>{searchStatusText(visibility.searchStatus)}</dd>
|
||||
</dl>
|
||||
<div>
|
||||
<div className={styles.links}>
|
||||
<ButtonLink to={paths.candidate.privacy} variant="secondary">
|
||||
Настроить видимость и согласия
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,17 +93,19 @@ function LatestResult({ page }: { page: AssessmentResultHistoryPage }) {
|
||||
if (!latest) return null;
|
||||
const summary = assessmentResultSummary(latest);
|
||||
return (
|
||||
<>
|
||||
<Card tone="raised">
|
||||
<p className={styles["result-text"]}>{summary.text}</p>
|
||||
{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}>
|
||||
<TextLink to={paths.candidate.result(latest.attempt_id)}>
|
||||
Открыть разбор результата
|
||||
</TextLink>
|
||||
<TextLink to={paths.candidate.results}>История результатов</TextLink>
|
||||
</div>
|
||||
</>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -134,7 +145,6 @@ export function CandidateHomePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Главная"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом."
|
||||
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 {
|
||||
ButtonLink,
|
||||
Card,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Notice,
|
||||
Page,
|
||||
Section,
|
||||
Skeleton,
|
||||
Tag,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import { invitationTagTone } from "../model/status-tone";
|
||||
import { InvitationTermsArticle } from "../../../widgets/invitation-preview";
|
||||
import styles from "./candidate-invitations.module.css";
|
||||
|
||||
@@ -183,16 +188,18 @@ function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerS
|
||||
onFailure={(failure) => onFailure("accept", failure)}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles["no-offer"]}>
|
||||
<Card tone="raised" className={styles["no-offer"]}>
|
||||
<h3 className={styles.subtitle}>Принять приглашение нельзя</h3>
|
||||
<p className={styles.text}>
|
||||
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в
|
||||
профиль, чтобы принять приглашение.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.profile} variant="secondary">
|
||||
Открыть профиль
|
||||
</ButtonLink>
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink to={paths.candidate.profile} variant="secondary">
|
||||
Открыть профиль
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
<DeclineInvitationForm
|
||||
key={invitation.id}
|
||||
@@ -221,31 +228,47 @@ function InvitationContent({
|
||||
}: InvitationContentProps) {
|
||||
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}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Компания</dt>
|
||||
<dd>{invitation.organization.name}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Состояние</dt>
|
||||
<dd data-state={invitation.state}>{candidateStatusLabel(invitation, serverNow)}</dd>
|
||||
<dt>Роль</dt>
|
||||
<dd className={styles["card-role"]}>{invitation.terms.role_title}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Срок ответа</dt>
|
||||
<dd data-term="deadline">
|
||||
<dd data-term="deadline" className={styles.mono}>
|
||||
<time dateTime={invitation.response_deadline_at}>
|
||||
{`До ${formatServerMoment(invitation.response_deadline_at)}`}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</Section>
|
||||
</Card>
|
||||
|
||||
{notice ? (
|
||||
<p className={styles.notice} role="status">
|
||||
{notice}
|
||||
</p>
|
||||
<div role="status">
|
||||
<Notice tone="info">
|
||||
<p className={styles.text}>{notice}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Section title="Условия приглашения">
|
||||
@@ -330,14 +353,13 @@ export function CandidateInvitationPage() {
|
||||
const serverNow = useServerNow();
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Приглашение"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead={invitation ? candidateStatusLabel(invitation, serverNow) : undefined}
|
||||
>
|
||||
<Page title="Приглашение" width="wide">
|
||||
{!validId ? <NotFoundState /> : null}
|
||||
{validId && accountId !== "" && detail.isPending ? (
|
||||
<LoadingState label="Открываем приглашение..." />
|
||||
<>
|
||||
<LoadingState label="Открываем приглашение..." />
|
||||
<Skeleton shape="card" lines={4} />
|
||||
</>
|
||||
) : null}
|
||||
{validId && detail.isError ? (
|
||||
isMissing(detail.error) ? (
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
AttentionDot,
|
||||
Button,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
@@ -18,7 +19,10 @@ import {
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Page,
|
||||
Skeleton,
|
||||
Tag,
|
||||
} from "../../../shared/ui";
|
||||
import { invitationTagTone, isNewInvitation } from "../model/status-tone";
|
||||
import styles from "./candidate-invitations.module.css";
|
||||
|
||||
const lead =
|
||||
@@ -45,9 +49,12 @@ export function CandidateInvitationsPage() {
|
||||
const serverNow = useServerNow();
|
||||
|
||||
return (
|
||||
<Page title="Приглашения" eyebrow="Кабинет кандидата" lead={lead}>
|
||||
<Page title="Приглашения" lead={lead} width="wide">
|
||||
{inbox.isPending && accountId !== "" ? (
|
||||
<LoadingState label="Загружаем приглашения..." />
|
||||
<>
|
||||
<LoadingState label="Загружаем приглашения..." />
|
||||
<Skeleton shape="card" lines={3} />
|
||||
</>
|
||||
) : null}
|
||||
{inbox.isError ? (
|
||||
isAccessDenied(inbox.error) ? (
|
||||
@@ -77,19 +84,24 @@ export function CandidateInvitationsPage() {
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link className={styles.card} to={paths.candidate.invitation(item.id)}>
|
||||
<span className={styles["card-company"]}>
|
||||
<span className={styles["card-label"]}>Компания</span>
|
||||
<span className={styles["card-title"]}>{item.organization.name}</span>
|
||||
<span className={styles["card-head"]}>
|
||||
<span className={styles["card-company"]}>
|
||||
<span className={styles["card-label"]}>Компания</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 className={styles["card-role"]}>{item.role_title}</span>
|
||||
<span className={styles.salary}>{formatSalaryRange(item.salary)}</span>
|
||||
<span className={styles["card-facts"]}>
|
||||
<span>{formatSalaryRange(item.salary)}</span>
|
||||
<span>
|
||||
{`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
|
||||
</span>
|
||||
</span>
|
||||
<span className={styles["card-status"]} data-state={item.state}>
|
||||
{candidateStatusLabel(item, serverNow)}
|
||||
{`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
|
||||
@@ -17,19 +17,68 @@
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
gap: var(--space-3);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-4);
|
||||
height: 100%;
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
transition: border-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
border-color: var(--color-border-strong);
|
||||
border-color: var(--color-border-hover);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.salary {
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 1.125rem;
|
||||
font-weight: var(--font-weight-bold);
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.summary {
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.summary-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.summary-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-xl);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.card:focus-visible {
|
||||
@@ -44,20 +93,28 @@
|
||||
|
||||
.card-label {
|
||||
color: var(--color-text-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
overflow-wrap: anywhere;
|
||||
display: inline-flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
font-weight: var(--font-weight-medium);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.card-role {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
font-weight: var(--font-weight-medium);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.card-facts {
|
||||
@@ -67,14 +124,6 @@
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.card-status {
|
||||
justify-self: start;
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
@@ -87,6 +136,12 @@
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.facts {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
@@ -104,13 +159,13 @@
|
||||
}
|
||||
|
||||
.section-title {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.text {
|
||||
@@ -119,29 +174,21 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.decisions {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
.decisions {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.no-offer {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.grant {
|
||||
@@ -166,3 +213,9 @@
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (width >= 80rem) {
|
||||
.list {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@@ -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 { getOnboardingDestination } from "../../../entities/session";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, LoadingState, Page, Section, StatusView } from "../../../shared/ui";
|
||||
import {
|
||||
buildSteps,
|
||||
ButtonLink,
|
||||
Card,
|
||||
LoadingState,
|
||||
Mono,
|
||||
Page,
|
||||
StatusView,
|
||||
Stepper,
|
||||
Tag,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./candidate-onboarding-page.module.css";
|
||||
|
||||
/**
|
||||
* The account steps of a candidate in the order the server advances them.
|
||||
* This page is shown only while the stored step is the first one.
|
||||
*/
|
||||
const accountSteps = [
|
||||
{
|
||||
id: "candidate_consents",
|
||||
label: "Согласия",
|
||||
text: "Прочитайте тексты согласий C2-C5 и выберите каждое отдельно. C1 вы уже приняли при регистрации.",
|
||||
},
|
||||
{
|
||||
id: "candidate_profile",
|
||||
label: "Профиль",
|
||||
text: "Контакты, роли, опыт, навыки и условия работы. Все поля необязательны, резюме не нужно.",
|
||||
},
|
||||
{
|
||||
id: "candidate_questionnaire",
|
||||
label: "Анкета",
|
||||
text: "Одна или две специализации и уровень, на который вы претендуете. Это самооценка.",
|
||||
},
|
||||
{
|
||||
id: "candidate_assessment",
|
||||
label: "Тест",
|
||||
text: "Проверка подтверждает уровень. Подтвержденную категорию присваивает только сервер.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function CandidateOnboardingPage() {
|
||||
const session = useGetCurrentSession();
|
||||
@@ -32,20 +70,57 @@ export function CandidateOnboardingPage() {
|
||||
return <Navigate to={destination} replace />;
|
||||
}
|
||||
|
||||
const currentIndex = accountSteps.findIndex((item) => item.id === step);
|
||||
|
||||
return (
|
||||
<Page title="Первые шаги" eyebrow="Кабинет кандидата">
|
||||
<Section
|
||||
title="Согласия"
|
||||
description="Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации."
|
||||
>
|
||||
<p>
|
||||
Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие
|
||||
отдельно.
|
||||
<Page
|
||||
title="Первые шаги"
|
||||
lead="Четыре шага до подтвержденной категории. Состояние шага хранится на сервере, поэтому его можно продолжить с любого устройства."
|
||||
width="wide"
|
||||
>
|
||||
<Card as="section" tone="panel" labelledBy="onboarding-progress-title">
|
||||
<h2 id="onboarding-progress-title" className={styles["panel-title"]}>
|
||||
Шаги аккаунта
|
||||
</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>
|
||||
</div>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
<p className={styles.note}>
|
||||
Сохраненный шаг хранит сервер. Профиль, анкета и тест открываются из меню кабинета и
|
||||
сохраняются независимо от него. Привязка ФСП ID и резюме для этого пути не нужны.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.privacy}>
|
||||
Открыть согласия и настройки приватности
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Card>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -28,9 +28,9 @@ function render(scenario: "candidate" | "employer", element: React.ReactElement)
|
||||
}
|
||||
|
||||
describe("notification pages", () => {
|
||||
it("name the cabinet and carry the single h1", () => {
|
||||
it("carry the single h1; the candidate shell names its cabinet next to the wordmark", () => {
|
||||
const candidate = render("candidate", <CandidateNotificationsPage />);
|
||||
expect(candidate).toContain("Кабинет кандидата");
|
||||
expect(candidate).not.toContain("Кабинет кандидата");
|
||||
expect(candidate.match(/<h1/g)).toHaveLength(1);
|
||||
const employer = render("employer", <EmployerNotificationsPage />);
|
||||
expect(employer).toContain("Кабинет работодателя");
|
||||
|
||||
@@ -6,7 +6,7 @@ const lead =
|
||||
|
||||
export function CandidateNotificationsPage() {
|
||||
return (
|
||||
<Page title="Уведомления" eyebrow="Кабинет кандидата" lead={lead}>
|
||||
<Page title="Уведомления" lead={lead}>
|
||||
<NotificationInbox scope={{ kind: "candidate" }} />
|
||||
</Page>
|
||||
);
|
||||
|
||||
@@ -6,15 +6,15 @@
|
||||
}
|
||||
|
||||
.note {
|
||||
margin: 0.75rem 0 0;
|
||||
margin: var(--space-3) 0 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.925rem;
|
||||
line-height: 1.55;
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.organization-columns section {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
@@ -22,7 +22,8 @@
|
||||
|
||||
.organization-columns h3 {
|
||||
margin: 0 0 var(--space-3);
|
||||
font-size: 1rem;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.organization-list,
|
||||
@@ -59,7 +60,13 @@
|
||||
.history-list time,
|
||||
.history-list span {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.9rem;
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.organization-list time,
|
||||
.history-list time {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.history-list li {
|
||||
@@ -82,21 +89,68 @@
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-block-start: var(--space-3);
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
.notice-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-block-start: var(--space-3);
|
||||
color: var(--color-text-secondary);
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
/* In-page contents as filter chips; on a phone the row scrolls sideways. */
|
||||
.contents {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.contents ul {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: 0 0 var(--space-1);
|
||||
overflow-x: auto;
|
||||
list-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.contents-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 2.25rem;
|
||||
padding: 0 var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-pill);
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-s);
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
background: var(--color-surface);
|
||||
transition: border-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.contents-link:hover {
|
||||
border-color: var(--color-border-strong);
|
||||
}
|
||||
|
||||
.anchor {
|
||||
display: grid;
|
||||
gap: var(--space-7);
|
||||
min-width: 0;
|
||||
scroll-margin-block-start: var(--space-4);
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.organization-columns {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
/* On a phone the two lists are plain blocks: a card around a nested empty
|
||||
* state would leave its text a narrow column. */
|
||||
.organization-columns section {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Notice,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
@@ -68,6 +69,16 @@ import { candidateViewQueryKeys } from "../../../entities/candidate-view";
|
||||
import styles from "./privacy-page.module.css";
|
||||
|
||||
const pageSize = 100;
|
||||
|
||||
/** In-page contents: each settings block has an anchor. */
|
||||
const privacySections = [
|
||||
{ id: "privacy-consents", label: "Согласия" },
|
||||
{ id: "privacy-publication", label: "Публикация" },
|
||||
{ id: "privacy-search", label: "Статус поиска" },
|
||||
{ id: "privacy-preview", label: "Предпросмотр" },
|
||||
{ id: "privacy-companies", label: "Компании" },
|
||||
{ id: "privacy-history", label: "История" },
|
||||
] as const;
|
||||
const noOrganizations: ReadonlySet<string> = new Set();
|
||||
const privateQueryOptions = {
|
||||
gcTime: 0,
|
||||
@@ -302,14 +313,18 @@ export function OrganizationVisibility({
|
||||
</div>
|
||||
<p className={styles.note}>{contactAccessAfterVisibilityChange}</p>
|
||||
{actionError ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{actionError}
|
||||
<div role="alert">
|
||||
<Notice tone="danger">
|
||||
<p className={styles["notice-text"]}>{actionError}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
{actionMessage ? (
|
||||
<p className={styles.message} role="status">
|
||||
{actionMessage}
|
||||
</p>
|
||||
<div role="status">
|
||||
<Notice tone="success">
|
||||
<p className={styles["notice-text"]}>{actionMessage}</p>
|
||||
</Notice>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
);
|
||||
@@ -801,7 +816,7 @@ export function PrivacyPage() {
|
||||
|
||||
if (session.isError) {
|
||||
return (
|
||||
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
|
||||
<Page title="Настройки приватности">
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
onRetry={() => void session.refetch()}
|
||||
@@ -815,14 +830,14 @@ export function PrivacyPage() {
|
||||
if (session.isPending) return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
|
||||
if (session.data?.account.scenario !== "candidate") {
|
||||
return (
|
||||
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
|
||||
<Page title="Настройки приватности">
|
||||
<ForbiddenState title="Настройки доступны только кандидату" />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (privateAccessLost) {
|
||||
return (
|
||||
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
|
||||
<Page title="Настройки приватности">
|
||||
<ForbiddenState
|
||||
title="Доступ к приватным данным потерян"
|
||||
description="Сеанс или права доступа изменились. Приватные данные очищены из текущего экрана; проверьте сессию и откройте страницу снова."
|
||||
@@ -832,7 +847,7 @@ export function PrivacyPage() {
|
||||
}
|
||||
if (settingsQuery.isError) {
|
||||
return (
|
||||
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
|
||||
<Page title="Настройки приватности">
|
||||
<ErrorState
|
||||
error={settingsQuery.error}
|
||||
onRetry={() => void settingsQuery.refetch()}
|
||||
@@ -846,26 +861,38 @@ export function PrivacyPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Настройки приватности"
|
||||
eyebrow="Кабинет кандидата"
|
||||
width="wide"
|
||||
lead="Согласие, публикация карточки, статус поиска и скрытие от компаний - отдельные настройки. Ни одно действие не включает другое автоматически."
|
||||
>
|
||||
{canShowConsentManagement ? (
|
||||
<>
|
||||
<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 ? (
|
||||
<>
|
||||
<Section
|
||||
title="Согласия и настройки приватности"
|
||||
description="Каждое согласие хранится и отзывается отдельно. Выдача или отзыв одного не меняет другие, а C2 не включает публикацию без отдельного сохранения ниже."
|
||||
/>
|
||||
<ConsentManagement key={actorId} hiddenOrganizationIds={hiddenOrganizationIds} />
|
||||
</>
|
||||
) : (
|
||||
<Section
|
||||
title="Согласия и настройки приватности"
|
||||
description="Каждое согласие хранится и отзывается отдельно. Выдача или отзыв одного не меняет другие, а C2 не включает публикацию без отдельного сохранения ниже."
|
||||
/>
|
||||
<ConsentManagement key={actorId} hiddenOrganizationIds={hiddenOrganizationIds} />
|
||||
</>
|
||||
) : (
|
||||
<Section
|
||||
title="Согласия и настройки приватности"
|
||||
description="Очищаем прежнюю приватную историю перед загрузкой текущего аккаунта."
|
||||
>
|
||||
<LoadingState label="Подготавливаем историю согласий..." />
|
||||
</Section>
|
||||
)}
|
||||
description="Очищаем прежнюю приватную историю перед загрузкой текущего аккаунта."
|
||||
>
|
||||
<LoadingState label="Подготавливаем историю согласий..." />
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{c2State === "checking" ? (
|
||||
<Section
|
||||
@@ -900,92 +927,104 @@ export function PrivacyPage() {
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<PublicationControls
|
||||
settings={settings}
|
||||
c2State={c2State}
|
||||
draft={draft ?? publicationDraftFromSettings(settings)}
|
||||
isDirty={draftIsDirty}
|
||||
isStale={draftIsStale}
|
||||
hasUnsupportedFields={hasUnsupportedPublishedFields(settings)}
|
||||
canSave={publicationCanSave}
|
||||
isSaving={publicationIsBusy}
|
||||
message={feedbackScope === "publication" ? actionMessage : null}
|
||||
error={feedbackScope === "publication" ? actionError : null}
|
||||
onDraftChange={(value) => {
|
||||
if (actor) setDraftState({ actorId: actor.account.id, value });
|
||||
}}
|
||||
onSave={() => void savePublication()}
|
||||
onReload={() => void reloadPublicationSettings()}
|
||||
onOpenConsent={openConsentBlock}
|
||||
/>
|
||||
|
||||
<SearchStatusControl
|
||||
settings={settings}
|
||||
isSaving={pendingAction !== null || settingsQuery.isFetching}
|
||||
message={feedbackScope === "search" ? actionMessage : null}
|
||||
error={feedbackScope === "search" ? actionError : null}
|
||||
onSetStatus={(value) => void setSearchStatus(value)}
|
||||
/>
|
||||
|
||||
<Section
|
||||
title="Предварительный просмотр карточки"
|
||||
description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации."
|
||||
>
|
||||
<EmployerCardPreview
|
||||
preview={previewQuery.data}
|
||||
isLoading={previewQuery.isPending || previewQuery.isFetching}
|
||||
error={previewQuery.error}
|
||||
onRetry={() => void previewQuery.refetch()}
|
||||
<div id="privacy-publication" className={styles.anchor}>
|
||||
<PublicationControls
|
||||
settings={settings}
|
||||
c2State={c2State}
|
||||
draft={draft ?? publicationDraftFromSettings(settings)}
|
||||
isDirty={draftIsDirty}
|
||||
isStale={draftIsStale}
|
||||
hasUnsupportedFields={hasUnsupportedPublishedFields(settings)}
|
||||
canSave={publicationCanSave}
|
||||
isSaving={publicationIsBusy}
|
||||
message={feedbackScope === "publication" ? actionMessage : null}
|
||||
error={feedbackScope === "publication" ? actionError : null}
|
||||
onDraftChange={(value) => {
|
||||
if (actor) setDraftState({ actorId: actor.account.id, value });
|
||||
}}
|
||||
onSave={() => void savePublication()}
|
||||
onReload={() => void reloadPublicationSettings()}
|
||||
onOpenConsent={openConsentBlock}
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<OrganizationVisibility
|
||||
accessRecords={accessRecords}
|
||||
accessLoading={accessHistory.isPending}
|
||||
accessError={accessHistory.error}
|
||||
accessHasMore={Boolean(accessHistory.hasNextPage)}
|
||||
accessFetching={accessHistory.isFetchingNextPage}
|
||||
onLoadAccess={() => void accessHistory.fetchNextPage()}
|
||||
hiddenOrganizations={hiddenOrganizations}
|
||||
hiddenLoading={hiddenOrganizationsQuery.isPending}
|
||||
hiddenError={hiddenOrganizationsQuery.error}
|
||||
hiddenHasMore={Boolean(hiddenOrganizationsQuery.hasNextPage)}
|
||||
hiddenFetching={hiddenOrganizationsQuery.isFetchingNextPage}
|
||||
onLoadHidden={() => void hiddenOrganizationsQuery.fetchNextPage()}
|
||||
pendingAction={pendingAction}
|
||||
actionError={feedbackScope === "organization" ? actionError : null}
|
||||
actionMessage={feedbackScope === "organization" ? actionMessage : null}
|
||||
onHide={hideFromOrganization}
|
||||
onUnhide={unhideOrganizationForCandidate}
|
||||
/>
|
||||
<div id="privacy-search" className={styles.anchor}>
|
||||
<SearchStatusControl
|
||||
settings={settings}
|
||||
isSaving={pendingAction !== null || settingsQuery.isFetching}
|
||||
message={feedbackScope === "search" ? actionMessage : null}
|
||||
error={feedbackScope === "search" ? actionError : null}
|
||||
onSetStatus={(value) => void setSearchStatus(value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<PrivacyHistory
|
||||
events={privacyEvents}
|
||||
isLoading={privacyHistory.isPending}
|
||||
error={privacyHistory.error}
|
||||
hasMore={Boolean(privacyHistory.hasNextPage)}
|
||||
isFetching={privacyHistory.isFetchingNextPage}
|
||||
onLoad={() => void privacyHistory.fetchNextPage()}
|
||||
/>
|
||||
<div id="privacy-preview" className={styles.anchor}>
|
||||
<Section
|
||||
title="Предварительный просмотр карточки"
|
||||
description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации."
|
||||
>
|
||||
<EmployerCardPreview
|
||||
preview={previewQuery.data}
|
||||
isLoading={previewQuery.isPending || previewQuery.isFetching}
|
||||
error={previewQuery.error}
|
||||
onRetry={() => void previewQuery.refetch()}
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<CardAccessHistory
|
||||
records={accessRecords}
|
||||
hiddenOrganizationIds={hiddenOrganizationIds}
|
||||
isLoading={accessHistory.isPending}
|
||||
error={accessHistory.error}
|
||||
hasMore={Boolean(accessHistory.hasNextPage)}
|
||||
isFetching={accessHistory.isFetchingNextPage}
|
||||
onLoad={() => void accessHistory.fetchNextPage()}
|
||||
/>
|
||||
<div id="privacy-companies" className={styles.anchor}>
|
||||
<OrganizationVisibility
|
||||
accessRecords={accessRecords}
|
||||
accessLoading={accessHistory.isPending}
|
||||
accessError={accessHistory.error}
|
||||
accessHasMore={Boolean(accessHistory.hasNextPage)}
|
||||
accessFetching={accessHistory.isFetchingNextPage}
|
||||
onLoadAccess={() => void accessHistory.fetchNextPage()}
|
||||
hiddenOrganizations={hiddenOrganizations}
|
||||
hiddenLoading={hiddenOrganizationsQuery.isPending}
|
||||
hiddenError={hiddenOrganizationsQuery.error}
|
||||
hiddenHasMore={Boolean(hiddenOrganizationsQuery.hasNextPage)}
|
||||
hiddenFetching={hiddenOrganizationsQuery.isFetchingNextPage}
|
||||
onLoadHidden={() => void hiddenOrganizationsQuery.fetchNextPage()}
|
||||
pendingAction={pendingAction}
|
||||
actionError={feedbackScope === "organization" ? actionError : null}
|
||||
actionMessage={feedbackScope === "organization" ? actionMessage : null}
|
||||
onHide={hideFromOrganization}
|
||||
onUnhide={unhideOrganizationForCandidate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div id="privacy-history" className={styles.anchor}>
|
||||
<PrivacyHistory
|
||||
events={privacyEvents}
|
||||
isLoading={privacyHistory.isPending}
|
||||
error={privacyHistory.error}
|
||||
hasMore={Boolean(privacyHistory.hasNextPage)}
|
||||
isFetching={privacyHistory.isFetchingNextPage}
|
||||
onLoad={() => void privacyHistory.fetchNextPage()}
|
||||
/>
|
||||
|
||||
<CardAccessHistory
|
||||
records={accessRecords}
|
||||
hiddenOrganizationIds={hiddenOrganizationIds}
|
||||
isLoading={accessHistory.isPending}
|
||||
error={accessHistory.error}
|
||||
hasMore={Boolean(accessHistory.hasNextPage)}
|
||||
isFetching={accessHistory.isFetchingNextPage}
|
||||
onLoad={() => void accessHistory.fetchNextPage()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Section title="Ручная оценка">
|
||||
<p>
|
||||
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
|
||||
автоматическую оценку. Запрос не включает согласие обратно.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,6 @@ export function ProfilePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Профиль"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Управляйте своими сведениями и проверяйте, какие данные подтверждены оценкой."
|
||||
width="wide"
|
||||
>
|
||||
|
||||
@@ -5,7 +5,6 @@ export function QuestionnairePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Анкета"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Укажите специализации и условия поиска. Самооценка не становится подтвержденной категорией."
|
||||
width="wide"
|
||||
>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
.event,
|
||||
.decision {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
@@ -39,17 +39,10 @@
|
||||
.event-heading h3,
|
||||
.decision h3 {
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.card-heading > span {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.case-card p,
|
||||
.event p,
|
||||
.decision p {
|
||||
@@ -65,6 +58,12 @@
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.date,
|
||||
.event-heading time {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.more {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
@@ -104,10 +103,6 @@
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > * {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-1);
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
getMySupportCase,
|
||||
listMySupportCases,
|
||||
} from "../../../shared/api/endpoints/support/support";
|
||||
import type { Session, SupportCase } from "../../../shared/api/schemas";
|
||||
import type { Session, SupportCase, SupportCaseStatus } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
@@ -37,11 +37,23 @@ import {
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
Tag,
|
||||
TextLink,
|
||||
type TagTone,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./support-cases-pages.module.css";
|
||||
|
||||
const supportCasePageSize = 20;
|
||||
|
||||
// The label states the status; the tone only marks the one that waits for the candidate.
|
||||
const supportCaseStatusTones: Readonly<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;
|
||||
|
||||
function isCaseAccessError(error: unknown): error is ApiRequestError {
|
||||
@@ -204,9 +216,7 @@ export function SupportCasesPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Мои обращения"
|
||||
eyebrow={
|
||||
actor.account.scenario === "candidate" ? "Кабинет кандидата" : "Кабинет работодателя"
|
||||
}
|
||||
eyebrow={actor.account.scenario === "candidate" ? undefined : "Кабинет работодателя"}
|
||||
lead="Здесь хранятся обращения этого аккаунта и ответы поддержки."
|
||||
width="wide"
|
||||
>
|
||||
@@ -302,7 +312,9 @@ function SupportCaseSummaryCard({
|
||||
<h3>
|
||||
<TextLink to={href}>{supportCase.number}</TextLink>
|
||||
</h3>
|
||||
<span>{supportCaseStatusLabels[supportCase.status]}</span>
|
||||
<Tag tone={supportCaseStatusTones[supportCase.status]}>
|
||||
{supportCaseStatusLabels[supportCase.status]}
|
||||
</Tag>
|
||||
</div>
|
||||
<p>{supportCaseTypeLabels[supportCase.type]}</p>
|
||||
<p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Ref } from "react";
|
||||
import type { AssessmentResult } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import { TextLink } from "../../../shared/ui";
|
||||
import { Mono, TextLink } from "../../../shared/ui";
|
||||
import { describeAssessmentResult } from "../../../entities/assessment";
|
||||
import styles from "./assessment-history.module.css";
|
||||
|
||||
@@ -23,7 +23,9 @@ export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHi
|
||||
const view = describeAssessmentResult(item, timeZone ? { timeZone } : {});
|
||||
return (
|
||||
<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>
|
||||
<p className={styles.summary}>{view.summary.text}</p>
|
||||
<dl className={styles.facts}>
|
||||
|
||||
@@ -10,22 +10,60 @@
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
/* A timeline: the results hang on a circuit trace, newest first. */
|
||||
.list {
|
||||
position: relative;
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
padding: 0 0 0 var(--space-5);
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.list::before {
|
||||
position: absolute;
|
||||
top: var(--space-5);
|
||||
bottom: var(--space-5);
|
||||
left: 0.25rem;
|
||||
width: var(--line-thin);
|
||||
content: "";
|
||||
background: var(--color-divider);
|
||||
}
|
||||
|
||||
.item {
|
||||
position: relative;
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
transition: border-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.item:hover {
|
||||
border-color: var(--color-border-hover);
|
||||
}
|
||||
|
||||
.item::before {
|
||||
position: absolute;
|
||||
top: var(--space-5);
|
||||
left: calc(-1 * var(--space-5) + 0.25rem - 0.25rem + 0.5px);
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border: var(--line-thin) solid var(--color-accent);
|
||||
border-radius: 50%;
|
||||
content: "";
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.item:first-child::before {
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.item p {
|
||||
@@ -35,6 +73,7 @@
|
||||
|
||||
.kind {
|
||||
color: var(--color-text-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
@@ -42,6 +81,7 @@
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
line-height: var(--line-height-snug);
|
||||
overflow-wrap: anywhere;
|
||||
@@ -76,7 +116,7 @@
|
||||
|
||||
@media (width < 42rem) {
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
isAssessmentAccessLoss,
|
||||
@@ -79,7 +80,14 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (history.isPending) return <LoadingState label="Загружаем историю результатов..." />;
|
||||
if (history.isPending) {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<LoadingState label="Загружаем историю результатов..." />
|
||||
<Skeleton shape="card" lines={3} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (history.isError && !history.data) {
|
||||
return (
|
||||
<ErrorState
|
||||
@@ -128,13 +136,15 @@ export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps
|
||||
onRetry={() => void loadMore()}
|
||||
/>
|
||||
) : history.hasNextPage ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={history.isFetchingNextPage}
|
||||
onClick={() => void loadMore()}
|
||||
>
|
||||
{history.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
<div className={styles.more}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={history.isFetchingNextPage}
|
||||
onClick={() => void loadMore()}
|
||||
>
|
||||
{history.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3,32 +3,55 @@
|
||||
gap: var(--space-6);
|
||||
}
|
||||
|
||||
/* The next step is the one dominant block of the home screen. */
|
||||
/* The next step is the one dominant block of the home screen: a panel with
|
||||
* the circuit trace drawn behind its right half. */
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-strong) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-l);
|
||||
background: var(--color-surface);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.decor {
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
top: 50%;
|
||||
right: calc(-1 * var(--space-6));
|
||||
width: min(28rem, 70%);
|
||||
height: auto;
|
||||
opacity: 0.55;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.decor {
|
||||
top: auto;
|
||||
bottom: calc(-1 * var(--space-6));
|
||||
opacity: 0.3;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.card-eyebrow {
|
||||
color: var(--color-accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-bold);
|
||||
font-weight: var(--font-weight-medium);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-snug);
|
||||
max-width: 36rem;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-title);
|
||||
font-weight: var(--font-weight-medium);
|
||||
letter-spacing: var(--letter-spacing-display);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.card-text {
|
||||
max-width: 44rem;
|
||||
max-width: 40rem;
|
||||
color: var(--color-text);
|
||||
font-size: var(--font-size-m);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
@@ -68,19 +91,26 @@
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.standing,
|
||||
.link {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
transition: border-color var(--duration-fast) var(--easing-standard);
|
||||
}
|
||||
|
||||
.link:hover {
|
||||
border-color: var(--color-border-hover);
|
||||
}
|
||||
|
||||
.standing-title {
|
||||
margin-bottom: var(--space-3);
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.facts {
|
||||
@@ -108,16 +138,10 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.link {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.link-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
color: var(--color-text-strong);
|
||||
font-family: var(--font-mono);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.link-status {
|
||||
|
||||
@@ -11,12 +11,16 @@ import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/ide
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
ButtonLink,
|
||||
Card,
|
||||
CircuitTrace,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Section,
|
||||
Skeleton,
|
||||
Tag,
|
||||
TextLink,
|
||||
TrustLevel,
|
||||
} from "../../../shared/ui";
|
||||
@@ -109,7 +113,8 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) {
|
||||
// produced a result, showing "consents" would contradict the result blocks.
|
||||
const showSavedStep = !journey.hasResults;
|
||||
return (
|
||||
<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>
|
||||
<h2 id="next-step-title" className={styles["card-title"]}>
|
||||
{view.title}
|
||||
@@ -135,7 +140,7 @@ function NextStepCard({ journey }: { journey: CandidateJourney }) {
|
||||
: null}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -155,34 +160,40 @@ function Standings({ journey }: { journey: CandidateJourney }) {
|
||||
) : (
|
||||
<ul className={styles.standings}>
|
||||
{journey.standings.map((standing) => (
|
||||
<li key={standing.specialization} className={styles.standing}>
|
||||
<h3 className={styles["standing-title"]}>
|
||||
{specializationLabels[standing.specialization]}
|
||||
</h3>
|
||||
<dl className={styles.facts}>
|
||||
<dt>Заявлено (самооценка)</dt>
|
||||
<dd>
|
||||
<TrustLevel
|
||||
level="claimed"
|
||||
label={
|
||||
standing.declaredGrade
|
||||
? `Заявлено: ${gradeLabels[standing.declaredGrade]}`
|
||||
: "Уровень не указан"
|
||||
}
|
||||
/>
|
||||
</dd>
|
||||
<dt>Подтвержденная категория</dt>
|
||||
<dd>
|
||||
{standing.confirmedGrade ? (
|
||||
<li key={standing.specialization}>
|
||||
<Card tone="raised" labelledBy={`standing-${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>
|
||||
<dl className={styles.facts}>
|
||||
<dt>Заявлено (самооценка)</dt>
|
||||
<dd>
|
||||
<TrustLevel
|
||||
level="confirmed"
|
||||
label={`Подтверждено тестом: ${gradeLabels[standing.confirmedGrade]}`}
|
||||
level="claimed"
|
||||
label={
|
||||
standing.declaredGrade
|
||||
? `Заявлено: ${gradeLabels[standing.declaredGrade]}`
|
||||
: "Уровень не указан"
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<TrustLevel level="none" label="Пока не подтверждена" />
|
||||
)}
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
<dt>Подтвержденная категория</dt>
|
||||
<dd>
|
||||
{standing.confirmedGrade ? (
|
||||
<TrustLevel
|
||||
level="confirmed"
|
||||
label={`Подтверждено тестом: ${gradeLabels[standing.confirmedGrade]}`}
|
||||
/>
|
||||
) : (
|
||||
<TrustLevel level="none" label="Пока не подтверждена" />
|
||||
)}
|
||||
</dd>
|
||||
</dl>
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -291,7 +302,12 @@ export function CandidateNextStep() {
|
||||
);
|
||||
}
|
||||
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 (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />;
|
||||
|
||||
@@ -100,3 +100,23 @@
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* A strip that hides tabs fades at that edge, so the cut tab reads as "more
|
||||
* to scroll". The fade is a mask, so the strip keeps its own background. */
|
||||
.list[data-fade-end] {
|
||||
mask-image: linear-gradient(to right, #000 calc(100% - 3rem), transparent);
|
||||
}
|
||||
|
||||
.list[data-fade-start] {
|
||||
mask-image: linear-gradient(to left, #000 calc(100% - 3rem), transparent);
|
||||
}
|
||||
|
||||
.list[data-fade-start][data-fade-end] {
|
||||
mask-image: linear-gradient(
|
||||
to right,
|
||||
transparent,
|
||||
#000 3rem,
|
||||
#000 calc(100% - 3rem),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { Outlet, useLocation } from "react-router-dom";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { HeaderPlate, MainRegion, NavItem, SkipLink, Wordmark } from "../../../shared/ui";
|
||||
@@ -13,7 +13,7 @@ const navigation = [
|
||||
{ to: paths.candidate.invitations, label: "Приглашения", end: false },
|
||||
{ to: paths.candidate.notifications, label: "Уведомления", end: false },
|
||||
{ to: paths.candidate.privacy, label: "Приватность", end: false },
|
||||
{ to: paths.support, label: "Поддержка", end: false },
|
||||
{ to: paths.candidate.supportCases, label: "Поддержка", end: false },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
@@ -35,6 +35,38 @@ function useCurrentTabInView() {
|
||||
return listRef;
|
||||
}
|
||||
|
||||
type ScrollEdges = { start: boolean; end: boolean };
|
||||
|
||||
/**
|
||||
* Whether the tab strip hides tabs before or after the visible part. The
|
||||
* shell fades that edge, so a cut tab reads as "scroll for more".
|
||||
*/
|
||||
function useScrollEdges(listRef: RefObject<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
|
||||
* section tabs form a bar at the bottom of the screen, within thumb reach;
|
||||
@@ -43,6 +75,7 @@ function useCurrentTabInView() {
|
||||
*/
|
||||
export function CandidateShell() {
|
||||
const listRef = useCurrentTabInView();
|
||||
const edges = useScrollEdges(listRef);
|
||||
|
||||
return (
|
||||
<div className={styles.shell}>
|
||||
@@ -51,7 +84,12 @@ export function CandidateShell() {
|
||||
<HeaderPlate className={styles.plate}>
|
||||
<Wordmark to={paths.candidate.root} context="Кабинет кандидата" />
|
||||
<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) => (
|
||||
<li key={item.to}>
|
||||
<NavItem to={item.to} end={item.end}>
|
||||
|
||||
Reference in new issue
Block a user