feat(frontend): keep focus, field errors and unsent answers on the minimal path
This commit is contained in:
1 parent
d4903a3796
commit
c94434cd09
12 files changed
+1174
-18
No files matched your search
@@ -185,7 +185,7 @@ function isInvitationCommand(request: Request): boolean {
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||||
for (const width of [360, 1280]) {
|
||||
for (const width of [360, 768, 1280]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||||
|
||||
@@ -0,0 +1,734 @@
|
||||
import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
|
||||
|
||||
// States, focus, and error binding of the minimal path with a stubbed API. The
|
||||
// API answers come from this file, so each test controls one failure at a time
|
||||
// and needs no fixtures on the stand. Every screen is checked at 360, 768, and
|
||||
// 1280 px: the stubbed content must fit without horizontal scrolling, and each
|
||||
// control is reached with the Tab key and shows a focus outline.
|
||||
//
|
||||
// The last describe block runs against the real backend: it registers a
|
||||
// candidate through the local mail fixture and checks the unsent assessment
|
||||
// answer after a reload. The registration helpers are copies of the ones in
|
||||
// assessment.spec.ts. See docs/en/TESTING.md, "Minimal path states and
|
||||
// accessibility", for what each part proves.
|
||||
|
||||
const widths = [360, 768, 1280] as const;
|
||||
const accountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4001";
|
||||
const invitationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4101";
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4201";
|
||||
const csrfToken = "A".repeat(43);
|
||||
const openDeadline = "2099-10-16T10:00:00Z";
|
||||
|
||||
test.use({ trace: "off", screenshot: "off", video: "off" });
|
||||
|
||||
type Answer = { status: number; body?: unknown; code?: string } | "abort";
|
||||
type Responder = Answer | ((call: number, request: Request) => Answer | Promise<Answer>);
|
||||
// Keys are "METHOD /api/v1/path". Each responder sees the number of its calls.
|
||||
type Routes = Record<string, Responder>;
|
||||
|
||||
function candidateSession() {
|
||||
return {
|
||||
account: {
|
||||
id: accountId,
|
||||
email: "candidate@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: csrfToken,
|
||||
};
|
||||
}
|
||||
|
||||
function problem(code: string, status: number): Answer {
|
||||
return { status, code };
|
||||
}
|
||||
|
||||
const candidateTerms = {
|
||||
role_title: "Middle Go-разработчик в команду платежей",
|
||||
specialization: "backend",
|
||||
grade: "middle",
|
||||
offer_type: "full_time",
|
||||
tasks: ["Развивать сервис выплат", "Перевести отчеты на события"],
|
||||
team: "Пять бэкенд-разработчиков\nи QA-инженер",
|
||||
tech_stack: ["Go", "PostgreSQL"],
|
||||
work_formats: ["remote", "hybrid"],
|
||||
location: "Москва",
|
||||
communication_method: { channel: "video_call", details: "Созвон с тимлидом" },
|
||||
salary: {
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
},
|
||||
package: {
|
||||
bonus: { status: "provided", description: "Квартальная премия до 20%" },
|
||||
equipment: { status: "provided", description: "Ноутбук и монитор" },
|
||||
training: { status: "not_provided" },
|
||||
health_insurance: { status: "not_provided" },
|
||||
},
|
||||
};
|
||||
|
||||
function candidateInvitation(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: invitationId,
|
||||
organization: { id: organizationId, name: "Северный ветер" },
|
||||
state: "delivered",
|
||||
expiry_reason: null,
|
||||
version: 1,
|
||||
terms_version: 1,
|
||||
terms: candidateTerms,
|
||||
response_deadline_at: openDeadline,
|
||||
delivered_at: "2026-10-09T10:00:00Z",
|
||||
viewed_at: null,
|
||||
responded_at: null,
|
||||
updated_at: "2026-10-09T10:00:00Z",
|
||||
contact_consent: null,
|
||||
decline: null,
|
||||
contact_grant: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function inboxItem() {
|
||||
const invitation = candidateInvitation();
|
||||
return {
|
||||
id: invitation.id,
|
||||
organization: invitation.organization,
|
||||
state: invitation.state,
|
||||
expiry_reason: null,
|
||||
version: 1,
|
||||
terms_version: 1,
|
||||
role_title: candidateTerms.role_title,
|
||||
salary: candidateTerms.salary,
|
||||
work_formats: candidateTerms.work_formats,
|
||||
response_deadline_at: openDeadline,
|
||||
delivered_at: invitation.delivered_at,
|
||||
viewed_at: null,
|
||||
updated_at: invitation.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve: (value: T) => void = () => undefined;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
// Answers every /api/v1 request from the routes; an unknown request is a 404
|
||||
// problem, so a missing stub shows up as a failed state instead of a hang.
|
||||
async function mockApi(page: Page, routes: Routes): Promise<Map<string, number>> {
|
||||
const calls = new Map<string, number>();
|
||||
await page.route("**/api/v1/**", async (route: Route) => {
|
||||
const request = route.request();
|
||||
const { pathname } = new URL(request.url());
|
||||
const key = `${request.method()} ${pathname}`;
|
||||
const count = (calls.get(key) ?? 0) + 1;
|
||||
calls.set(key, count);
|
||||
const responder = routes[key];
|
||||
const answer: Answer =
|
||||
responder === undefined
|
||||
? problem("not_found", 404)
|
||||
: typeof responder === "function"
|
||||
? await responder(count, request)
|
||||
: responder;
|
||||
if (answer === "abort") {
|
||||
await route.abort("failed");
|
||||
return;
|
||||
}
|
||||
if (answer.status >= 400) {
|
||||
await route.fulfill({
|
||||
status: answer.status,
|
||||
contentType: "application/problem+json",
|
||||
body: JSON.stringify({
|
||||
type: `urn:lincodex:problem:${answer.code ?? "error"}`,
|
||||
title: answer.code ?? "error",
|
||||
status: answer.status,
|
||||
code: answer.code ?? "error",
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: answer.status,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(answer.body ?? null),
|
||||
});
|
||||
});
|
||||
return calls;
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page, width: number): Promise<void> {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||||
);
|
||||
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
|
||||
}
|
||||
|
||||
// The focus outline comes from the global :focus-visible rule. A control that
|
||||
// has focus from the keyboard must match that selector and draw an outline.
|
||||
async function expectFocusOutline(target: Locator): Promise<void> {
|
||||
const style = await target.evaluate((element) => {
|
||||
const computed = getComputedStyle(element);
|
||||
return {
|
||||
focusVisible: element.matches(":focus-visible"),
|
||||
outlineStyle: computed.outlineStyle,
|
||||
outlineWidth: Number.parseFloat(computed.outlineWidth),
|
||||
};
|
||||
});
|
||||
expect(style.focusVisible, "the control matches :focus-visible").toBe(true);
|
||||
expect(style.outlineStyle, "the focus outline is drawn").not.toBe("none");
|
||||
expect(style.outlineWidth, "the focus outline has a width").toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
// Moves focus to the target with Tab from the top of the document, as a
|
||||
// keyboard user does, and checks that the target shows its focus outline.
|
||||
async function tabTo(page: Page, target: Locator, maxSteps = 80): Promise<void> {
|
||||
await expect(target).toBeVisible();
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
for (let step = 0; step < maxSteps; step += 1) {
|
||||
await page.keyboard.press("Tab");
|
||||
if (await target.evaluate((element) => element === document.activeElement)) {
|
||||
await expectFocusOutline(target);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("Keyboard navigation did not reach the target control.");
|
||||
}
|
||||
|
||||
test.describe("minimal path states with a stubbed API", () => {
|
||||
for (const width of widths) {
|
||||
test(`sign-in at ${width}px: bound field errors and failed answers keep the typed email`, async ({
|
||||
page,
|
||||
}) => {
|
||||
let answers = 0;
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": problem("unauthenticated", 401),
|
||||
"POST /api/v1/identity/sessions": () => {
|
||||
answers += 1;
|
||||
return answers === 1
|
||||
? problem("internal_error", 500)
|
||||
: problem("invalid_credentials", 401);
|
||||
},
|
||||
});
|
||||
await page.goto("/login");
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Вход" })).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
|
||||
const email = page.getByLabel("Электронная почта");
|
||||
const password = page.getByLabel("Пароль", { exact: true });
|
||||
const submit = page.locator('button[type="submit"]');
|
||||
|
||||
// An empty submit binds each message to its field and marks it invalid.
|
||||
await tabTo(page, submit);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(email).toHaveAttribute("aria-invalid", "true");
|
||||
await expect(email).toHaveAccessibleDescription(
|
||||
"Введите корректный адрес электронной почты.",
|
||||
);
|
||||
await expect(password).toHaveAttribute("aria-invalid", "true");
|
||||
await expect(password).toHaveAccessibleDescription("Введите пароль.");
|
||||
|
||||
// A server failure is an alert; the typed email stays in place.
|
||||
await tabTo(page, email);
|
||||
await page.keyboard.type("candidate@example.test");
|
||||
await tabTo(page, password);
|
||||
await page.keyboard.type("correct horse battery staple 2026");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("alert")).toHaveText(
|
||||
"Не удалось выполнить вход. Проверьте соединение и повторите попытку.",
|
||||
);
|
||||
await expect(email).toHaveValue("candidate@example.test");
|
||||
await expect(email).not.toHaveAttribute("aria-invalid", "true");
|
||||
await expect(password).toBeFocused();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
|
||||
// A second answer with invalid credentials is a different alert.
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("alert")).toHaveText(
|
||||
"Не удалось войти. Проверьте адрес и пароль.",
|
||||
);
|
||||
await expect(email).toHaveValue("candidate@example.test");
|
||||
await expect(submit).toHaveText("Войти");
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
|
||||
test(`sign-in at ${width}px: a pending answer keeps the focus in the form and reads as busy`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const release = deferred<Answer>();
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": problem("unauthenticated", 401),
|
||||
"POST /api/v1/identity/sessions": () => release.promise,
|
||||
});
|
||||
await page.goto("/login");
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
const email = page.getByLabel("Электронная почта");
|
||||
const password = page.getByLabel("Пароль", { exact: true });
|
||||
const submit = page.locator('button[type="submit"]');
|
||||
await tabTo(page, email);
|
||||
await page.keyboard.type("candidate@example.test");
|
||||
await tabTo(page, password);
|
||||
await page.keyboard.type("correct horse battery staple 2026");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(submit).toHaveText("Входим...");
|
||||
await expect(submit).toHaveAttribute("aria-busy", "true");
|
||||
await expect(
|
||||
page.getByRole("status").filter({ hasText: "Проверяем учетные данные" }),
|
||||
).toBeVisible();
|
||||
// A read-only field keeps the keyboard focus while the answer is pending.
|
||||
await expect(password).toBeFocused();
|
||||
await expect(password).toHaveAttribute("readonly", "");
|
||||
release.resolve(problem("invalid_credentials", 401));
|
||||
await expect(page.getByRole("alert")).toHaveText(
|
||||
"Не удалось войти. Проверьте адрес и пароль.",
|
||||
);
|
||||
await expect(submit).toHaveText("Войти");
|
||||
await expect(password).not.toHaveAttribute("readonly");
|
||||
});
|
||||
|
||||
test(`candidate inbox at ${width}px: loading, error with a keyboard retry, empty, and forbidden`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const gate = deferred<void>();
|
||||
let failing = true;
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/invitations": async () => {
|
||||
await gate.promise;
|
||||
return failing
|
||||
? problem("internal_error", 500)
|
||||
: { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } };
|
||||
},
|
||||
});
|
||||
await page.goto("/candidate/invitations");
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
await expect(page.getByText("Загружаем приглашения...")).toBeVisible();
|
||||
gate.resolve();
|
||||
|
||||
// Queries retry server errors twice, so the error appears after the retries.
|
||||
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", {
|
||||
timeout: 15_000,
|
||||
});
|
||||
failing = false;
|
||||
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("Приглашений пока нет")).toBeVisible();
|
||||
await expect(page.getByRole("alert")).toHaveCount(0);
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
|
||||
test(`candidate inbox at ${width}px: a dropped connection is named and can be retried`, async ({
|
||||
page,
|
||||
}) => {
|
||||
let online = false;
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/invitations": () =>
|
||||
online
|
||||
? { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } }
|
||||
: "abort",
|
||||
});
|
||||
await page.goto("/candidate/invitations");
|
||||
// A network error is retried like a server error, so the message follows the retries.
|
||||
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", {
|
||||
timeout: 15_000,
|
||||
});
|
||||
await expect(page.getByRole("alert")).toContainText("Проверьте подключение к интернету");
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
online = true;
|
||||
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("Приглашений пока нет")).toBeVisible();
|
||||
});
|
||||
|
||||
test(`candidate inbox at ${width}px: a forbidden answer shows no retry`, async ({ page }) => {
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/invitations": problem("forbidden", 403),
|
||||
});
|
||||
await page.goto("/candidate/invitations");
|
||||
await expect(page.getByText("Нет доступа")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
|
||||
test(`candidate inbox at ${width}px: an invitation card names the company, the role, and the state in text`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/invitations": {
|
||||
status: 200,
|
||||
body: { items: [inboxItem()], page: { has_more: false, next_cursor: null } },
|
||||
},
|
||||
});
|
||||
await page.goto("/candidate/invitations");
|
||||
const list = page.getByRole("region", { name: "Список приглашений" });
|
||||
await expect(list).toBeVisible();
|
||||
await expect(list).toContainText("Северный ветер");
|
||||
await expect(list).toContainText("Middle Go-разработчик в команду платежей");
|
||||
await expect(list).toContainText("Ждет вашего решения");
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
await tabTo(page, list.getByRole("link").first());
|
||||
});
|
||||
|
||||
test(`candidate invitation at ${width}px: an error with a retry, then a failed decline keeps the comment`, async ({
|
||||
page,
|
||||
}) => {
|
||||
let failing = true;
|
||||
let declines = 0;
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
[`GET /api/v1/me/invitations/${invitationId}`]: () =>
|
||||
failing ? problem("internal_error", 500) : { status: 200, body: candidateInvitation() },
|
||||
[`POST /api/v1/me/invitations/${invitationId}/view`]: {
|
||||
status: 200,
|
||||
body: candidateInvitation({ state: "viewed", viewed_at: "2026-10-09T10:05:00Z" }),
|
||||
},
|
||||
[`POST /api/v1/me/invitations/${invitationId}/decline`]: () => {
|
||||
declines += 1;
|
||||
if (declines === 1) return problem("internal_error", 500);
|
||||
return {
|
||||
status: 200,
|
||||
body: candidateInvitation({
|
||||
state: "declined",
|
||||
version: 2,
|
||||
responded_at: "2026-10-09T10:06:00Z",
|
||||
decline: {
|
||||
reason: "salary",
|
||||
comment: "Ждали вилку выше.",
|
||||
declined_at: "2026-10-09T10:06:00Z",
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
await page.goto(`/candidate/invitations/${invitationId}`);
|
||||
await expect(page.getByRole("alert")).toContainText("Не удалось открыть приглашение", {
|
||||
timeout: 15_000,
|
||||
});
|
||||
failing = false;
|
||||
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Приглашение" })).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
|
||||
await tabTo(page, page.getByLabel("Вилка зарплаты не подходит"));
|
||||
await page.keyboard.press("Space");
|
||||
const comment = page.getByLabel("Комментарий (необязательно)");
|
||||
await tabTo(page, comment);
|
||||
await page.keyboard.type("Ждали вилку выше.");
|
||||
const decline = page.getByRole("button", { name: "Отклонить приглашение" });
|
||||
await tabTo(page, decline);
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
const alert = page.getByRole("alert");
|
||||
await expect(alert).toBeVisible();
|
||||
await expect(alert).toBeFocused();
|
||||
await expect(comment).toHaveValue("Ждали вилку выше.");
|
||||
await expect(page.getByLabel("Вилка зарплаты не подходит")).toBeChecked();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
|
||||
await tabTo(page, decline);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("Вы отклонили приглашение").first()).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Отклонить приглашение" })).toHaveCount(0);
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
|
||||
test(`assessment availability at ${width}px: an error with a retry, then the empty specialization state`, async ({
|
||||
page,
|
||||
}) => {
|
||||
let failing = true;
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/assessment-availability": () =>
|
||||
failing ? problem("internal_error", 500) : { status: 200, body: { specializations: [] } },
|
||||
"GET /api/v1/me/questionnaire": {
|
||||
status: 200,
|
||||
body: { version: 0, specializations: [], work_context: null, updated_at: null },
|
||||
},
|
||||
});
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("alert")).toContainText(
|
||||
"Не удалось загрузить состояние проверки",
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
failing = false;
|
||||
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("Сначала выберите специализацию")).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "Открыть анкету" })).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
|
||||
test(`candidate profile at ${width}px: loading, an error with a retry, and access denied`, async ({
|
||||
page,
|
||||
}) => {
|
||||
// The profile query does not retry, so the state changes only when the
|
||||
// candidate presses the retry button: the second answer is a 403.
|
||||
const release = deferred<void>();
|
||||
let stage: "error" | "forbidden" = "error";
|
||||
await mockApi(page, {
|
||||
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
|
||||
"GET /api/v1/me/profile": async () => {
|
||||
await release.promise;
|
||||
return stage === "error" ? problem("internal_error", 500) : problem("forbidden", 403);
|
||||
},
|
||||
});
|
||||
await page.goto("/candidate/profile");
|
||||
await expect(page.getByText("Загружаем профиль кандидата...")).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
release.resolve();
|
||||
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить профиль");
|
||||
stage = "forbidden";
|
||||
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByText("Профиль недоступен")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
|
||||
await expectNoHorizontalOverflow(page, width);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Real-backend part. It needs the mail fixture for registration and the
|
||||
// questionnaire fixture for a reviewed assessment bank, so it runs only in
|
||||
// `make -C deploy test-e2e-registration`, like the assessment specs.
|
||||
|
||||
type InboxMessage = { text?: string; html?: string };
|
||||
type InboxResponse = { messages: InboxMessage[] };
|
||||
type AttemptSnapshot = { id: string; version: number; current_item: { id: string } | null };
|
||||
|
||||
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
||||
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
|
||||
const password = "correct horse battery staple 2026";
|
||||
const draftKeyPrefix = "lincodex.assessment-answer-draft.v1:";
|
||||
|
||||
function baseUrl(): string {
|
||||
const value = process.env.E2E_BASE_URL;
|
||||
if (!value) throw new Error("The local end-to-end base URL is not configured.");
|
||||
return value;
|
||||
}
|
||||
|
||||
async function readInbox(email: string): Promise<InboxMessage[]> {
|
||||
const inboxUrl = process.env.E2E_MAILBOX_URL;
|
||||
const token = process.env.E2E_MAILBOX_TOKEN;
|
||||
if (!inboxUrl || !token)
|
||||
throw new Error("The local registration mailbox fixture is not configured.");
|
||||
const url = new URL(inboxUrl);
|
||||
url.searchParams.set("to", email);
|
||||
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
|
||||
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
|
||||
return ((await response.json()) as InboxResponse).messages;
|
||||
}
|
||||
|
||||
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
const message = (await readInbox(email)).at(-1);
|
||||
if (message) return message;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
throw new Error("The local registration mailbox did not receive the verification message.");
|
||||
}
|
||||
|
||||
function verificationToken(message: InboxMessage): string {
|
||||
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
|
||||
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
|
||||
if (!token) throw new Error("The local registration message had no verification link.");
|
||||
return token;
|
||||
}
|
||||
|
||||
async function registerVerifiedCandidate(page: Page): Promise<string> {
|
||||
const email = `assessment-${crypto.randomUUID()}@example.test`;
|
||||
await page.goto("/register");
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(/C4/)).toHaveCount(0);
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
await page.getByRole("radio", { name: /Кандидат/ }).check();
|
||||
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
||||
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
||||
|
||||
const message = await waitForVerificationMessage(email);
|
||||
const verificationUrl = new URL("/verify-email", baseUrl());
|
||||
verificationUrl.hash = `token=${verificationToken(message)}`;
|
||||
await page.goto(verificationUrl.toString());
|
||||
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
|
||||
await expect.poll(() => page.evaluate(() => window.location.hash)).toBe("");
|
||||
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
|
||||
const confirmResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/identity/email-verifications",
|
||||
);
|
||||
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
||||
expect((await confirmResponse).status()).toBe(200);
|
||||
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
||||
|
||||
await page.goto("/candidate/questionnaire");
|
||||
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
const loginResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/identity/sessions",
|
||||
);
|
||||
await page.getByRole("button", { name: "Войти" }).click();
|
||||
expect((await loginResponse).status()).toBe(201);
|
||||
return email;
|
||||
}
|
||||
|
||||
async function grantC3(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/privacy");
|
||||
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
|
||||
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
new URL(item.url()).pathname === "/api/v1/me/consents/c3",
|
||||
);
|
||||
await page.getByRole("button", { name: "Дать согласие C3" }).click();
|
||||
expect((await response).status()).toBe(200);
|
||||
}
|
||||
|
||||
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/questionnaire");
|
||||
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("junior");
|
||||
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
new URL(item.url()).pathname === "/api/v1/me/questionnaire",
|
||||
);
|
||||
await page.getByRole("button", { name: "Сохранить анкету" }).click();
|
||||
expect((await response).status()).toBe(200);
|
||||
}
|
||||
|
||||
// Waits for the control, then walks the Tab order to it with the keyboard and
|
||||
// checks its focus outline. The control can appear after a save, so the wait is
|
||||
// longer than the default expectation on a loaded stand.
|
||||
async function focusWithKeyboard(page: Page, target: Locator): Promise<void> {
|
||||
await expect(target).toBeVisible({ timeout: 20_000 });
|
||||
await tabTo(page, target, 120);
|
||||
}
|
||||
|
||||
test.describe("minimal path with the real backend", () => {
|
||||
test.skip(
|
||||
!mailFixtureEnabled || !questionnaireFixtureEnabled,
|
||||
"Requires the isolated reviewed assessment-bank and mail fixtures.",
|
||||
);
|
||||
|
||||
test("an unsent answer on a phone survives a reload, and an accepted answer clears it", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 360, height: 800 });
|
||||
await registerVerifiedCandidate(page);
|
||||
await grantC3(page);
|
||||
await saveAssessmentQuestionnaire(page);
|
||||
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible();
|
||||
await page.getByLabel("Язык задания").selectOption("python");
|
||||
const createResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
|
||||
);
|
||||
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать полную проверку" }));
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("dialog", { name: /какие сигналы собираются/ })).toBeVisible();
|
||||
await focusWithKeyboard(
|
||||
page,
|
||||
page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }),
|
||||
);
|
||||
await page.keyboard.press("Enter");
|
||||
const createResponse = await createResponsePromise;
|
||||
expect(createResponse.status()).toBe(201);
|
||||
const attempt = (await createResponse.json()) as AttemptSnapshot;
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`));
|
||||
|
||||
const startPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${attempt.id}/sessions`,
|
||||
);
|
||||
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await startPromise).status()).toBe(200);
|
||||
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
|
||||
|
||||
// The typed answer is not sent: the candidate reloads before submitting it.
|
||||
const answer = page.getByRole("textbox", { name: /^Числовой ответ/ });
|
||||
await focusWithKeyboard(page, answer);
|
||||
await page.keyboard.type("42");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(
|
||||
(prefix) =>
|
||||
Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length,
|
||||
draftKeyPrefix,
|
||||
),
|
||||
)
|
||||
.toBe(1);
|
||||
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
|
||||
|
||||
const reloadPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}`,
|
||||
);
|
||||
await page.reload();
|
||||
expect((await reloadPromise).status()).toBe(200);
|
||||
const resumePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${attempt.id}/sessions`,
|
||||
);
|
||||
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" }));
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await resumePromise).status()).toBe(200);
|
||||
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
|
||||
await expect(page.getByRole("textbox", { name: /^Числовой ответ/ })).toHaveValue("42");
|
||||
await expectNoHorizontalOverflow(page, 768);
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
|
||||
// An accepted answer moves to the next item and removes the stored draft.
|
||||
const answerPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/answers`,
|
||||
);
|
||||
await focusWithKeyboard(page, page.getByRole("button", { name: "Отправить ответ" }));
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await answerPromise).status()).toBe(200);
|
||||
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(
|
||||
(prefix) =>
|
||||
Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length,
|
||||
draftKeyPrefix,
|
||||
),
|
||||
)
|
||||
.toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
export { AnswerForm } from "./ui/answer-form";
|
||||
export { buildAnswerSubmission, emptyAnswerDraft, newIdempotencyKey } from "./model/answer-draft";
|
||||
export { submitPendingAnswerCommand } from "./model/answer-command";
|
||||
export { clearAnswerDraft } from "./model/answer-draft-store";
|
||||
export type { AnswerDraft, AnswerBuildResult } from "./model/answer-draft";
|
||||
export type { AnswerCommandOutcome, PendingAnswerCommand } from "./model/answer-command";
|
||||
@@ -0,0 +1,191 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AssessmentItem } from "../../../shared/api/schemas";
|
||||
import type { AnswerDraft } from "./answer-draft";
|
||||
import {
|
||||
clearAnswerDraft,
|
||||
maxStoredDraftLength,
|
||||
restoredAnswerDraft,
|
||||
saveAnswerDraft,
|
||||
} from "./answer-draft-store";
|
||||
|
||||
const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01";
|
||||
const itemId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02";
|
||||
|
||||
const stringItem = {
|
||||
id: itemId,
|
||||
sequence: 1,
|
||||
prompt: "Назовите протокол",
|
||||
content: { format: "string", max_length: 64 },
|
||||
} satisfies AssessmentItem;
|
||||
|
||||
const orderItem = {
|
||||
id: itemId,
|
||||
sequence: 1,
|
||||
prompt: "Расставьте шаги",
|
||||
content: {
|
||||
format: "order",
|
||||
elements: [
|
||||
{ id: "a", text: "Первый" },
|
||||
{ id: "b", text: "Второй" },
|
||||
],
|
||||
},
|
||||
} satisfies AssessmentItem;
|
||||
|
||||
const practiceItem = {
|
||||
id: itemId,
|
||||
sequence: 1,
|
||||
prompt: "Решите задачу",
|
||||
content: {
|
||||
format: "practice",
|
||||
languages: ["python", "go"],
|
||||
public_examples: [],
|
||||
max_source_length: 4096,
|
||||
},
|
||||
} satisfies AssessmentItem;
|
||||
|
||||
// A minimal in-memory sessionStorage; its methods can be made to throw.
|
||||
function fakeSessionStorage() {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
values,
|
||||
failWrites: false,
|
||||
failReads: false,
|
||||
getItem(key: string) {
|
||||
if (this.failReads) throw new Error("blocked");
|
||||
return values.get(key) ?? null;
|
||||
},
|
||||
setItem(key: string, value: string) {
|
||||
if (this.failWrites) throw new Error("quota");
|
||||
values.set(key, value);
|
||||
},
|
||||
removeItem(key: string) {
|
||||
values.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function useStorage(store: ReturnType<typeof fakeSessionStorage>) {
|
||||
vi.stubGlobal("window", { sessionStorage: store });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("answer draft store", () => {
|
||||
it("restores an unsent string answer for the same attempt and item", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
const draft: AnswerDraft = { format: "string", value: "HTTP/2" };
|
||||
|
||||
saveAnswerDraft(attemptId, itemId, draft);
|
||||
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual(draft);
|
||||
});
|
||||
|
||||
it("keeps drafts of other attempts and items apart", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
saveAnswerDraft(attemptId, itemId, { format: "string", value: "HTTP/2" });
|
||||
|
||||
expect(restoredAnswerDraft("01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d09", stringItem)).toEqual({
|
||||
format: "string",
|
||||
value: "",
|
||||
});
|
||||
expect(
|
||||
restoredAnswerDraft(attemptId, { ...stringItem, id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03" }),
|
||||
).toEqual({ format: "string", value: "" });
|
||||
});
|
||||
|
||||
it("ignores a stored value that does not fit the item format", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
saveAnswerDraft(attemptId, itemId, { format: "choice", optionIds: ["a"] });
|
||||
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" });
|
||||
});
|
||||
|
||||
it("ignores malformed JSON and an order that is not a permutation of the elements", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
store.setItem(`lincodex.assessment-answer-draft.v1:${attemptId}:${itemId}`, "{not json");
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" });
|
||||
|
||||
saveAnswerDraft(attemptId, itemId, { format: "order", elementIds: ["a", "a"] });
|
||||
expect(restoredAnswerDraft(attemptId, orderItem)).toEqual({
|
||||
format: "order",
|
||||
elementIds: ["a", "b"],
|
||||
});
|
||||
});
|
||||
|
||||
it("restores a practice language only when the item offers it", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
saveAnswerDraft(attemptId, itemId, {
|
||||
format: "practice",
|
||||
language: "go",
|
||||
sourceCode: "package main",
|
||||
});
|
||||
expect(restoredAnswerDraft(attemptId, practiceItem)).toEqual({
|
||||
format: "practice",
|
||||
language: "go",
|
||||
sourceCode: "package main",
|
||||
});
|
||||
|
||||
saveAnswerDraft(attemptId, itemId, {
|
||||
format: "practice",
|
||||
language: "rust" as "go",
|
||||
sourceCode: "fn main() {}",
|
||||
});
|
||||
// The fallback is the empty draft of the item, whose language is its first one.
|
||||
expect(restoredAnswerDraft(attemptId, practiceItem)).toEqual({
|
||||
format: "practice",
|
||||
language: "python",
|
||||
sourceCode: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("removes a stored draft once the answer is accepted", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
saveAnswerDraft(attemptId, itemId, { format: "string", value: "HTTP/2" });
|
||||
|
||||
clearAnswerDraft(attemptId, itemId);
|
||||
|
||||
expect(store.values.size).toBe(0);
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" });
|
||||
});
|
||||
|
||||
it("does not store a draft larger than the limit and drops an older copy", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
saveAnswerDraft(attemptId, itemId, { format: "string", value: "short" });
|
||||
|
||||
saveAnswerDraft(attemptId, itemId, {
|
||||
format: "string",
|
||||
value: "x".repeat(maxStoredDraftLength),
|
||||
});
|
||||
|
||||
expect(store.values.size).toBe(0);
|
||||
});
|
||||
|
||||
it("never throws when storage is blocked or full, and falls back to an empty answer", () => {
|
||||
const store = fakeSessionStorage();
|
||||
useStorage(store);
|
||||
store.failWrites = true;
|
||||
store.failReads = true;
|
||||
|
||||
expect(() =>
|
||||
saveAnswerDraft(attemptId, itemId, { format: "string", value: "a" }),
|
||||
).not.toThrow();
|
||||
expect(() => clearAnswerDraft(attemptId, itemId)).not.toThrow();
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" });
|
||||
});
|
||||
|
||||
it("works without any browser storage, for example outside a window", () => {
|
||||
expect(() =>
|
||||
saveAnswerDraft(attemptId, itemId, { format: "string", value: "a" }),
|
||||
).not.toThrow();
|
||||
expect(restoredAnswerDraft(attemptId, stringItem)).toEqual({ format: "string", value: "" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { AssessmentItem } from "../../../shared/api/schemas";
|
||||
import { emptyAnswerDraft, type AnswerDraft } from "./answer-draft";
|
||||
|
||||
// An unsent answer is kept in this tab's sessionStorage, so a reload restores
|
||||
// what the candidate typed. The server never reads this copy. An accepted
|
||||
// answer removes it, and the attempt itself comes from the server after a
|
||||
// reload. Storage can be blocked or full, so every access is guarded and the
|
||||
// form works without it.
|
||||
|
||||
const keyPrefix = "lincodex.assessment-answer-draft.v1";
|
||||
|
||||
/** Drafts whose JSON is longer than this stay in the form state only. */
|
||||
export const maxStoredDraftLength = 64 * 1024;
|
||||
|
||||
function draftKey(attemptId: string, itemId: string): string {
|
||||
return `${keyPrefix}:${attemptId}:${itemId}`;
|
||||
}
|
||||
|
||||
function sessionStore(): Storage | null {
|
||||
try {
|
||||
return window.sessionStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the unsent answer of one item of one attempt; a failed write is ignored. */
|
||||
export function saveAnswerDraft(attemptId: string, itemId: string, draft: AnswerDraft): void {
|
||||
const store = sessionStore();
|
||||
if (!store) return;
|
||||
const key = draftKey(attemptId, itemId);
|
||||
try {
|
||||
const value = JSON.stringify(draft);
|
||||
if (value.length > maxStoredDraftLength) {
|
||||
store.removeItem(key);
|
||||
} else {
|
||||
store.setItem(key, value);
|
||||
}
|
||||
} catch {
|
||||
// A full or blocked store leaves the draft in the form state only.
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes the stored draft once the server has accepted the answer. */
|
||||
export function clearAnswerDraft(attemptId: string, itemId: string): void {
|
||||
try {
|
||||
sessionStore()?.removeItem(draftKey(attemptId, itemId));
|
||||
} catch {
|
||||
// Nothing to clear when storage is blocked.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft an item's form starts with: the stored one when it fits the item
|
||||
* exactly, otherwise the empty draft. The server still validates the answer on
|
||||
* submit, so a stored value only has to be safe to render.
|
||||
*/
|
||||
export function restoredAnswerDraft(attemptId: string, item: AssessmentItem): AnswerDraft {
|
||||
const fallback = emptyAnswerDraft(item);
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = sessionStore()?.getItem(draftKey(attemptId, item.id)) ?? null;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
if (raw === null) return fallback;
|
||||
return parseStoredDraft(raw, item) ?? fallback;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
||||
}
|
||||
|
||||
function parseStoredDraft(raw: string, item: AssessmentItem): AnswerDraft | null {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!isRecord(value) || value.format !== item.content.format) return null;
|
||||
const content = item.content;
|
||||
|
||||
switch (content.format) {
|
||||
case "choice": {
|
||||
const known = new Set(content.options.map((option) => option.id));
|
||||
if (!isStringArray(value.optionIds) || !value.optionIds.every((id) => known.has(id))) {
|
||||
return null;
|
||||
}
|
||||
return { format: "choice", optionIds: [...value.optionIds] };
|
||||
}
|
||||
case "number":
|
||||
return typeof value.value === "string" ? { format: "number", value: value.value } : null;
|
||||
case "string":
|
||||
return typeof value.value === "string" ? { format: "string", value: value.value } : null;
|
||||
case "configuration":
|
||||
return typeof value.value === "string"
|
||||
? { format: "configuration", value: value.value }
|
||||
: null;
|
||||
case "order": {
|
||||
const stored = value.elementIds;
|
||||
const ids = content.elements.map((element) => element.id);
|
||||
if (
|
||||
!isStringArray(stored) ||
|
||||
stored.length !== ids.length ||
|
||||
!ids.every((id) => stored.includes(id))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { format: "order", elementIds: [...stored] };
|
||||
}
|
||||
case "find_error":
|
||||
return Array.isArray(value.lineNumbers) &&
|
||||
value.lineNumbers.every((line) => Number.isInteger(line))
|
||||
? { format: "find_error", lineNumbers: value.lineNumbers as number[] }
|
||||
: null;
|
||||
case "practice": {
|
||||
const language = value.language;
|
||||
const allowed: readonly unknown[] = [null, ...content.languages];
|
||||
if (!allowed.includes(language) || typeof value.sourceCode !== "string") return null;
|
||||
return {
|
||||
format: "practice",
|
||||
language: language === null ? null : (language as "go" | "python"),
|
||||
sourceCode: value.sourceCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import type { AssessmentItem } from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import { emptyAnswerDraft, type AnswerDraft } from "../model/answer-draft";
|
||||
import type { AnswerDraft } from "../model/answer-draft";
|
||||
import { restoredAnswerDraft, saveAnswerDraft } from "../model/answer-draft-store";
|
||||
import styles from "./answer-form.module.css";
|
||||
|
||||
type AnswerFormProps = {
|
||||
attemptId: string;
|
||||
item: AssessmentItem;
|
||||
isSaving: boolean;
|
||||
retryable: boolean;
|
||||
@@ -14,6 +16,7 @@ type AnswerFormProps = {
|
||||
};
|
||||
|
||||
export function AnswerForm({
|
||||
attemptId,
|
||||
item,
|
||||
isSaving,
|
||||
retryable,
|
||||
@@ -21,23 +24,36 @@ export function AnswerForm({
|
||||
onSubmit,
|
||||
onRetry,
|
||||
}: AnswerFormProps) {
|
||||
const [draft, setDraft] = useState<AnswerDraft>(() => emptyAnswerDraft(item));
|
||||
// The unsent answer survives a reload in this tab; see answer-draft-store.
|
||||
const [draft, setDraftState] = useState<AnswerDraft>(() => restoredAnswerDraft(attemptId, item));
|
||||
const errorId = useId();
|
||||
const setDraft = (next: AnswerDraft) => {
|
||||
setDraftState(next);
|
||||
saveAnswerDraft(attemptId, item.id, next);
|
||||
};
|
||||
const frozen = isSaving || retryable;
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (frozen) return;
|
||||
// The fields are disabled while the answer is saved, which would drop the
|
||||
// focus of a keyboard user; the submit control keeps it instead.
|
||||
event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
|
||||
onSubmit(draft);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit}>
|
||||
<fieldset className={styles.fields} disabled={frozen}>
|
||||
<fieldset
|
||||
className={styles.fields}
|
||||
disabled={frozen}
|
||||
aria-describedby={errorMessage ? errorId : undefined}
|
||||
>
|
||||
<legend className={styles.legend}>Ваш ответ</legend>
|
||||
<AnswerFields item={item} draft={draft} setDraft={setDraft} />
|
||||
</fieldset>
|
||||
{errorMessage ? (
|
||||
<p className={styles.error} role="alert">
|
||||
<p className={styles.error} id={errorId} role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
@@ -287,6 +287,8 @@ export function NeedEditor({
|
||||
draft.location.status !== "unknown" ||
|
||||
draft.salary.status !== "unknown";
|
||||
const salaryError = salaryInputError(salaryDraft);
|
||||
const salaryMessage = salaryError ?? fieldErrors.salary ?? null;
|
||||
const salaryMessageId = `${inputId}-salary-error`;
|
||||
const csrfValid =
|
||||
session.account.id === accountId &&
|
||||
session.account.scenario === "employer" &&
|
||||
@@ -691,12 +693,17 @@ export function NeedEditor({
|
||||
required
|
||||
value={draft.title}
|
||||
aria-invalid={Boolean(fieldErrors.title)}
|
||||
aria-describedby={fieldErrors.title ? `${inputId}-title-error` : undefined}
|
||||
onChange={(event) => {
|
||||
const title = event.currentTarget.value;
|
||||
changeDraft((current) => ({ ...current, title }));
|
||||
}}
|
||||
/>
|
||||
{fieldErrors.title ? <p className={styles["field-error"]}>{fieldErrors.title}</p> : null}
|
||||
{fieldErrors.title ? (
|
||||
<p className={styles["field-error"]} id={`${inputId}-title-error`}>
|
||||
{fieldErrors.title}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${inputId}-source`}>Описание работы</label>
|
||||
@@ -733,6 +740,9 @@ export function NeedEditor({
|
||||
id={`${inputId}-specialization`}
|
||||
value={draft.specialization.status === "unknown" ? "" : draft.specialization.value}
|
||||
aria-invalid={Boolean(fieldErrors.specialization)}
|
||||
aria-describedby={
|
||||
fieldErrors.specialization ? `${inputId}-specialization-error` : undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
changeSpecialization(event.currentTarget.value as SpecializationCode | "")
|
||||
}
|
||||
@@ -747,7 +757,9 @@ export function NeedEditor({
|
||||
<Provenance state={draft.specialization} />
|
||||
{missing("specialization")}
|
||||
{fieldErrors.specialization ? (
|
||||
<p className={styles["field-error"]}>{fieldErrors.specialization}</p>
|
||||
<p className={styles["field-error"]} id={`${inputId}-specialization-error`}>
|
||||
{fieldErrors.specialization}
|
||||
</p>
|
||||
) : null}
|
||||
{draft.specialization.status === "extracted" ? (
|
||||
<Button
|
||||
@@ -765,6 +777,7 @@ export function NeedEditor({
|
||||
id={`${inputId}-grade`}
|
||||
value={draft.grade.status === "unknown" ? "" : draft.grade.value}
|
||||
aria-invalid={Boolean(fieldErrors.grade)}
|
||||
aria-describedby={fieldErrors.grade ? `${inputId}-grade-error` : undefined}
|
||||
onChange={(event) => changeGrade(event.currentTarget.value as GradeCode | "")}
|
||||
>
|
||||
<option value="">Не указано</option>
|
||||
@@ -776,7 +789,11 @@ export function NeedEditor({
|
||||
</select>
|
||||
<Provenance state={draft.grade} />
|
||||
{missing("grade")}
|
||||
{fieldErrors.grade ? <p className={styles["field-error"]}>{fieldErrors.grade}</p> : null}
|
||||
{fieldErrors.grade ? (
|
||||
<p className={styles["field-error"]} id={`${inputId}-grade-error`}>
|
||||
{fieldErrors.grade}
|
||||
</p>
|
||||
) : null}
|
||||
{draft.grade.status === "extracted" ? (
|
||||
<Button
|
||||
variant="quiet"
|
||||
@@ -896,6 +913,7 @@ export function NeedEditor({
|
||||
step={1000}
|
||||
value={salaryDraft.from}
|
||||
aria-invalid={Boolean(salaryError || fieldErrors.salary)}
|
||||
aria-describedby={salaryMessage ? salaryMessageId : undefined}
|
||||
onChange={(event) => changeSalary("from", event.currentTarget.value)}
|
||||
/>
|
||||
</div>
|
||||
@@ -910,6 +928,7 @@ export function NeedEditor({
|
||||
step={1000}
|
||||
value={salaryDraft.to}
|
||||
aria-invalid={Boolean(salaryError || fieldErrors.salary)}
|
||||
aria-describedby={salaryMessage ? salaryMessageId : undefined}
|
||||
onChange={(event) => changeSalary("to", event.currentTarget.value)}
|
||||
/>
|
||||
</div>
|
||||
@@ -919,6 +938,7 @@ export function NeedEditor({
|
||||
id={`${inputId}-salary-basis`}
|
||||
value={salaryDraft.taxBasis}
|
||||
aria-invalid={Boolean(salaryError || fieldErrors.salary)}
|
||||
aria-describedby={salaryMessage ? salaryMessageId : undefined}
|
||||
onChange={(event) => changeSalary("taxBasis", event.currentTarget.value)}
|
||||
>
|
||||
<option value="">Не выбрана</option>
|
||||
@@ -932,8 +952,10 @@ export function NeedEditor({
|
||||
</p>
|
||||
<Provenance state={draft.salary} />
|
||||
{missing("salary")}
|
||||
{salaryError || fieldErrors.salary ? (
|
||||
<p className={styles["field-error"]}>{salaryError ?? fieldErrors.salary}</p>
|
||||
{salaryMessage ? (
|
||||
<p className={styles["field-error"]} id={salaryMessageId}>
|
||||
{salaryMessage}
|
||||
</p>
|
||||
) : null}
|
||||
{draft.salary.status !== "unknown" ? (
|
||||
<Button variant="quiet" onClick={clearSalary}>
|
||||
@@ -1072,6 +1094,8 @@ function SkillList({
|
||||
id={`${id}-add`}
|
||||
maxLength={100}
|
||||
disabled={disabled}
|
||||
aria-invalid={Boolean(error) || undefined}
|
||||
aria-describedby={error ? `${id}-error` : undefined}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
@@ -1090,7 +1114,11 @@ function SkillList({
|
||||
Добавить
|
||||
</Button>
|
||||
</div>
|
||||
{error ? <p className={styles["field-error"]}>{error}</p> : null}
|
||||
{error ? (
|
||||
<p className={styles["field-error"]} id={`${id}-error`}>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1156,6 +1184,8 @@ function TaskList({
|
||||
id={`${id}-add`}
|
||||
maxLength={300}
|
||||
disabled={disabled}
|
||||
aria-invalid={Boolean(error) || undefined}
|
||||
aria-describedby={error ? `${id}-error` : undefined}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
@@ -1174,7 +1204,11 @@ function TaskList({
|
||||
Добавить
|
||||
</Button>
|
||||
</div>
|
||||
{error ? <p className={styles["field-error"]}>{error}</p> : null}
|
||||
{error ? (
|
||||
<p className={styles["field-error"]} id={`${id}-error`}>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -259,6 +259,9 @@ export function InvitationForm({
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
// The fields are disabled while the send runs, which would drop the focus
|
||||
// of a keyboard user; the submit control keeps it instead.
|
||||
event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
|
||||
void send();
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,9 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
errors.email = "Введите корректный адрес электронной почты.";
|
||||
}
|
||||
const passwordLength = Array.from(password.normalize("NFKC")).length;
|
||||
if (passwordLength < 1 || passwordLength > 128) {
|
||||
if (passwordLength < 1) {
|
||||
errors.password = "Введите пароль.";
|
||||
} else if (passwordLength > 128) {
|
||||
errors.password = "Введите пароль длиной не более 128 символов.";
|
||||
}
|
||||
setFieldError(errors);
|
||||
@@ -72,6 +74,8 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
onUnverified("");
|
||||
}
|
||||
|
||||
// The fields are read-only while the request is pending, not disabled: a
|
||||
// disabled field drops keyboard focus, and the user would lose the place.
|
||||
return (
|
||||
<div className={styles.form}>
|
||||
<form onSubmit={(event) => void submit(event)} noValidate>
|
||||
@@ -89,7 +93,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
required
|
||||
maxLength={254}
|
||||
value={email}
|
||||
disabled={login.isPending}
|
||||
readOnly={login.isPending}
|
||||
aria-invalid={Boolean(fieldError.email)}
|
||||
aria-describedby={fieldError.email ? `${id}-email-error` : undefined}
|
||||
onChange={(event) => {
|
||||
@@ -117,7 +121,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
required
|
||||
maxLength={512}
|
||||
value={password}
|
||||
disabled={login.isPending}
|
||||
readOnly={login.isPending}
|
||||
aria-invalid={Boolean(fieldError.password)}
|
||||
aria-describedby={fieldError.password ? `${id}-password-error` : undefined}
|
||||
onChange={(event) => {
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
import {
|
||||
AnswerForm,
|
||||
buildAnswerSubmission,
|
||||
clearAnswerDraft,
|
||||
newIdempotencyKey,
|
||||
submitPendingAnswerCommand,
|
||||
} from "../../../features/answer-assessment";
|
||||
@@ -325,6 +326,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
}
|
||||
if (outcome.kind === "rejected") throw outcome.error;
|
||||
const saved = outcome.attempt;
|
||||
clearAnswerDraft(currentAttemptId, command.itemId);
|
||||
const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId);
|
||||
queryClient.setQueryData<AssessmentAttempt>(key, (current) =>
|
||||
current && current.version > saved.version ? current : saved,
|
||||
@@ -604,6 +606,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
|
||||
<AnswerForm
|
||||
key={currentItem.id}
|
||||
attemptId={attempt.id}
|
||||
item={currentItem}
|
||||
isSaving={answerBusy}
|
||||
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
|
||||
|
||||
Reference in new issue
Block a user