Compare commits
14 Commits
feat/phase
...
fix/api-pr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53b9561a54 | ||
| 7e9c20d4bf | |||
|
|
e0ed0b6435 | ||
| 8442c761c2 | |||
|
|
87d6505fbf | ||
| 99ae7410ce | |||
|
|
42ee36d0a2 | ||
| fc995ed07d | |||
|
|
0f0c7c2607 | ||
| ef423b322f | |||
| d77dc205dc | |||
| 8a7e87385a | |||
| b92fad6939 | |||
|
|
7260fb59ea |
@@ -24,10 +24,16 @@ API_PORT=3001
|
||||
# CALENDAR_RUN_MOCK_DB=1
|
||||
|
||||
# ─── CORS ────────────────────────────────────────────────────
|
||||
# Должен совпадать с origin в браузере (схема + хост + порт, без пути), иначе API «молчит».
|
||||
# Локальный Vite: http://localhost:5173
|
||||
# Стек с фронтом на 3033: http://localhost:3033
|
||||
# Прод: https://ваш-домен — несколько origin через запятую: https://a.ru,https://www.a.ru
|
||||
CORS_ORIGIN=http://localhost:5173
|
||||
|
||||
# ─── Версия API (опционально) ─────────────────────────────────
|
||||
# Если в образе не удаётся прочитать package.json, подставьте вручную (видно в GET /health).
|
||||
# APP_VERSION=1.0.0
|
||||
|
||||
# ─── Frontend (Vite, локально из каталога frontend/) ─────────
|
||||
# В Docker-образе фронта базовый URL API задаётся при сборке (/api), не из .env.
|
||||
VITE_API_BASE_URL=http://localhost:3001
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ node_modules/
|
||||
dist/
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
100
FRONTEND_PLAN.md
100
FRONTEND_PLAN.md
@@ -1,100 +0,0 @@
|
||||
---
|
||||
|
||||
name: Frontend implementation plan
|
||||
overview: Собрать минималистичный frontend для календаря забегов по UI-инструкции, строго в рамках текущего API-контракта.
|
||||
todos:
|
||||
|
||||
- id: frontend-structure
|
||||
content: Подготовить структуру frontend, роутинг, базовые layout-компоненты и дизайн-токены на CSS variables + BEM
|
||||
status: completed
|
||||
- id: api-contract-layer
|
||||
content: Реализовать типизированный API-клиент и слой нормализации/обработки ошибок по контракту backend-api-for-frontend.md
|
||||
status: completed
|
||||
- id: dashboard-and-calendar
|
||||
content: Собрать Dashboard, списки будущих/прошедших стартов и базовые карточки по минималистичному UI-гайду
|
||||
status: completed
|
||||
- id: race-details-and-metrics
|
||||
content: Реализовать экран карточки старта, вычисление темпа на фронте и отображение completed-метрик
|
||||
status: completed
|
||||
- id: pr-and-comparison
|
||||
content: Сделать блок PR и сравнение стартов с fallback для отсутствующего поля place
|
||||
status: completed
|
||||
- id: backend-dependency-task
|
||||
content: "Расширение API полем finishPlace: миграция 002, маппер, DTO, фронтенд-интеграция — выполнено"
|
||||
status: completed
|
||||
isProject: false
|
||||
|
||||
---
|
||||
|
||||
# План frontend части Calendar Run
|
||||
|
||||
## Исходные опоры
|
||||
|
||||
- UI и UX принципы: минимализм, воздух, акцент на данных, спокойная палитра, быстрые сценарии (дизайн-токены в `frontend/src/styles/tokens.css`).
|
||||
- Продуктовые ограничения и структура экранов сверяем с [d:\vaka.pro\calendar_run\PLAN.md](d:/vaka.pro/calendar_run/PLAN.md).
|
||||
- Интеграционный контракт берём из [d:\vaka.pro\calendar_run\docs\backend-api-for-frontend.md](d:/vaka.pro/calendar_run/docs/backend-api-for-frontend.md).
|
||||
- Общий контекст запуска/окружения — [d:\vaka.pro\calendar_run\README.md](d:/vaka.pro/calendar_run/README.md) и [d:\vaka.pro\calendar_run\docs\backend.md](d:/vaka.pro/calendar_run/docs/backend.md).
|
||||
|
||||
## Границы версии (V1)
|
||||
|
||||
- Только frontend + интеграция с текущим API.
|
||||
- Статус `зарегистрирован` трактуется как UI-вариант `planned` (без изменения backend-контракта).
|
||||
- Для completed-забегов обязательно показываем `темп`; считаем на фронте из `finishTime` и `distanceKm`.
|
||||
- Для completed-забегов поле `место` (`finishPlace`) доступно в API (миграция 002, маппер, DTO); фронтенд отображает его в карточке и таблице сравнения.
|
||||
|
||||
## Архитектура frontend
|
||||
|
||||
- Базовая структура: `frontend/src/app`, `frontend/src/pages`, `frontend/src/components`, `frontend/src/api`, `frontend/src/features`, `frontend/src/lib`, `frontend/src/styles`.
|
||||
- Дизайн-система на CSS variables: токены цвета/типографики/отступов/радиусов, единые состояния (`success`, `warning`, `error`).
|
||||
- БЭМ для всех UI-блоков и модификаторов (`block`, `block__element`, `block--modifier`).
|
||||
- Единый слой API-клиента:
|
||||
- `GET /races`, `GET /races/:id`, `POST /races`, `PATCH /races/:id`, `DELETE /races/:id` (если используется UI-сценарием).
|
||||
- Типы `Race`, `RaceStatus`, DTO для POST/PATCH.
|
||||
- Централизованный маппинг ошибок API (`validation_error`, `not_found`, `database_unavailable`, `conflict`) в UX-сообщения.
|
||||
|
||||
## Экранная модель и сценарии
|
||||
|
||||
- Dashboard:
|
||||
- `Ближайший старт`, `Последний результат`, `Личный рекорд`, `Сезон`.
|
||||
- CTA к календарю и добавлению старта.
|
||||
- Календарь стартов:
|
||||
- Переключение `Будущие` / `Прошедшие`.
|
||||
- Карточка старта: `title`, `date`, `distanceKm`, статус-лейбл.
|
||||
- Карточка старта:
|
||||
- Базовые поля + `finishTime`, вычисляемый `pace`, `finishPlace`, `notes`.
|
||||
- PR блок:
|
||||
- Дистанции: 5K, 10K, 21.1, 42.2 (согласно UI-инструкции).
|
||||
- Расчёт по completed-забегам с валидным `finishTime`.
|
||||
- Сравнение стартов (ключевая фича):
|
||||
- Таблица/карточки по годам с `time`, `pace`, `finishPlace`.
|
||||
- Если `finishPlace` не заполнено — graceful-degradation: колонка в состоянии «нет данных».
|
||||
|
||||
## UX и визуальные требования
|
||||
|
||||
- Визуальная система: светлый фон, белые карточки, один акцентный цвет, без кислотных сочетаний.
|
||||
- Иерархия типографики: H1/H2/body/caption, крупные числовые метрики.
|
||||
- Минимум визуального шума, 2–3 клика на частые действия.
|
||||
- Консистентные состояния загрузки/ошибок/пустых данных.
|
||||
- A11y-базис: фокус-стили, клавиатурная навигация, контраст, корректная разметка интерактивных элементов.
|
||||
|
||||
## Зависимая задача (выполнена)
|
||||
|
||||
- Поле `finishPlace` добавлено в модель `Race`: миграция `002_finish_place_and_registered_status.sql`, маппер `race.ts`, DTO, API-документация.
|
||||
- Frontend-типы, карточка и блок сравнения используют `finishPlace`.
|
||||
|
||||
## Порядок реализации
|
||||
|
||||
1. Подготовить каркас frontend и дизайн-токены (BEM + CSS variables).
|
||||
2. Реализовать API-клиент и типы данных с обработкой ошибок.
|
||||
3. Собрать Dashboard и календарные списки (будущие/прошедшие).
|
||||
4. Реализовать карточку старта с вычислением `pace` на клиенте.
|
||||
5. Реализовать PR и блок сравнения стартов с fallback для `place`.
|
||||
6. Добавить состояния пустых данных/ошибок/загрузки и а11y-полировку.
|
||||
|
||||
## Definition of Done для frontend
|
||||
|
||||
- Все ключевые экраны из UI-инструкции доступны и консистентны визуально.
|
||||
- API-интеграция работает по текущему контракту без локальных обходов хранилища.
|
||||
- `pace` считается корректно для completed-забегов.
|
||||
- `registered` не ломает модель: визуально интерпретируется в рамках `planned`.
|
||||
- `finishPlace` интегрирован; при отсутствии значения — безопасный fallback в UI.
|
||||
64
PLAN.md
64
PLAN.md
@@ -1,64 +0,0 @@
|
||||
# Calendar Run — план продукта
|
||||
|
||||
Монорепозиторий: **backend** (Express + PostgreSQL) и **frontend** (React + Vite). Цель — календарь стартов с метриками бегуна: планирование, результаты, PR и сравнение.
|
||||
|
||||
## Вне объёма (намеренно)
|
||||
|
||||
- Авторизация, мультипользовательность, личные кабинеты.
|
||||
- Парсинг сайтов организаторов и автозагрузка результатов.
|
||||
- Отдача статики SPA с того же процесса, что и API (фронт — отдельный Vite/build).
|
||||
|
||||
## Модель данных `Race` (API — camelCase)
|
||||
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
| ----------------- | --------------------------------------------- | ----------------------------------------------- |
|
||||
| `id` | string | Стабильный ключ, например `{YYYY-MM-DD}-{slug}` |
|
||||
| `date` | string | `YYYY-MM-DD` |
|
||||
| `title` | string | Название |
|
||||
| `distanceKm` | number | Дистанция, км |
|
||||
| `status` | `planned` | `registered` | `completed` | null | Жизненный цикл старта |
|
||||
| `officialUrl` | string | null | Сайт организатора |
|
||||
| `startTime` | string | null | Время старта (строка, напр. `09:30`) |
|
||||
| `clusterSchedule` | string | null | Расписание кластеров |
|
||||
| `bibPickup` | string | null | Выдача номеров |
|
||||
| `bibNumber` | string | null | Стартовый номер |
|
||||
| `finishTime` | string | null | Результат `H:MM:SS` или `MM:SS` |
|
||||
| `finishPlace` | string | null | Место на финише (текст: «3», «3/120» и т.п.) |
|
||||
| `notes` | string | null | Заметки |
|
||||
| `createdAt` | string | ISO, read-only |
|
||||
| `updatedAt` | string | null | ISO, read-only |
|
||||
|
||||
|
||||
PostgreSQL: `snake_case` столбцы, маппинг в `[backend/src/mappers/race.ts](backend/src/mappers/race.ts)`.
|
||||
|
||||
## HTTP API (минимум)
|
||||
|
||||
- `GET /health` — liveness без БД.
|
||||
- `GET /ready` — readiness (подключение к БД; в режиме mock считается доступной — только для dev/CI).
|
||||
- `GET /races` — список; query: `year`, `month` (целые; `month` 1–12).
|
||||
- `GET /races/:id`, `POST /races`, `PATCH /races/:id`, `DELETE /races/:id`.
|
||||
|
||||
Ошибки: JSON, единый стиль (`validation_error`, `not_found`, `conflict`, `database_unavailable`). Подробности — `[docs/backend-api-for-frontend.md](docs/backend-api-for-frontend.md)`.
|
||||
|
||||
## Seed
|
||||
|
||||
- Файл `[import/races_2026_calendar.csv](import/races_2026_calendar.csv)`.
|
||||
- Стабильный `id`, upsert по `id`. Повторный запуск безопасен.
|
||||
|
||||
## Режим без PostgreSQL (dev/CI)
|
||||
|
||||
Переменная `CALENDAR_RUN_MOCK_DB=1` (или `true`): HTTP-обработчики используют заглушку пула **без** реальной БД. **Не использовать** для `npm run db:migrate` и `npm run seed` — нужен настоящий Postgres и `DB_`*.
|
||||
|
||||
## Frontend (SPA)
|
||||
|
||||
- Маршруты: дашборд (`/`), список стартов (`/races`), карточка (`/races/:id`).
|
||||
- Дашборд: ближайший старт, последний результат, PR, сезон, PR по ключевым дистанциям, сравнение завершённых стартов, при необходимости — лёгкая визуализация прогресса.
|
||||
- Список: будущие / прошедшие; фильтрация по году и месяцу через API.
|
||||
- Стили: BEM и дизайн-токены (см. `frontend/src/styles/tokens.css`).
|
||||
|
||||
## Критерии готовности текущей итерации
|
||||
|
||||
- Документация согласована с кодом: `[README.md](README.md)`, `[docs/backend.md](docs/backend.md)`, `[docs/backend-api-for-frontend.md](docs/backend-api-for-frontend.md)`.
|
||||
- Миграции и seed воспроизводимы; контракт API покрыт smoke-тестами в CI при необходимости с mock-БД.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "calendar-run-backend",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
|
||||
@@ -12,6 +12,9 @@ export function createApp(): express.Express {
|
||||
|
||||
app.use(healthRouter);
|
||||
app.use(racesRouter);
|
||||
// Тот же API под /api/* — если прокси не снимает префикс или запрос идёт напрямую на порт бэкенда с /api.
|
||||
app.use("/api", healthRouter);
|
||||
app.use("/api", racesRouter);
|
||||
|
||||
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
||||
if (err instanceof SyntaxError && "body" in err) {
|
||||
|
||||
@@ -33,5 +33,21 @@ export const config = {
|
||||
password: requireEnv("DB_PASSWORD"),
|
||||
},
|
||||
apiPort: parseInt(process.env.PORT || process.env.API_PORT || "3001", 10),
|
||||
corsOrigin: process.env.CORS_ORIGIN || "http://localhost:5173",
|
||||
/** Одно значение или несколько через запятую (прод: https://домен) */
|
||||
corsOrigin: parseCorsOrigins(),
|
||||
};
|
||||
|
||||
function parseCorsOrigins(): string | string[] {
|
||||
const raw = process.env.CORS_ORIGIN?.trim();
|
||||
if (!raw) {
|
||||
return "http://localhost:5173";
|
||||
}
|
||||
const parts = raw.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "http://localhost:5173";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
return parts[0]!;
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ const poolConfig: PoolConfig = {
|
||||
|
||||
function mockRowFromInsert(sql: string, params: unknown[]): RaceRow {
|
||||
const match = sql.match(/INSERT INTO races\s*\(([^)]+)\)\s*VALUES/i);
|
||||
const now = new Date().toISOString();
|
||||
const now = new Date();
|
||||
if (!match) {
|
||||
return {
|
||||
id: String(params[0] ?? ""),
|
||||
@@ -108,7 +108,7 @@ function createMockPool(): Pool {
|
||||
if (!existing) {
|
||||
return emptyResult();
|
||||
}
|
||||
const updated = { ...existing, updated_at: new Date().toISOString() };
|
||||
const updated = { ...existing, updated_at: new Date() };
|
||||
store.set(id, updated);
|
||||
return {
|
||||
rows: [updated as unknown as T],
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/** Row shape returned by PostgreSQL (snake_case). */
|
||||
/**
|
||||
* Row shape returned by PostgreSQL (snake_case).
|
||||
* pg returns DATE as string, NUMERIC as string, TIMESTAMPTZ as Date.
|
||||
*/
|
||||
export interface RaceRow {
|
||||
id: string;
|
||||
race_date: string;
|
||||
race_date: string | Date;
|
||||
title: string;
|
||||
distance_km: string;
|
||||
status: string | null;
|
||||
@@ -13,8 +16,8 @@ export interface RaceRow {
|
||||
finish_time: string | null;
|
||||
finish_place: string | null;
|
||||
notes: string | null;
|
||||
created_at: string;
|
||||
updated_at: string | null;
|
||||
created_at: Date;
|
||||
updated_at: Date | null;
|
||||
}
|
||||
|
||||
/** API shape (camelCase). */
|
||||
@@ -36,11 +39,27 @@ export interface RaceDto {
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function toISOString(value: Date | string): string {
|
||||
return value instanceof Date ? value.toISOString() : String(value);
|
||||
}
|
||||
|
||||
/** DATE column may arrive as string or Date; API always exposes YYYY-MM-DD for the calendar day. */
|
||||
function raceDateToApiValue(value: string | Date): string {
|
||||
if (typeof value === "string") {
|
||||
const m = value.match(/^(\d{4}-\d{2}-\d{2})/);
|
||||
return m ? m[1]! : value;
|
||||
}
|
||||
const y = value.getFullYear();
|
||||
const mo = String(value.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(value.getDate()).padStart(2, "0");
|
||||
return `${y}-${mo}-${day}`;
|
||||
}
|
||||
|
||||
/** Convert a DB row to the API DTO (camelCase). */
|
||||
export function rowToDto(row: RaceRow): RaceDto {
|
||||
return {
|
||||
id: row.id,
|
||||
date: row.race_date,
|
||||
date: raceDateToApiValue(row.race_date),
|
||||
title: row.title,
|
||||
distanceKm: parseFloat(row.distance_km),
|
||||
status: row.status,
|
||||
@@ -52,8 +71,8 @@ export function rowToDto(row: RaceRow): RaceDto {
|
||||
finishTime: row.finish_time,
|
||||
finishPlace: row.finish_place,
|
||||
notes: row.notes,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
createdAt: toISOString(row.created_at),
|
||||
updatedAt: row.updated_at ? toISOString(row.updated_at) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { checkDbConnection } from "../db";
|
||||
import { getBackendVersion } from "../version";
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get("/health", (_req: Request, res: Response) => {
|
||||
res.json({ status: "ok" });
|
||||
res.json({ status: "ok", version: getBackendVersion() });
|
||||
});
|
||||
|
||||
router.get("/ready", async (_req: Request, res: Response) => {
|
||||
|
||||
@@ -24,10 +24,24 @@ function makeId(date: string, title: string): string {
|
||||
return `${date}-${slugify(title)}`;
|
||||
}
|
||||
|
||||
const CSV_NAME = "races_2026_calendar.csv";
|
||||
|
||||
function resolveCsvPath(): string | null {
|
||||
// Docker image: /app/dist/*.js → ../import = /app/import (matches Dockerfile COPY import ./import)
|
||||
// Local monorepo: backend/dist/*.js → ../../import = repo root import/
|
||||
const candidates = [
|
||||
path.resolve(__dirname, "../import", CSV_NAME),
|
||||
path.resolve(__dirname, "../../import", CSV_NAME),
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) ?? null;
|
||||
}
|
||||
|
||||
async function seed() {
|
||||
const csvPath = path.resolve(__dirname, "../../import/races_2026_calendar.csv");
|
||||
if (!fs.existsSync(csvPath)) {
|
||||
console.error(`[seed] CSV not found: ${csvPath}`);
|
||||
const csvPath = resolveCsvPath();
|
||||
if (!csvPath) {
|
||||
console.error(
|
||||
`[seed] CSV not found: ${CSV_NAME}. Tried:\n - ${path.resolve(__dirname, "../import", CSV_NAME)}\n - ${path.resolve(__dirname, "../../import", CSV_NAME)}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
24
backend/src/version.ts
Normal file
24
backend/src/version.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
let cached: string | null = null;
|
||||
|
||||
export function getBackendVersion(): string {
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const fromEnv = process.env.APP_VERSION?.trim();
|
||||
if (fromEnv) {
|
||||
cached = fromEnv;
|
||||
return cached;
|
||||
}
|
||||
try {
|
||||
const pkgPath = path.join(__dirname, "..", "package.json");
|
||||
const raw = fs.readFileSync(pkgPath, "utf-8");
|
||||
cached = (JSON.parse(raw) as { version: string }).version;
|
||||
return cached;
|
||||
} catch {
|
||||
cached = "0.0.0";
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,13 @@ const app = createApp();
|
||||
test("GET /health returns ok", async () => {
|
||||
const res = await request(app).get("/health").expect(200);
|
||||
assert.equal(res.body.status, "ok");
|
||||
assert.equal(typeof res.body.version, "string");
|
||||
assert.ok(res.body.version.length > 0);
|
||||
});
|
||||
|
||||
test("GET /api/health returns ok (prefix without proxy strip)", async () => {
|
||||
const res = await request(app).get("/api/health").expect(200);
|
||||
assert.equal(res.body.status, "ok");
|
||||
});
|
||||
|
||||
test("GET /ready succeeds with mock database", async () => {
|
||||
@@ -32,6 +39,11 @@ test("GET /races accepts year and month", async () => {
|
||||
assert.ok(Array.isArray(res.body));
|
||||
});
|
||||
|
||||
test("GET /api/races mirrors GET /races", async () => {
|
||||
const res = await request(app).get("/api/races?year=2026&month=5").expect(200);
|
||||
assert.ok(Array.isArray(res.body));
|
||||
});
|
||||
|
||||
test("GET /races/:id returns not_found", async () => {
|
||||
const res = await request(app).get("/races/does-not-exist").expect(404);
|
||||
assert.equal(res.body.error, "not_found");
|
||||
|
||||
@@ -27,6 +27,9 @@ services:
|
||||
- PORT=3000
|
||||
ports:
|
||||
- "3001:3000"
|
||||
volumes:
|
||||
# CSV и прочие данные import/ на хосте (Synology: ./import рядом с compose) без пересборки образа
|
||||
- ./import:/app/import:ro
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- postgres_default
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Calendar Run</title>
|
||||
<title>Календарь стартов</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "calendar-run-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -35,14 +35,45 @@ function normalizeApiCode(value: string | undefined): ApiErrorCode {
|
||||
value === "validation_error" ||
|
||||
value === "not_found" ||
|
||||
value === "database_unavailable" ||
|
||||
value === "conflict"
|
||||
value === "conflict" ||
|
||||
value === "unknown_error"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "unknown_error";
|
||||
}
|
||||
|
||||
function isGatewayStatus(status: number): boolean {
|
||||
return status === 502 || status === 503 || status === 504;
|
||||
}
|
||||
|
||||
function hasStructuredApiError(payload: unknown): payload is ApiErrorPayload {
|
||||
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
||||
return false;
|
||||
}
|
||||
return typeof (payload as ApiErrorPayload).error === "string";
|
||||
}
|
||||
|
||||
export function toApiError(status: number, payload: unknown): ApiError {
|
||||
if (isGatewayStatus(status) && !hasStructuredApiError(payload)) {
|
||||
return new ApiError({
|
||||
code: "network_error",
|
||||
status,
|
||||
message: "Сервер временно недоступен. Попробуйте обновить страницу.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!hasStructuredApiError(payload) && (status === 401 || status === 403 || status === 404)) {
|
||||
return new ApiError({
|
||||
code: "network_error",
|
||||
status,
|
||||
message:
|
||||
status === 404
|
||||
? "API не найден по этому адресу. Проверьте прокси и префикс /api."
|
||||
: "Запрос отклонён сервером. Проверьте переменную CORS_ORIGIN на бэкенде.",
|
||||
});
|
||||
}
|
||||
|
||||
const maybePayload = payload as ApiErrorPayload;
|
||||
const code = normalizeApiCode(maybePayload?.error);
|
||||
const details = Array.isArray(maybePayload?.details)
|
||||
@@ -69,6 +100,8 @@ export function getApiErrorMessage(code: ApiErrorCode): string {
|
||||
return "Запись с таким идентификатором уже существует.";
|
||||
case "network_error":
|
||||
return "Не удалось связаться с сервером.";
|
||||
case "unknown_error":
|
||||
return "Сервер не смог обработать запрос. Попробуйте позже или обновите страницу.";
|
||||
default:
|
||||
return "Произошла неизвестная ошибка.";
|
||||
}
|
||||
|
||||
10
frontend/src/api/health.ts
Normal file
10
frontend/src/api/health.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { requestJson } from "./http";
|
||||
|
||||
export type HealthResponse = {
|
||||
status: string;
|
||||
version: string;
|
||||
};
|
||||
|
||||
export async function getHealth(init?: RequestInit): Promise<HealthResponse> {
|
||||
return requestJson<HealthResponse>("/health", init);
|
||||
}
|
||||
@@ -20,36 +20,73 @@ async function parseResponseBody(response: Response): Promise<unknown> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
try {
|
||||
const response = await fetch(buildUrl(path), {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
const GATEWAY_RETRY_STATUSES = new Set([502, 503, 504]);
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const payload = await parseResponseBody(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw toApiError(response.status, payload);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new ApiError({
|
||||
code: "network_error",
|
||||
status: null,
|
||||
message: "Не удалось связаться с сервером.",
|
||||
});
|
||||
}
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const idempotent = method === "GET" || method === "HEAD";
|
||||
const maxAttempts = idempotent ? 3 : 1;
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
||||
try {
|
||||
const defaultHeaders: Record<string, string> = {};
|
||||
if (method !== "GET" && method !== "HEAD") {
|
||||
defaultHeaders["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
const response = await fetch(buildUrl(path), {
|
||||
...init,
|
||||
headers: {
|
||||
...defaultHeaders,
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const payload = await parseResponseBody(response);
|
||||
|
||||
if (!response.ok) {
|
||||
const retryable = idempotent && GATEWAY_RETRY_STATUSES.has(response.status) && attempt < maxAttempts;
|
||||
if (retryable) {
|
||||
await delay(80 * attempt);
|
||||
continue;
|
||||
}
|
||||
throw toApiError(response.status, payload);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof DOMException && error.name === "AbortError") {
|
||||
throw error;
|
||||
}
|
||||
const retryable = idempotent && attempt < maxAttempts;
|
||||
if (retryable) {
|
||||
await delay(80 * attempt);
|
||||
continue;
|
||||
}
|
||||
throw new ApiError({
|
||||
code: "network_error",
|
||||
status: null,
|
||||
message: "Не удалось связаться с сервером.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
throw new ApiError({
|
||||
code: "network_error",
|
||||
status: null,
|
||||
message: "Не удалось связаться с сервером.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export type { CreateRacePayload, Race, RacesQuery, RaceStatus, UpdateRacePayload } from "./types";
|
||||
export { ApiError, getApiErrorMessage } from "./errors";
|
||||
export type { HealthResponse } from "./health";
|
||||
export { getHealth } from "./health";
|
||||
export { getRaceById, getRaces, createRace, updateRace, deleteRace } from "./races";
|
||||
|
||||
@@ -77,8 +77,8 @@ function buildRacesQuery(query?: RacesQuery): string {
|
||||
return serialized ? `?${serialized}` : "";
|
||||
}
|
||||
|
||||
export async function getRaces(query?: RacesQuery): Promise<Race[]> {
|
||||
const response = await requestJson<unknown[]>(`/races${buildRacesQuery(query)}`);
|
||||
export async function getRaces(query?: RacesQuery, init?: RequestInit): Promise<Race[]> {
|
||||
const response = await requestJson<unknown[]>(`/races${buildRacesQuery(query)}`, init);
|
||||
if (!Array.isArray(response)) {
|
||||
throw new ApiError({
|
||||
code: "unknown_error",
|
||||
@@ -90,8 +90,8 @@ export async function getRaces(query?: RacesQuery): Promise<Race[]> {
|
||||
return response.map(normalizeRace);
|
||||
}
|
||||
|
||||
export async function getRaceById(id: string): Promise<Race> {
|
||||
return normalizeRace(await requestJson<unknown>(`/races/${id}`));
|
||||
export async function getRaceById(id: string, init?: RequestInit): Promise<Race> {
|
||||
return normalizeRace(await requestJson<unknown>(`/races/${id}`, init));
|
||||
}
|
||||
|
||||
export async function createRace(payload: CreateRacePayload): Promise<Race> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { NavLink, Outlet } from "react-router-dom";
|
||||
import { AppShellFooter } from "./AppShellFooter";
|
||||
|
||||
export function AppLayout(): JSX.Element {
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<header className="app-shell__header">
|
||||
<div className="app-shell__brand">Calendar Run</div>
|
||||
<nav className="app-shell__nav" aria-label="Primary navigation">
|
||||
<div className="app-shell__brand">Календарь стартов</div>
|
||||
<nav className="app-shell__nav" aria-label="Основная навигация">
|
||||
<NavLink
|
||||
to="/"
|
||||
end
|
||||
@@ -13,7 +14,7 @@ export function AppLayout(): JSX.Element {
|
||||
isActive ? "app-shell__link app-shell__link--active" : "app-shell__link"
|
||||
}
|
||||
>
|
||||
Dashboard
|
||||
Обзор
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/races"
|
||||
@@ -21,7 +22,7 @@ export function AppLayout(): JSX.Element {
|
||||
isActive ? "app-shell__link app-shell__link--active" : "app-shell__link"
|
||||
}
|
||||
>
|
||||
Races
|
||||
Старты
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/races/new"
|
||||
@@ -36,6 +37,7 @@ export function AppLayout(): JSX.Element {
|
||||
<main className="app-shell__main">
|
||||
<Outlet />
|
||||
</main>
|
||||
<AppShellFooter />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
40
frontend/src/app/layouts/AppShellFooter.tsx
Normal file
40
frontend/src/app/layouts/AppShellFooter.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getHealth } from "../../api";
|
||||
import { FRONTEND_VERSION } from "../../frontendVersion";
|
||||
|
||||
export function AppShellFooter(): JSX.Element {
|
||||
const [backendVersion, setBackendVersion] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const ac = new AbortController();
|
||||
void getHealth({ signal: ac.signal })
|
||||
.then((h) => {
|
||||
if (ac.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
const v = h.version;
|
||||
setBackendVersion(typeof v === "string" && v.length > 0 ? v : "не указана");
|
||||
})
|
||||
.catch(() => {
|
||||
if (ac.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setBackendVersion("недоступна");
|
||||
});
|
||||
return () => ac.abort();
|
||||
}, []);
|
||||
|
||||
const backendLabel = backendVersion === null ? "…" : backendVersion;
|
||||
|
||||
return (
|
||||
<footer className="app-shell__footer">
|
||||
<p className="app-shell__footer-versions">
|
||||
Версия клиента: {FRONTEND_VERSION}
|
||||
<span className="app-shell__footer-sep" aria-hidden="true">
|
||||
{" · "}
|
||||
</span>
|
||||
Версия сервера: {backendLabel}
|
||||
</p>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,12 @@
|
||||
import type { Race } from "../api";
|
||||
import { formatRaceDate, isCloseDistance, parseFinishTimeToSeconds } from "../lib";
|
||||
import { formatRaceDate, isCloseDistance, parseFinishTimeToSeconds, parseRaceDate } from "../lib";
|
||||
|
||||
type PaceTrendChartProps = {
|
||||
races: Race[];
|
||||
distanceKm: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Minimal SVG sparkline: finish time (minutes) over chronological completed races
|
||||
* at the selected distance. Lower time = higher point (better).
|
||||
*/
|
||||
/** Линейный график: время финиша (минуты) по завершённым стартам выбранной дистанции. */
|
||||
export function PaceTrendChart(props: PaceTrendChartProps): JSX.Element {
|
||||
const { races, distanceKm } = props;
|
||||
|
||||
@@ -21,7 +18,7 @@ export function PaceTrendChart(props: PaceTrendChartProps): JSX.Element {
|
||||
parseFinishTimeToSeconds(race.finishTime) != null,
|
||||
)
|
||||
.sort(
|
||||
(a, b) => new Date(`${a.date}T00:00:00`).getTime() - new Date(`${b.date}T00:00:00`).getTime(),
|
||||
(a, b) => parseRaceDate(a.date).getTime() - parseRaceDate(b.date).getTime(),
|
||||
)
|
||||
.map((race) => {
|
||||
const seconds = parseFinishTimeToSeconds(race.finishTime)!;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export {};
|
||||
3
frontend/src/frontendVersion.ts
Normal file
3
frontend/src/frontendVersion.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import packageJson from "../package.json";
|
||||
|
||||
export const FRONTEND_VERSION: string = packageJson.version;
|
||||
@@ -7,6 +7,8 @@ export {
|
||||
getRaceStatusLabel,
|
||||
isCloseDistance,
|
||||
parseFinishTimeToSeconds,
|
||||
parseRaceDate,
|
||||
raceNeedsResultEntry,
|
||||
sortByDateAsc,
|
||||
sortByDateDesc,
|
||||
splitRacesByDate,
|
||||
|
||||
@@ -2,8 +2,14 @@ import type { Race } from "../api";
|
||||
|
||||
const MS_IN_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
function parseRaceDate(date: string): Date {
|
||||
return new Date(`${date}T00:00:00`);
|
||||
/** API date: YYYY-MM-DD или ISO-строка от сериализации (не склеивать с «T00:00:00» повторно). */
|
||||
export function parseRaceDate(date: string): Date {
|
||||
const ymd = date.slice(0, 10);
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(ymd)) {
|
||||
return new Date(`${ymd}T00:00:00`);
|
||||
}
|
||||
const parsed = new Date(date);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function parseFinishTimeToSeconds(value: string | null): number | null {
|
||||
@@ -116,18 +122,36 @@ export function getPaceLabel(finishTime: string | null, distanceKm: number): str
|
||||
return `${String(paceMinutes).padStart(2, "0")}:${String(paceRemainder).padStart(2, "0")} /км`;
|
||||
}
|
||||
|
||||
export function getRaceStatusClassName(status: Race["status"]): string {
|
||||
const base = "race-card__status";
|
||||
if (status === "completed") {
|
||||
return `${base} ${base}--completed`;
|
||||
function isPastDateNeedingResult(status: Race["status"], raceDate: string): boolean {
|
||||
if (status !== "planned" && status !== "registered") {
|
||||
return false;
|
||||
}
|
||||
if (status === "registered") {
|
||||
return `${base} ${base}--registered`;
|
||||
}
|
||||
return `${base} ${base}--planned`;
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return parseRaceDate(raceDate).getTime() < today.getTime();
|
||||
}
|
||||
|
||||
export function getRaceStatusLabel(status: Race["status"]): string {
|
||||
export function raceNeedsResultEntry(race: Race): boolean {
|
||||
return isPastDateNeedingResult(race.status, race.date);
|
||||
}
|
||||
|
||||
export function getRaceStatusClassName(status: Race["status"], raceDate?: string): string {
|
||||
const base = "race-card__status";
|
||||
let tier = `${base}--planned`;
|
||||
if (status === "completed") {
|
||||
tier = `${base}--completed`;
|
||||
} else if (status === "registered") {
|
||||
tier = `${base}--registered`;
|
||||
}
|
||||
const needs =
|
||||
raceDate && isPastDateNeedingResult(status, raceDate) ? ` ${base}--needs-result` : "";
|
||||
return `${base} ${tier}${needs}`;
|
||||
}
|
||||
|
||||
export function getRaceStatusLabel(status: Race["status"], raceDate?: string): string {
|
||||
if (raceDate && isPastDateNeedingResult(status, raceDate)) {
|
||||
return "внесите результат";
|
||||
}
|
||||
if (status === "completed") {
|
||||
return "пробежал";
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
getPaceLabel,
|
||||
isCloseDistance,
|
||||
parseFinishTimeToSeconds,
|
||||
parseRaceDate,
|
||||
splitRacesByDate,
|
||||
} from "../lib";
|
||||
|
||||
@@ -18,7 +19,7 @@ function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.message;
|
||||
}
|
||||
return "Не удалось загрузить данные dashboard.";
|
||||
return "Не удалось загрузить данные обзора.";
|
||||
}
|
||||
|
||||
export function DashboardPage(): JSX.Element {
|
||||
@@ -28,23 +29,24 @@ export function DashboardPage(): JSX.Element {
|
||||
const [chartDistanceKm, setChartDistanceKm] = useState<number>(10);
|
||||
|
||||
useEffect(() => {
|
||||
const ac = new AbortController();
|
||||
let isMounted = true;
|
||||
|
||||
async function loadDashboardData(): Promise<void> {
|
||||
try {
|
||||
const items = await getRaces();
|
||||
if (!isMounted) {
|
||||
const items = await getRaces(undefined, { signal: ac.signal });
|
||||
if (!isMounted || ac.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setRaces(items);
|
||||
setErrorMessage(null);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
if (ac.signal.aborted || !isMounted) {
|
||||
return;
|
||||
}
|
||||
setErrorMessage(getErrorMessage(error));
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
if (isMounted && !ac.signal.aborted) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
@@ -53,6 +55,7 @@ export function DashboardPage(): JSX.Element {
|
||||
void loadDashboardData();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
ac.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -80,7 +83,7 @@ export function DashboardPage(): JSX.Element {
|
||||
}
|
||||
|
||||
const currentYear = new Date().getFullYear();
|
||||
const seasonRaces = races.filter((race) => new Date(`${race.date}T00:00:00`).getFullYear() === currentYear);
|
||||
const seasonRaces = races.filter((race) => parseRaceDate(race.date).getFullYear() === currentYear);
|
||||
const seasonCompleted = seasonRaces.filter((race) => race.status === "completed");
|
||||
|
||||
return {
|
||||
@@ -130,7 +133,7 @@ export function DashboardPage(): JSX.Element {
|
||||
.filter((race) => race.status === "completed")
|
||||
.map((race) => ({
|
||||
id: race.id,
|
||||
year: new Date(`${race.date}T00:00:00`).getFullYear(),
|
||||
year: parseRaceDate(race.date).getFullYear(),
|
||||
title: race.title,
|
||||
distance: formatDistance(race.distanceKm),
|
||||
finishTime: race.finishTime ?? "время не указано",
|
||||
@@ -143,7 +146,7 @@ export function DashboardPage(): JSX.Element {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<section className="page page--dashboard" aria-busy="true">
|
||||
<h1 className="page__title">Dashboard</h1>
|
||||
<h1 className="page__title">Обзор</h1>
|
||||
<p className="page__subtitle">Загружаем ваши старты...</p>
|
||||
</section>
|
||||
);
|
||||
@@ -152,7 +155,7 @@ export function DashboardPage(): JSX.Element {
|
||||
if (errorMessage) {
|
||||
return (
|
||||
<section className="page page--dashboard" role="alert">
|
||||
<h1 className="page__title">Dashboard</h1>
|
||||
<h1 className="page__title">Обзор</h1>
|
||||
<p className="page__subtitle page__subtitle--error">{errorMessage}</p>
|
||||
</section>
|
||||
);
|
||||
@@ -160,7 +163,7 @@ export function DashboardPage(): JSX.Element {
|
||||
|
||||
return (
|
||||
<section className="page page--dashboard">
|
||||
<h1 className="page__title">Dashboard</h1>
|
||||
<h1 className="page__title">Обзор</h1>
|
||||
<p className="page__subtitle">Ключевые метрики по вашему календарю стартов.</p>
|
||||
|
||||
<div className="dashboard-grid" aria-label="Ключевые метрики">
|
||||
@@ -205,7 +208,7 @@ export function DashboardPage(): JSX.Element {
|
||||
<p className="dashboard-card__hint">Лучший темп среди завершённых стартов.</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="dashboard-card__empty">Недостаточно данных для PR.</p>
|
||||
<p className="dashboard-card__empty">Недостаточно данных для личного рекорда.</p>
|
||||
)}
|
||||
</article>
|
||||
|
||||
@@ -242,7 +245,7 @@ export function DashboardPage(): JSX.Element {
|
||||
</section>
|
||||
|
||||
<section className="dashboard-section" aria-label="Личные рекорды по дистанциям">
|
||||
<h2 className="dashboard-section__title">PR по дистанциям</h2>
|
||||
<h2 className="dashboard-section__title">Рекорды по дистанциям</h2>
|
||||
<div className="dashboard-grid dashboard-grid--pr">
|
||||
{personalRecordsByDistance.map((item) => (
|
||||
<article key={item.distanceKm} className="dashboard-card">
|
||||
@@ -291,7 +294,7 @@ export function DashboardPage(): JSX.Element {
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="dashboard-card__empty">Нет completed-стартов для сравнения.</p>
|
||||
<p className="dashboard-card__empty">Нет завершённых стартов для сравнения.</p>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getPaceLabel,
|
||||
getRaceStatusClassName,
|
||||
getRaceStatusLabel,
|
||||
raceNeedsResultEntry,
|
||||
} from "../lib";
|
||||
import type { Race } from "../api";
|
||||
|
||||
@@ -57,6 +58,7 @@ export function RaceDetailsPage(): JSX.Element {
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const ac = new AbortController();
|
||||
let isMounted = true;
|
||||
|
||||
async function loadRace(): Promise<void> {
|
||||
@@ -67,19 +69,19 @@ export function RaceDetailsPage(): JSX.Element {
|
||||
}
|
||||
|
||||
try {
|
||||
const item = await getRaceById(raceId);
|
||||
if (!isMounted) {
|
||||
const item = await getRaceById(raceId, { signal: ac.signal });
|
||||
if (!isMounted || ac.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setRace(item);
|
||||
setErrorMessage(null);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
if (ac.signal.aborted || !isMounted) {
|
||||
return;
|
||||
}
|
||||
setErrorMessage(getErrorMessage(error));
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
if (isMounted && !ac.signal.aborted) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
@@ -88,6 +90,7 @@ export function RaceDetailsPage(): JSX.Element {
|
||||
void loadRace();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
ac.abort();
|
||||
};
|
||||
}, [raceId]);
|
||||
|
||||
@@ -146,9 +149,19 @@ export function RaceDetailsPage(): JSX.Element {
|
||||
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
||||
</p>
|
||||
</div>
|
||||
<span className={getRaceStatusClassName(race.status)}>{getRaceStatusLabel(race.status)}</span>
|
||||
<span className={getRaceStatusClassName(race.status, race.date)}>{getRaceStatusLabel(race.status, race.date)}</span>
|
||||
</div>
|
||||
|
||||
{raceNeedsResultEntry(race) ? (
|
||||
<p className="race-details-past-hint" role="status">
|
||||
Дата старта уже прошла —{" "}
|
||||
<Link className="race-details-past-hint__link" to={`/races/${race.id}/edit`}>
|
||||
внесите результат или обновите статус
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="race-details-actions">
|
||||
<Link className="btn btn--primary" to={`/races/${race.id}/edit`}>
|
||||
Редактировать
|
||||
@@ -200,7 +213,7 @@ export function RaceDetailsPage(): JSX.Element {
|
||||
</div>
|
||||
<div className="race-details-meta__item">
|
||||
<dt className="race-details-meta__key">Статус</dt>
|
||||
<dd className="race-details-meta__value">{getRaceStatusLabel(race.status)}</dd>
|
||||
<dd className="race-details-meta__value">{getRaceStatusLabel(race.status, race.date)}</dd>
|
||||
</div>
|
||||
<DetailLink label="Сайт организатора" url={race.officialUrl} />
|
||||
<DetailItem label="Время старта" value={race.startTime} />
|
||||
|
||||
@@ -54,8 +54,9 @@ const EMPTY_FORM: FormData = {
|
||||
};
|
||||
|
||||
function raceToFormData(race: Race): FormData {
|
||||
const dateValue = race.date.length >= 10 ? race.date.slice(0, 10) : race.date;
|
||||
return {
|
||||
date: race.date,
|
||||
date: dateValue,
|
||||
title: race.title,
|
||||
distanceKm: String(race.distanceKm),
|
||||
status: race.status ?? "",
|
||||
@@ -310,7 +311,7 @@ export function RaceFormPage(): JSX.Element {
|
||||
name="officialUrl"
|
||||
value={form.officialUrl}
|
||||
onChange={handleChange}
|
||||
placeholder="https://example.com"
|
||||
placeholder="https://…"
|
||||
/>
|
||||
</label>
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ function RaceList(props: { title: string; races: Race[] }): JSX.Element {
|
||||
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
||||
</p>
|
||||
</div>
|
||||
<span className={getRaceStatusClassName(race.status)}>{getRaceStatusLabel(race.status)}</span>
|
||||
<span className={getRaceStatusClassName(race.status, race.date)}>{getRaceStatusLabel(race.status, race.date)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -100,24 +100,25 @@ export function RacesPage(): JSX.Element {
|
||||
}, [yearFilter, monthFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
const ac = new AbortController();
|
||||
let isMounted = true;
|
||||
|
||||
async function loadRaces(): Promise<void> {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const items = await getRaces(listQuery);
|
||||
if (!isMounted) {
|
||||
const items = await getRaces(listQuery, { signal: ac.signal });
|
||||
if (!isMounted || ac.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setRaces(items);
|
||||
setErrorMessage(null);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
if (ac.signal.aborted || !isMounted) {
|
||||
return;
|
||||
}
|
||||
setErrorMessage(getErrorMessage(error));
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
if (isMounted && !ac.signal.aborted) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
@@ -126,6 +127,7 @@ export function RacesPage(): JSX.Element {
|
||||
void loadRaces();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
ac.abort();
|
||||
};
|
||||
}, [listQuery]);
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ a {
|
||||
.app-shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-rows: auto 1fr;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
}
|
||||
|
||||
.app-shell__header {
|
||||
@@ -77,6 +77,24 @@ a {
|
||||
padding: var(--space-6);
|
||||
}
|
||||
|
||||
.app-shell__footer {
|
||||
margin-top: auto;
|
||||
padding: var(--space-3) var(--space-6);
|
||||
border-top: 1px solid var(--color-border);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.app-shell__footer-versions {
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.app-shell__footer-sep {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.page {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
@@ -273,6 +291,31 @@ a {
|
||||
color: #8a5a00;
|
||||
}
|
||||
|
||||
.race-card__status--needs-result {
|
||||
outline: 1px solid var(--color-warning);
|
||||
}
|
||||
|
||||
.race-details-past-hint {
|
||||
margin: 0 0 var(--space-4);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--color-warning);
|
||||
background: #fffaf0;
|
||||
color: var(--color-text);
|
||||
font-size: var(--font-size-caption);
|
||||
}
|
||||
|
||||
.race-details-past-hint__link {
|
||||
color: var(--color-accent);
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.race-details-past-hint__link:hover,
|
||||
.race-details-past-hint__link:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.races-filter {
|
||||
margin-top: var(--space-5);
|
||||
display: flex;
|
||||
|
||||
1
frontend/src/vite-env.d.ts
vendored
Normal file
1
frontend/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -2,5 +2,5 @@ import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()]
|
||||
plugins: [react()],
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user