diff --git a/.agents/standards/frontend.md b/.agents/standards/frontend.md index 2494630..7988bdc 100644 --- a/.agents/standards/frontend.md +++ b/.agents/standards/frontend.md @@ -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. diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index dafdbb1..4a6916e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 6d1bed2..efe9ff0 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -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. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 706144c..72fa4fd 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -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 не подтверждают бизнес-сценарий. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 26859c0..9e1d8cd 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -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, который выглядит как рабочий результат. diff --git a/frontend/README.en.md b/frontend/README.en.md index 5f167d9..79bf206 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -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). diff --git a/frontend/README.md b/frontend/README.md index d64e227..e642849 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -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). diff --git a/frontend/index.html b/frontend/index.html index 9c23cb6..13243c3 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,7 @@ - + Lincodex diff --git a/frontend/src/app/main.tsx b/frontend/src/app/main.tsx index 49ceaa7..ff915ea 100644 --- a/frontend/src/app/main.tsx +++ b/frontend/src/app/main.tsx @@ -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"); diff --git a/frontend/src/app/providers/query-client.test.tsx b/frontend/src/app/providers/query-client.test.tsx new file mode 100644 index 0000000..0dfcd67 --- /dev/null +++ b/frontend/src/app/providers/query-client.test.tsx @@ -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): string { + return renderToStaticMarkup( + {(health) =>

API: {health.status}

}
, + ); +} + +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>/); + + // 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("

API: ok

"); + 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("= 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, + }, + }, + }); +} diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx new file mode 100644 index 0000000..042e1d2 --- /dev/null +++ b/frontend/src/app/router/routes.test.tsx @@ -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 { + 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( + + + , + ); +} + +async function renderHtml(path: string): Promise { + 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(/]*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, /]/)).toBe(1); + expect(html).toMatch(new RegExp(`]*>${heading}`)); + expect(html).toMatch(new RegExp(`]*aria-label="${navLabel}"`)); + expect(count(html, /]/)).toBe(1); + expect(html).toMatch(/]*id="main-content"[^>]*tabindex="-1"/i); + expect(html).toContain(`${heading} - Lincodex`); + }); + + 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>/); + + 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>/); + expect(html).toMatch(new RegExp(`]*href="${home}"[^>]*>${label}`)); + }); +}); + +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(/]*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("Экран будет реализован в одной из следующих задач"); + } + }); +}); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx new file mode 100644 index 0000000..4aeacd2 --- /dev/null +++ b/frontend/src/app/router/routes.tsx @@ -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: , + errorElement: , + children: [ + { + element: , + children: [ + { index: true, element: }, + { path: paths.login, element: }, + { path: paths.register, element: }, + { path: paths.verifyEmail, element: }, + { path: paths.support, element: }, + { path: paths.status, element: }, + { path: "*", element: }, + ], + }, + { + path: paths.candidate.root, + element: , + children: [ + { index: true, element: }, + { + path: paths.candidate.onboarding, + element: , + }, + { path: paths.candidate.profile, element: }, + { + path: paths.candidate.assessment, + element: , + }, + { path: paths.candidate.results, element: }, + { + path: paths.candidate.invitations, + element: , + }, + { path: paths.candidate.privacy, element: }, + { + path: "*", + element: ( + + ), + }, + ], + }, + { + path: paths.employer.root, + element: , + children: [ + // The employer flow starts with the company profile. + { index: true, loader: () => redirect(paths.employer.company) }, + { path: paths.employer.company, element: }, + { path: paths.employer.needs, element: }, + { + path: paths.employer.candidates, + element: , + }, + { + path: paths.employer.invitations, + element: , + }, + { + path: "*", + element: ( + + ), + }, + ], + }, + ], + }, +]; diff --git a/frontend/src/app/ui/app.tsx b/frontend/src/app/ui/app.tsx index c236b31..0e0f6bf 100644 --- a/frontend/src/app/ui/app.tsx +++ b/frontend/src/app/ui/app.tsx @@ -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 ( - - - } /> - - + ); } diff --git a/frontend/src/app/ui/root-layout.tsx b/frontend/src/app/ui/root-layout.tsx new file mode 100644 index 0000000..95c49dd --- /dev/null +++ b/frontend/src/app/ui/root-layout.tsx @@ -0,0 +1,11 @@ +import { Outlet, ScrollRestoration } from "react-router-dom"; + +/** Top route element shared by every route group. */ +export function RootLayout() { + return ( + <> + + + + ); +} diff --git a/frontend/src/app/ui/route-error-page.tsx b/frontend/src/app/ui/route-error-page.tsx new file mode 100644 index 0000000..98d6243 --- /dev/null +++ b/frontend/src/app/ui/route-error-page.tsx @@ -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 ( +
+ + { + window.location.reload(); + }} + /> + +
+ ); +} diff --git a/frontend/src/app/ui/styles.css b/frontend/src/app/ui/styles.css index 306de26..881d786 100644 --- a/frontend/src/app/ui/styles.css +++ b/frontend/src/app/ui/styles.css @@ -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; + } } diff --git a/frontend/src/pages/home/index.ts b/frontend/src/pages/home/index.ts deleted file mode 100644 index c0e57bf..0000000 --- a/frontend/src/pages/home/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { HomePage } from "./ui/home-page"; diff --git a/frontend/src/pages/home/ui/home-page.module.css b/frontend/src/pages/home/ui/home-page.module.css deleted file mode 100644 index 1ec8bb2..0000000 --- a/frontend/src/pages/home/ui/home-page.module.css +++ /dev/null @@ -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; - } -} diff --git a/frontend/src/pages/home/ui/home-page.tsx b/frontend/src/pages/home/ui/home-page.tsx deleted file mode 100644 index ab2478e..0000000 --- a/frontend/src/pages/home/ui/home-page.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import styles from "./home-page.module.css"; - -export function HomePage() { - return ( -
-
-
-
- ); -} diff --git a/frontend/src/pages/not-found/index.ts b/frontend/src/pages/not-found/index.ts new file mode 100644 index 0000000..f483da2 --- /dev/null +++ b/frontend/src/pages/not-found/index.ts @@ -0,0 +1 @@ +export { NotFoundPage } from "./ui/not-found-page"; diff --git a/frontend/src/pages/not-found/ui/not-found-page.tsx b/frontend/src/pages/not-found/ui/not-found-page.tsx new file mode 100644 index 0000000..ebbeedc --- /dev/null +++ b/frontend/src/pages/not-found/ui/not-found-page.tsx @@ -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 ( + + Адрес {pathname} не ведет ни на один экран. Проверьте ссылку или вернитесь к + началу. + + } + > +
+ {homeLabel} +
+
+ ); +} diff --git a/frontend/src/pages/placeholder/index.ts b/frontend/src/pages/placeholder/index.ts new file mode 100644 index 0000000..2ce492e --- /dev/null +++ b/frontend/src/pages/placeholder/index.ts @@ -0,0 +1,2 @@ +export { PlaceholderPage } from "./ui/placeholder-page"; +export type { ScreenId } from "./model/screens"; diff --git a/frontend/src/pages/placeholder/model/screens.ts b/frontend/src/pages/placeholder/model/screens.ts new file mode 100644 index 0000000..80a56ee --- /dev/null +++ b/frontend/src/pages/placeholder/model/screens.ts @@ -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> = { + 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; + +export type ScreenId = keyof typeof screens; diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.module.css b/frontend/src/pages/placeholder/ui/placeholder-page.module.css new file mode 100644 index 0000000..0f35319 --- /dev/null +++ b/frontend/src/pages/placeholder/ui/placeholder-page.module.css @@ -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); +} diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.tsx b/frontend/src/pages/placeholder/ui/placeholder-page.tsx new file mode 100644 index 0000000..8aa6d50 --- /dev/null +++ b/frontend/src/pages/placeholder/ui/placeholder-page.tsx @@ -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 ( + +

+ Заготовка + Экран будет реализован в одной из следующих задач. Сейчас здесь нет данных и действий. +

+
+
    + {plan.planned.map((item, index) => ( +
  1. + {String(index + 1).padStart(2, "0")} + {item} +
  2. + ))} +
+
+
+ ); +} diff --git a/frontend/src/pages/status/index.ts b/frontend/src/pages/status/index.ts new file mode 100644 index 0000000..0f3bef6 --- /dev/null +++ b/frontend/src/pages/status/index.ts @@ -0,0 +1 @@ +export { StatusPage } from "./ui/status-page"; diff --git a/frontend/src/pages/status/ui/state-fixtures.module.css b/frontend/src/pages/status/ui/state-fixtures.module.css new file mode 100644 index 0000000..ce22b54 --- /dev/null +++ b/frontend/src/pages/status/ui/state-fixtures.module.css @@ -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); +} diff --git a/frontend/src/pages/status/ui/state-fixtures.tsx b/frontend/src/pages/status/ui/state-fixtures.tsx new file mode 100644 index 0000000..85eb5ac --- /dev/null +++ b/frontend/src/pages/status/ui/state-fixtures.tsx @@ -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 { + 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 ( + + {(result) => ( +
+

+ Повторный запрос выполнен, попытка {result.attempt}. +

+ +
+ )} +
+ ); +} + +/** + * 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 ( +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + +
+
+ + + + + + +
+
+

+ Кандидат K-0427, результат 87 / 100, попытка{" "} + 2 от 14.09.2026. +

+
+
+ ); +} diff --git a/frontend/src/pages/status/ui/status-page.tsx b/frontend/src/pages/status/ui/status-page.tsx new file mode 100644 index 0000000..2fd285e --- /dev/null +++ b/frontend/src/pages/status/ui/status-page.tsx @@ -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 ( + + + {import.meta.env.DEV ? : null} + + ); +} diff --git a/frontend/src/pages/welcome/index.ts b/frontend/src/pages/welcome/index.ts new file mode 100644 index 0000000..4f7b16b --- /dev/null +++ b/frontend/src/pages/welcome/index.ts @@ -0,0 +1 @@ +export { WelcomePage } from "./ui/welcome-page"; diff --git a/frontend/src/pages/welcome/ui/welcome-page.module.css b/frontend/src/pages/welcome/ui/welcome-page.module.css new file mode 100644 index 0000000..bd0d674 --- /dev/null +++ b/frontend/src/pages/welcome/ui/welcome-page.module.css @@ -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)); + } +} diff --git a/frontend/src/pages/welcome/ui/welcome-page.tsx b/frontend/src/pages/welcome/ui/welcome-page.tsx new file mode 100644 index 0000000..819dbd8 --- /dev/null +++ b/frontend/src/pages/welcome/ui/welcome-page.tsx @@ -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 ( + +
+
    + {cabinets.map((cabinet) => ( +
  • + + {cabinet.format} + {cabinet.title} + {cabinet.summary} + Пустой каркас + +
  • + ))} +
+
+
+

+ Заготовки: вход,{" "} + регистрация,{" "} + подтверждение почты и{" "} + поддержка. +

+
+
+ ); +} diff --git a/frontend/src/shared/config/index.ts b/frontend/src/shared/config/index.ts new file mode 100644 index 0000000..64cdea6 --- /dev/null +++ b/frontend/src/shared/config/index.ts @@ -0,0 +1 @@ +export { paths } from "./paths"; diff --git a/frontend/src/shared/config/paths.ts b/frontend/src/shared/config/paths.ts new file mode 100644 index 0000000..63cdeab --- /dev/null +++ b/frontend/src/shared/config/paths.ts @@ -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; diff --git a/frontend/src/shared/ui/.gitkeep b/frontend/src/shared/ui/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/frontend/src/shared/ui/brand/brand-logo.module.css b/frontend/src/shared/ui/brand/brand-logo.module.css new file mode 100644 index 0000000..f4d1ec2 --- /dev/null +++ b/frontend/src/shared/ui/brand/brand-logo.module.css @@ -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); +} diff --git a/frontend/src/shared/ui/brand/brand-logo.tsx b/frontend/src/shared/ui/brand/brand-logo.tsx new file mode 100644 index 0000000..7382179 --- /dev/null +++ b/frontend/src/shared/ui/brand/brand-logo.tsx @@ -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 ( + + ФСП +