feat(frontend): add cabinet shells, brand tokens, and state primitives

This commit is contained in:
shira committed 2026-10-06 01:09:08 +03:00
1 parent dda3825786
commit 0e2a3b02ab
85 files changed
+3313 -113

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./ui/app";
import "../shared/ui/theme/fonts.css";
import "../shared/ui/theme/tokens.css";
import "./ui/styles.css";
const rootElement = document.getElementById("root");
@@ -0,0 +1,108 @@
import { QueryObserver, type QueryObserverResult } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiRequestError, networkErrorCode } from "../../shared/api";
import { getGetHealthzQueryOptions } from "../../shared/api/endpoints/health/health";
import type { HealthResponse } from "../../shared/api/schemas";
import { QueryView } from "../../shared/ui";
import { createQueryClient, maxQueryRetries, shouldRetryQuery } from "./query-client";
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
function problemResponse(status: number, code: string, traceId: string): Response {
return new Response(
JSON.stringify({ type: `urn:lincodex:problem:${code}`, title: code, status, code }),
{
status,
headers: { "content-type": "application/problem+json", "x-request-id": traceId },
},
);
}
function healthyResponse(): Response {
return new Response(JSON.stringify({ status: "ok" }), {
headers: { "content-type": "application/json" },
});
}
function renderHealth(result: QueryObserverResult<HealthResponse, unknown>): string {
return renderToStaticMarkup(
<QueryView query={result}>{(health) => <p>API: {health.status}</p>}</QueryView>,
);
}
describe("shouldRetryQuery", () => {
const error = (status: number, code: ApiRequestError["code"]) =>
new ApiRequestError({ status, code, title: "fixture" });
it.each([
["no response", error(0, networkErrorCode), true],
["a server error", error(503, "http_error"), true],
["an internal error", error(500, "internal"), true],
["an operation that is not implemented", error(501, "not_implemented"), false],
["a validation error", error(400, "validation_failed"), false],
["a missing session", error(401, "unauthenticated"), false],
["a forbidden request", error(403, "forbidden"), false],
["rate limiting", error(429, "rate_limited"), false],
["an invalid response body", error(200, "invalid_response"), false],
["a programming error", new TypeError("bad path"), false],
])("retry after %s: %s", (_name, failure, expected) => {
expect(shouldRetryQuery(0, failure)).toBe(expected);
});
it("stops after the retry budget", () => {
expect(shouldRetryQuery(maxQueryRetries, error(503, "http_error"))).toBe(false);
});
});
describe("query error and retry through the shared client", () => {
it("shows the error state for a failing request and recovers on retry", async () => {
vi.useFakeTimers();
const request = vi
.fn()
.mockImplementation(() => Promise.resolve(problemResponse(503, "http_error", "req-503")));
vi.stubGlobal("fetch", request);
const queryClient = createQueryClient();
const observer = new QueryObserver(queryClient, getGetHealthzQueryOptions());
const unsubscribe = observer.subscribe(() => undefined);
// The first attempt and two automatic retries all fail.
await vi.runAllTimersAsync();
const failed = observer.getCurrentResult();
expect(request).toHaveBeenCalledTimes(1 + maxQueryRetries);
expect(request).toHaveBeenCalledWith("/api/v1/healthz", expect.anything());
expect(failed.status).toBe("error");
const errorHtml = renderHealth(failed);
expect(errorHtml).toContain('role="alert"');
expect(errorHtml).toContain("Сервис временно недоступен");
expect(errorHtml).toContain("req-503");
expect(errorHtml).toMatch(/<button[^>]*>Повторить<\/button>/);
// The retry button calls refetch on the same query.
request.mockImplementation(() => Promise.resolve(healthyResponse()));
await failed.refetch();
const recovered = observer.getCurrentResult();
expect(recovered.status).toBe("success");
expect(renderHealth(recovered)).toBe("<p>API: ok</p>");
unsubscribe();
});
it("does not retry a forbidden response and shows the forbidden state", async () => {
const request = vi.fn().mockResolvedValue(problemResponse(403, "forbidden", "req-403"));
vi.stubGlobal("fetch", request);
const queryClient = createQueryClient();
const observer = new QueryObserver(queryClient, getGetHealthzQueryOptions());
await observer.refetch();
const html = renderHealth(observer.getCurrentResult());
expect(request).toHaveBeenCalledTimes(1);
expect(html).toContain("Нет доступа");
expect(html).not.toContain("<button");
});
});
@@ -0,0 +1,45 @@
import { QueryClient } from "@tanstack/react-query";
import { ApiRequestError, invalidResponseCode } from "../../shared/api";
/** Automatic retries after the first failure of a query. */
export const maxQueryRetries = 2;
/**
* Retries only failures that a later attempt can fix: no response (status 0)
* and server errors other than 501. Client errors (4xx), invalid response
* bodies, and programming errors fail at once so their state shows quickly.
*/
export function shouldRetryQuery(failureCount: number, error: unknown): boolean {
if (failureCount >= maxQueryRetries || !(error instanceof ApiRequestError)) {
return false;
}
if (error.code === invalidResponseCode) {
return false;
}
return error.status === 0 || (error.status >= 500 && error.status !== 501);
}
/**
* Server cache for the application. Generated Orval hooks supply each query
* function through the shared same-origin apiRequest client, so there is no
* default query function here.
*
* Window focus does not refetch: cabinets hold forms and long reads where a
* background refetch would flicker states; screens that need fresh data opt
* in per query. Mutations never retry automatically because they are not
* idempotent until the API supports Idempotency-Key.
*/
export function createQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: shouldRetryQuery,
staleTime: 30_000,
refetchOnWindowFocus: false,
},
mutations: {
retry: false,
},
},
});
}
+134
View File
@@ -0,0 +1,134 @@
import { QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { createQueryClient } from "../providers/query-client";
import { routes } from "./routes";
// Node has no DOM in this project's Vitest setup, so routes are rendered
// through React Router's static handler: the same route tree, loaders, and
// layouts as in the browser, checked as server-rendered HTML.
async function render(path: string): Promise<string | Response> {
const handler = createStaticHandler(routes);
const context = await handler.query(new Request(`http://localhost${path}`));
if (context instanceof Response) {
return context;
}
const router = createStaticRouter(handler.dataRoutes, context);
return renderToString(
<QueryClientProvider client={createQueryClient()}>
<StaticRouterProvider router={router} context={context} hydrate={false} />
</QueryClientProvider>,
);
}
async function renderHtml(path: string): Promise<string> {
const result = await render(path);
if (typeof result !== "string") {
throw new Error(`Expected HTML for ${path}, got a ${result.status} response.`);
}
return result;
}
function count(html: string, pattern: RegExp): number {
return html.match(new RegExp(pattern.source, "g"))?.length ?? 0;
}
function currentLinkText(html: string): string[] {
return [...html.matchAll(/<a[^>]*aria-current="page"[^>]*>(.*?)<\/a>/g)].map(
(match) => match[1] ?? "",
);
}
describe("route groups", () => {
it.each([
["/", "Протокол подтвержденных навыков", "Публичные разделы"],
["/login", "Вход", "Публичные разделы"],
["/register", "Регистрация", "Публичные разделы"],
["/verify-email", "Подтверждение почты", "Публичные разделы"],
["/support", "Поддержка", "Публичные разделы"],
["/candidate", "Главная", "Разделы кабинета кандидата"],
["/candidate/profile", "Профиль", "Разделы кабинета кандидата"],
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
["/employer/company", "Компания и команда", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
const html = await renderHtml(path);
expect(count(html, /<h1[\s>]/)).toBe(1);
expect(html).toMatch(new RegExp(`<h1[^>]*>${heading}</h1>`));
expect(html).toMatch(new RegExp(`<nav[^>]*aria-label="${navLabel}"`));
expect(count(html, /<main[\s>]/)).toBe(1);
expect(html).toMatch(/<main[^>]*id="main-content"[^>]*tabindex="-1"/i);
expect(html).toContain(`<title>${heading} - Lincodex</title>`);
});
it("puts the skip link before any other link and points it at main", async () => {
for (const path of ["/", "/candidate", "/employer/needs"]) {
const html = await renderHtml(path);
const firstLink = html.match(/<a[^>]*>(.*?)<\/a>/);
expect(firstLink?.[0]).toContain('href="#main-content"');
expect(firstLink?.[1]).toBe("Перейти к основному содержимому");
}
});
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("/employer/invitations"))).toEqual(["Приглашения"]);
});
it("separates the cabinets: each shell shows only its own navigation", async () => {
const candidate = await renderHtml("/candidate");
const employer = await renderHtml("/employer/company");
expect(candidate).not.toContain("Разделы кабинета работодателя");
expect(candidate).not.toContain("Публичные разделы");
expect(employer).not.toContain("Разделы кабинета кандидата");
expect(employer).not.toContain("Публичные разделы");
});
it("sends the employer cabinet root to the company screen", async () => {
const result = await render("/employer");
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(302);
expect((result as Response).headers.get("Location")).toBe("/employer/company");
});
it.each([
["/missing", "/", "На главную"],
["/candidate/missing", "/candidate", "В кабинет кандидата"],
["/employer/missing", "/employer/company", "В кабинет работодателя"],
])("shows a not-found page for %s inside the matching shell", async (path, home, label) => {
const html = await renderHtml(path);
expect(html).toMatch(/<h1[^>]*>Страница не найдена<\/h1>/);
expect(html).toMatch(new RegExp(`<a[^>]*href="${home}"[^>]*>${label}</a>`));
});
});
describe("product readiness", () => {
it("presents the root page as a scaffold, not as a working product", async () => {
const html = await renderHtml("/");
expect(html).toContain("Сейчас доступен только каркас интерфейса");
// The API liveness check lives on the technical page, not on the landing.
expect(html).not.toContain("healthz");
expect(html).toMatch(/<a[^>]*href="\/status"[^>]*>Технический статус<\/a>/);
});
it("labels the status page as technical", async () => {
const html = await renderHtml("/status");
expect(html).toContain("Служебная страница");
expect(html).toContain("Это не показатель готовности продукта");
});
it("labels every cabinet screen as a placeholder", async () => {
for (const path of ["/candidate", "/candidate/privacy", "/employer/needs"]) {
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
}
});
});
+89
View File
@@ -0,0 +1,89 @@
import { redirect, type RouteObject } from "react-router-dom";
import { NotFoundPage } from "../../pages/not-found";
import { PlaceholderPage } from "../../pages/placeholder";
import { StatusPage } from "../../pages/status";
import { WelcomePage } from "../../pages/welcome";
import { paths } from "../../shared/config";
import { CandidateShell } from "../../widgets/candidate-shell";
import { EmployerShell } from "../../widgets/employer-shell";
import { PublicShell } from "../../widgets/public-shell";
import { RootLayout } from "../ui/root-layout";
import { RouteErrorPage } from "../ui/route-error-page";
/**
* Route tree with three groups: public pages, the candidate cabinet, and the
* employer cabinet. Each group has its own shell and its own not-found page.
* Access control is not implemented yet; the server will enforce it.
*/
export const routes: RouteObject[] = [
{
element: <RootLayout />,
errorElement: <RouteErrorPage />,
children: [
{
element: <PublicShell />,
children: [
{ index: true, element: <WelcomePage /> },
{ path: paths.login, element: <PlaceholderPage screen="login" /> },
{ path: paths.register, element: <PlaceholderPage screen="register" /> },
{ path: paths.verifyEmail, element: <PlaceholderPage screen="verifyEmail" /> },
{ path: paths.support, element: <PlaceholderPage screen="support" /> },
{ path: paths.status, element: <StatusPage /> },
{ path: "*", element: <NotFoundPage /> },
],
},
{
path: paths.candidate.root,
element: <CandidateShell />,
children: [
{ index: true, element: <PlaceholderPage screen="candidateHome" /> },
{
path: paths.candidate.onboarding,
element: <PlaceholderPage screen="candidateOnboarding" />,
},
{ path: paths.candidate.profile, element: <PlaceholderPage screen="candidateProfile" /> },
{
path: paths.candidate.assessment,
element: <PlaceholderPage screen="candidateAssessment" />,
},
{ path: paths.candidate.results, element: <PlaceholderPage screen="candidateResults" /> },
{
path: paths.candidate.invitations,
element: <PlaceholderPage screen="candidateInvitations" />,
},
{ path: paths.candidate.privacy, element: <PlaceholderPage screen="candidatePrivacy" /> },
{
path: "*",
element: (
<NotFoundPage homePath={paths.candidate.root} homeLabel="В кабинет кандидата" />
),
},
],
},
{
path: paths.employer.root,
element: <EmployerShell />,
children: [
// The employer flow starts with the company profile.
{ index: true, loader: () => redirect(paths.employer.company) },
{ path: paths.employer.company, element: <PlaceholderPage screen="employerCompany" /> },
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
{
path: paths.employer.candidates,
element: <PlaceholderPage screen="employerCandidates" />,
},
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{
path: "*",
element: (
<NotFoundPage homePath={paths.employer.company} homeLabel="В кабинет работодателя" />
),
},
],
},
],
},
];
+7 -16
View File
@@ -1,24 +1,15 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { HomePage } from "../../pages/home";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { createQueryClient } from "../providers/query-client";
import { routes } from "../router/routes";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: 30_000,
},
},
});
const queryClient = createQueryClient();
const router = createBrowserRouter(routes);
export function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route path="*" element={<HomePage />} />
</Routes>
</BrowserRouter>
<RouterProvider router={router} />
</QueryClientProvider>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { Outlet, ScrollRestoration } from "react-router-dom";
/** Top route element shared by every route group. */
export function RootLayout() {
return (
<>
<ScrollRestoration />
<Outlet />
</>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { useRouteError } from "react-router-dom";
import { ErrorState, Page } from "../../shared/ui";
/**
* Last-resort boundary for errors thrown while rendering a route. It has no
* shell, because the shell itself may be what failed.
*/
export function RouteErrorPage() {
const error = useRouteError();
return (
<main>
<Page title="Ошибка интерфейса" eyebrow="Lincodex">
<ErrorState
error={error}
title="Не удалось показать страницу"
onRetry={() => {
window.location.reload();
}}
/>
</Page>
</main>
);
}
+67 -12
View File
@@ -1,32 +1,87 @@
/* Global base styles. Tokens and fonts are imported before this file. */
:root {
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
color: #15202b;
background: #f4f6f8;
color: var(--color-text);
font-family: var(--font-text);
font-size: 100%;
line-height: var(--line-height-body);
background-color: var(--color-canvas);
color-scheme: light;
font-synthesis: none;
text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
min-width: 320px;
min-width: 20rem;
min-height: 100vh;
margin: 0;
font-size: var(--font-size-m);
/* Sparse dot grid: a quiet "protocol paper" texture behind surfaces. */
background-image: radial-gradient(circle at 1px 1px, rgb(27 28 33 / 9%) 1px, transparent 1.5px);
background-size: 1.5rem 1.5rem;
}
h1,
h2,
h3,
h4,
p,
ul,
ol,
dl,
dd,
figure {
margin: 0;
}
h1,
h2,
h3,
h4 {
line-height: var(--line-height-snug);
text-wrap: balance;
}
button,
input,
select,
textarea {
font: inherit;
color: inherit;
}
img,
svg {
display: block;
max-width: 100%;
}
/* One focus indicator for every interactive element. Local dark regions
* override --color-focus-ring with a checked value. */
:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
:focus:not(:focus-visible) {
outline: none;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
}
}