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

+3 -1
View File
@@ -10,6 +10,8 @@ Use the generated Orval client as the contract-derived transport surface. Put sh
Model server data in the selected query library and form drafts in form state. Avoid adding a second store for data already owned by the server cache. Show loading, empty, error, retry, and forbidden states as product flows are implemented.
MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current page is a minimal status view; do not document full candidate or employer interfaces as implemented.
MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current interface is a scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, shared UI tokens, and primitives for loading, empty, error, forbidden, and saving states. The sign-in, registration, email confirmation, support, and all cabinet screens are placeholders; business screens are later tasks, so do not document candidate or employer workflows as implemented. /status is a technical API liveness page, not a product readiness indicator.
Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior; clicks, keyboard focus, and layout are verified manually in a browser until the planned Playwright suite exists.
All source comments are in English. User-facing interface copy can be localized.
+1 -1
View File
@@ -4,7 +4,7 @@ This document separates the target product architecture from the technical scaff
## Current scaffold
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a minimal React status page, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
+4 -2
View File
@@ -50,7 +50,7 @@ What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has a home page, a generated API client, and MSW handlers.
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka.
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding.
@@ -136,7 +136,9 @@ Redis connects through the outbound cache port and `backend/internal/adapter/sec
S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules.
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added. Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added.
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, brand tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono 2.304 is self-hosted from the brandbook with its OFL license. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM, so clicks and keyboard focus are verified manually in a browser until the Playwright suite exists. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result.
+1 -1
View File
@@ -4,7 +4,7 @@
## Что работает сейчас
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, минимальную React-страницу состояния, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Это технический каркас. В нем нет регистрации, ролей, профилей, тестов, грейдов, поиска, приглашений, загрузки/анализа резюме, PDF или интеграции с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
+4 -2
View File
@@ -50,7 +50,7 @@ Frontend зависимости выбираются из актуальных s
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть домашняя страница, generated API client и MSW handlers.
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness.
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md).
@@ -136,7 +136,9 @@ Redis подключен через outbound-порт кеша и `backend/inter
S3-хранилище подключено через outbound-порт `ObjectStorage` и `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS - отдельный сервер, а AWS SDK for Go v2 - клиент Go внутри адаптера. Put/Get передают содержимое потоком; Put требует известный размер в байтах, а вызывающий код обязан закрыть тело, возвращенное Get. Таймаут Get действует до завершения чтения тела. Адаптер ограничивает время операций и отличает отсутствие объекта от ошибки сервиса. Bucket создается при запуске контейнера; Go проверяет его через HeadBucket, не создавая инфраструктуру при обработке запросов. Не добавляйте прямую выдачу приватных файлов Nginx или продуктовые upload/download endpoints без правил доступа.
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы. Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы.
Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены бренда в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. JetBrains Mono 2.304 раздается с нашего сервера из брендбука вместе с лицензией OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока нет набора Playwright. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат.
+71 -3
View File
@@ -2,13 +2,81 @@
[Русский](README.md) | English
A React and TypeScript SPA built with Vite and organized using FSD. The current page shows backend status; candidate and employer dashboards are not implemented yet.
A React and TypeScript SPA built with Vite and organized using FSD. The interface scaffold exists: public pages and the candidate and employer cabinet shells with navigation, shared screen states, and brand tokens. Every screen is a placeholder; business screens are separate tasks.
- `src/app/` starts the application; `pages/`, `widgets/`, `features/`, and `entities/` are the interface layers.
- `src/shared/` contains shared components and the API client, including generated endpoints, Zod schemas, and MSW mocks.
- `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page.
- `src/pages/` holds pages: `welcome` (start page), `placeholder` (screen placeholders and the screen map), `status` (technical status), `not-found`.
- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget.
- `src/features/` and `src/entities/` are still empty.
- `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks.
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract.
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
## Routes
| Group | Paths | Shell |
| --------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Candidate | `/candidate` and `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Access control is not implemented in the interface; the server enforces it.
`/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it.
## Server data
Generated Orval hooks call the shared same-origin `apiRequest` client, so the `QueryClient` has no default query function. Defaults in `app/providers/query-client.ts`:
- retries: up to two, only for no response (status 0) and 5xx except 501; 4xx and `invalid_response` fail at once;
- `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query;
- mutations do not retry until the API supports `Idempotency-Key`.
## Tokens and theme
Tokens live in `shared/ui/theme/tokens.css`: palette, semantic colors, type scale, spacing in 4px steps, radii, lines, focus ring, content widths, and motion. Breakpoints are fixed in media queries: 360px minimum, 768px tablet (`48rem`), 1024px desktop navigation (`64rem`), and 1280px verified wide layout.
Only the light theme ships. The graphite employer sidebar is a local dark region with its own checked text, link, and focus colors. A dark theme must define and check its own pairs instead of inheriting the light accents.
WCAG 2.2 contrast of the pairs in use:
| Foreground | Background | Ratio | Use |
| ---------- | ---------- | ----- | ----------------------------------------- |
| #1B1C21 | #FFFFFF | 17.01 | Text on surfaces |
| #1B1C21 | #EDEDED | 14.53 | Text on the canvas |
| #2D2E37 | #FFFFFF | 13.48 | Secondary text |
| #2D2E37 | #EDEDED | 11.52 | Secondary text on the canvas |
| #402FFF | #FFFFFF | 6.84 | Links, active navigation, focus ring |
| #402FFF | #EDEDED | 5.85 | Labels and links on the canvas |
| #FFFFFF | #402FFF | 6.84 | Primary button, skip link |
| #EDEDED | #1B1C21 | 14.53 | Employer sidebar text |
| #FFFFFF | #1B1C21 | 17.01 | Active item and focus ring in the sidebar |
| #EC1D35 | #FFFFFF | 4.38 | Error graphics only (needs 3:1) |
| #FFFFFF | #EC1D35 | 4.38 | Glyph inside the error mark (graphic) |
Excluded pairs: red is not used for body text (4.38 is below 4.5); #402FFF on #1B1C21 (2.49) and on #2D2E37 (1.97) is not used; grey #C8C9CA (1.66 on white) is only for decorative dividers.
## Fonts and logos
JetBrains Mono 2.304 (SIL OFL 1.1) is self-hosted from `requirements/brandbook/`: regular and bold woff2 files plus the license and authors list live in `shared/ui/theme/fonts/`. The font is used through `Mono` for numbers, scores, codes, and pseudonyms. Text uses the system font stack: Unbounded and Golos Text are not added, because their files and licenses are not in the repository.
The header uses the FSP brandbook logo: `logo_02w.svg` on light backgrounds and `logo_01.svg` on the graphite sidebar, unchanged, with the product name beside it.
## Shared components
- `Page`, `Section`, `Stack`: page layout; `Page` owns the only `h1` and the document title.
- `Button`, `ButtonLink`, `TextLink`, `NavItem`: controls with text labels; `NavItem` marks the active section with `aria-current`, a bar, and weight.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus`: screen states. Each state has its own shape and text. `ErrorState` shows the code, status, server text, and request ID as plain text and offers a retry.
- `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.
- `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`, `BrandLogo`.
Accessibility: every shell starts with a skip link to `main`, has landmarks and a visible focus ring, and moves focus to `main` after navigation. Animations respect `prefers-reduced-motion`.
## Tests
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Clicks and focus movement are checked manually in a browser; automated interaction tests need a DOM environment, which is a separate dependency decision.
See the [development guide](../docs/en/DEVELOPMENT.md).
+71 -3
View File
@@ -2,13 +2,81 @@
Русский | [English](README.en.md)
SPA на React и TypeScript со сборкой Vite и структурой FSD. Сейчас интерфейс показывает состояние backend; кабинеты кандидата и работодателя пока не реализованы.
SPA на React и TypeScript со сборкой Vite и структурой FSD. Готов каркас интерфейса: публичные страницы и оболочки кабинетов кандидата и работодателя с навигацией, общими состояниями экранов и токенами бренда. Все экраны - заготовки; бизнес-экраны делаются отдельными задачами.
- `src/app/` - запуск приложения; `pages/`, `widgets/`, `features/`, `entities/` - слои интерфейса.
- `src/shared/` - общие компоненты и API-клиент, включая сгенерированные endpoints, схемы Zod и MSW-моки.
- `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута.
- `src/pages/` - страницы: `welcome` (стартовая), `placeholder` (заготовки экранов и карта экранов), `status` (технический статус), `not-found`.
- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`.
- `src/features/` и `src/entities/` пока пусты.
- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта.
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
## Маршруты
| Группа | Пути | Оболочка |
| ------------ | ------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Контроль доступа в интерфейсе не реализован; его обеспечивает сервер.
`/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает.
## Серверные данные
Сгенерированные хуки Orval вызывают общий клиент `apiRequest` того же origin, поэтому у `QueryClient` нет функции запроса по умолчанию. Настройки в `app/providers/query-client.ts`:
- повторы: не больше двух и только при отсутствии ответа (статус 0) и 5xx, кроме 501; 4xx и `invalid_response` завершаются сразу;
- `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса;
- мутации не повторяются, пока API не поддерживает `Idempotency-Key`.
## Токены и тема
Токены лежат в `shared/ui/theme/tokens.css`: палитра, семантические цвета, шкала шрифтов, отступы с шагом 4px, радиусы, линии, кольцо фокуса, ширины контента и анимация. Точки перелома зафиксированы в media-запросах: минимум 360px, планшет 768px (`48rem`), навигация для компьютера 1024px (`64rem`) и проверенная широкая ширина 1280px.
Поставляется только светлая тема. Графитовая боковая панель работодателя - локальная темная область со своими проверенными цветами текста, ссылок и фокуса. Темная тема должна задать и проверить свои пары, а не наследовать светлые акценты.
Контраст используемых пар по WCAG 2.2:
| Текст | Фон | Контраст | Где |
| ------- | ------- | -------- | ----------------------------------------- |
| #1B1C21 | #FFFFFF | 17.01 | Текст на поверхностях |
| #1B1C21 | #EDEDED | 14.53 | Текст на фоне страницы |
| #2D2E37 | #FFFFFF | 13.48 | Второстепенный текст |
| #2D2E37 | #EDEDED | 11.52 | Второстепенный текст на фоне страницы |
| #402FFF | #FFFFFF | 6.84 | Ссылки, активная навигация, кольцо фокуса |
| #402FFF | #EDEDED | 5.85 | Метки и ссылки на фоне страницы |
| #FFFFFF | #402FFF | 6.84 | Основная кнопка, ссылка пропуска |
| #EDEDED | #1B1C21 | 14.53 | Текст боковой панели работодателя |
| #FFFFFF | #1B1C21 | 17.01 | Активный пункт и кольцо фокуса в панели |
| #EC1D35 | #FFFFFF | 4.38 | Только графика ошибок (нужно 3:1) |
| #FFFFFF | #EC1D35 | 4.38 | Знак внутри метки ошибки (графика) |
Исключенные пары: красный не используется для основного текста (4.38 меньше 4.5); #402FFF на #1B1C21 (2.49) и на #2D2E37 (1.97) не используется; серый #C8C9CA (1.66 на белом) - только для декоративных разделителей.
## Шрифты и логотипы
JetBrains Mono 2.304 (SIL OFL 1.1) раздается с нашего сервера из `requirements/brandbook/`: файлы woff2 обычного и жирного начертания, текст лицензии и список авторов лежат в `shared/ui/theme/fonts/`. Шрифт применяется через `Mono` для чисел, баллов, кодов и псевдонимов. Для текста используется системный набор шрифтов: Unbounded и Golos Text не добавлены, потому что их файлов и лицензий нет в репозитории.
В шапке используется логотип ФСП из брендбука без изменений: `logo_02w.svg` на светлом фоне и `logo_01.svg` на графитовой панели, рядом - название продукта.
## Общие компоненты
- `Page`, `Section`, `Stack` - раскладка страницы; `Page` содержит единственный `h1` и задает заголовок документа.
- `Button`, `ButtonLink`, `TextLink`, `NavItem` - элементы управления с текстовыми подписями; `NavItem` отмечает активный раздел через `aria-current`, полосу и насыщенность.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus` - состояния экранов. У каждого состояния своя форма и текст. `ErrorState` показывает код, статус, текст сервера и идентификатор запроса как обычный текст и предлагает повтор.
- `QueryView` - превращает результат запроса в загрузку, ошибку, отсутствие доступа (401 и 403 без повтора), пустое состояние или данные.
- `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью.
- `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`, `BrandLogo`.
Доступность: каждая оболочка начинается со ссылки пропуска к `main`, содержит ориентиры и видимое кольцо фокуса и переводит фокус на `main` после перехода. Анимации учитывают `prefers-reduced-motion`.
## Тесты
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия и перемещение фокуса проверяются вручную в браузере; автоматические тесты взаимодействия требуют DOM-окружения, а это отдельное решение о зависимости.
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f4f6f8" />
<meta name="theme-color" content="#ededed" />
<title>Lincodex</title>
</head>
<body>
+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;
}
}
-1
View File
@@ -1 +0,0 @@
export { HomePage } from "./ui/home-page";
@@ -1,54 +0,0 @@
.page {
display: grid;
min-height: 100vh;
padding: 2rem;
place-items: center;
}
.panel {
width: min(100%, 38rem);
padding: clamp(1.5rem, 5vw, 3rem);
border: 1px solid #dce3e9;
border-radius: 1.25rem;
background: #fff;
box-shadow: 0 1.5rem 4rem rgb(21 32 43 / 8%);
}
.status-mark {
display: block;
width: 0.65rem;
height: 0.65rem;
margin-bottom: 1.75rem;
border-radius: 50%;
background: #477a68;
}
.eyebrow {
margin: 0 0 0.75rem;
color: #52616f;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.panel h1 {
margin: 0;
font-size: clamp(1.8rem, 5vw, 2.5rem);
letter-spacing: -0.04em;
line-height: 1.15;
}
.description {
max-width: 31rem;
margin: 1rem 0 0;
color: #52616f;
font-size: 1rem;
line-height: 1.65;
}
@media (width <= 36rem) {
.page {
padding: 1rem;
}
}
-16
View File
@@ -1,16 +0,0 @@
import styles from "./home-page.module.css";
export function HomePage() {
return (
<main className={styles.page}>
<section aria-labelledby="page-title" className={styles.panel}>
<span aria-hidden="true" className={styles["status-mark"]} />
<p className={styles.eyebrow}>Lincodex</p>
<h1 id="page-title">Интерфейсная основа</h1>
<p className={styles.description}>
Сейчас доступен экран статуса каркаса. Пользовательские сценарии еще не подключены.
</p>
</section>
</main>
);
}
+1
View File
@@ -0,0 +1 @@
export { NotFoundPage } from "./ui/not-found-page";
@@ -0,0 +1,29 @@
import { useLocation } from "react-router-dom";
import { ButtonLink, Mono, Page } from "../../../shared/ui";
type NotFoundPageProps = {
/** Where the recovery link leads, for example the current cabinet. */
homePath?: string;
homeLabel?: string;
};
export function NotFoundPage({ homePath = "/", homeLabel = "На главную" }: NotFoundPageProps) {
const { pathname } = useLocation();
return (
<Page
title="Страница не найдена"
eyebrow="Ошибка 404"
lead={
<>
Адрес <Mono>{pathname}</Mono> не ведет ни на один экран. Проверьте ссылку или вернитесь к
началу.
</>
}
>
<div>
<ButtonLink to={homePath}>{homeLabel}</ButtonLink>
</div>
</Page>
);
}
+2
View File
@@ -0,0 +1,2 @@
export { PlaceholderPage } from "./ui/placeholder-page";
export type { ScreenId } from "./model/screens";
@@ -0,0 +1,142 @@
/**
* Screen map from the product requirements. Each entry is a placeholder
* until its business task implements the real screen; the "planned" lines
* describe intent, not implemented behavior.
*/
export type ScreenArea = "public" | "candidate" | "employer";
export type ScreenPlan = {
area: ScreenArea;
title: string;
planned: readonly string[];
};
export const areaLabels: Readonly<Record<ScreenArea, string>> = {
public: "Публичный раздел",
candidate: "Кабинет кандидата",
employer: "Кабинет работодателя",
};
export const screens = {
login: {
area: "public",
title: "Вход",
planned: ["Вход по почте и паролю", "Восстановление доступа", "Переход в кабинет по роли"],
},
register: {
area: "public",
title: "Регистрация",
planned: [
"Выбор сценария: кандидат или работодатель",
"Согласие на обработку персональных данных",
"Письмо для подтверждения почты",
],
},
verifyEmail: {
area: "public",
title: "Подтверждение почты",
planned: [
"Проверка ссылки из письма",
"Повторная отправка письма",
"Понятное сообщение об устаревшей ссылке",
],
},
support: {
area: "public",
title: "Поддержка",
planned: [
"Контакты поддержки",
"Ответы на частые вопросы",
"Как передать идентификатор запроса при ошибке",
],
},
candidateHome: {
area: "candidate",
title: "Главная",
planned: [
"Текущая категория и подтвержденный грейд",
"Следующий шаг по профилю",
"Новые приглашения",
],
},
candidateOnboarding: {
area: "candidate",
title: "Первые шаги",
planned: [
"Согласия и видимость профиля",
"Анкета и ожидаемый грейд",
"Переход к первому тесту",
],
},
candidateProfile: {
area: "candidate",
title: "Профиль",
planned: [
"Специальность и навыки",
"Резюме и достижения ФСП",
"Контакты, скрытые от компаний до приглашения",
],
},
candidateAssessment: {
area: "candidate",
title: "Тест",
planned: ["Выбор уровня теста", "Прохождение заданий", "Сохранение ответов"],
},
candidateResults: {
area: "candidate",
title: "Результаты",
planned: [
"Подтвержденная категория",
"История попыток и грейдов",
"Разбор результата по компетенциям",
],
},
candidateInvitations: {
area: "candidate",
title: "Приглашения",
planned: [
"Предложения компаний с вилкой зарплаты",
"Принятие или отказ",
"Какие компании получили доступ к контактам",
],
},
candidatePrivacy: {
area: "candidate",
title: "Приватность",
planned: ["Видимость профиля в поиске", "Отзыв согласий", "Журнал доступа к контактам"],
},
employerCompany: {
area: "employer",
title: "Компания и команда",
planned: ["Профиль компании", "Участники и их роли", "Приглашение коллег"],
},
employerNeeds: {
area: "employer",
title: "Потребности",
planned: [
"Описание потребности",
"Подтверждение извлеченных навыков",
"Фильтры поиска кандидатов",
],
},
employerCandidates: {
area: "employer",
title: "Кандидаты",
planned: [
"Объяснимая выдача по потребности",
"Шортлист",
"Псевдонимы вместо контактов до принятия приглашения",
],
},
employerInvitations: {
area: "employer",
title: "Приглашения",
planned: [
"Отправленные предложения",
"Статусы: отправлено, просмотрено, принято, отклонено",
"Доступ к контактам после принятия",
],
},
} as const satisfies Record<string, ScreenPlan>;
export type ScreenId = keyof typeof screens;
@@ -0,0 +1,43 @@
.notice {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: baseline;
padding: var(--space-4) var(--space-5);
border: var(--line-thin) dashed var(--color-border-strong);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.tag {
padding: 0 var(--space-2);
border: var(--line-thin) solid var(--color-accent);
border-radius: var(--radius-pill);
color: var(--color-accent);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.plan {
display: grid;
gap: 0;
margin: 0;
padding: 0;
list-style: none;
}
.plan li {
display: grid;
grid-template-columns: 2.5rem minmax(0, 1fr);
gap: var(--space-3);
padding: var(--space-3) 0;
border-bottom: var(--line-thin) solid var(--color-divider);
font-size: var(--font-size-l);
line-height: var(--line-height-snug);
}
.plan li > :first-child {
color: var(--color-accent);
}
@@ -0,0 +1,38 @@
import { Mono, Page, Section } from "../../../shared/ui";
import { areaLabels, screens, type ScreenId } from "../model/screens";
import styles from "./placeholder-page.module.css";
type PlaceholderPageProps = {
screen: ScreenId;
};
/**
* Honest stand-in for a screen that a later task implements. It names the
* screen and lists what is planned, without imitating working features.
*/
export function PlaceholderPage({ screen }: PlaceholderPageProps) {
const plan = screens[screen];
return (
<Page
title={plan.title}
eyebrow={areaLabels[plan.area]}
width={plan.area === "employer" ? "wide" : "narrow"}
>
<p className={styles.notice}>
<span className={styles.tag}>Заготовка</span>
Экран будет реализован в одной из следующих задач. Сейчас здесь нет данных и действий.
</p>
<Section title="Что здесь появится" headingLevel={2}>
<ol className={styles.plan}>
{plan.planned.map((item, index) => (
<li key={item}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono>
<span>{item}</span>
</li>
))}
</ol>
</Section>
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { StatusPage } from "./ui/status-page";
@@ -0,0 +1,11 @@
.success {
display: flex;
flex-wrap: wrap;
gap: var(--space-4);
align-items: center;
justify-content: space-between;
padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
@@ -0,0 +1,131 @@
import { useQuery } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import {
Button,
EmptyState,
ForbiddenState,
LoadingState,
Mono,
QueryView,
SavingStatus,
Section,
Stack,
TrustLevel,
} from "../../../shared/ui";
import styles from "./state-fixtures.module.css";
const fixtureDelayMs = 600;
let fixtureAttempts = 0;
function wait(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Built on demand so production bundles keep no fixture objects.
function forbiddenFixture(): ApiRequestError {
return new ApiRequestError({
status: 403,
code: "forbidden",
title: "Forbidden",
traceId: "fixture-trace-0002",
});
}
// Fails on every odd attempt, so "retry" visibly recovers.
async function flakyFixtureRequest(): Promise<{ attempt: number }> {
fixtureAttempts += 1;
const attempt = fixtureAttempts;
await wait(fixtureDelayMs);
if (attempt % 2 === 1) {
throw new ApiRequestError({
status: 500,
code: "internal",
title: "Internal server error",
detail: "Fixture failure for the development state gallery.",
traceId: "fixture-trace-0001",
});
}
return { attempt };
}
function FlakyRequestFixture() {
const query = useQuery({
queryKey: ["dev-fixture", "flaky-request"],
queryFn: flakyFixtureRequest,
retry: false,
staleTime: Infinity,
});
return (
<QueryView query={query} loadingLabel="Выполняем запрос-фикстуру...">
{(result) => (
<div className={styles.success}>
<p>
Повторный запрос выполнен, попытка <Mono strong>{result.attempt}</Mono>.
</p>
<Button
variant="secondary"
isBusy={query.isFetching}
onClick={() => {
void query.refetch();
}}
>
Снова получить ошибку
</Button>
</div>
)}
</QueryView>
);
}
/**
* Development-only gallery of shared states. Every value here is a local
* fixture; nothing comes from the server or proves an API workflow.
*/
export function StateFixtures() {
return (
<Section
title="Состояния экранов"
description="Видно только в режиме разработки. Все данные здесь вымышленные и не приходят с сервера."
>
<Section title="Ошибка и повтор" headingLevel={3}>
<FlakyRequestFixture />
</Section>
<Section title="Загрузка" headingLevel={3}>
<LoadingState />
</Section>
<Section title="Пусто" headingLevel={3}>
<EmptyState
title="Приглашений пока нет"
description="Когда компания отправит предложение, оно появится здесь."
/>
</Section>
<Section title="Нет доступа" headingLevel={3}>
<ForbiddenState error={forbiddenFixture()} />
</Section>
<Section title="Сохранение" headingLevel={3}>
<Stack gap={1}>
<SavingStatus state="saving" />
<SavingStatus state="saved" />
<SavingStatus state="failed" />
</Stack>
</Section>
<Section title="Уровни доверия" headingLevel={3}>
<Stack gap={2}>
<TrustLevel level="none" />
<TrustLevel level="claimed" />
<TrustLevel level="partial" />
<TrustLevel level="confirmed" />
</Stack>
</Section>
<Section title="Числа и псевдонимы" headingLevel={3}>
<p>
Кандидат <Mono strong>K-0427</Mono>, результат <Mono strong>87 / 100</Mono>, попытка{" "}
<Mono>2</Mono> от <Mono>14.09.2026</Mono>.
</p>
</Section>
</Section>
);
}
@@ -0,0 +1,20 @@
import { Page } from "../../../shared/ui";
import { SystemStatus } from "../../../widgets/system-status";
import { StateFixtures } from "./state-fixtures";
/**
* Service page for developers and operations. It is linked from the public
* footer only and is explicitly not a product readiness indicator.
*/
export function StatusPage() {
return (
<Page
title="Технический статус"
eyebrow="Служебная страница"
lead="Показывает, отвечает ли процесс API. Это не показатель готовности продукта: пользовательские сценарии здесь не проверяются."
>
<SystemStatus />
{import.meta.env.DEV ? <StateFixtures /> : null}
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { WelcomePage } from "./ui/welcome-page";
@@ -0,0 +1,79 @@
.cabinets {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.card {
position: relative;
display: grid;
gap: var(--space-2);
padding: var(--space-5);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-l);
color: var(--color-text);
text-decoration: none;
background: var(--color-surface);
transition:
border-color var(--duration-fast) var(--easing-standard),
transform var(--duration-base) var(--easing-standard);
}
/* Connector node in the corner, echoing the brand line graphics. */
.card::after {
position: absolute;
top: var(--space-5);
right: var(--space-5);
width: 0.75rem;
height: 0.75rem;
border: var(--line-strong) solid var(--color-accent);
border-radius: 50%;
content: "";
transition: background-color var(--duration-fast) var(--easing-standard);
}
.card:hover {
border-color: var(--color-accent);
transform: translateY(-2px);
}
.card:hover::after {
background: var(--color-accent);
}
.format {
color: var(--color-accent);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.card-title {
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
text-decoration: underline;
text-decoration-thickness: var(--line-thin);
text-underline-offset: 0.2em;
}
.summary {
color: var(--color-text-secondary);
}
.state {
width: fit-content;
padding: 0 var(--space-2);
border: var(--line-thin) dashed var(--color-border-strong);
border-radius: var(--radius-pill);
font-size: var(--font-size-xs);
}
@media (width >= 48rem) {
.cabinets {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@@ -0,0 +1,56 @@
import { Link } from "react-router-dom";
import { paths } from "../../../shared/config";
import { Page, Section, TextLink } from "../../../shared/ui";
import styles from "./welcome-page.module.css";
const cabinets = [
{
to: paths.candidate.root,
title: "Кабинет кандидата",
format: "Для телефона",
summary: "Профиль, тест, результаты, приглашения и настройки приватности.",
},
{
to: paths.employer.root,
title: "Кабинет работодателя",
format: "Для компьютера",
summary: "Компания и команда, потребности, подбор кандидатов и приглашения.",
},
] as const;
/**
* Public start page. It states plainly that only the interface scaffold
* exists, so it cannot be mistaken for a working product.
*/
export function WelcomePage() {
return (
<Page
title="Протокол подтвержденных навыков"
eyebrow="Lincodex"
lead="Сейчас доступен только каркас интерфейса: навигация, общие состояния экранов и оформление. Вход, регистрация и рабочие сценарии кабинетов появятся в следующих задачах."
>
<Section title="Кабинеты">
<ul className={styles.cabinets}>
{cabinets.map((cabinet) => (
<li key={cabinet.to}>
<Link className={styles.card} to={cabinet.to}>
<span className={styles.format}>{cabinet.format}</span>
<span className={styles["card-title"]}>{cabinet.title}</span>
<span className={styles.summary}>{cabinet.summary}</span>
<span className={styles.state}>Пустой каркас</span>
</Link>
</li>
))}
</ul>
</Section>
<Section title="Публичные страницы">
<p>
Заготовки: <TextLink to={paths.login}>вход</TextLink>,{" "}
<TextLink to={paths.register}>регистрация</TextLink>,{" "}
<TextLink to={paths.verifyEmail}>подтверждение почты</TextLink> и{" "}
<TextLink to={paths.support}>поддержка</TextLink>.
</p>
</Section>
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { paths } from "./paths";
+28
View File
@@ -0,0 +1,28 @@
/**
* Route paths shared by the router (app) and navigation (widgets), so a path
* is defined once. Cabinet paths are absolute and nest under their root.
*/
export const paths = {
home: "/",
login: "/login",
register: "/register",
verifyEmail: "/verify-email",
support: "/support",
status: "/status",
candidate: {
root: "/candidate",
onboarding: "/candidate/onboarding",
profile: "/candidate/profile",
assessment: "/candidate/assessment",
results: "/candidate/results",
invitations: "/candidate/invitations",
privacy: "/candidate/privacy",
},
employer: {
root: "/employer",
company: "/employer/company",
needs: "/employer/needs",
candidates: "/employer/candidates",
invitations: "/employer/invitations",
},
} as const;
View File
Whitespace-only changes.
@@ -0,0 +1,45 @@
.root {
display: inline-flex;
gap: var(--space-3);
align-items: center;
min-height: 2.75rem;
border-radius: var(--radius-s);
text-decoration: none;
}
.logo {
width: auto;
height: 1.75rem;
}
.divider {
align-self: stretch;
width: var(--line-thin);
margin-block: var(--space-2);
background: currentcolor;
opacity: 0.4;
}
.name {
display: grid;
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
letter-spacing: -0.01em;
line-height: 1.1;
}
.context {
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
letter-spacing: 0;
}
/* Graphite on white 17.01:1. */
.light {
color: var(--color-text);
}
/* Light grey on graphite 14.53:1. */
.dark {
color: var(--palette-light);
}
@@ -0,0 +1,36 @@
import { Link } from "react-router-dom";
import logoOnDark from "./fsp-logo-on-dark.svg";
import logoOnLight from "./fsp-logo-on-light.svg";
import styles from "./brand-logo.module.css";
type BrandLogoProps = {
/** Background the logo sits on; selects the brandbook color variant. */
tone?: "light" | "dark";
/** Destination of the home link. */
to?: string;
/** Cabinet name shown after the product name. */
context?: string | undefined;
};
/**
* Brandbook FSP logo (logo_02w for light, logo_01 for dark backgrounds)
* followed by the product name. The whole block is one link home.
*/
export function BrandLogo({ tone = "light", to = "/", context }: BrandLogoProps) {
return (
<Link to={to} className={`${styles.root} ${styles[tone]}`}>
<img
className={styles.logo}
src={tone === "dark" ? logoOnDark : logoOnLight}
alt="ФСП"
width="345"
height="116"
/>
<span className={styles.divider} aria-hidden="true" />
<span className={styles.name}>
Lincodex
{context ? <span className={styles.context}>{context}</span> : null}
</span>
</Link>
);
}
@@ -0,0 +1,12 @@
<svg width="345.000000" height="117.000000" viewBox="0 0 345 117" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<desc>
Created with Pixso.
</desc>
<defs/>
<path id="Vector" d="M36.42 96.37C35.54 95.73 34.88 94.83 34.54 93.79C34.2 92.76 34.2 91.64 34.53 90.61L35.61 86.15C35.81 85.36 36.16 84.63 36.66 83.99C37.15 83.35 37.78 82.82 38.49 82.44L42.03 80.58C44.22 79.45 45.97 77.62 47 75.38C48.02 73.15 48.28 70.63 47.72 68.24L47.67 68.01C47.01 65.33 45.38 62.99 43.08 61.45C40.79 59.9 38 59.27 35.27 59.67L31.3 60.24C30.5 60.35 29.68 60.3 28.89 60.07C28.11 59.85 27.39 59.46 26.76 58.94L23.26 55.97C22.39 55.32 21.75 54.41 21.41 53.38C21.08 52.35 21.08 51.24 21.41 50.21C22.15 47.92 22.13 45.45 21.34 43.17C20.56 40.89 19.05 38.93 17.05 37.59C15.05 36.24 12.67 35.58 10.26 35.71C7.85 35.84 5.55 36.74 3.71 38.29C1.86 39.84 0.57 41.95 0.03 44.3C-0.51 46.64 -0.27 49.1 0.72 51.3C1.7 53.5 3.37 55.32 5.48 56.48C7.59 57.65 10.03 58.09 12.41 57.75C12.8 57.7 13.18 57.61 13.56 57.52L14.59 57.32C15.45 57.16 16.33 57.18 17.17 57.4C18.02 57.62 18.8 58.03 19.46 58.6L24.22 62.72C24.95 63.35 25.51 64.16 25.84 65.07C26.17 65.98 26.27 66.95 26.13 67.91L26.01 68.63L25.91 69.27L25.91 69.32C25.76 70.64 25.84 71.98 26.16 73.27C26.16 73.35 26.16 73.42 26.22 73.49L26.22 73.57C26.67 75.32 27.56 76.93 28.79 78.26C28.94 78.42 29.09 78.57 29.24 78.71L29.76 79.23C30.45 79.93 30.95 80.78 31.21 81.72C31.47 82.66 31.5 83.65 31.27 84.6L29.82 90.7C29.62 91.54 29.23 92.33 28.68 93.01C28.12 93.68 27.42 94.22 26.63 94.58L25.74 94.99C25.38 95.13 25.02 95.3 24.68 95.48C23.06 96.33 21.67 97.58 20.66 99.1C18.97 101.51 18.32 104.49 18.83 107.38C19.35 110.27 21 112.84 23.41 114.52C25.82 116.2 28.8 116.86 31.7 116.34C34.6 115.83 37.17 114.18 38.85 111.77C39.85 110.41 40.52 108.84 40.81 107.17C40.88 106.8 40.93 106.42 40.96 106.04L41.08 105.07C41.01 103.36 40.56 101.69 39.75 100.18C38.94 98.67 37.81 97.37 36.42 96.37Z" fill="#EDEDED" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M121.18 43.37C120.59 41.59 119.56 39.98 118.18 38.7C116.81 37.42 115.12 36.51 113.3 36.05C111.47 35.6 109.56 35.62 107.74 36.1C105.92 36.59 104.26 37.53 102.9 38.83C102.61 39.09 102.34 39.37 102.08 39.66L101.41 40.38C100.82 41.02 100.09 41.52 99.28 41.83C98.47 42.15 97.6 42.28 96.73 42.21L90.47 41.7C89.5 41.62 88.56 41.3 87.75 40.76C86.93 40.22 86.27 39.48 85.82 38.61L85.49 37.96C85.39 37.76 85.3 37.57 85.19 37.39L85.19 37.33C84.54 36.17 83.69 35.14 82.66 34.28L82.5 34.15L82.42 34.08C81.02 32.94 79.36 32.16 77.59 31.8L77.52 31.8L76.89 31.7L76.15 31.64C75.19 31.48 74.28 31.08 73.52 30.48C72.75 29.88 72.15 29.09 71.77 28.19L69.35 22.43C69.01 21.63 68.87 20.76 68.92 19.89C68.97 19.02 69.22 18.17 69.64 17.41L70.13 16.59C70.34 16.26 70.53 15.92 70.7 15.58C71.44 14.06 71.83 12.4 71.83 10.71C71.75 7.82 70.54 5.08 68.47 3.07C66.4 1.05 63.62 -0.07 60.73 -0.07C57.84 -0.07 55.06 1.05 52.99 3.07C50.92 5.08 49.71 7.82 49.63 10.71C49.63 12.4 50.02 14.06 50.76 15.58C50.94 15.92 51.13 16.26 51.33 16.59L51.82 17.41C52.25 18.17 52.49 19.02 52.54 19.89C52.59 20.76 52.45 21.63 52.11 22.43L49.69 28.19C49.32 29.09 48.72 29.87 47.96 30.47C47.2 31.08 46.3 31.48 45.34 31.64L44.62 31.75L43.98 31.86L43.92 31.86C42.61 32.12 41.36 32.62 40.23 33.33L40.07 33.43C40.03 33.45 40 33.47 39.98 33.49C38.45 34.47 37.19 35.81 36.31 37.4L36.31 37.46C36.21 37.64 36.11 37.84 36.02 38.03C31.52 47.67 41.37 53.02 42.61 53.35C44.13 53.81 45.73 53.95 47.31 53.77C48.89 53.59 50.41 53.09 51.78 52.3L51.99 52.16C54.34 50.71 56.06 48.43 56.81 45.77C57.56 43.12 57.29 40.28 56.05 37.81L54.25 34.19C53.89 33.46 53.69 32.66 53.66 31.85C53.63 31.04 53.78 30.23 54.08 29.48L55.8 25.23C56.15 24.2 56.81 23.31 57.69 22.68C58.57 22.05 59.63 21.71 60.71 21.71C61.79 21.71 62.85 22.05 63.73 22.68C64.61 23.31 65.27 24.2 65.62 25.23L67.37 29.48C67.68 30.23 67.82 31.04 67.8 31.85C67.77 32.66 67.57 33.46 67.21 34.19L65.44 37.78C64.34 39.99 64 42.5 64.5 44.92C64.99 47.34 66.28 49.52 68.16 51.12L68.33 51.28C69.77 52.49 71.5 53.31 73.35 53.67C75.2 54.03 77.11 53.92 78.9 53.33C80.54 52.81 82.03 51.9 83.26 50.69L86.13 47.9C86.71 47.33 87.41 46.88 88.17 46.6C88.94 46.31 89.76 46.2 90.58 46.26L95.16 46.6C96.24 46.62 97.29 46.97 98.17 47.6C99.05 48.24 99.7 49.14 100.04 50.16C100.75 52.32 102.52 56.46 109 57.7C110.87 57.97 112.77 57.75 114.53 57.08C116.28 56.41 117.84 55.3 119.05 53.86C120.27 52.42 121.09 50.7 121.45 48.85C121.81 47 121.7 45.1 121.12 43.31L121.18 43.37Z" fill="#EC1D35" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M81.12 60.1C79.62 60.62 78.24 61.44 77.07 62.51C75.9 63.59 74.96 64.89 74.32 66.34C74.32 66.42 74.25 66.49 74.23 66.57C73.2 69.12 73.16 71.97 74.11 74.56C75.07 77.15 76.96 79.28 79.41 80.56L82.96 82.42C83.68 82.8 84.31 83.33 84.81 83.97C85.31 84.61 85.66 85.35 85.86 86.14L86.95 90.6C87.28 91.63 87.27 92.75 86.94 93.78C86.6 94.81 85.94 95.71 85.06 96.35C84.18 96.99 83.12 97.33 82.03 97.33C80.94 97.34 79.88 96.99 79 96.36L75.09 93.95C74.39 93.53 73.8 92.97 73.33 92.3C72.88 91.63 72.56 90.87 72.42 90.07L71.74 86.13C71.34 83.7 70.14 81.47 68.32 79.79C66.5 78.12 64.18 77.11 61.72 76.9L61.48 76.9C58.72 76.7 55.99 77.54 53.82 79.25C51.65 80.96 50.19 83.41 49.74 86.14C48.17 95.52 56.62 98.57 59.89 98.99L60.2 98.99C62 99.09 63.81 98.75 65.45 98L65.51 98L66.09 97.71L66.74 97.38C67.61 96.94 68.58 96.73 69.56 96.77C70.53 96.8 71.48 97.09 72.32 97.59L77.68 100.88C78.43 101.34 79.06 101.95 79.53 102.69C80 103.42 80.3 104.25 80.39 105.11L80.51 106.09C80.54 106.47 80.58 106.86 80.65 107.25C80.97 109.1 81.76 110.84 82.94 112.31C84.13 113.77 85.66 114.92 87.41 115.62C89.16 116.33 91.06 116.58 92.93 116.35C94.8 116.13 96.58 115.43 98.11 114.32C99.63 113.21 100.85 111.74 101.65 110.03C102.44 108.33 102.79 106.45 102.66 104.57C102.53 102.69 101.92 100.88 100.89 99.3C99.86 97.72 98.44 96.43 96.78 95.55C96.43 95.37 96.08 95.21 95.71 95.07L94.82 94.65C94.03 94.29 93.33 93.76 92.78 93.09C92.23 92.41 91.83 91.62 91.63 90.78L90.18 84.67C89.96 83.72 89.98 82.73 90.25 81.79C90.51 80.86 91.01 80 91.69 79.31L92.21 78.79C92.37 78.64 92.52 78.49 92.66 78.33L92.66 78.29C93.57 77.31 94.29 76.18 94.79 74.94L94.86 74.76L94.86 74.66C95.52 72.98 95.75 71.16 95.54 69.36L95.54 69.3C94.07 58.58 83.49 59.22 81.12 60.1Z" fill="#402FFF" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M174.15 98.32L174.15 89.57L163.44 89.57C161 89.52 158.61 88.83 156.52 87.58C154.21 86.22 150.12 81.72 148.86 79.94C147.62 78 147 75.74 147.08 73.44L147.08 41.91C146.99 39.58 147.61 37.28 148.86 35.32C150.12 33.68 154.21 29.14 156.52 27.78C158.61 26.53 161 25.85 163.44 25.79L174.15 25.79L174.15 17.3L185.8 17.3L185.8 25.78L196.26 25.78C198.69 25.84 201.07 26.53 203.18 27.76C205.49 29.13 209.47 33.63 210.84 35.31C212.09 37.27 212.71 39.57 212.62 41.89L212.62 73.43C212.7 75.72 212.08 77.99 210.84 79.92C209.47 81.71 205.49 86.21 203.18 87.56C201.08 88.8 198.69 89.49 196.26 89.56L185.8 89.56L185.8 98.3L174.15 98.32ZM163.69 77.32L174.15 77.32L174.15 38.03L163.8 38.03C162.33 39.17 161.02 40.51 159.92 42.01L159.92 73.44C160.99 74.91 162.26 76.21 163.69 77.32ZM199.82 41.93C198.82 40.42 197.54 39.1 196.05 38.05L185.8 38.05L185.8 77.34L195.94 77.34C197.37 76.19 198.67 74.89 199.82 73.47L199.82 41.93Z" fill="#EDEDED" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M268.09 44.63C266.94 41.93 265 39.63 262.53 38.05L243.89 38.05C242.31 39.23 240.92 40.64 239.77 42.24L239.77 73.46C240.82 75.05 242.23 76.38 243.89 77.33L262.73 77.33C264.99 75.69 266.83 73.54 268.09 71.05L280.05 73.99C279.18 76.37 277.98 78.63 276.48 80.68C273.96 84.25 269.06 89.59 262.64 89.59L243.36 89.59C240.92 89.52 238.54 88.84 236.44 87.6C234.24 86.24 230.25 82.05 228.78 80.06C227.6 78.1 226.98 75.85 226.99 73.57L226.99 41.8C226.9 39.5 227.52 37.23 228.78 35.31C230.03 33.66 234.13 29.23 236.54 27.76C238.62 26.56 240.96 25.88 243.36 25.78L262.64 25.78C269.04 25.78 273.87 31.12 276.38 34.57C277.87 36.62 279.07 38.87 279.95 41.25L268.09 44.63Z" fill="#EDEDED" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M332.05 89.05L332.05 38.45L305.54 38.45L305.54 89.05L292.74 89.05L292.74 29.73C292.74 28.8 293.11 27.91 293.77 27.26C294.43 26.6 295.31 26.23 296.24 26.23L341.35 26.23C342.27 26.23 343.16 26.6 343.82 27.26C344.47 27.91 344.84 28.8 344.85 29.73L344.85 89.1L332.05 89.05Z" fill="#EDEDED" fill-opacity="1.000000" fill-rule="nonzero"/>
</svg>

After

Width:  |  Height:  |  Size: 8.2 KiB

@@ -0,0 +1,12 @@
<svg width="345.000000" height="116.000000" viewBox="0 0 345 116" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<desc>
Created with Pixso.
</desc>
<defs/>
<path id="Vector" d="M36.42 95.22C35.54 94.59 34.88 93.7 34.54 92.67C34.2 91.65 34.2 90.54 34.53 89.51L35.61 85.09C35.81 84.32 36.16 83.59 36.66 82.96C37.15 82.33 37.78 81.8 38.49 81.42L42.03 79.58C44.22 78.46 45.97 76.64 47 74.43C48.02 72.21 48.28 69.72 47.72 67.35L47.67 67.13C47.01 64.47 45.38 62.15 43.08 60.62C40.79 59.09 38 58.46 35.27 58.86L31.3 59.42C30.5 59.54 29.68 59.48 28.89 59.26C28.11 59.04 27.39 58.65 26.76 58.13L23.26 55.19C22.39 54.55 21.75 53.65 21.41 52.63C21.08 51.61 21.08 50.51 21.41 49.48C22.15 47.21 22.13 44.76 21.34 42.51C20.56 40.25 19.05 38.31 17.05 36.98C15.05 35.64 12.67 34.99 10.26 35.11C7.85 35.24 5.55 36.14 3.71 37.68C1.86 39.21 0.57 41.3 0.03 43.63C-0.51 45.95 -0.27 48.39 0.72 50.57C1.7 52.74 3.37 54.55 5.48 55.7C7.59 56.85 10.03 57.3 12.41 56.96C12.8 56.9 13.18 56.82 13.56 56.73L14.59 56.54C15.45 56.37 16.33 56.39 17.17 56.61C18.02 56.83 18.8 57.24 19.46 57.8L24.22 61.88C24.95 62.51 25.51 63.31 25.84 64.21C26.17 65.11 26.27 66.08 26.13 67.02L26.01 67.74L25.91 68.37L25.91 68.43C25.76 69.73 25.84 71.06 26.16 72.34C26.16 72.41 26.16 72.49 26.22 72.55L26.22 72.63C26.67 74.37 27.56 75.97 28.79 77.28C28.94 77.44 29.09 77.58 29.24 77.73L29.76 78.24C30.45 78.93 30.95 79.78 31.21 80.71C31.47 81.64 31.5 82.62 31.27 83.56L29.82 89.6C29.62 90.44 29.23 91.23 28.68 91.9C28.12 92.56 27.42 93.1 26.63 93.45L25.74 93.86C25.38 94 25.02 94.16 24.68 94.34C23.06 95.19 21.67 96.42 20.66 97.93C18.97 100.32 18.32 103.27 18.83 106.14C19.35 109 21 111.55 23.41 113.21C25.82 114.88 28.8 115.53 31.7 115.02C34.6 114.51 37.17 112.88 38.85 110.49C39.85 109.14 40.52 107.58 40.81 105.93C40.88 105.56 40.93 105.18 40.96 104.81L41.08 103.84C41.01 102.15 40.56 100.5 39.75 99C38.94 97.51 37.81 96.22 36.42 95.22Z" fill="#C8C9CA" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M121.18 42.71C120.59 40.94 119.56 39.35 118.18 38.08C116.81 36.81 115.12 35.91 113.3 35.46C111.47 35.01 109.56 35.02 107.74 35.51C105.92 35.99 104.26 36.92 102.9 38.21C102.61 38.47 102.34 38.74 102.08 39.03L101.41 39.74C100.82 40.38 100.09 40.87 99.28 41.18C98.47 41.5 97.6 41.63 96.73 41.56L90.47 41.06C89.5 40.98 88.56 40.65 87.75 40.12C86.93 39.58 86.27 38.85 85.82 37.99L85.49 37.35C85.39 37.15 85.3 36.96 85.19 36.78L85.19 36.73C84.54 35.57 83.69 34.55 82.66 33.7L82.5 33.57L82.42 33.5C81.02 32.37 79.36 31.6 77.59 31.25L77.52 31.25L76.89 31.14L76.15 31.08C75.19 30.93 74.28 30.53 73.52 29.93C72.75 29.34 72.15 28.56 71.77 27.67L69.35 21.96C69.01 21.16 68.87 20.3 68.92 19.44C68.97 18.57 69.22 17.74 69.64 16.98L70.13 16.17C70.34 15.84 70.53 15.51 70.7 15.16C71.44 13.67 71.83 12.02 71.83 10.34C71.75 7.48 70.54 4.77 68.47 2.77C66.4 0.78 63.62 -0.34 60.73 -0.34C57.84 -0.34 55.06 0.78 52.99 2.77C50.92 4.77 49.71 7.48 49.63 10.34C49.63 12.02 50.02 13.67 50.76 15.16C50.94 15.51 51.13 15.84 51.33 16.17L51.82 16.98C52.25 17.74 52.49 18.57 52.54 19.44C52.59 20.3 52.45 21.16 52.11 21.96L49.69 27.67C49.32 28.55 48.72 29.33 47.96 29.93C47.2 30.52 46.3 30.92 45.34 31.08L44.62 31.2L43.98 31.3L43.92 31.3C42.61 31.56 41.36 32.05 40.23 32.75L40.07 32.86C40.03 32.87 40 32.89 39.98 32.92C38.45 33.89 37.19 35.22 36.31 36.79L36.31 36.85C36.21 37.03 36.11 37.22 36.02 37.41C31.52 46.97 41.37 52.27 42.61 52.6C44.13 53.05 45.73 53.19 47.31 53.01C48.89 52.83 50.41 52.34 51.78 51.55L51.99 51.42C54.34 49.98 56.06 47.72 56.81 45.09C57.56 42.46 57.29 39.64 56.05 37.2L54.25 33.61C53.89 32.89 53.69 32.1 53.66 31.29C53.63 30.49 53.78 29.68 54.08 28.94L55.8 24.73C56.15 23.71 56.81 22.83 57.69 22.2C58.57 21.58 59.63 21.24 60.71 21.24C61.79 21.24 62.85 21.58 63.73 22.2C64.61 22.83 65.27 23.71 65.62 24.73L67.37 28.94C67.68 29.68 67.82 30.49 67.8 31.29C67.77 32.1 67.57 32.89 67.21 33.61L65.44 37.17C64.34 39.35 64 41.84 64.5 44.24C64.99 46.64 66.28 48.8 68.16 50.39L68.33 50.54C69.77 51.74 71.5 52.56 73.35 52.92C75.2 53.27 77.11 53.16 78.9 52.58C80.54 52.06 82.03 51.16 83.26 49.96L86.13 47.2C86.71 46.63 87.41 46.19 88.17 45.91C88.94 45.62 89.76 45.51 90.58 45.57L95.16 45.91C96.24 45.92 97.29 46.27 98.17 46.9C99.05 47.54 99.7 48.42 100.04 49.44C100.75 51.58 102.52 55.68 109 56.91C110.87 57.17 112.77 56.96 114.53 56.29C116.28 55.63 117.84 54.53 119.05 53.1C120.27 51.67 121.09 49.97 121.45 48.14C121.81 46.31 121.7 44.42 121.12 42.65L121.18 42.71Z" fill="#EC1D35" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M81.12 59.28C79.62 59.8 78.24 60.61 77.07 61.68C75.9 62.74 74.96 64.03 74.32 65.47C74.32 65.55 74.25 65.62 74.23 65.69C73.2 68.23 73.16 71.05 74.11 73.61C75.07 76.18 76.96 78.3 79.41 79.56L82.96 81.4C83.68 81.78 84.31 82.3 84.81 82.94C85.31 83.57 85.66 84.3 85.86 85.09L86.95 89.51C87.28 90.53 87.27 91.64 86.94 92.66C86.6 93.68 85.94 94.57 85.06 95.21C84.18 95.84 83.12 96.18 82.03 96.18C80.94 96.18 79.88 95.85 79 95.22L75.09 92.83C74.39 92.41 73.8 91.86 73.33 91.19C72.88 90.53 72.56 89.78 72.42 88.98L71.74 85.08C71.34 82.67 70.14 80.46 68.32 78.8C66.5 77.15 64.18 76.14 61.72 75.94L61.48 75.94C58.72 75.74 55.99 76.57 53.82 78.26C51.65 79.95 50.19 82.39 49.74 85.09C48.17 94.38 56.62 97.41 59.89 97.82L60.2 97.82C62 97.93 63.81 97.59 65.45 96.84L65.51 96.84L66.09 96.55L66.74 96.23C67.61 95.79 68.58 95.58 69.56 95.62C70.53 95.66 71.48 95.94 72.32 96.44L77.68 99.7C78.43 100.15 79.06 100.76 79.53 101.49C80 102.21 80.3 103.04 80.39 103.89L80.51 104.85C80.54 105.24 80.58 105.62 80.65 106C80.97 107.84 81.76 109.57 82.94 111.02C84.13 112.47 85.67 113.6 87.41 114.31C89.16 115.01 91.06 115.26 92.93 115.03C94.8 114.81 96.58 114.11 98.11 113.02C99.63 111.92 100.85 110.46 101.65 108.77C102.44 107.07 102.79 105.21 102.66 103.35C102.53 101.49 101.92 99.69 100.89 98.13C99.86 96.57 98.44 95.29 96.78 94.42C96.43 94.24 96.08 94.08 95.71 93.93L94.82 93.53C94.03 93.17 93.33 92.64 92.78 91.97C92.23 91.31 91.83 90.52 91.63 89.69L90.18 83.63C89.96 82.69 89.98 81.71 90.25 80.78C90.51 79.85 91.01 79.01 91.69 78.32L92.21 77.8C92.37 77.66 92.52 77.51 92.66 77.36L92.66 77.31C93.57 76.34 94.29 75.22 94.79 74L94.86 73.81L94.86 73.72C95.52 72.05 95.75 70.25 95.54 68.47L95.54 68.4C94.07 57.78 83.49 58.41 81.12 59.28Z" fill="#402FFF" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M174.15 97.16L174.15 88.49L163.44 88.49C161 88.44 158.61 87.76 156.52 86.52C154.21 85.17 150.12 80.71 148.86 78.94C147.62 77.03 147 74.78 147.08 72.51L147.08 41.26C146.99 38.95 147.61 36.68 148.86 34.73C150.12 33.1 154.21 28.61 156.52 27.25C158.61 26.02 161 25.34 163.44 25.29L174.15 25.29L174.15 16.87L185.8 16.87L185.8 25.27L196.26 25.27C198.69 25.34 201.07 26.02 203.18 27.24C205.49 28.59 209.47 33.05 210.84 34.72C212.09 36.66 212.71 38.94 212.62 41.24L212.62 72.49C212.7 74.76 212.08 77.01 210.84 78.93C209.47 80.69 205.49 85.16 203.18 86.5C201.08 87.73 198.69 88.41 196.26 88.47L185.8 88.47L185.8 97.14L174.15 97.16ZM163.69 76.35L174.15 76.35L174.15 37.42L163.8 37.42C162.33 38.54 161.02 39.87 159.92 41.36L159.92 72.51C160.99 73.96 162.26 75.25 163.69 76.35ZM199.82 41.28C198.82 39.78 197.54 38.48 196.05 37.44L185.8 37.44L185.8 76.37L195.94 76.37C197.37 75.23 198.67 73.94 199.82 72.53L199.82 41.28Z" fill="#1B1C21" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M268.09 43.96C266.94 41.28 265 39 262.53 37.43L243.89 37.43C242.31 38.6 240.92 40 239.77 41.58L239.77 72.52C240.82 74.1 242.23 75.41 243.89 76.36L262.73 76.36C264.99 74.74 266.83 72.6 268.09 70.13L280.05 73.05C279.18 75.41 277.98 77.65 276.48 79.68C273.96 83.21 269.06 88.51 262.64 88.51L243.36 88.51C240.92 88.44 238.54 87.76 236.44 86.53C234.24 85.19 230.25 81.04 228.78 79.06C227.6 77.12 226.98 74.9 226.99 72.63L226.99 41.15C226.9 38.87 227.52 36.62 228.78 34.72C230.03 33.09 234.13 28.7 236.54 27.24C238.62 26.05 240.96 25.38 243.36 25.27L262.64 25.27C269.04 25.27 273.87 30.57 276.38 33.99C277.87 36.02 279.07 38.25 279.95 40.6L268.09 43.96Z" fill="#1B1C21" fill-opacity="1.000000" fill-rule="nonzero"/>
<path id="Vector" d="M332.05 87.98L332.05 37.83L305.54 37.83L305.54 87.98L292.74 87.98L292.74 29.19C292.74 28.27 293.11 27.39 293.77 26.74C294.43 26.09 295.31 25.73 296.24 25.72L341.35 25.72C342.27 25.73 343.16 26.09 343.82 26.74C344.47 27.39 344.84 28.27 344.85 29.19L344.85 88.02L332.05 87.98Z" fill="#1B1C21" fill-opacity="1.000000" fill-rule="nonzero"/>
</svg>

After

Width:  |  Height:  |  Size: 8.2 KiB

@@ -0,0 +1,63 @@
.root {
display: inline-flex;
gap: var(--space-2);
align-items: center;
justify-content: center;
min-height: 2.75rem;
padding: var(--space-2) var(--space-5);
border: var(--line-strong) solid transparent;
border-radius: var(--radius-pill);
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
text-align: center;
text-decoration: none;
cursor: pointer;
transition:
background-color var(--duration-fast) var(--easing-standard),
color var(--duration-fast) var(--easing-standard),
transform var(--duration-fast) var(--easing-standard);
}
.root:active {
transform: translateY(1px);
}
.root[aria-disabled="true"] {
cursor: progress;
}
/* White on violet: 6.84:1. */
.primary {
color: var(--color-on-accent);
background: var(--color-accent);
}
.primary:hover {
background: var(--palette-graphite);
}
/* Graphite border and text on white: 17.01:1. */
.secondary {
border-color: var(--color-border-strong);
color: var(--color-text);
background: var(--color-surface);
}
.secondary:hover {
border-color: var(--color-accent);
color: var(--color-accent);
}
/* Violet text on white 6.84:1, on light grey 5.85:1. */
.quiet {
padding-inline: var(--space-3);
color: var(--color-link);
background: transparent;
text-decoration: underline;
text-underline-offset: 0.2em;
}
.quiet:hover {
text-decoration-thickness: var(--line-strong);
}
+61
View File
@@ -0,0 +1,61 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { Link, type LinkProps } from "react-router-dom";
import styles from "./button.module.css";
export type ButtonVariant = "primary" | "secondary" | "quiet";
function buttonClassName(variant: ButtonVariant, className: string | undefined): string {
const base = `${styles.root} ${styles[variant]}`;
return className ? `${base} ${className}` : base;
}
type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className"> & {
variant?: ButtonVariant;
/** Marks a pending action without removing the button from the tab order. */
isBusy?: boolean;
className?: string | undefined;
children: ReactNode;
};
/**
* Button with a text label. A busy button stays focusable and announces
* aria-disabled instead of the native disabled state, which would drop focus.
*/
export function Button({
variant = "primary",
type = "button",
isBusy = false,
className,
onClick,
children,
...rest
}: ButtonProps) {
return (
<button
{...rest}
type={type}
className={buttonClassName(variant, className)}
aria-disabled={isBusy ? true : rest["aria-disabled"]}
aria-busy={isBusy || undefined}
onClick={(event) => {
if (isBusy) {
event.preventDefault();
return;
}
onClick?.(event);
}}
>
{children}
</button>
);
}
type ButtonLinkProps = Omit<LinkProps, "className"> & {
variant?: ButtonVariant;
className?: string | undefined;
};
/** Router link that looks like a button, for navigation calls to action. */
export function ButtonLink({ variant = "primary", className, ...rest }: ButtonLinkProps) {
return <Link {...rest} className={buttonClassName(variant, className)} />;
}
+24
View File
@@ -0,0 +1,24 @@
export { BrandLogo } from "./brand/brand-logo";
export { Button, ButtonLink, type ButtonVariant } from "./button/button";
export { Page } from "./layout/page";
export { Section } from "./layout/section";
export { Stack } from "./layout/stack";
export { NavItem, TextLink, type NavItemTone } from "./link/text-link";
export { MainRegion, mainContentId } from "./main-region/main-region";
export { Mono } from "./mono/mono";
export { SkipLink } from "./skip-link/skip-link";
export { describeError, isAccessDenied, type ErrorDescription } from "./status-view/describe-error";
export { QueryView, type QueryViewSource } from "./status-view/query-view";
export {
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
SavingStatus,
StatusView,
type SavingStatusValue,
type StatusKind,
} from "./status-view/status-view";
export { TrustLevel } from "./trust-level/trust-level";
export { trustLevelLabels, type TrustLevelValue } from "./trust-level/trust-level-labels";
export { VisuallyHidden } from "./visually-hidden/visually-hidden";
@@ -0,0 +1,117 @@
.page {
width: 100%;
margin-inline: auto;
padding: var(--space-6) var(--gutter) var(--space-8);
}
.narrow {
max-width: calc(var(--content-width-narrow) + 2 * var(--gutter));
}
.wide {
max-width: calc(var(--content-width-wide) + 2 * var(--gutter));
}
.page-header {
display: grid;
gap: var(--space-3);
padding-bottom: var(--space-5);
border-bottom: var(--line-thin) solid var(--color-divider);
}
.eyebrow {
color: var(--color-accent);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.title {
font-size: var(--font-size-display);
font-weight: var(--font-weight-bold);
letter-spacing: var(--letter-spacing-display);
line-height: var(--line-height-tight);
overflow-wrap: anywhere;
hyphens: auto;
}
.lead {
max-width: 38rem;
color: var(--color-text-secondary);
font-size: var(--font-size-l);
line-height: var(--line-height-body);
}
.page-body {
display: grid;
gap: var(--space-6);
padding-top: var(--space-6);
}
.section {
position: relative;
display: grid;
gap: var(--space-3);
padding-left: var(--space-5);
}
/* Node at the heading plus a thin line down the section. */
.connector {
position: absolute;
top: 0.55em;
bottom: 0;
left: 0;
width: var(--space-3);
border-left: var(--line-thin) solid var(--color-accent);
border-bottom-left-radius: var(--radius-m);
}
.connector::before {
position: absolute;
top: -0.3rem;
left: calc(-0.3rem - 0.5px);
width: 0.6rem;
height: 0.6rem;
border-radius: 50%;
content: "";
background: var(--color-accent);
}
.section-title {
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
}
.section-description {
color: var(--color-text-secondary);
}
.section-body {
display: grid;
gap: var(--space-4);
padding-top: var(--space-2);
}
.stack {
display: flex;
flex-direction: column;
gap: var(--stack-gap);
min-width: 0;
}
.stack[data-direction="row"] {
flex-direction: row;
}
.stack[data-wrap] {
flex-wrap: wrap;
}
.stack[data-align="start"] {
align-items: flex-start;
}
.stack[data-align="center"] {
align-items: center;
}
+32
View File
@@ -0,0 +1,32 @@
import type { ReactNode } from "react";
import styles from "./layout.module.css";
const productName = "Lincodex";
type PageProps = {
/** Text of the page's single h1 and of the document title. */
title: string;
/** Short context line above the heading, for example the cabinet name. */
eyebrow?: string | undefined;
lead?: ReactNode;
width?: "narrow" | "wide";
children?: ReactNode;
};
/**
* 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>).
*/
export function Page({ title, eyebrow, lead, width = "narrow", children }: PageProps) {
return (
<div className={`${styles.page} ${styles[width]}`}>
<title>{`${title} - ${productName}`}</title>
<header className={styles["page-header"]}>
{eyebrow ? <p className={styles.eyebrow}>{eyebrow}</p> : null}
<h1 className={styles.title}>{title}</h1>
{lead ? <div className={styles.lead}>{lead}</div> : null}
</header>
{children ? <div className={styles["page-body"]}>{children}</div> : null}
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { useId, type ReactNode } from "react";
import styles from "./layout.module.css";
type SectionProps = {
title: string;
headingLevel?: 2 | 3;
description?: ReactNode;
children?: ReactNode;
};
/**
* Titled block of a page. A thin connector line with a node marks the
* section, echoing the brand's linked-facts graphics; it is decorative.
*/
export function Section({ title, headingLevel = 2, description, children }: SectionProps) {
const headingId = useId();
const Heading = headingLevel === 2 ? "h2" : "h3";
return (
<section className={styles.section} aria-labelledby={headingId}>
<span className={styles.connector} aria-hidden="true" />
<Heading id={headingId} className={styles["section-title"]}>
{title}
</Heading>
{description ? <div className={styles["section-description"]}>{description}</div> : null}
{children ? <div className={styles["section-body"]}>{children}</div> : null}
</section>
);
}
+35
View File
@@ -0,0 +1,35 @@
import type { CSSProperties, ReactNode } from "react";
import styles from "./layout.module.css";
type SpaceStep = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type StackProps = {
gap?: SpaceStep;
direction?: "column" | "row";
/** Rows wrap onto new lines on narrow screens. */
wrap?: boolean;
align?: "start" | "center" | "stretch";
children: ReactNode;
};
/** Flex container with a gap from the spacing scale. */
export function Stack({
gap = 4,
direction = "column",
wrap = false,
align = "stretch",
children,
}: StackProps) {
const style = { "--stack-gap": `var(--space-${gap})` } as CSSProperties;
return (
<div
className={styles.stack}
style={style}
data-direction={direction}
data-wrap={wrap || undefined}
data-align={align}
>
{children}
</div>
);
}
@@ -0,0 +1,67 @@
.link {
color: var(--color-link);
text-decoration: underline;
text-decoration-thickness: var(--line-thin);
text-underline-offset: 0.2em;
}
.link:hover {
text-decoration-thickness: var(--line-strong);
}
.nav {
position: relative;
display: inline-flex;
align-items: center;
min-height: 2.75rem;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-s);
font-size: var(--font-size-s);
font-weight: var(--font-weight-medium);
line-height: var(--line-height-snug);
text-decoration: none;
white-space: nowrap;
}
/* Active marker: a bar under the label plus bold text. */
.nav::after {
position: absolute;
right: var(--space-3);
bottom: var(--space-1);
left: var(--space-3);
height: var(--line-strong);
border-radius: var(--radius-pill);
content: "";
background: currentcolor;
transform: scaleX(0);
transform-origin: left;
transition: transform var(--duration-base) var(--easing-standard);
}
.nav[aria-current="page"] {
font-weight: var(--font-weight-bold);
}
.nav[aria-current="page"]::after {
transform: scaleX(1);
}
/* Graphite on white 17.01:1; active violet on white 6.84:1. */
.light {
color: var(--color-text);
}
.light:hover,
.light[aria-current="page"] {
color: var(--color-accent);
}
/* Light grey on graphite 14.53:1; white on graphite 17.01:1. */
.dark {
color: var(--palette-light);
}
.dark:hover,
.dark[aria-current="page"] {
color: var(--palette-white);
}
+31
View File
@@ -0,0 +1,31 @@
import { Link, NavLink, type LinkProps, type NavLinkProps } from "react-router-dom";
import styles from "./text-link.module.css";
type TextLinkProps = Omit<LinkProps, "className"> & {
className?: string | undefined;
};
/** Inline router link. Links are underlined so color is not the only cue. */
export function TextLink({ className, ...rest }: TextLinkProps) {
return <Link {...rest} className={className ? `${styles.link} ${className}` : styles.link} />;
}
export type NavItemTone = "light" | "dark";
type NavItemProps = Omit<NavLinkProps, "className" | "children"> & {
tone?: NavItemTone;
children: string;
};
/**
* Navigation link of a cabinet. NavLink sets aria-current="page" on the
* active item; the active state is shown by a bar and a heavier weight, not
* by color alone.
*/
export function NavItem({ tone = "light", children, ...rest }: NavItemProps) {
return (
<NavLink {...rest} className={`${styles.nav} ${styles[tone]}`}>
{children}
</NavLink>
);
}
@@ -0,0 +1,9 @@
.root {
display: block;
min-width: 0;
}
/* The landmark receives programmatic focus only; it is not a control. */
.root:focus {
outline: none;
}
@@ -0,0 +1,41 @@
import { useEffect, useRef, type ReactNode } from "react";
import { useLocation } from "react-router-dom";
import styles from "./main-region.module.css";
/** ID of the single main landmark; the skip link targets it. */
export const mainContentId = "main-content";
type MainRegionProps = {
children: ReactNode;
className?: string | undefined;
};
/**
* The page's main landmark. After a client-side navigation it takes focus so
* keyboard and screen reader users start at the new content instead of the
* link they activated. The first render keeps the browser's default focus.
*/
export function MainRegion({ children, className }: MainRegionProps) {
const ref = useRef<HTMLElement>(null);
const { pathname } = useLocation();
const previousPathname = useRef(pathname);
useEffect(() => {
if (previousPathname.current === pathname) {
return;
}
previousPathname.current = pathname;
ref.current?.focus({ preventScroll: true });
}, [pathname]);
return (
<main
ref={ref}
id={mainContentId}
tabIndex={-1}
className={className ? `${styles.root} ${className}` : styles.root}
>
{children}
</main>
);
}
@@ -0,0 +1,12 @@
.root {
font-family: var(--font-mono);
font-size: 0.94em;
font-variant-numeric: tabular-nums slashed-zero;
font-weight: var(--font-weight-regular);
letter-spacing: 0;
overflow-wrap: anywhere;
}
.strong {
font-weight: var(--font-weight-bold);
}
+18
View File
@@ -0,0 +1,18 @@
import type { ReactNode } from "react";
import styles from "./mono.module.css";
type MonoProps = {
children: ReactNode;
/** Bold weight for scores and other key figures. */
strong?: boolean;
};
/**
* JetBrains Mono for numbers, scores, codes, and pseudonyms. Digits use
* tabular figures so columns of numbers line up.
*/
export function Mono({ children, strong = false }: MonoProps) {
return (
<span className={strong ? `${styles.root} ${styles.strong}` : styles.root}>{children}</span>
);
}
@@ -0,0 +1,22 @@
.root {
position: absolute;
z-index: 100;
top: var(--space-2);
left: var(--space-2);
padding: var(--space-3) var(--space-4);
border-radius: var(--radius-s);
color: var(--palette-white);
font-weight: var(--font-weight-bold);
text-decoration: none;
background: var(--palette-violet);
transform: translateY(calc(-100% - var(--space-4)));
transition: transform var(--duration-fast) var(--easing-standard);
}
/* A white inner and graphite outer ring stay visible on light and dark headers. */
.root:focus {
outline: var(--focus-ring-width) solid var(--palette-white);
outline-offset: 0;
box-shadow: 0 0 0 calc(var(--focus-ring-width) * 2) var(--palette-graphite);
transform: translateY(0);
}
@@ -0,0 +1,26 @@
import type { MouseEvent } from "react";
import { mainContentId } from "../main-region/main-region";
import styles from "./skip-link.module.css";
/**
* First focusable element of every shell. It moves focus to the main
* landmark without changing the URL, so the router does not see a hash
* navigation.
*/
export function SkipLink() {
function handleClick(event: MouseEvent<HTMLAnchorElement>) {
const target = document.getElementById(mainContentId);
if (!target) {
return;
}
event.preventDefault();
target.focus();
target.scrollIntoView({ block: "start" });
}
return (
<a className={styles.root} href={`#${mainContentId}`} onClick={handleClick}>
Перейти к основному содержимому
</a>
);
}
@@ -0,0 +1,130 @@
import {
ApiRequestError,
invalidResponseCode,
networkErrorCode,
type ApiErrorCode,
} from "../../api";
type ErrorMessage = {
title: string;
description: string;
};
/** User-facing explanation of a failed request plus safe technical facts. */
export type ErrorDescription = ErrorMessage & {
/** Present only for API errors; rendered as text, never as HTML. */
technical?: {
code: string;
status: number;
serverTitle: string;
serverDetail: string | undefined;
traceId: string | undefined;
};
};
const unauthenticated: ErrorMessage = {
title: "Нужен вход",
description: "Войдите в аккаунт, чтобы открыть этот раздел.",
};
const forbidden: ErrorMessage = {
title: "Нет доступа",
description: "У вашей учетной записи нет прав на этот раздел.",
};
const serverUnavailable: ErrorMessage = {
title: "Сервис временно недоступен",
description: "Повторите попытку через несколько минут.",
};
const requestFailed: ErrorMessage = {
title: "Не удалось выполнить запрос",
description: "Повторите попытку. Если ошибка повторяется, обратитесь в поддержку.",
};
const unexpectedError: ErrorMessage = {
title: "Что-то пошло не так",
description: "Повторите попытку. Если ошибка повторяется, обновите страницу.",
};
const codeMessages: Partial<Record<ApiErrorCode, ErrorMessage>> = {
[networkErrorCode]: {
title: "Нет связи с сервером",
description: "Проверьте подключение к интернету и повторите попытку.",
},
[invalidResponseCode]: {
title: "Сервер ответил в неожиданном формате",
description:
"Повторите попытку позже. Если ошибка повторяется, передайте в поддержку идентификатор запроса.",
},
unauthenticated,
invalid_credentials: unauthenticated,
forbidden,
email_not_verified: {
title: "Почта не подтверждена",
description: "Перейдите по ссылке из письма, чтобы открыть этот раздел.",
},
csrf_check_failed: {
title: "Запрос не прошел проверку безопасности",
description: "Обновите страницу и повторите действие.",
},
not_found: {
title: "Данные не найдены",
description: "Возможно, они удалены или скрыты от вас.",
},
rate_limited: {
title: "Слишком много запросов",
description: "Подождите немного и повторите попытку.",
},
validation_failed: {
title: "Запрос не прошел проверку",
description: "Проверьте введенные данные и повторите попытку.",
},
not_implemented: {
title: "Функция еще не реализована",
description: "Этот раздел появится в одной из следующих версий.",
},
};
/** Access errors are shown by ForbiddenState instead of ErrorState. */
export function isAccessDenied(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || (error.status === 403 && error.code !== "csrf_check_failed"))
);
}
// Unknown codes fall back to the HTTP status, as the contract requires.
function messageFor(error: ApiRequestError): ErrorMessage {
const byCode = codeMessages[error.code];
if (byCode) {
return byCode;
}
if (error.status === 401) {
return unauthenticated;
}
if (error.status === 403) {
return forbidden;
}
return error.status >= 500 ? serverUnavailable : requestFailed;
}
/**
* Maps any thrown value to Russian copy. Server-provided text is kept only as
* technical detail; React renders it as text, never as markup.
*/
export function describeError(error: unknown): ErrorDescription {
if (!(error instanceof ApiRequestError)) {
return unexpectedError;
}
return {
...messageFor(error),
technical: {
code: error.code,
status: error.status,
serverTitle: error.title,
serverDetail: error.detail,
traceId: error.traceId,
},
};
}
@@ -0,0 +1,55 @@
import type { ReactNode } from "react";
import type { UseQueryResult } from "@tanstack/react-query";
import { isAccessDenied } from "./describe-error";
import { EmptyState, ErrorState, ForbiddenState, LoadingState } from "./status-view";
/** The part of a TanStack Query result that QueryView reads. */
export type QueryViewSource<TData> = Pick<
UseQueryResult<TData, unknown>,
"status" | "data" | "error" | "isRefetching" | "refetch"
>;
type QueryViewProps<TData> = {
query: QueryViewSource<TData>;
loadingLabel?: string;
/** Returns true when successful data has nothing to show. */
isEmpty?: (data: TData) => boolean;
empty?: ReactNode;
children: (data: TData) => ReactNode;
};
/**
* Renders the loading, error, forbidden, empty, or data state of one query.
* 401 and 403 responses show the forbidden state without a retry, because
* repeating the same request cannot change the answer.
*/
export function QueryView<TData>({
query,
loadingLabel,
isEmpty,
empty,
children,
}: QueryViewProps<TData>) {
if (query.status === "pending") {
return <LoadingState {...(loadingLabel ? { label: loadingLabel } : {})} />;
}
if (query.status === "error") {
if (isAccessDenied(query.error)) {
return <ForbiddenState error={query.error} />;
}
return (
<ErrorState
error={query.error}
isRetrying={query.isRefetching}
onRetry={() => {
void query.refetch();
}}
/>
);
}
const data = query.data as TData;
if (isEmpty?.(data)) {
return empty ?? <EmptyState title="Здесь пока ничего нет" />;
}
return children(data);
}
@@ -0,0 +1,146 @@
.root {
display: flex;
gap: var(--space-4);
align-items: flex-start;
padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
/* Error blocks add a red edge; the triangle and the title carry meaning too. */
.root[data-kind="error"] {
border-color: var(--color-danger);
box-shadow: inset var(--space-1) 0 0 var(--color-danger);
}
.mark {
flex: none;
width: 2.5rem;
height: 2.5rem;
}
.track {
fill: none;
stroke: var(--color-divider);
stroke-width: 3;
}
.spinner {
fill: none;
stroke: var(--color-accent);
stroke-linecap: round;
stroke-width: 3;
transform-origin: 20px 20px;
animation: spin 900ms linear infinite;
}
.outline {
fill: none;
stroke: var(--color-text);
stroke-linejoin: round;
stroke-width: 2;
}
.root[data-kind="empty"] .outline {
stroke-dasharray: 4 4;
}
.danger {
fill: var(--color-danger);
stroke: var(--color-danger);
stroke-linejoin: round;
stroke-width: 2;
}
.danger-glyph {
fill: none;
stroke: var(--palette-white);
stroke-linecap: round;
stroke-width: 3;
}
.content {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.title {
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
}
.description {
color: var(--color-text-secondary);
}
.action {
padding-top: var(--space-2);
}
.details {
font-size: var(--font-size-s);
}
.details summary {
width: fit-content;
border-radius: var(--radius-s);
color: var(--color-link);
text-decoration: underline;
text-underline-offset: 0.2em;
cursor: pointer;
}
.facts {
display: grid;
grid-template-columns: minmax(0, max-content) minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
padding-top: var(--space-3);
}
.facts dt {
color: var(--color-text-secondary);
}
.server-text {
overflow-wrap: anywhere;
}
.saving {
min-height: 1.6em;
font-size: var(--font-size-s);
}
.saving[data-state="failed"]::before {
display: inline-block;
width: 0.6em;
height: 0.6em;
margin-right: var(--space-2);
content: "";
background: var(--color-danger);
transform: rotate(45deg);
}
@media (width < 30rem) {
.facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-top: var(--space-2);
}
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
@@ -0,0 +1,126 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { ApiRequestError, networkErrorCode } from "../../api";
import { describeError } from "./describe-error";
import { EmptyState, ErrorState, ForbiddenState, LoadingState, SavingStatus } from "./status-view";
function text(html: string): string {
return html
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
describe("state views", () => {
it("announces loading politely and marks it busy", () => {
const html = renderToStaticMarkup(<LoadingState label="Загружаем профиль..." />);
expect(html).toMatch(/role="status"/);
expect(html).toMatch(/aria-busy="true"/);
expect(text(html)).toBe("Загружаем профиль...");
});
it("shows the empty state with its title, description, and action", () => {
const html = renderToStaticMarkup(
<EmptyState
title="Приглашений пока нет"
description="Они появятся здесь."
action={<a href="/candidate/profile">Заполнить профиль</a>}
/>,
);
expect(html).toMatch(/role="status"/);
expect(text(html)).toBe("Приглашений пока нет Они появятся здесь. Заполнить профиль");
});
it("renders an API error as an alert with safe technical details and a retry", () => {
const error = new ApiRequestError({
status: 500,
code: "internal",
title: "Internal server error",
detail: '<img src=x onerror="alert(1)">',
traceId: "trace-500",
});
const html = renderToStaticMarkup(<ErrorState error={error} onRetry={() => undefined} />);
expect(html).toMatch(/role="alert"/);
expect(text(html)).toContain("Сервис временно недоступен");
expect(text(html)).toContain("Код internal");
expect(text(html)).toContain("HTTP-статус 500");
expect(text(html)).toContain("Идентификатор запроса trace-500");
// Server text is escaped, never injected as markup.
expect(html).not.toContain("<img src=x");
expect(html).toContain("&lt;img src=x onerror=&quot;alert(1)&quot;&gt;");
expect(html).toMatch(/<button[^>]*type="button"[^>]*>Повторить<\/button>/);
});
it("keeps a retrying button focusable and announces that it is busy", () => {
const html = renderToStaticMarkup(
<ErrorState
error={new ApiRequestError({ status: 0, code: networkErrorCode, title: "offline" })}
onRetry={() => undefined}
isRetrying
/>,
);
expect(html).toMatch(/<button[^>]*aria-disabled="true"[^>]*>Повторяем...<\/button>/);
expect(html).not.toMatch(/<button[^>]*\sdisabled/);
expect(text(html)).toContain("Нет связи с сервером");
expect(text(html)).toContain("HTTP-статус нет ответа");
});
it("omits the retry button when retrying cannot help", () => {
const html = renderToStaticMarkup(<ErrorState error={new Error("render failed")} />);
expect(text(html)).toBe(
"Что-то пошло не так Повторите попытку. Если ошибка повторяется, обновите страницу.",
);
expect(html).not.toContain("<button");
});
it.each([
[401, "unauthenticated", "Нужен вход"],
[403, "forbidden", "Нет доступа"],
[403, "email_not_verified", "Почта не подтверждена"],
] as const)("shows the forbidden state for %i %s", (status, code, title) => {
const error = new ApiRequestError({ status, code, title: code });
const html = renderToStaticMarkup(<ForbiddenState error={error} />);
expect(html).toMatch(/role="status"/);
expect(text(html)).toContain(title);
});
it.each([
["saving", "Сохраняем изменения..."],
["saved", "Изменения сохранены"],
["failed", "Не удалось сохранить изменения"],
["idle", ""],
] as const)("announces the %s saving state as text", (state, label) => {
const html = renderToStaticMarkup(<SavingStatus state={state} />);
expect(html).toMatch(/role="status"/);
expect(text(html)).toBe(label);
});
});
describe("describeError", () => {
it("falls back to the HTTP status for a code the client does not know", () => {
const error = new ApiRequestError({ status: 503, code: "http_error", title: "Bad gateway" });
expect(describeError(error)).toMatchObject({
title: "Сервис временно недоступен",
technical: { code: "http_error", status: 503, serverTitle: "Bad gateway" },
});
});
it("treats a CSRF rejection as an error, not as missing access", () => {
const error = new ApiRequestError({ status: 403, code: "csrf_check_failed", title: "csrf" });
const html = renderToStaticMarkup(<ErrorState error={error} onRetry={() => undefined} />);
expect(text(html)).toContain("Запрос не прошел проверку безопасности");
});
it("does not expose details of errors that are not API errors", () => {
expect(describeError(new Error("secret internals"))).not.toHaveProperty("technical");
});
});
@@ -0,0 +1,195 @@
import type { ReactNode } from "react";
import { Button } from "../button/button";
import { Mono } from "../mono/mono";
import { describeError, isAccessDenied } from "./describe-error";
import styles from "./status-view.module.css";
export type StatusKind = "loading" | "empty" | "error" | "forbidden";
type StatusViewProps = {
kind: StatusKind;
title: string;
description?: ReactNode;
action?: ReactNode;
children?: ReactNode;
};
// Each kind has its own shape, so the state is readable without color.
function StatusMark({ kind }: { kind: StatusKind }) {
return (
<svg className={styles.mark} viewBox="0 0 40 40" aria-hidden="true" focusable="false">
{kind === "loading" ? (
<>
<circle className={styles.track} cx="20" cy="20" r="15" />
<path className={styles.spinner} d="M20 5a15 15 0 0 1 15 15" />
</>
) : null}
{kind === "empty" ? <circle className={styles.outline} cx="20" cy="20" r="15" /> : null}
{kind === "error" ? (
<>
<path className={styles.danger} d="M20 4 37 34H3Z" />
<path className={styles["danger-glyph"]} d="M20 15v9M20 28v1" />
</>
) : null}
{kind === "forbidden" ? (
<>
<rect className={styles.outline} x="8" y="17" width="24" height="18" rx="3" />
<path className={styles.outline} d="M13 17v-4a7 7 0 0 1 14 0v4" />
</>
) : null}
</svg>
);
}
/**
* Shared presentation of loading, empty, error, and forbidden states.
* Loading, empty, and forbidden are polite status messages; errors use the
* alert role so they are announced when they replace content.
*/
export function StatusView({ kind, title, description, action, children }: StatusViewProps) {
return (
<div
className={styles.root}
data-kind={kind}
role={kind === "error" ? "alert" : "status"}
aria-busy={kind === "loading" || undefined}
>
<StatusMark kind={kind} />
<div className={styles.content}>
<p className={styles.title}>{title}</p>
{description ? <div className={styles.description}>{description}</div> : null}
{children}
{action ? <div className={styles.action}>{action}</div> : null}
</div>
</div>
);
}
type LoadingStateProps = {
label?: string;
};
export function LoadingState({ label = "Загружаем данные..." }: LoadingStateProps) {
return <StatusView kind="loading" title={label} />;
}
type EmptyStateProps = {
title: string;
description?: ReactNode;
action?: ReactNode;
};
export function EmptyState({ title, description, action }: EmptyStateProps) {
return <StatusView kind="empty" title={title} description={description} action={action} />;
}
type ForbiddenStateProps = {
/** The access error, if any; its code selects the wording. */
error?: unknown;
title?: string;
description?: ReactNode;
action?: ReactNode;
};
export function ForbiddenState({ error, title, description, action }: ForbiddenStateProps) {
const described = describeError(error);
const known = isAccessDenied(error);
return (
<StatusView
kind="forbidden"
title={title ?? (known ? described.title : "Нет доступа")}
description={
description ??
(known ? described.description : "У вашей учетной записи нет прав на этот раздел.")
}
action={action}
/>
);
}
type ErrorStateProps = {
error: unknown;
/** Called by the retry button; omit when retrying cannot help. */
onRetry?: (() => void) | undefined;
isRetrying?: boolean;
title?: string;
};
/**
* Error with an explanation, an optional retry, and technical details for
* support. Server text is rendered as plain text.
*/
export function ErrorState({ error, onRetry, isRetrying = false, title }: ErrorStateProps) {
const described = describeError(error);
const technical = described.technical;
return (
<StatusView
kind="error"
title={title ?? described.title}
description={described.description}
action={
onRetry ? (
<Button variant="secondary" isBusy={isRetrying} onClick={onRetry}>
{isRetrying ? "Повторяем..." : "Повторить"}
</Button>
) : null
}
>
{technical ? (
<details className={styles.details}>
<summary>Технические сведения</summary>
<dl className={styles.facts}>
<dt>Код</dt>
<dd>
<Mono>{technical.code}</Mono>
</dd>
<dt>HTTP-статус</dt>
<dd>
<Mono>{technical.status === 0 ? "нет ответа" : technical.status}</Mono>
</dd>
<dt>Ответ сервера</dt>
<dd className={styles["server-text"]}>
{technical.serverDetail
? `${technical.serverTitle} ${technical.serverDetail}`
: technical.serverTitle}
</dd>
{technical.traceId ? (
<>
<dt>Идентификатор запроса</dt>
<dd>
<Mono>{technical.traceId}</Mono>
</dd>
</>
) : null}
</dl>
</details>
) : null}
</StatusView>
);
}
export type SavingStatusValue = "idle" | "saving" | "saved" | "failed";
const savingLabels: Readonly<Record<SavingStatusValue, string>> = {
idle: "",
saving: "Сохраняем изменения...",
saved: "Изменения сохранены",
failed: "Не удалось сохранить изменения",
};
type SavingStatusProps = {
state: SavingStatusValue;
};
/**
* Inline saving indicator for forms. The live region stays mounted while
* idle so screen readers announce later changes.
*/
export function SavingStatus({ state }: SavingStatusProps) {
return (
<p className={styles.saving} data-state={state} role="status">
{savingLabels[state]}
</p>
);
}
+20
View File
@@ -0,0 +1,20 @@
/*
* JetBrains Mono 2.304, SIL Open Font License 1.1.
* The license and authors list are next to the font files in ./fonts/.
* Only the regular and bold weights are shipped; no external font CDN.
*/
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("./fonts/JetBrainsMono-Regular.woff2") format("woff2");
}
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("./fonts/JetBrainsMono-Bold.woff2") format("woff2");
}
@@ -0,0 +1,10 @@
# This is the official list of project authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS.txt file.
# See the latter for an explanation.
#
# Names should be added to this file as:
# Name or Organization <email address>
JetBrains <>
Philipp Nurullin <philipp.nurullin@jetbrains.com>
Konstantin Bulenkov <kb@jetbrains.com>
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+114
View File
@@ -0,0 +1,114 @@
/*
* Design tokens of the Lincodex interface.
*
* Palette values come from the product requirements (section 5). Only the
* light theme exists: dark surfaces are local regions (for example the
* employer header) that override the text, link, and focus tokens with
* checked pairs. A dark theme must define and check its own pairs instead of
* inheriting the light accents. See frontend/README.en.md for the contrast
* table of every text and background pair in use.
*
* Breakpoints cannot be custom properties inside media queries, so they are
* fixed values used directly by components:
* 360px - smallest supported width (body min-width: 20rem)
* 768px - tablet: (width >= 48rem)
* 1024px - desktop navigation: (width >= 64rem)
* 1280px - wide desktop, verified layout width
*/
:root {
/* Brand palette. Use the semantic tokens below in components. */
--palette-violet: #402fff;
--palette-red: #ec1d35;
--palette-graphite: #1b1c21;
--palette-graphite-soft: #2d2e37;
--palette-light: #ededed;
--palette-grey: #c8c9ca;
--palette-white: #fff;
/* Semantic colors for the light theme. */
--color-canvas: var(--palette-light);
--color-surface: var(--palette-white);
--color-text: var(--palette-graphite);
--color-text-secondary: var(--palette-graphite-soft);
--color-accent: var(--palette-violet);
--color-on-accent: var(--palette-white);
--color-link: var(--palette-violet);
/* Red is reserved for errors and problems. It reaches only 4.38:1 on white,
* so it marks error graphics (borders, icons) and never carries body text. */
--color-danger: var(--palette-red);
/* Decorative dividers only: grey does not reach 3:1 and must not be the
* only boundary of an interactive control. */
--color-divider: var(--palette-grey);
--color-border-strong: var(--palette-graphite);
--color-focus-ring: var(--palette-violet);
/* Typography. Text uses the system stack; JetBrains Mono is self-hosted for
* numbers, scores, codes, and pseudonyms. */
--font-text:
ui-sans-serif, system-ui, -apple-system, "Segoe UI", roboto, "Helvetica Neue", arial, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", menlo, consolas, monospace;
--font-size-xs: 0.8125rem;
--font-size-s: 0.9375rem;
--font-size-m: 1.0625rem;
--font-size-l: 1.25rem;
--font-size-xl: clamp(1.375rem, 1.2rem + 0.8vw, 1.75rem);
--font-size-display: clamp(2rem, 1.45rem + 2.4vw, 3.25rem);
--font-weight-regular: 400;
--font-weight-medium: 500;
--font-weight-bold: 700;
--line-height-tight: 1.1;
--line-height-snug: 1.3;
--line-height-body: 1.6;
--letter-spacing-display: -0.03em;
--letter-spacing-label: 0.08em;
/* Spacing scale with a 4px base. */
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 0.75rem;
--space-4: 1rem;
--space-5: 1.5rem;
--space-6: 2rem;
--space-7: 3rem;
--space-8: 4rem;
--space-9: 6rem;
/* Radii follow the rounded corners of the brand connector lines. */
--radius-s: 0.375rem;
--radius-m: 0.75rem;
--radius-l: 1.25rem;
--radius-pill: 999px;
/* Lines. */
--line-thin: 1px;
--line-strong: 2px;
/* Focus indicator: 3px ring outside the element. */
--focus-ring-width: 3px;
--focus-ring-offset: 2px;
/* Layout widths. */
--content-width-narrow: 40rem;
--content-width-wide: 80rem;
--gutter: var(--space-4);
/* Motion. Reduced motion collapses durations below. */
--duration-fast: 120ms;
--duration-base: 220ms;
--easing-standard: cubic-bezier(0.2, 0, 0, 1);
}
@media (width >= 48rem) {
:root {
--gutter: var(--space-6);
}
}
@media (prefers-reduced-motion: reduce) {
:root {
--duration-fast: 0ms;
--duration-base: 0ms;
}
}
@@ -0,0 +1,13 @@
/**
* Trust levels from least to most confirmed. Each level has its own shape
* (empty mark, ring, partial fill, full mark) and a text label, so meaning
* never depends on color.
*/
export type TrustLevelValue = "none" | "claimed" | "partial" | "confirmed";
export const trustLevelLabels: Readonly<Record<TrustLevelValue, string>> = {
none: "Не подтверждено",
claimed: "Заявлено",
partial: "Подтверждено частично",
confirmed: "Подтверждено",
};
@@ -0,0 +1,34 @@
.root {
display: inline-flex;
gap: var(--space-2);
align-items: center;
font-size: var(--font-size-s);
line-height: var(--line-height-snug);
}
.mark {
flex: none;
width: 1.25rem;
height: 1.25rem;
}
/* Graphics need 3:1: graphite 17.01:1 and violet 6.84:1 on white. */
.empty {
fill: none;
stroke: var(--color-text);
stroke-width: 1.5;
}
.ring {
fill: none;
stroke: var(--color-accent);
stroke-width: 2;
}
.fill {
fill: var(--color-accent);
}
.label {
color: var(--color-text);
}
@@ -0,0 +1,31 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { TrustLevel } from "./trust-level";
import { trustLevelLabels, type TrustLevelValue } from "./trust-level-labels";
const levels = Object.keys(trustLevelLabels) as TrustLevelValue[];
describe("TrustLevel", () => {
it.each(levels)("shows the %s level as visible text next to a hidden mark", (level) => {
const html = renderToStaticMarkup(<TrustLevel level={level} />);
expect(html).toMatch(/<svg[^>]*aria-hidden="true"/);
expect(html.replace(/<[^>]+>/g, "")).toBe(trustLevelLabels[level]);
});
it("gives every level a distinct shape, not only a color", () => {
const shapes = levels.map((level) =>
renderToStaticMarkup(<TrustLevel level={level} />)
.match(/<svg[\s\S]*<\/svg>/)?.[0]
.replace(/class="[^"]*"/g, ""),
);
expect(new Set(shapes).size).toBe(levels.length);
});
it("accepts domain wording for the label", () => {
const html = renderToStaticMarkup(<TrustLevel level="confirmed" label="Подтверждено тестом" />);
expect(html.replace(/<[^>]+>/g, "")).toBe("Подтверждено тестом");
});
});
@@ -0,0 +1,41 @@
import { trustLevelLabels, type TrustLevelValue } from "./trust-level-labels";
import styles from "./trust-level.module.css";
type TrustLevelProps = {
level: TrustLevelValue;
/** Domain-specific wording; the default label describes the level. */
label?: string | undefined;
};
// Shapes live in markup (including the dash pattern of the empty mark), so
// levels stay distinguishable without CSS or color.
function TrustMark({ level }: { level: TrustLevelValue }) {
return (
<svg
className={styles.mark}
viewBox="0 0 20 20"
width="20"
height="20"
aria-hidden="true"
focusable="false"
>
{level === "none" ? (
<circle className={styles.empty} cx="10" cy="10" r="7" strokeDasharray="2.2 2.2" />
) : (
<circle className={styles.ring} cx="10" cy="10" r="7" />
)}
{level === "partial" ? <path className={styles.fill} d="M10 3a7 7 0 0 0 0 14Z" /> : null}
{level === "confirmed" ? <circle className={styles.fill} cx="10" cy="10" r="7" /> : null}
</svg>
);
}
/** Shape plus visible text that states how well a fact is confirmed. */
export function TrustLevel({ level, label }: TrustLevelProps) {
return (
<span className={styles.root} data-level={level}>
<TrustMark level={level} />
<span className={styles.label}>{label ?? trustLevelLabels[level]}</span>
</span>
);
}
@@ -0,0 +1,12 @@
/* Hides content visually while keeping it in the accessibility tree. */
.root {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip-path: inset(50%) !important;
white-space: nowrap !important;
border: 0 !important;
}
@@ -0,0 +1,11 @@
import type { ReactNode } from "react";
import styles from "./visually-hidden.module.css";
type VisuallyHiddenProps = {
children: ReactNode;
};
/** Text for assistive technology that is not shown on screen. */
export function VisuallyHidden({ children }: VisuallyHiddenProps) {
return <span className={styles.root}>{children}</span>;
}
View File
Whitespace-only changes.
@@ -0,0 +1 @@
export { CandidateShell } from "./ui/candidate-shell";
@@ -0,0 +1,52 @@
/* Mobile first: base rules target 360px; wider screens add layout. */
.shell {
min-height: 100vh;
}
.header {
position: sticky;
z-index: 10;
top: 0;
display: grid;
gap: var(--space-1);
padding: var(--space-2) var(--gutter) 0;
border-bottom: var(--line-thin) solid var(--color-divider);
background: var(--color-surface);
}
/* The strip scrolls sideways; padding keeps focus rings inside the clip. */
.nav {
margin-inline: calc(-1 * var(--gutter));
overflow-x: auto;
overscroll-behavior-x: contain;
scrollbar-width: thin;
}
.list {
display: flex;
gap: var(--space-1);
width: max-content;
margin: 0;
padding: var(--space-1) var(--gutter) var(--space-2);
list-style: none;
}
@media (width >= 64rem) {
.header {
grid-template-columns: auto 1fr;
gap: var(--space-6);
align-items: center;
padding-block: var(--space-2);
}
.nav {
margin-inline: 0;
overflow-x: visible;
}
.list {
justify-content: flex-end;
width: auto;
padding: 0;
}
}
@@ -0,0 +1,42 @@
import { Outlet } from "react-router-dom";
import { paths } from "../../../shared/config";
import { BrandLogo, MainRegion, NavItem, SkipLink } from "../../../shared/ui";
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.assessment, label: "Тест", end: false },
{ to: paths.candidate.results, label: "Результаты", end: false },
{ to: paths.candidate.invitations, label: "Приглашения", end: false },
{ to: paths.candidate.privacy, label: "Приватность", end: false },
] as const;
/**
* Candidate cabinet layout, designed for phones first: a compact header and
* a horizontally scrollable section strip that becomes one row on desktop.
*/
export function CandidateShell() {
return (
<div className={styles.shell}>
<SkipLink />
<header className={styles.header}>
<BrandLogo to={paths.candidate.root} context="Кабинет кандидата" />
<nav className={styles.nav} aria-label="Разделы кабинета кандидата">
<ul className={styles.list}>
{navigation.map((item) => (
<li key={item.to}>
<NavItem to={item.to} end={item.end}>
{item.label}
</NavItem>
</li>
))}
</ul>
</nav>
</header>
<MainRegion>
<Outlet />
</MainRegion>
</div>
);
}
@@ -0,0 +1 @@
export { EmployerShell } from "./ui/employer-shell";
@@ -0,0 +1,76 @@
/* Desktop first: base rules target 1024px and wider; narrow screens adapt. */
.shell {
display: grid;
grid-template-columns: 17rem minmax(0, 1fr);
min-height: 100vh;
}
/* Dark region: violet fails on graphite (2.49:1), so text, links, and the
* focus ring switch to checked light values here. */
.sidebar {
--color-focus-ring: var(--palette-white);
position: sticky;
top: 0;
display: flex;
flex-direction: column;
gap: var(--space-6);
height: 100vh;
padding: var(--space-4) var(--space-4) var(--space-6);
color: var(--palette-light);
background: var(--palette-graphite);
}
.nav {
border-top: var(--line-thin) solid var(--palette-graphite-soft);
padding-top: var(--space-4);
}
.list {
display: grid;
gap: var(--space-1);
margin: 0;
padding: 0;
list-style: none;
}
.list a {
width: 100%;
}
.main {
min-width: 0;
}
@media (width < 64rem) {
.shell {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto 1fr;
}
.sidebar {
z-index: 10;
gap: var(--space-1);
height: auto;
padding: var(--space-2) var(--gutter) 0;
}
.nav {
margin-inline: calc(-1 * var(--gutter));
padding-top: 0;
border-top: 0;
overflow-x: auto;
overscroll-behavior-x: contain;
scrollbar-width: thin;
}
.list {
display: flex;
width: max-content;
padding: var(--space-1) var(--gutter) var(--space-2);
}
.list a {
width: auto;
}
}
@@ -0,0 +1,41 @@
import { Outlet } from "react-router-dom";
import { paths } from "../../../shared/config";
import { BrandLogo, MainRegion, NavItem, SkipLink } from "../../../shared/ui";
import styles from "./employer-shell.module.css";
const navigation = [
{ to: paths.employer.company, label: "Компания и команда" },
{ to: paths.employer.needs, label: "Потребности" },
{ to: paths.employer.candidates, label: "Кандидаты" },
{ to: paths.employer.invitations, label: "Приглашения" },
] as const;
/**
* Employer cabinet layout, designed for desktop first: a graphite sidebar
* with vertical navigation next to a wide work area. Below 1024px the
* sidebar turns into a top bar with a scrollable section strip.
*/
export function EmployerShell() {
return (
<div className={styles.shell}>
<SkipLink />
<header className={styles.sidebar}>
<BrandLogo tone="dark" to={paths.employer.root} context="Кабинет работодателя" />
<nav className={styles.nav} aria-label="Разделы кабинета работодателя">
<ul className={styles.list}>
{navigation.map((item) => (
<li key={item.to}>
<NavItem to={item.to} tone="dark">
{item.label}
</NavItem>
</li>
))}
</ul>
</nav>
</header>
<MainRegion className={styles.main}>
<Outlet />
</MainRegion>
</div>
);
}
@@ -0,0 +1 @@
export { PublicShell } from "./ui/public-shell";
@@ -0,0 +1,42 @@
.shell {
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-5);
align-items: center;
justify-content: space-between;
padding: var(--space-3) var(--gutter);
border-bottom: var(--line-thin) solid var(--color-divider);
background: var(--color-surface);
}
.nav {
display: flex;
flex-wrap: wrap;
gap: var(--space-1);
margin: 0 calc(-1 * var(--space-3));
padding: 0;
list-style: none;
}
.main {
width: 100%;
}
.footer {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-5);
align-items: center;
justify-content: space-between;
padding: var(--space-4) var(--gutter);
border-top: var(--line-thin) solid var(--color-divider);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
background: var(--color-surface);
}
@@ -0,0 +1,36 @@
import { Outlet } from "react-router-dom";
import { paths } from "../../../shared/config";
import { BrandLogo, MainRegion, NavItem, SkipLink, TextLink } from "../../../shared/ui";
import styles from "./public-shell.module.css";
/** Layout of public pages: sign-in, registration, email confirmation, support. */
export function PublicShell() {
return (
<div className={styles.shell}>
<SkipLink />
<header className={styles.header}>
<BrandLogo />
<nav aria-label="Публичные разделы">
<ul className={styles.nav}>
<li>
<NavItem to={paths.login}>Вход</NavItem>
</li>
<li>
<NavItem to={paths.register}>Регистрация</NavItem>
</li>
<li>
<NavItem to={paths.support}>Поддержка</NavItem>
</li>
</ul>
</nav>
</header>
<MainRegion className={styles.main}>
<Outlet />
</MainRegion>
<footer className={styles.footer}>
<p>Lincodex. Каркас интерфейса: пользовательские сценарии в разработке.</p>
<TextLink to={paths.status}>Технический статус</TextLink>
</footer>
</div>
);
}
@@ -0,0 +1 @@
export { SystemStatus } from "./ui/system-status";
@@ -0,0 +1,21 @@
.result {
display: flex;
flex-wrap: wrap;
gap: var(--space-4);
align-items: center;
justify-content: space-between;
padding: var(--space-5);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.facts {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
}
.facts dt {
color: var(--color-text-secondary);
}
@@ -0,0 +1,50 @@
import { useGetHealthz } from "../../../shared/api/endpoints/health/health";
import { Button, Mono, QueryView, Section } from "../../../shared/ui";
import styles from "./system-status.module.css";
const timeFormat = new Intl.DateTimeFormat("ru-RU", {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
/**
* Technical API liveness check. It shows only that the API process answers
* /healthz; it says nothing about product workflows.
*/
export function SystemStatus() {
const query = useGetHealthz();
return (
<Section
title="Ответ API"
description="Проверка /api/v1/healthz. Это технический сигнал, а не проверка пользовательских сценариев."
>
<QueryView query={query} loadingLabel="Проверяем API...">
{(health) => (
<div className={styles.result}>
<dl className={styles.facts}>
<dt>Статус</dt>
<dd>
<Mono strong>{health.status}</Mono>
</dd>
<dt>Проверено</dt>
<dd>
<Mono>{timeFormat.format(query.dataUpdatedAt)}</Mono>
</dd>
</dl>
<Button
variant="secondary"
isBusy={query.isFetching}
onClick={() => {
void query.refetch();
}}
>
{query.isFetching ? "Проверяем..." : "Проверить снова"}
</Button>
</div>
)}
</QueryView>
</Section>
);
}