feat(frontend): simplify the candidate cabinet header

This commit is contained in:
shira committed 2026-10-10 15:34:42 +03:00
1 parent 90ff71735a
commit 89932b8714
28 files changed
+1154 -179

No files matched your search

+10 -2
View File
@@ -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(/<a[^>]*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(["Приглашения"]);
});
+2 -2
View File
@@ -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;
}
+2
View File
@@ -0,0 +1,2 @@
export { requestSignOut } from "./model/request-sign-out";
export { useSignOut } from "./model/use-sign-out";
@@ -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);
},
);
});
@@ -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<void> {
try {
await logout({ headers: session ? { "X-CSRF-Token": session.csrf_token } : {} });
} catch (error: unknown) {
if (error instanceof ApiRequestError && error.status === 401) {
return;
}
throw error;
}
}
@@ -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<Session>(getGetCurrentSessionQueryKey())),
onSuccess: () => {
window.location.assign(paths.login);
},
});
return {
signOut: () => mutation.mutate(),
isPending: mutation.isPending || mutation.isSuccess,
failed: mutation.isError,
};
}
+3 -1
View File
@@ -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";
@@ -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;
+16
View File
@@ -0,0 +1,16 @@
import { createContext, useContext, type ReactNode } from "react";
const PageNavContext = createContext<ReactNode>(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);
}
+5 -1
View File
@@ -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 <title> 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}`}</title>
{sectionNav ? <div className={styles["section-nav"]}>{sectionNav}</div> : null}
<header className={styles["page-header"]}>
{eyebrow ? <p className={styles.eyebrow}>{eyebrow}</p> : null}
<h1 className={styles.title}>{title}</h1>
@@ -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);
}
+32 -4
View File
@@ -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<LinkProps, "className"> & {
@@ -12,19 +13,46 @@ export function TextLink({ className, ...rest }: TextLinkProps) {
export type NavItemLayout = "row" | "rail";
type NavItemProps = Omit<NavLinkProps, "className" | "children"> & {
/**
* 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<NavLinkProps, "className" | "children" | "style"> & {
/** "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 (
<Link
{...linkProps}
className={className}
aria-current={current === "none" ? undefined : current}
>
{children}
</Link>
);
}
return (
<NavLink {...rest} className={className}>
{children}
@@ -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);
}
@@ -7,13 +7,32 @@ type MenuButtonProps = {
onToggle: () => void;
buttonRef: RefObject<HTMLButtonElement | null>;
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 (
<button
ref={buttonRef}
@@ -21,13 +40,35 @@ export function MenuButton({ menuId, isOpen, onToggle, buttonRef, className }: M
className={className ? `${styles.root} ${className}` : styles.root}
aria-expanded={isOpen}
aria-controls={menuId}
data-current={current || undefined}
onClick={onToggle}
>
<span className={styles.icon} aria-hidden="true" data-open={isOpen || undefined}>
<span />
<span />
</span>
Меню
{icon === "bars" ? (
<span className={styles.icon} aria-hidden="true" data-open={isOpen || undefined}>
<span />
<span />
</span>
) : null}
{label}
{icon === "chevron" ? (
<svg
className={styles.chevron}
viewBox="0 0 12 12"
width="12"
height="12"
aria-hidden="true"
focusable="false"
>
<path
d="M2.5 4.5 6 8l3.5-3.5"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
) : null}
</button>
);
}
@@ -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<HTMLButtonElement>(null);
const rootRef = useRef<HTMLDivElement>(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 };
}
@@ -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);
}
@@ -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 (
<nav aria-label={label} className={styles.root}>
<ul className={styles.track}>
{items.map((item) => (
<li key={item.to} className={styles.segment}>
<Link
to={item.to}
className={styles.link}
aria-current={item.current === "none" ? undefined : item.current}
>
{item.label}
</Link>
</li>
))}
</ul>
</nav>
);
}
@@ -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");
}
@@ -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;
}
}
@@ -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 (
<div ref={rootRef} className={styles.root} data-variant={variant}>
<MenuButton
className={styles.button}
menuId={menuId}
isOpen={isOpen}
onToggle={toggle}
buttonRef={buttonRef}
label={isMore ? "Ещё" : "Аккаунт"}
icon={isMore ? "none" : "chevron"}
current={links.some((link) => currentOf(pathname, link) !== "none")}
/>
<div id={menuId} className={styles.panel} hidden={!isOpen}>
<ul className={styles.items}>
{links.map((link) => {
const current = currentOf(pathname, link);
return (
<li key={link.id}>
<Link
to={link.to}
className={styles.item}
aria-current={current === "none" ? undefined : current}
>
{link.label}
</Link>
</li>
);
})}
<li className={styles.separated}>
<button type="button" className={styles.item} disabled={isPending} onClick={signOut}>
{isPending ? "Выходим..." : "Выйти"}
</button>
</li>
</ul>
{failed ? (
<p className={styles.error} role="alert">
Не удалось выйти. Вы остаетесь в кабинете, попробуйте еще раз.
</p>
) : null}
</div>
</div>
);
}
@@ -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
);
}
@@ -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(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/candidate" element={<CandidateShell />}>
<Route path="*" element={<Page title="Страница" />} />
<Route index element={<Page title="Страница" />} />
</Route>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
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\s([^>]*)>(.*?)<\/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, /<nav[^>]*aria-label="Разделы кабинета кандидата"/, "</nav>");
}
/** The four section links, without the "more" item and its sheet. */
function primaryLinks(html: string): Link[] {
return links(primaryNav(html).replace(/<li[^>]*><div[^>]*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, /<header/, "</header>");
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, /<nav[^>]*aria-label="Разделы профиля"/, "</nav>");
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("<h1"));
});
it("lets the test pages switch between the check and the results", () => {
const onAttempt = between(
render(`/candidate/assessment/${attemptId}`),
/<nav[^>]*aria-label="Проверка и результаты"/,
"</nav>",
);
expect(links(onAttempt)).toEqual([
{ href: "/candidate/assessment", label: "Проверка", current: "true" },
{ href: "/candidate/results", label: "Результаты", current: null },
]);
const onResult = between(
render(`/candidate/results/${attemptId}`),
/<nav[^>]*aria-label="Проверка и результаты"/,
"</nav>",
);
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, /<a[^>]*aria-label="Уведомления"/, "</a>"));
expect(bell).toEqual([
{ href: "/candidate/notifications", label: "Уведомления", current: null },
]);
expect(html).toMatch(/<a[^>]*aria-label="Уведомления"[^>]*><svg[^>]*aria-hidden="true"/);
});
it("is current on the notifications page", () => {
const html = render("/candidate/notifications");
expect(html).toMatch(/<a[^>]*aria-label="Уведомления"[^>]*aria-current="page"/);
});
});
describe("account menu", () => {
const panel = (html: string, variant: "account" | "more") =>
between(html, new RegExp(`data-variant="${variant}"`), "</ul>");
it("collapses privacy, support, and sign-out behind one button", () => {
const html = render("/candidate");
const account = panel(html, "account");
const button = /<button[^>]*aria-controls="([^"]*)"[^>]*>/.exec(account);
expect(account).toMatch(/<button[^>]*aria-expanded="false"[^>]*>Аккаунт</);
// The panel is hidden until the button opens it, and the button names it.
expect(account).toMatch(new RegExp(`id="${button?.[1]}"[^>]*hidden`));
expect(links(account)).toEqual([
{ href: "/candidate/privacy", label: "Приватность", current: null },
{ href: "/candidate/support/cases", label: "Поддержка", current: null },
]);
expect(account).toMatch(/<button[^>]*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(/<button[^>]*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"/, "</ul>");
expect(more).toMatch(/<button[^>]*aria-expanded="false"[^>]*>Ещё<\/button>/);
expect(links(more).map((link) => link.label)).toEqual([
"Уведомления",
"Приватность",
"Поддержка",
]);
expect(more).toMatch(/<button[^>]*type="button"[^>]*>Выйти<\/button>/);
});
it("keeps the more item inside the cabinet navigation landmark", () => {
expect(primaryNav(render("/candidate"))).toContain("Ещё");
});
});
@@ -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<HTMLUListElement>(null);
const { pathname } = useLocation();
useEffect(() => {
const list = listRef.current;
const current = list?.querySelector<HTMLElement>('[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<HTMLUListElement | null>): ScrollEdges {
const [edges, setEdges] = useState<ScrollEdges>({ start: false, end: false });
useEffect(() => {
const list = listRef.current;
if (!list) return;
const update = () => {
const start = list.scrollLeft > 1;
const end = list.scrollLeft + list.clientWidth < list.scrollWidth - 1;
setEdges((current) =>
current.start === start && current.end === end ? current : { start, end },
);
};
update();
list.addEventListener("scroll", update, { passive: true });
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update);
observer?.observe(list);
return () => {
list.removeEventListener("scroll", update);
observer?.disconnect();
};
}, [listRef]);
return edges;
/** Bell icon: decoration; the link's accessible name is its aria-label. */
function BellIcon() {
return (
<svg
viewBox="0 0 24 24"
width="20"
height="20"
aria-hidden="true"
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M6 9.5a6 6 0 1 1 12 0c0 4.2 1.5 5.6 2 6.5H4c.5-.9 2-2.3 2-6.5Z" />
<path d="M10 19.5a2 2 0 0 0 4 0" />
</svg>
);
}
/**
* 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 (
<div className={styles.shell}>
<SkipLink />
<header className={styles.header}>
<HeaderPlate className={styles.plate}>
<Wordmark to={paths.candidate.root} context="Кабинет кандидата" />
<Wordmark to={paths.candidate.root} />
<nav className={styles.nav} aria-label="Разделы кабинета кандидата">
<ul
ref={listRef}
className={styles.list}
data-fade-start={edges.start || undefined}
data-fade-end={edges.end || undefined}
>
{navigation.map((item) => (
<li key={item.to}>
<NavItem to={item.to} end={item.end}>
<ul className={styles.list}>
{primarySections.map((item) => (
<li key={item.id}>
<NavItem to={item.to} current={currentOf(pathname, item)}>
{item.label}
</NavItem>
</li>
))}
<li className={styles.more}>
<CabinetMenu variant="more" />
</li>
</ul>
</nav>
<div className={styles.actions}>
<Link
to={notificationsLink.to}
className={styles.bell}
aria-label={notificationsLink.label}
aria-current={notifications === "none" ? undefined : notifications}
>
<BellIcon />
</Link>
<div className={styles.account}>
<CabinetMenu variant="account" />
</div>
</div>
</HeaderPlate>
</header>
<MainRegion className={styles.main}>
<Outlet />
<PageNavProvider
value={
sub ? (
<SectionSwitch
label={sub.label}
items={sub.items.map((item) => ({
to: item.to,
label: item.label,
current: currentOf(pathname, item),
}))}
/>
) : null
}
>
<Outlet />
</PageNavProvider>
</MainRegion>
</div>
);