diff --git a/frontend/README.en.md b/frontend/README.en.md index cf65bf0..fbe4770 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -77,7 +77,7 @@ Clipboard contents and typed text are never read into a signal or sent. The past ## Candidate results -`/candidate/results` lists the completed real assessments of the current candidate (`GET /me/assessment-results`, 20 records per page; the cursor comes only from the server response and is never built on the client). `/candidate/results/:attemptId` opens one record by a direct URL. Both screens read data only for a confirmed candidate session: query keys include the account identifier and the session token, data does not outlive the screen (`gcTime: 0`) and is removed when the session changes or ends. A 401, 403, or 404 response shows an "unavailable" screen without data and does not reveal whether another candidate's result exists; the assessment cache is cleared only on 401, while a network or 5xx failure offers a retry and is not treated as lost access. A failed background refresh keeps the data that was already loaded and says so. Dates are shown in the browser time zone with its name. "Show more" moves the focus to the first new row and announces how many were loaded. Loading, empty history, and error states with retry exist. A failed attempt after a successful one, adaptive estimate values, retry dates, and missing-field cases are covered by unit contract fixtures because the stand cannot produce them; the e2e test checks the shape of the flow (a real result, the express run, ownership, sign-out; the interface has no sign-out control yet, so the session ends through the API). By contract, express tests are not part of the history; their result opens from the attempt screen or by a direct URL and is captioned "Экспресс-тест без грейда" (express test without a grade). +`/candidate/results` lists the completed real assessments of the current candidate (`GET /me/assessment-results`, 20 records per page; the cursor comes only from the server response and is never built on the client). `/candidate/results/:attemptId` opens one record by a direct URL. Both screens read data only for a confirmed candidate session: query keys include the account identifier and the session token, data does not outlive the screen (`gcTime: 0`) and is removed when the session changes or ends. A 401, 403, or 404 response shows an "unavailable" screen without data and does not reveal whether another candidate's result exists; the assessment cache is cleared only on 401, while a network or 5xx failure offers a retry and is not treated as lost access. A failed background refresh keeps the data that was already loaded and says so. Dates are shown in the browser time zone with its name. "Show more" moves the focus to the first new row and announces how many were loaded. Loading, empty history, and error states with retry exist. A failed attempt after a successful one, adaptive estimate values, retry dates, and missing-field cases are covered by unit contract fixtures because the stand cannot produce them; the e2e test checks the shape of the flow (a real result, the express run, ownership, sign-out; the session ends through the API, not through the account menu, because the menu reloads the page). By contract, express tests are not part of the history; their result opens from the attempt screen or by a direct URL and is captioned "Экспресс-тест без грейда" (express test without a grade). On the attempt screen only the phrase "Result received" is a live message; the record is ordinary content, and the focus moves to its heading. The shared `AssessmentResultView` component (`entities/assessment`) only restates the fields of the server response: @@ -257,11 +257,11 @@ The interface has no FSP logo. `Wordmark` is the text mark "Lincodex" with a ter ## Shared components - `Page`, `Section`, `Stack`: page layout; `Page` owns the only `h1` and the document title. `Section` hangs on a circuit trace: a node at the heading and a line down the section. -- `Button`, `ButtonLink` (variants `primary`, `secondary`, `quiet`), `TextLink`, `NavItem`: controls with text labels; `NavItem` marks the active section with `aria-current` and an inverted capsule. -- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark`: the shell header: a floating glass plate, a menu button with `aria-expanded` (the menu closes after a navigation and on Escape, and focus returns to the button), and the wordmark. +- `Button`, `ButtonLink` (variants `primary`, `secondary`, `quiet`), `TextLink`, `NavItem`: controls with text labels; `NavItem` marks the active section with `aria-current` and an inverted capsule; a shell can state the current state itself (`current`) for a section that stays active on the routes of its sub-sections. +- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark`: the shell header: a floating glass plate, a menu button with `aria-expanded` (the menu closes after a navigation and on Escape, and focus returns to the button; with `dismissOutside` it also closes on a press or focus outside it), and the wordmark. - `Card` (`raised`, `inset`, `panel`), `Tag` (`neutral`, `grade`, `stack`, `accent`, `success`, `danger`), `AttentionDot`, `Notice`: containers, tags, and messages. The meaning is always given in text; color only repeats it. - `Stepper` and `buildSteps`: progress through a multi-step flow: a "Шаг N из M" line and a list with `aria-current="step"` and a text status for each step. -- `Tabs` (WAI-ARIA tabs pattern, arrow keys, Home and End; inactive panels stay mounted with the hidden attribute, so form state survives) and `SegmentedControl` (a native radio group drawn as capsules). +- `Tabs` (WAI-ARIA tabs pattern, arrow keys, Home and End; inactive panels stay mounted with the hidden attribute, so form state survives) and `SegmentedControl` (a native radio group drawn as capsules). `SectionSwitch` is a sub-section switch drawn as capsules but made of links to routes: it has no panels, so tabs do not fit. - `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus`: screen states. Each state has its own shape and text; the empty state draws a circuit trace that ends at an open node. `ErrorState` shows the code, status, server text, and request ID as plain text and offers a retry. `Skeleton`: decorative placeholder lines while loading, always next to a loading message. - `QueryView`: maps a query result to loading, error, forbidden (401 and 403 without retry), empty, or data. - `TrustLevel`: an empty mark, ring, partial fill, or full mark with a visible label. @@ -269,7 +269,7 @@ The interface has no FSP logo. `Wordmark` is the text mark "Lincodex" with a ter The steps of a long form (`form-steps.tsx`, `use-form-steps.ts`: a step panel whose heading takes the focus, "Назад" and "Далее" navigation, and a review block with "Изменить") are identical copies in `features/edit-profile` and `features/fill-questionnaire` for now; a shared version belongs in `shared/ui`. -Shells. Public: a floating plate with the wordmark and links; below 700px the links open from a "Меню" button; a footer links the technical status. Candidate (phone first): below 700px the sections form a scrolling bottom tab bar and the current tab scrolls to the middle; from 700px the tabs sit in the plate. When the tabs do not fit, the strip fades at the edge that hides more of them. The navigation comes before `main` in the document, so the keyboard order is the same at every width. Employer (desktop first): from 1024px a floating 240px sidebar, below that a plate with a "Меню" button. +Shells. Public: a floating plate with the wordmark and links; below 700px the links open from a "Меню" button; a footer links the technical status. Candidate: the plate holds the wordmark, four sections (Главная, Профиль, Тест, Приглашения), a notifications bell, and an "Аккаунт" menu (Приватность, Поддержка, Выйти); there is no unread badge because the shell does not read notification data. The questionnaire belongs to "Профиль" and the results belong to "Тест": such a section stays current on the routes of its sub-sections (`aria-current="true"`, and `"page"` on the section page itself), and the sub-section pages show a `SectionSwitch` above the heading ("Профиль" and "Анкета", "Проверка" and "Результаты"), which the shell passes to the pages through `PageNavProvider`. Below 1024px the sections form a bottom bar of five items (the four sections and "Ещё"), the plate keeps the wordmark and the bell, and "Ещё" opens a sheet with notifications, privacy, support, and sign-out. Sign-out ends the session on the server and fully reloads the page on the sign-in screen, so no account data stays in memory; on failure the menu says that you are still signed in. The menu closes on Escape (focus returns to the button), after a navigation, and on a press or focus outside it. The navigation comes before `main` in the document, so the keyboard order is the same at every width. Employer (desktop first): from 1024px a floating 240px sidebar, below that a plate with a "Меню" button. Accessibility: every shell starts with a skip link to `main`, has landmarks and a visible focus ring (2px `#9A92FF`, 2px offset), and moves focus to `main` after navigation. Animations respect `prefers-reduced-motion`. diff --git a/frontend/README.md b/frontend/README.md index fe11f4c..6952d5a 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -77,7 +77,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS ## Результаты кандидата -`/candidate/results` показывает историю завершенных реальных проверок текущего кандидата (`GET /me/assessment-results`, по 20 записей, курсор берется только из ответа сервера и не строится на клиенте). `/candidate/results/:attemptId` открывает одну запись по прямому URL. Оба экрана читают данные только при подтвержденной сессии кандидата: ключи запросов содержат идентификатор аккаунта и токен сессии, данные не живут после ухода с экрана (`gcTime: 0`) и удаляются при смене или потере сессии. Ответ 401, 403 или 404 дает экран "недоступно" без данных и не раскрывает, существует ли чужой результат; кеш ассессмента очищается только при 401, а сбой сети или 5xx предлагает повтор и не считается потерей доступа. Неудачное фоновое обновление оставляет уже загруженные данные и сообщает об этом. Даты показываются в часовом поясе браузера с его названием. "Показать еще" переносит фокус на первую новую запись и сообщает о числе загруженных. Есть состояния загрузки, пустой истории и ошибки с повтором. Неудачная попытка после успешной, значения адаптивной оценки, даты пересдачи и случаи без полей покрыты модульными фикстурами контракта: на стенде их получить нельзя, e2e проверяет форму потока (реальный результат, экспресс, владение, выход из аккаунта; в интерфейсе пока нет кнопки выхода, сессия завершается через API). Экспресс-тесты по контракту в историю не входят; их результат открывается по ссылке из экрана попытки или по прямому URL и подписан "Экспресс-тест без грейда". +`/candidate/results` показывает историю завершенных реальных проверок текущего кандидата (`GET /me/assessment-results`, по 20 записей, курсор берется только из ответа сервера и не строится на клиенте). `/candidate/results/:attemptId` открывает одну запись по прямому URL. Оба экрана читают данные только при подтвержденной сессии кандидата: ключи запросов содержат идентификатор аккаунта и токен сессии, данные не живут после ухода с экрана (`gcTime: 0`) и удаляются при смене или потере сессии. Ответ 401, 403 или 404 дает экран "недоступно" без данных и не раскрывает, существует ли чужой результат; кеш ассессмента очищается только при 401, а сбой сети или 5xx предлагает повтор и не считается потерей доступа. Неудачное фоновое обновление оставляет уже загруженные данные и сообщает об этом. Даты показываются в часовом поясе браузера с его названием. "Показать еще" переносит фокус на первую новую запись и сообщает о числе загруженных. Есть состояния загрузки, пустой истории и ошибки с повтором. Неудачная попытка после успешной, значения адаптивной оценки, даты пересдачи и случаи без полей покрыты модульными фикстурами контракта: на стенде их получить нельзя, e2e проверяет форму потока (реальный результат, экспресс, владение, выход из аккаунта; сессия завершается через API, а не через меню аккаунта, потому что меню перезагружает страницу). Экспресс-тесты по контракту в историю не входят; их результат открывается по ссылке из экрана попытки или по прямому URL и подписан "Экспресс-тест без грейда". На экране попытки живым сообщением остается только фраза "Результат получен", запись результата - обычное содержимое, а фокус переходит на ее заголовок. Общий компонент `AssessmentResultView` (`entities/assessment`) только пересказывает поля серверного ответа: @@ -257,11 +257,11 @@ SPA на React и TypeScript со сборкой Vite и структурой FS ## Общие компоненты - `Page`, `Section`, `Stack` - раскладка страницы; `Page` содержит единственный `h1` и задает заголовок документа. `Section` висит на дорожке платы: узел у заголовка и линия вдоль раздела. -- `Button`, `ButtonLink` (варианты `primary`, `secondary`, `quiet`), `TextLink`, `NavItem` - элементы управления с текстовыми подписями; `NavItem` отмечает активный раздел через `aria-current` и инверсией капсулы. -- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark` - шапка оболочек: плавающая стеклянная плашка, кнопка меню с `aria-expanded` (меню закрывается после перехода и по Escape, фокус возвращается на кнопку) и словесный знак. +- `Button`, `ButtonLink` (варианты `primary`, `secondary`, `quiet`), `TextLink`, `NavItem` - элементы управления с текстовыми подписями; `NavItem` отмечает активный раздел через `aria-current` и инверсией капсулы; оболочка может сама задать состояние (`current`) для раздела, который остается активным на маршрутах подразделов. +- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark` - шапка оболочек: плавающая стеклянная плашка, кнопка меню с `aria-expanded` (меню закрывается после перехода и по Escape, фокус возвращается на кнопку; с параметром `dismissOutside` еще и при нажатии или фокусе вне меню) и словесный знак. - `Card` (`raised`, `inset`, `panel`), `Tag` (`neutral`, `grade`, `stack`, `accent`, `success`, `danger`), `AttentionDot`, `Notice` - контейнеры, метки и сообщения. Смысл всегда передан текстом, цвет его только повторяет. - `Stepper` и `buildSteps` - ход многошагового сценария: строка "Шаг N из M", список с `aria-current="step"` и текстовым статусом каждого шага. -- `Tabs` (шаблон вкладок WAI-ARIA, стрелки, Home и End, неактивные панели остаются в дереве со скрытым атрибутом, поэтому состояние формы сохраняется) и `SegmentedControl` (нативная группа радиокнопок в виде капсул). +- `Tabs` (шаблон вкладок WAI-ARIA, стрелки, Home и End, неактивные панели остаются в дереве со скрытым атрибутом, поэтому состояние формы сохраняется) и `SegmentedControl` (нативная группа радиокнопок в виде капсул). `SectionSwitch` - переключатель подразделов в виде капсул, но из ссылок на маршруты: у него нет панелей, поэтому вкладки не подходят. - `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus` - состояния экранов. У каждого состояния своя форма и текст; пустое состояние рисует дорожку платы, которая заканчивается пустым узлом. `ErrorState` показывает код, статус, текст сервера и идентификатор запроса как обычный текст и предлагает повтор. `Skeleton` - декоративные заготовки строк при загрузке, только вместе с сообщением о загрузке. - `QueryView` - превращает результат запроса в загрузку, ошибку, отсутствие доступа (401 и 403 без повтора), пустое состояние или данные. - `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью. @@ -269,7 +269,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Шаги длинной формы (`form-steps.tsx`, `use-form-steps.ts`: панель шага с заголовком, получающим фокус, навигация «Назад» и «Далее», блок проверки с кнопкой «Изменить») пока лежат одинаковыми копиями в `features/edit-profile` и `features/fill-questionnaire`; общий вариант стоит перенести в `shared/ui`. -Оболочки. Публичная: плавающая плашка со словесным знаком и ссылками, ниже 700px ссылки открываются кнопкой "Меню"; подвал со ссылкой на технический статус. Кандидат (сначала телефон): ниже 700px разделы образуют нижнюю панель вкладок с прокруткой, текущая вкладка прокручивается в середину; с 700px вкладки стоят в плашке. Если вкладки не помещаются, полоса затухает у того края, за которым они остались. Навигация в документе идет до `main`, поэтому порядок клавиатуры одинаков на любой ширине. Работодатель (сначала компьютер): с 1024px плавающая боковая панель 240px, ниже - плашка с кнопкой "Меню". +Оболочки. Публичная: плавающая плашка со словесным знаком и ссылками, ниже 700px ссылки открываются кнопкой "Меню"; подвал со ссылкой на технический статус. Кандидат: в плашке словесный знак, четыре раздела (Главная, Профиль, Тест, Приглашения), колокольчик уведомлений и меню "Аккаунт" (Приватность, Поддержка, Выйти); бейджа непрочитанных нет, потому что оболочка не читает данные уведомлений. Анкета - часть раздела "Профиль", результаты - часть раздела "Тест": такой раздел остается текущим на маршрутах своих подразделов (`aria-current="true"`, на самой странице раздела `"page"`), а страницы подраздела показывают над заголовком переключатель `SectionSwitch` ("Профиль" и "Анкета", "Проверка" и "Результаты"), который оболочка передает страницам через `PageNavProvider`. Ниже 1024px разделы образуют нижнюю панель из пяти пунктов (четвертый раздел и "Ещё"), плашка остается со словесным знаком и колокольчиком; "Ещё" открывает лист с уведомлениями, приватностью, поддержкой и выходом. Выход завершает сессию на сервере и полностью перезагружает страницу на входе, чтобы в памяти не осталось данных аккаунта; при ошибке меню сообщает, что вы остались в кабинете. Меню закрывается по Escape (фокус возвращается на кнопку), после перехода и при нажатии или фокусе вне меню. Навигация в документе идет до `main`, поэтому порядок клавиатуры одинаков на любой ширине. Работодатель (сначала компьютер): с 1024px плавающая боковая панель 240px, ниже - плашка с кнопкой "Меню". Доступность: каждая оболочка начинается со ссылки пропуска к `main`, содержит ориентиры и видимое кольцо фокуса (2px `#9A92FF` с отступом 2px) и переводит фокус на `main` после перехода. Анимации учитывают `prefers-reduced-motion`. diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index 9efc93c..68967d2 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -1086,9 +1086,10 @@ test("results keep the express run apart and stay private to the signed-in candi await otherContext.close(); } - // After sign-out the SPA keeps its in-memory state. The app has no sign-out - // control yet, so the session ends through the API; moving inside the app - // must then show no stored data, and a fresh load must ask for sign-in. + // After the session ends elsewhere the SPA keeps its in-memory state. The + // session ends through the API here, not through the account menu, which + // reloads the page; moving inside the app must then show no stored data, and + // a fresh load must ask for sign-in. await navigateInApp(page, "/candidate/results"); await expect(history.getByRole("listitem")).toHaveCount(1); await signOut(page); diff --git a/frontend/e2e/questionnaire.spec.ts b/frontend/e2e/questionnaire.spec.ts index 4af55fa..582075c 100644 --- a/frontend/e2e/questionnaire.spec.ts +++ b/frontend/e2e/questionnaire.spec.ts @@ -386,7 +386,10 @@ test.describe("candidate questionnaire", () => { ); await registerVerifiedCandidate(page); - await page.getByRole("link", { name: "Профиль" }).click(); + await page + .getByRole("navigation", { name: "Разделы кабинета кандидата" }) + .getByRole("link", { name: "Профиль" }) + .click(); await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible(); await page.route("**/api/v1/me/questionnaire", async (route) => { if (route.request().method() === "GET") { diff --git a/frontend/e2e/support-cases.spec.ts b/frontend/e2e/support-cases.spec.ts index 3265bb9..6911846 100644 --- a/frontend/e2e/support-cases.spec.ts +++ b/frontend/e2e/support-cases.spec.ts @@ -193,6 +193,8 @@ test.describe("candidate support cases and manual assessment", () => { }) => { await registerCandidate(page, "support-author"); await page.goto("/candidate/assessment"); + // Support sits in the account menu of the header. + await page.getByRole("button", { name: "Аккаунт" }).click(); await expect(page.getByRole("link", { name: "Поддержка", exact: true })).toBeVisible(); await page.getByRole("link", { name: "Поддержка", exact: true }).click(); await expect(page).toHaveURL(/\/candidate\/support\/cases$/); diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 56ae022..a6381d5 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -197,8 +197,16 @@ describe("route groups", () => { it("marks the active cabinet section with aria-current", async () => { expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]); - expect(currentLinkText(await renderHtml("/candidate/results"))).toEqual(["Результаты"]); - expect(currentLinkText(await renderHtml("/candidate/privacy"))).toEqual(["Приватность"]); + // The results are a sub-section of the test: the switch segment is the + // page, and the primary "Тест" item is current as the section (true). + const results = await renderHtml("/candidate/results"); + expect(currentLinkText(results)).toEqual(["Результаты"]); + expect(results).toMatch(/]*aria-current="true"[^>]*>Тест<\/a>/); + // The account menu is rendered for the header and for the phone tab bar. + expect(currentLinkText(await renderHtml("/candidate/privacy"))).toEqual([ + "Приватность", + "Приватность", + ]); expect(currentLinkText(await renderHtml("/employer/invitations"))).toEqual(["Приглашения"]); }); diff --git a/frontend/src/app/ui/styles.css b/frontend/src/app/ui/styles.css index bf5af58..6a20533 100644 --- a/frontend/src/app/ui/styles.css +++ b/frontend/src/app/ui/styles.css @@ -30,8 +30,8 @@ html { var(--space-4); } -/* The candidate cabinet has a bottom tab bar on phones. */ -@media (width < 43.75rem) { +/* The candidate cabinet has a bottom tab bar below 1024px. */ +@media (width < 64rem) { html { scroll-padding-bottom: 5rem; } diff --git a/frontend/src/features/sign-out/index.ts b/frontend/src/features/sign-out/index.ts new file mode 100644 index 0000000..587d243 --- /dev/null +++ b/frontend/src/features/sign-out/index.ts @@ -0,0 +1,2 @@ +export { requestSignOut } from "./model/request-sign-out"; +export { useSignOut } from "./model/use-sign-out"; diff --git a/frontend/src/features/sign-out/model/request-sign-out.test.ts b/frontend/src/features/sign-out/model/request-sign-out.test.ts new file mode 100644 index 0000000..5b8a272 --- /dev/null +++ b/frontend/src/features/sign-out/model/request-sign-out.test.ts @@ -0,0 +1,80 @@ +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import type { Session } from "../../../shared/api/schemas"; +import { requestSignOut } from "./request-sign-out"; + +const server = setupServer(); +const sessionUrl = "http://localhost/api/v1/identity/sessions/current"; + +const session = { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), +} satisfies Session; + +beforeAll(() => server.listen()); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +function stubRelativeFetch() { + const interceptedFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + interceptedFetch(new URL(input, "http://localhost"), init), + ); +} + +describe("requestSignOut", () => { + it("deletes the current session with the CSRF token of that session", async () => { + stubRelativeFetch(); + const seen: Array<{ method: string; csrf: string | null }> = []; + server.use( + http.delete(sessionUrl, ({ request }) => { + seen.push({ method: request.method, csrf: request.headers.get("X-CSRF-Token") }); + return new HttpResponse(null, { status: 204 }); + }), + ); + + await expect(requestSignOut(session)).resolves.toBeUndefined(); + expect(seen).toEqual([{ method: "DELETE", csrf: session.csrf_token }]); + }); + + it("treats a session that is already gone as signed out", async () => { + stubRelativeFetch(); + server.use( + http.delete(sessionUrl, () => + HttpResponse.json( + { + type: "urn:lincodex:problem:unauthenticated", + title: "Unauthenticated", + status: 401, + code: "unauthenticated", + }, + { status: 401, headers: { "Content-Type": "application/problem+json" } }, + ), + ), + ); + + await expect(requestSignOut(session)).resolves.toBeUndefined(); + }); + + it.each([403, 500])( + "reports a %i answer, because the session may still be alive", + async (status) => { + stubRelativeFetch(); + server.use(http.delete(sessionUrl, () => new HttpResponse(null, { status }))); + + await expect(requestSignOut(session)).rejects.toBeInstanceOf(ApiRequestError); + }, + ); +}); diff --git a/frontend/src/features/sign-out/model/request-sign-out.ts b/frontend/src/features/sign-out/model/request-sign-out.ts new file mode 100644 index 0000000..59387cc --- /dev/null +++ b/frontend/src/features/sign-out/model/request-sign-out.ts @@ -0,0 +1,20 @@ +import { ApiRequestError } from "../../../shared/api"; +import { logout } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; + +/** + * Ends the current session on the server. A 401 means the session is already + * gone (expired or revoked elsewhere), which is the state the caller wants, + * so it counts as success. Any other failure is thrown: the session may still + * be alive and the user must be told that they are not signed out. + */ +export async function requestSignOut(session: Session | undefined): Promise { + try { + await logout({ headers: session ? { "X-CSRF-Token": session.csrf_token } : {} }); + } catch (error: unknown) { + if (error instanceof ApiRequestError && error.status === 401) { + return; + } + throw error; + } +} diff --git a/frontend/src/features/sign-out/model/use-sign-out.ts b/frontend/src/features/sign-out/model/use-sign-out.ts new file mode 100644 index 0000000..c983f94 --- /dev/null +++ b/frontend/src/features/sign-out/model/use-sign-out.ts @@ -0,0 +1,30 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { requestSignOut } from "./request-sign-out"; + +/** + * Sign-out command for a cabinet shell. On success the page is replaced by a + * full load of the sign-in screen: that drops every in-memory copy of the + * account's data (the query cache, form drafts), which a client-side + * navigation would keep until the cache is cleared piece by piece. The CSRF + * token is read from the cached session when the command runs, so the shell + * does not subscribe to the session query. + */ +export function useSignOut() { + const queryClient = useQueryClient(); + const mutation = useMutation({ + mutationFn: () => + requestSignOut(queryClient.getQueryData(getGetCurrentSessionQueryKey())), + onSuccess: () => { + window.location.assign(paths.login); + }, + }); + + return { + signOut: () => mutation.mutate(), + isPending: mutation.isPending || mutation.isSuccess, + failed: mutation.isError, + }; +} diff --git a/frontend/src/shared/ui/index.ts b/frontend/src/shared/ui/index.ts index 884f4a8..6eac77d 100644 --- a/frontend/src/shared/ui/index.ts +++ b/frontend/src/shared/ui/index.ts @@ -4,15 +4,17 @@ export { Card } from "./card/card"; export { CircuitTrace } from "./decor/circuit-trace"; export { HeaderPlate } from "./header-plate/header-plate"; export { Page } from "./layout/page"; +export { PageNavProvider } from "./layout/page-nav"; export { Section } from "./layout/section"; export { Stack } from "./layout/stack"; -export { NavItem, TextLink, type NavItemLayout } from "./link/text-link"; +export { NavItem, TextLink, type NavItemCurrent, type NavItemLayout } from "./link/text-link"; export { MainRegion, mainContentId } from "./main-region/main-region"; export { MenuButton } from "./menu-button/menu-button"; export { useMenuToggle } from "./menu-button/use-menu-toggle"; export { Mono } from "./mono/mono"; export { Notice, type NoticeTone } from "./notice/notice"; export { SegmentedControl, type SegmentedOption } from "./segmented-control/segmented-control"; +export { SectionSwitch, type SectionSwitchItem } from "./section-switch/section-switch"; export { Skeleton } from "./skeleton/skeleton"; export { SkipLink } from "./skip-link/skip-link"; export { describeError, isAccessDenied, type ErrorDescription } from "./status-view/describe-error"; diff --git a/frontend/src/shared/ui/layout/layout.module.css b/frontend/src/shared/ui/layout/layout.module.css index 1f88903..4dbaaf5 100644 --- a/frontend/src/shared/ui/layout/layout.module.css +++ b/frontend/src/shared/ui/layout/layout.module.css @@ -12,6 +12,11 @@ max-width: calc(var(--content-width-wide) + 2 * var(--gutter)); } +/* Secondary navigation of the shell's section, above the heading. */ +.section-nav { + margin-bottom: var(--space-5); +} + /* The header closes with a hairline trace that starts at a node. */ .page-header { position: relative; diff --git a/frontend/src/shared/ui/layout/page-nav.ts b/frontend/src/shared/ui/layout/page-nav.ts new file mode 100644 index 0000000..abfcaff --- /dev/null +++ b/frontend/src/shared/ui/layout/page-nav.ts @@ -0,0 +1,16 @@ +import { createContext, useContext, type ReactNode } from "react"; + +const PageNavContext = createContext(null); + +/** + * Lets a shell hand a secondary navigation (for example a switch between the + * sub-sections of a cabinet section) to the pages inside it. Every Page shows + * it above its heading, so it lines up with the page content at any width + * without each screen repeating it. + */ +export const PageNavProvider = PageNavContext.Provider; + +/** The secondary navigation provided by the shell, or null. */ +export function usePageNav(): ReactNode { + return useContext(PageNavContext); +} diff --git a/frontend/src/shared/ui/layout/page.tsx b/frontend/src/shared/ui/layout/page.tsx index 5d526ad..fa68a78 100644 --- a/frontend/src/shared/ui/layout/page.tsx +++ b/frontend/src/shared/ui/layout/page.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from "react"; import styles from "./layout.module.css"; +import { usePageNav } from "./page-nav"; const productName = "Lincodex"; @@ -15,12 +16,15 @@ type PageProps = { /** * Page content inside a shell's main landmark. It owns the only h1 of the - * page and sets the document title (React hoists into <head>). + * page and sets the document title (React hoists <title> into <head>). A + * secondary navigation from the shell (see PageNavProvider) sits above it. */ export function Page({ title, eyebrow, lead, width = "narrow", children }: PageProps) { + const sectionNav = usePageNav(); return ( <div className={`${styles.page} ${styles[width]}`}> <title>{`${title} - ${productName}`} + {sectionNav ?
{sectionNav}
: null}
{eyebrow ?

{eyebrow}

: null}

{title}

diff --git a/frontend/src/shared/ui/link/text-link.module.css b/frontend/src/shared/ui/link/text-link.module.css index 32edc5b..c301538 100644 --- a/frontend/src/shared/ui/link/text-link.module.css +++ b/frontend/src/shared/ui/link/text-link.module.css @@ -43,7 +43,7 @@ background-color: var(--color-surface-tint-hover); } -.nav[aria-current="page"] { +.nav[aria-current] { color: var(--color-on-inverse); background-color: var(--color-inverse); } diff --git a/frontend/src/shared/ui/link/text-link.tsx b/frontend/src/shared/ui/link/text-link.tsx index 48c18f7..7470df1 100644 --- a/frontend/src/shared/ui/link/text-link.tsx +++ b/frontend/src/shared/ui/link/text-link.tsx @@ -1,4 +1,5 @@ -import { Link, NavLink, type LinkProps, type NavLinkProps } from "react-router-dom"; +import { Link, NavLink, type NavLinkProps } from "react-router-dom"; +import type { LinkProps } from "react-router-dom"; import styles from "./text-link.module.css"; type TextLinkProps = Omit & { @@ -12,19 +13,46 @@ export function TextLink({ className, ...rest }: TextLinkProps) { export type NavItemLayout = "row" | "rail"; -type NavItemProps = Omit & { +/** + * Current state set by the shell for a section that owns several routes: + * "page" when the link points at the open page, "true" when the open page is + * a sub-page of the section, "none" when the section is not open. + */ +export type NavItemCurrent = "page" | "true" | "none"; + +type NavItemProps = Omit & { /** "rail" stretches the item to the width of a vertical list. */ layout?: NavItemLayout; + /** + * Overrides the route match of NavLink, for a section that stays active on + * the routes of its sub-sections. + */ + current?: NavItemCurrent; children: string; }; /** * Navigation link of a shell. NavLink sets aria-current="page" on the active * item; the active item is an inverted capsule, a change of fill rather than - * of hue alone. + * of hue alone. A shell can state the current state itself with `current`. */ -export function NavItem({ layout = "row", children, ...rest }: NavItemProps) { +export function NavItem({ layout = "row", current, children, ...rest }: NavItemProps) { const className = layout === "rail" ? `${styles.nav} ${styles.rail}` : (styles.nav ?? ""); + if (current !== undefined) { + // The route match options belong to NavLink and are not valid on Link. + const { end, caseSensitive, ...linkProps } = rest; + void end; + void caseSensitive; + return ( + + {children} + + ); + } return ( {children} diff --git a/frontend/src/shared/ui/menu-button/menu-button.module.css b/frontend/src/shared/ui/menu-button/menu-button.module.css index 4b59134..2f8bd0a 100644 --- a/frontend/src/shared/ui/menu-button/menu-button.module.css +++ b/frontend/src/shared/ui/menu-button/menu-button.module.css @@ -56,3 +56,19 @@ .icon[data-open] span:last-child { transform: translateY(-0.28rem) rotate(-45deg); } + +/* Caret of a menu that drops from a control; it turns up while open. */ +.chevron { + flex: none; + transition: transform var(--duration-base) var(--easing-emphasized); +} + +.root[aria-expanded="true"] .chevron { + transform: rotate(180deg); +} + +/* The open page is one of the menu's destinations: a hairline ring in the + * accent color, a change of outline rather than of fill alone. */ +.root[data-current]:not([aria-expanded="true"]) { + border-color: var(--color-accent); +} diff --git a/frontend/src/shared/ui/menu-button/menu-button.tsx b/frontend/src/shared/ui/menu-button/menu-button.tsx index 6edfe05..190cef2 100644 --- a/frontend/src/shared/ui/menu-button/menu-button.tsx +++ b/frontend/src/shared/ui/menu-button/menu-button.tsx @@ -7,13 +7,32 @@ type MenuButtonProps = { onToggle: () => void; buttonRef: RefObject; className?: string | undefined; + /** Visible label; "Меню" unless the menu has a more specific name. */ + label?: string; + /** + * "bars" is the burger that turns into a cross, for a menu that replaces a + * navigation. "chevron" is a caret, for a menu that drops from a control. + * "none" is the label alone, for a button that sits among text tabs. + */ + icon?: "bars" | "chevron" | "none"; + /** Marks the button when the open page is one of the menu's destinations. */ + current?: boolean; }; /** - * Button that shows or hides a collapsed navigation menu. The visible label - * stays "Меню"; aria-expanded tells whether the menu is open. + * Button that shows or hides a collapsed navigation menu. aria-expanded tells + * whether the menu is open. */ -export function MenuButton({ menuId, isOpen, onToggle, buttonRef, className }: MenuButtonProps) { +export function MenuButton({ + menuId, + isOpen, + onToggle, + buttonRef, + className, + label = "Меню", + icon = "bars", + current = false, +}: MenuButtonProps) { return ( ); } diff --git a/frontend/src/shared/ui/menu-button/use-menu-toggle.ts b/frontend/src/shared/ui/menu-button/use-menu-toggle.ts index 5109bb2..7ad8157 100644 --- a/frontend/src/shared/ui/menu-button/use-menu-toggle.ts +++ b/frontend/src/shared/ui/menu-button/use-menu-toggle.ts @@ -1,14 +1,25 @@ import { useCallback, useEffect, useId, useRef, useState } from "react"; import { useLocation } from "react-router-dom"; +type MenuToggleOptions = { + /** + * Also closes the menu when a pointer press or keyboard focus lands outside + * the element that holds the button and the menu (`rootRef`). For a menu + * that floats over the page, where leaving it by Tab or by a press on the + * page should dismiss it. + */ + dismissOutside?: boolean; +}; + /** * State of a navigation menu that collapses behind a button on narrow * screens. The menu closes after a navigation and on Escape; Escape returns * focus to the button so keyboard users keep their place. */ -export function useMenuToggle() { +export function useMenuToggle({ dismissOutside = false }: MenuToggleOptions = {}) { const menuId = useId(); const buttonRef = useRef(null); + const rootRef = useRef(null); const [isOpen, setIsOpen] = useState(false); const { pathname } = useLocation(); const [openedAt, setOpenedAt] = useState(pathname); @@ -26,14 +37,30 @@ export function useMenuToggle() { setIsOpen(false); buttonRef.current?.focus(); } + function handleOutside(event: Event) { + const root = rootRef.current; + if (root && event.target instanceof Node && !root.contains(event.target)) { + setIsOpen(false); + } + } document.addEventListener("keydown", handleKeyDown); - return () => document.removeEventListener("keydown", handleKeyDown); - }, [isOpen]); + if (dismissOutside) { + document.addEventListener("pointerdown", handleOutside); + document.addEventListener("focusin", handleOutside); + } + return () => { + document.removeEventListener("keydown", handleKeyDown); + document.removeEventListener("pointerdown", handleOutside); + document.removeEventListener("focusin", handleOutside); + }; + }, [isOpen, dismissOutside]); const toggle = useCallback(() => { setOpenedAt(pathname); setIsOpen((open) => !open); }, [pathname]); - return { menuId, buttonRef, isOpen, toggle }; + const close = useCallback(() => setIsOpen(false), []); + + return { menuId, buttonRef, rootRef, isOpen, toggle, close }; } diff --git a/frontend/src/shared/ui/section-switch/section-switch.module.css b/frontend/src/shared/ui/section-switch/section-switch.module.css new file mode 100644 index 0000000..a5ee270 --- /dev/null +++ b/frontend/src/shared/ui/section-switch/section-switch.module.css @@ -0,0 +1,50 @@ +.root { + min-width: 0; +} + +.track { + display: flex; + gap: var(--space-1); + width: fit-content; + max-width: 100%; + margin: 0; + padding: var(--space-1); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-pill); + list-style: none; + background: var(--color-surface); +} + +.segment { + display: flex; + min-width: 0; +} + +/* 44px tall: the segment is a touch target. */ +.link { + display: inline-flex; + align-items: center; + min-height: var(--control-height); + padding: var(--space-2) var(--space-4); + border-radius: var(--radius-pill); + color: var(--color-text-secondary); + font-family: var(--font-mono); + font-size: var(--font-size-s); + font-weight: var(--font-weight-medium); + text-decoration: none; + white-space: nowrap; + transition: + background-color var(--duration-fast) var(--easing-standard), + color var(--duration-fast) var(--easing-standard); +} + +.link:hover { + color: var(--color-text); + background: var(--color-surface-tint-hover); +} + +/* The open segment: graphite on paper 14.53:1. */ +.link[aria-current] { + color: var(--color-on-inverse); + background: var(--color-inverse); +} diff --git a/frontend/src/shared/ui/section-switch/section-switch.tsx b/frontend/src/shared/ui/section-switch/section-switch.tsx new file mode 100644 index 0000000..063249b --- /dev/null +++ b/frontend/src/shared/ui/section-switch/section-switch.tsx @@ -0,0 +1,42 @@ +import { Link } from "react-router-dom"; +import type { NavItemCurrent } from "../link/text-link"; +import styles from "./section-switch.module.css"; + +export type SectionSwitchItem = { + to: string; + label: string; + current: NavItemCurrent; +}; + +type SectionSwitchProps = { + /** Accessible name of the navigation landmark. */ + label: string; + items: readonly SectionSwitchItem[]; +}; + +/** + * Switch between the sub-sections of one section, drawn as a capsule track + * like Tabs. Each segment is a link to its own route, so the browser history, + * the address, and aria-current work as for any navigation; the open segment + * is inverted to paper. Tabs would be wrong here: there is no panel to + * control, only another page. + */ +export function SectionSwitch({ label, items }: SectionSwitchProps) { + return ( + + ); +} diff --git a/frontend/src/widgets/candidate-shell/model/sections.ts b/frontend/src/widgets/candidate-shell/model/sections.ts new file mode 100644 index 0000000..cddd2d9 --- /dev/null +++ b/frontend/src/widgets/candidate-shell/model/sections.ts @@ -0,0 +1,119 @@ +import { paths } from "../../../shared/config"; +import type { NavItemCurrent } from "../../../shared/ui"; + +/** A destination of the candidate cabinet and the routes that belong to it. */ +export type CabinetLink = { + id: string; + label: string; + to: string; + /** + * Route prefixes that keep the link current while a deeper page is open, + * for example an attempt below the assessment screen. A path matches a + * prefix when it equals it or continues after a slash. + */ + owns: readonly string[]; +}; + +/** A primary section; some sections hold a switch between sub-sections. */ +export type CabinetSection = CabinetLink & { + sub?: { + /** Accessible name of the sub-section switch. */ + label: string; + items: readonly CabinetLink[]; + }; +}; + +export const profileLink: CabinetLink = { + id: "profile", + label: "Профиль", + to: paths.candidate.profile, + owns: [paths.candidate.profile], +}; +export const questionnaireLink: CabinetLink = { + id: "questionnaire", + label: "Анкета", + to: paths.candidate.questionnaire, + owns: [paths.candidate.questionnaire], +}; +export const assessmentLink: CabinetLink = { + id: "assessment", + label: "Проверка", + to: paths.candidate.assessment, + owns: [paths.candidate.assessment], +}; +export const resultsLink: CabinetLink = { + id: "results", + label: "Результаты", + to: paths.candidate.results, + owns: [paths.candidate.results], +}; + +/** + * The four primary sections. The questionnaire belongs to the profile and + * the results belong to the test, so those pages are reached through a + * switch inside the section, not through the top level. + */ +export const primarySections: readonly CabinetSection[] = [ + { id: "home", label: "Главная", to: paths.candidate.root, owns: [] }, + { + ...profileLink, + owns: [...profileLink.owns, ...questionnaireLink.owns], + sub: { label: "Разделы профиля", items: [profileLink, questionnaireLink] }, + }, + { + id: "test", + label: "Тест", + to: paths.candidate.assessment, + owns: [...assessmentLink.owns, ...resultsLink.owns], + sub: { label: "Проверка и результаты", items: [assessmentLink, resultsLink] }, + }, + { + id: "invitations", + label: "Приглашения", + to: paths.candidate.invitations, + owns: [paths.candidate.invitations], + }, +]; + +export const notificationsLink: CabinetLink = { + id: "notifications", + label: "Уведомления", + to: paths.candidate.notifications, + owns: [paths.candidate.notifications], +}; +export const privacyLink: CabinetLink = { + id: "privacy", + label: "Приватность", + to: paths.candidate.privacy, + owns: [paths.candidate.privacy], +}; +export const supportLink: CabinetLink = { + id: "support", + label: "Поддержка", + to: paths.candidate.supportCases, + owns: ["/candidate/support"], +}; + +function trimTrailingSlash(pathname: string): string { + return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname; +} + +function within(pathname: string, prefix: string): boolean { + return pathname === prefix || pathname.startsWith(`${prefix}/`); +} + +/** + * "page" when the link points at the open page, "true" when the open page is + * a deeper page of the link's section, "none" otherwise. The home link owns + * no deeper pages, so it is current only on the home page itself. + */ +export function currentOf(pathname: string, link: CabinetLink): NavItemCurrent { + const path = trimTrailingSlash(pathname); + if (path === link.to) return "page"; + return link.owns.some((prefix) => within(path, prefix)) ? "true" : "none"; +} + +/** The primary section that owns the open page, if any. */ +export function findSection(pathname: string): CabinetSection | undefined { + return primarySections.find((section) => currentOf(pathname, section) !== "none"); +} diff --git a/frontend/src/widgets/candidate-shell/ui/cabinet-menu.module.css b/frontend/src/widgets/candidate-shell/ui/cabinet-menu.module.css new file mode 100644 index 0000000..4fd516f --- /dev/null +++ b/frontend/src/widgets/candidate-shell/ui/cabinet-menu.module.css @@ -0,0 +1,114 @@ +/* The drop-down of the desktop header and the sheet of the phone tab bar + * share the panel; the variant decides where it opens. */ +.root { + position: relative; +} + +/* 44px tall on desktop; the phone variant is restyled as a tab below. */ +.button { + min-height: var(--control-height); +} + +/* No display here: the hidden attribute keeps the panel out of the layout, + * the accessibility tree, and the tab order while the menu is closed. */ +.panel { + position: absolute; + z-index: 30; + min-width: 14rem; + padding: var(--space-2); + border: var(--line-thin) solid var(--color-border-hover); + border-radius: var(--radius-m); + background: var(--color-surface-elevated); + box-shadow: var(--shadow-popover); +} + +.panel:not([hidden]) { + animation: open var(--duration-base) var(--easing-emphasized); +} + +.root[data-variant="account"] .panel { + top: calc(100% + var(--space-2)); + right: 0; +} + +/* The sheet opens upward from the bar, aligned to the bar's right edge. */ +.root[data-variant="more"] { + position: static; +} + +.root[data-variant="more"] .panel { + right: var(--space-3); + bottom: calc(100% + var(--space-2)); + width: min(18rem, calc(100vw - 2 * var(--space-3))); +} + +.items { + display: grid; + gap: var(--space-1); + margin: 0; + padding: 0; + list-style: none; +} + +/* Sign-out is set apart from the destinations by a hairline. */ +.separated { + margin-top: var(--space-1); + padding-top: var(--space-1); + border-top: var(--line-thin) solid var(--color-border-hover); +} + +.item { + display: flex; + align-items: center; + width: 100%; + min-height: var(--control-height); + padding: var(--space-2) var(--space-4); + border: 0; + border-radius: var(--radius-s); + color: var(--color-text); + font-family: var(--font-mono); + font-size: var(--font-size-s); + font-weight: var(--font-weight-medium); + text-align: left; + text-decoration: none; + cursor: pointer; + background: transparent; + transition: background-color var(--duration-fast) var(--easing-standard); +} + +.item:disabled { + color: var(--color-text-secondary); + cursor: progress; +} + +.item:hover:not(:disabled) { + background: var(--color-surface-tint-hover); +} + +.item[aria-current] { + color: var(--color-on-inverse); + background: var(--color-inverse); +} + +/* Danger text on the elevated surface is below 4.5:1, so the failure is + * stated in the primary text color with a stripe in the danger color. */ +.error { + margin: var(--space-2) 0 0; + padding: var(--space-2) var(--space-3); + border-left: var(--line-strong) solid var(--color-danger); + font-size: var(--font-size-xs); + line-height: var(--line-height-snug); +} + +@keyframes open { + from { + opacity: 0; + transform: translateY(-4px); + } +} + +@media (prefers-reduced-motion: reduce) { + .panel:not([hidden]) { + animation: none; + } +} diff --git a/frontend/src/widgets/candidate-shell/ui/cabinet-menu.tsx b/frontend/src/widgets/candidate-shell/ui/cabinet-menu.tsx new file mode 100644 index 0000000..6349cb9 --- /dev/null +++ b/frontend/src/widgets/candidate-shell/ui/cabinet-menu.tsx @@ -0,0 +1,81 @@ +import { Link, useLocation } from "react-router-dom"; +import { useSignOut } from "../../../features/sign-out"; +import { MenuButton, useMenuToggle } from "../../../shared/ui"; +import { + currentOf, + notificationsLink, + privacyLink, + supportLink, + type CabinetLink, +} from "../model/sections"; +import styles from "./cabinet-menu.module.css"; + +type CabinetMenuProps = { + /** + * "account" is the drop-down of the desktop header. "more" is the last item + * of the phone tab bar; it also holds the notifications, which the phone + * header shows only as an icon. + */ + variant: "account" | "more"; +}; + +const accountLinks: readonly CabinetLink[] = [privacyLink, supportLink]; +const moreLinks: readonly CabinetLink[] = [notificationsLink, privacyLink, supportLink]; + +/** + * The rarely used destinations of the cabinet and the sign-out action behind + * one button. It is a disclosure: the button carries aria-expanded and + * aria-controls, the links and the button follow it in the tab order, Escape + * closes the menu and returns focus to the button, and so do a navigation + * and a press or focus outside of the menu. + */ +export function CabinetMenu({ variant }: CabinetMenuProps) { + const { menuId, buttonRef, rootRef, isOpen, toggle } = useMenuToggle({ dismissOutside: true }); + const { signOut, isPending, failed } = useSignOut(); + const { pathname } = useLocation(); + const links = variant === "more" ? moreLinks : accountLinks; + const isMore = variant === "more"; + + return ( +
+ currentOf(pathname, link) !== "none")} + /> + +
+ ); +} diff --git a/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css b/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css index a91e56e..caa63f0 100644 --- a/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css +++ b/frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css @@ -11,8 +11,14 @@ top: 0; } -/* Phone: the tab strip is a bar fixed to the bottom edge. It scrolls - * sideways; the current tab is scrolled into the middle by the shell. */ +/* Below 1024px a blurred plate would become the containing block of the + * fixed tab bar inside it, so the plate is solid. */ +.plate { + background: var(--color-surface); + backdrop-filter: none; +} + +/* Phone and tablet: the sections are a bar fixed to the bottom edge. */ .nav { position: fixed; z-index: 20; @@ -20,27 +26,101 @@ bottom: 0; left: 0; border-top: var(--line-thin) solid var(--color-divider); - background: rgb(27 28 33 / 92%); + background: rgb(27 28 33 / 94%); backdrop-filter: blur(14px) saturate(140%); } +/* Five equal slots; "Приглашения" is the longest label, so the labels are + * set small and tight enough for 360px. */ .list { - display: flex; - gap: var(--space-1); + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + max-width: 36rem; min-height: var(--tab-bar-height); - margin: 0; - padding: var(--space-2) var(--space-3) calc(var(--space-2) + env(safe-area-inset-bottom)); - overflow-x: auto; - overscroll-behavior-x: contain; + margin: 0 auto; + padding: var(--space-2) var(--space-1) calc(var(--space-2) + env(safe-area-inset-bottom)); list-style: none; - scroll-snap-type: x proximity; - scrollbar-width: none; } -.list li { +.list > li { display: flex; + min-width: 0; +} + +.list > li > a, +.more button[aria-controls] { + flex: 1; + justify-content: center; + min-width: 0; + min-height: var(--control-height); + padding-inline: 0; + font-size: 0.6875rem; + letter-spacing: -0.04em; +} + +/* The menu wrapper takes the slot, so its button can fill it. */ +.more > div { + display: flex; + flex: 1; + min-width: 0; +} + +/* "Ещё" looks like the other tabs: no outline, no burger. */ +.more button[aria-controls] { + width: 100%; + border: 0; + color: var(--color-text-secondary); + background: transparent; +} + +.more button[aria-controls]:hover { + color: var(--color-text); + background: var(--color-surface-tint-hover); +} + +.more button[aria-controls][aria-expanded="true"] { + color: var(--color-on-inverse); + background: var(--color-inverse); +} + +.more button[aria-controls][data-current]:not([aria-expanded="true"]) { + color: var(--color-text); +} + +.actions { + display: flex; + gap: var(--space-2); align-items: center; - scroll-snap-align: center; +} + +/* The account drop-down is a desktop control. */ +.account { + display: none; +} + +/* Notifications: an icon button, 44px. */ +.bell { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: var(--control-height); + height: var(--control-height); + border-radius: var(--radius-pill); + color: var(--color-text-secondary); + transition: + background-color var(--duration-fast) var(--easing-standard), + color var(--duration-fast) var(--easing-standard); +} + +.bell:hover { + color: var(--color-text); + background: var(--color-surface-tint-hover); +} + +.bell[aria-current] { + color: var(--color-on-inverse); + background: var(--color-inverse); } /* Room for the bottom bar, so the end of a page is never under it. */ @@ -48,35 +128,59 @@ padding-bottom: calc(var(--tab-bar-height) + env(safe-area-inset-bottom)); } -/* A blurred plate would become the containing block of the fixed bar, so - * the phone plate is solid. */ -@media (width < 43.75rem) { - .plate { - background: var(--color-surface); - backdrop-filter: none; +/* Tablet: the slots are wide enough for the regular label size. */ +@media (width >= 43.75rem) { + .list > li > a, + .more button[aria-controls] { + font-size: var(--font-size-xs); + letter-spacing: 0; } } -/* Tablet: the tabs move into the plate, under the wordmark. */ -@media (width >= 43.75rem) { +/* Desktop: one row. The wordmark, the four sections to its right, then the + * bell and the account menu at the far end. */ +@media (width >= 64rem) { .plate { - flex-wrap: wrap; - row-gap: 0; + justify-content: flex-start; + background: rgb(32 33 41 / 88%); + backdrop-filter: blur(14px) saturate(140%); } .nav { position: static; - flex: 1 1 100%; - min-width: 0; - margin-inline: calc(-1 * var(--space-2)); - border-top: var(--line-thin) solid var(--color-divider); + margin-left: var(--space-3); + border-top: 0; background: none; backdrop-filter: none; } .list { + display: flex; + gap: var(--space-1); + max-width: none; min-height: auto; - padding: var(--space-2) var(--space-1); + margin: 0; + padding: 0; + } + + .list > li > a { + flex: none; + padding-inline: 0.875rem; + font-size: var(--font-size-s); + letter-spacing: 0; + } + + .list .more { + display: none; + } + + .actions { + margin-left: auto; + padding-right: var(--space-1); + } + + .account { + display: block; } .main { @@ -84,39 +188,8 @@ } } -/* Desktop: one row, the tabs to the right of the wordmark. */ -@media (width >= 64rem) { - .plate { - flex-wrap: nowrap; - } - +@supports not (backdrop-filter: blur(1px)) { .nav { - flex: 0 1 auto; - margin-inline: 0; - border-top: 0; - } - - .list { - padding: 0; + background: var(--color-surface); } } - -/* A strip that hides tabs fades at that edge, so the cut tab reads as "more - * to scroll". The fade is a mask, so the strip keeps its own background. */ -.list[data-fade-end] { - mask-image: linear-gradient(to right, #000 calc(100% - 3rem), transparent); -} - -.list[data-fade-start] { - mask-image: linear-gradient(to left, #000 calc(100% - 3rem), transparent); -} - -.list[data-fade-start][data-fade-end] { - mask-image: linear-gradient( - to right, - transparent, - #000 3rem, - #000 calc(100% - 3rem), - transparent - ); -} diff --git a/frontend/src/widgets/candidate-shell/ui/candidate-shell.test.tsx b/frontend/src/widgets/candidate-shell/ui/candidate-shell.test.tsx new file mode 100644 index 0000000..10a1505 --- /dev/null +++ b/frontend/src/widgets/candidate-shell/ui/candidate-shell.test.tsx @@ -0,0 +1,213 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { Page } from "../../../shared/ui"; +import { CandidateShell } from "./candidate-shell"; + +const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"; + +function render(path: string): string { + return renderToStaticMarkup( + + + + }> + } /> + } /> + + + + , + ); +} + +function text(html: string): string { + return html + .replace(/<[^>]+>/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function between(html: string, start: RegExp, end: string): string { + const from = html.search(start); + expect(from).toBeGreaterThanOrEqual(0); + const rest = html.slice(from); + return rest.slice(0, rest.indexOf(end) + end.length); +} + +type Link = { href: string; label: string; current: string | null }; + +/** Anchors of a markup fragment with their destination and aria-current. */ +function links(html: string): Link[] { + return [...html.matchAll(/]*)>(.*?)<\/a>/gs)].map((match) => { + const attributes = match[1] ?? ""; + return { + href: /href="([^"]*)"/.exec(attributes)?.[1] ?? "", + label: /aria-label="([^"]*)"/.exec(attributes)?.[1] ?? text(match[2] ?? ""), + current: /aria-current="([^"]*)"/.exec(attributes)?.[1] ?? null, + }; + }); +} + +function primaryNav(html: string): string { + return between(html, /]*aria-label="Разделы кабинета кандидата"/, ""); +} + +/** The four section links, without the "more" item and its sheet. */ +function primaryLinks(html: string): Link[] { + return links(primaryNav(html).replace(/]*>]*data-variant="more".*$/s, "")); +} + +function currentPrimary(html: string): Array<[string, string | null]> { + return primaryLinks(html) + .filter((link) => link.current !== null) + .map((link) => [link.label, link.current]); +} + +describe("candidate shell header", () => { + it("shows the wordmark alone and four primary sections", () => { + const html = render("/candidate"); + const header = between(html, /
"); + const topLevel = primaryLinks(html); + + expect(links(header)[0]).toMatchObject({ href: "/candidate", label: "Lincodex" }); + expect(text(header)).not.toContain("Кабинет кандидата"); + expect(topLevel.map((link) => link.label)).toEqual([ + "Главная", + "Профиль", + "Тест", + "Приглашения", + ]); + expect(topLevel.map((link) => link.href)).toEqual([ + "/candidate", + "/candidate/profile", + "/candidate/assessment", + "/candidate/invitations", + ]); + }); + + it.each([ + ["/candidate", [["Главная", "page"]]], + ["/candidate/profile", [["Профиль", "page"]]], + ["/candidate/questionnaire", [["Профиль", "true"]]], + ["/candidate/assessment", [["Тест", "page"]]], + [`/candidate/assessment/${attemptId}`, [["Тест", "true"]]], + ["/candidate/results", [["Тест", "true"]]], + [`/candidate/results/${attemptId}`, [["Тест", "true"]]], + ["/candidate/invitations", [["Приглашения", "page"]]], + [`/candidate/invitations/${attemptId}`, [["Приглашения", "true"]]], + ["/candidate/notifications", []], + ["/candidate/privacy", []], + ["/candidate/support/cases/new", []], + ])("marks the primary section of %s as current", (path, expected) => { + expect(currentPrimary(render(path))).toEqual(expected); + }); +}); + +describe("secondary switch", () => { + it("lets the profile pages switch between the profile and the questionnaire", () => { + const html = render("/candidate/questionnaire"); + const nav = between(html, /]*aria-label="Разделы профиля"/, ""); + + expect(links(nav)).toEqual([ + { href: "/candidate/profile", label: "Профиль", current: null }, + { href: "/candidate/questionnaire", label: "Анкета", current: "page" }, + ]); + // The switch sits above the heading, inside the page. + expect(html.indexOf("Разделы профиля")).toBeLessThan(html.indexOf(" { + const onAttempt = between( + render(`/candidate/assessment/${attemptId}`), + /]*aria-label="Проверка и результаты"/, + "", + ); + expect(links(onAttempt)).toEqual([ + { href: "/candidate/assessment", label: "Проверка", current: "true" }, + { href: "/candidate/results", label: "Результаты", current: null }, + ]); + + const onResult = between( + render(`/candidate/results/${attemptId}`), + /]*aria-label="Проверка и результаты"/, + "", + ); + expect(links(onResult).map((link) => link.current)).toEqual([null, "true"]); + }); + + it.each(["/candidate", "/candidate/invitations", "/candidate/privacy"])( + "is absent on %s", + (path) => { + const html = render(path); + expect(html).not.toContain("Разделы профиля"); + expect(html).not.toContain("Проверка и результаты"); + }, + ); +}); + +describe("notifications bell", () => { + it("is a named link to the notifications page", () => { + const html = render("/candidate"); + const bell = links(between(html, /]*aria-label="Уведомления"/, "")); + + expect(bell).toEqual([ + { href: "/candidate/notifications", label: "Уведомления", current: null }, + ]); + expect(html).toMatch(/]*aria-label="Уведомления"[^>]*>]*aria-hidden="true"/); + }); + + it("is current on the notifications page", () => { + const html = render("/candidate/notifications"); + + expect(html).toMatch(/]*aria-label="Уведомления"[^>]*aria-current="page"/); + }); +}); + +describe("account menu", () => { + const panel = (html: string, variant: "account" | "more") => + between(html, new RegExp(`data-variant="${variant}"`), ""); + + it("collapses privacy, support, and sign-out behind one button", () => { + const html = render("/candidate"); + const account = panel(html, "account"); + const button = /]*aria-controls="([^"]*)"[^>]*>/.exec(account); + + expect(account).toMatch(/]*aria-expanded="false"[^>]*>Аккаунт]*hidden`)); + expect(links(account)).toEqual([ + { href: "/candidate/privacy", label: "Приватность", current: null }, + { href: "/candidate/support/cases", label: "Поддержка", current: null }, + ]); + expect(account).toMatch(/]*type="button"[^>]*>Выйти<\/button>/); + }); + + it("marks the destination that is open and the button that holds it", () => { + const html = render("/candidate/support/cases/new"); + const account = panel(html, "account"); + + expect(links(account).map((link) => link.current)).toEqual([null, "true"]); + expect(account).toMatch(/]*data-current="true"/); + }); +}); + +describe("tab bar menu for narrow screens", () => { + it("has a fifth item that opens notifications, privacy, support, and sign-out", () => { + const html = render("/candidate"); + const more = between(html, /data-variant="more"/, ""); + + expect(more).toMatch(/]*aria-expanded="false"[^>]*>Ещё<\/button>/); + expect(links(more).map((link) => link.label)).toEqual([ + "Уведомления", + "Приватность", + "Поддержка", + ]); + expect(more).toMatch(/]*type="button"[^>]*>Выйти<\/button>/); + }); + + it("keeps the more item inside the cabinet navigation landmark", () => { + expect(primaryNav(render("/candidate"))).toContain("Ещё"); + }); +}); diff --git a/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx b/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx index d32099d..2ebced8 100644 --- a/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx +++ b/frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx @@ -1,108 +1,106 @@ -import { useEffect, useRef, useState, type RefObject } from "react"; -import { Outlet, useLocation } from "react-router-dom"; +import { Link, Outlet, useLocation } from "react-router-dom"; import { paths } from "../../../shared/config"; -import { HeaderPlate, MainRegion, NavItem, SkipLink, Wordmark } from "../../../shared/ui"; +import { + HeaderPlate, + MainRegion, + NavItem, + PageNavProvider, + SectionSwitch, + SkipLink, + Wordmark, +} from "../../../shared/ui"; +import { currentOf, findSection, notificationsLink, primarySections } from "../model/sections"; +import { CabinetMenu } from "./cabinet-menu"; import styles from "./candidate-shell.module.css"; -const navigation = [ - { to: paths.candidate.root, label: "Главная", end: true }, - { to: paths.candidate.profile, label: "Профиль", end: false }, - { to: paths.candidate.questionnaire, label: "Анкета", end: false }, - { to: paths.candidate.assessment, label: "Тест", end: false }, - { to: paths.candidate.results, label: "Результаты", end: false }, - { to: paths.candidate.invitations, label: "Приглашения", end: false }, - { to: paths.candidate.notifications, label: "Уведомления", end: false }, - { to: paths.candidate.privacy, label: "Приватность", end: false }, - { to: paths.candidate.supportCases, label: "Поддержка", end: false }, -] as const; - -/** - * Keeps the current section visible in a horizontally scrolling tab strip. - * Only the strip scrolls; the page does not move. - */ -function useCurrentTabInView() { - const listRef = useRef(null); - const { pathname } = useLocation(); - - useEffect(() => { - const list = listRef.current; - const current = list?.querySelector('[aria-current="page"]'); - if (!list || !current || list.scrollWidth <= list.clientWidth) return; - const left = current.offsetLeft - (list.clientWidth - current.offsetWidth) / 2; - list.scrollLeft = Math.max(0, left); - }, [pathname]); - - return listRef; -} - -type ScrollEdges = { start: boolean; end: boolean }; - -/** - * Whether the tab strip hides tabs before or after the visible part. The - * shell fades that edge, so a cut tab reads as "scroll for more". - */ -function useScrollEdges(listRef: RefObject): ScrollEdges { - const [edges, setEdges] = useState({ start: false, end: false }); - - useEffect(() => { - const list = listRef.current; - if (!list) return; - const update = () => { - const start = list.scrollLeft > 1; - const end = list.scrollLeft + list.clientWidth < list.scrollWidth - 1; - setEdges((current) => - current.start === start && current.end === end ? current : { start, end }, - ); - }; - update(); - list.addEventListener("scroll", update, { passive: true }); - const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update); - observer?.observe(list); - return () => { - list.removeEventListener("scroll", update); - observer?.disconnect(); - }; - }, [listRef]); - - return edges; +/** Bell icon: decoration; the link's accessible name is its aria-label. */ +function BellIcon() { + return ( + + ); } /** - * 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; - * from 700px they sit in the header plate. The navigation comes before main - * in the document, so the keyboard order is the same at every width. + * Candidate cabinet layout. The header carries the wordmark, four primary + * sections, the notifications bell, and an account menu; the questionnaire + * and the results are reached through a switch at the top of their section's + * pages. Below 1024px the sections move into a bar at the bottom of the + * screen, within thumb reach, and the header keeps the wordmark and the bell. + * The navigation comes before main in the document, so the keyboard order is + * the same at every width. */ export function CandidateShell() { - const listRef = useCurrentTabInView(); - const edges = useScrollEdges(listRef); + const { pathname } = useLocation(); + const section = findSection(pathname); + const sub = section?.sub; + const notifications = currentOf(pathname, notificationsLink); return (
- + +
+ + + +
+ +
+
- + ({ + to: item.to, + label: item.label, + current: currentOf(pathname, item), + }))} + /> + ) : null + } + > + +
);