Compare commits
21 Commits
feat/race-
...
feature/ra
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00985732ec | ||
|
|
0153f223f2 | ||
| b1b363a7e8 | |||
|
|
f5e16c44b3 | ||
| c5ca511ea7 | |||
|
|
42057ddb1c | ||
| 1a37afd16f | |||
|
|
f7b611bbbe | ||
| 55fc23ec64 | |||
|
|
dffbb48d99 | ||
| 0b7ad23252 | |||
|
|
19e9e59125 | ||
| bfbbaeae59 | |||
|
|
0da7454033 | ||
| 7b0267f9ac | |||
|
|
a581ffaaff | ||
| 429a2924d7 | |||
|
|
afb0f7ef31 | ||
| 92c2360feb | |||
|
|
4ea8faf16f | ||
| 74f059593e |
2
backend/migrations/003_cover_image_url.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE races
|
||||||
|
ADD COLUMN IF NOT EXISTS cover_image_url TEXT;
|
||||||
4
backend/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "calendar-run-backend",
|
"name": "calendar-run-backend",
|
||||||
"version": "1.2.2",
|
"version": "1.3.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "calendar-run-backend",
|
"name": "calendar-run-backend",
|
||||||
"version": "1.2.2",
|
"version": "1.3.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"csv-parse": "^5.6.0",
|
"csv-parse": "^5.6.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "calendar-run-backend",
|
"name": "calendar-run-backend",
|
||||||
"version": "1.2.2",
|
"version": "1.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ function mockRowFromInsert(sql: string, params: unknown[]): RaceRow {
|
|||||||
distance_km: "0",
|
distance_km: "0",
|
||||||
status: null,
|
status: null,
|
||||||
official_url: null,
|
official_url: null,
|
||||||
|
cover_image_url: null,
|
||||||
start_time: null,
|
start_time: null,
|
||||||
cluster_schedule: null,
|
cluster_schedule: null,
|
||||||
bib_pickup: null,
|
bib_pickup: null,
|
||||||
@@ -47,6 +48,7 @@ function mockRowFromInsert(sql: string, params: unknown[]): RaceRow {
|
|||||||
distance_km: String(row.distance_km ?? "0"),
|
distance_km: String(row.distance_km ?? "0"),
|
||||||
status: row.status != null ? String(row.status) : null,
|
status: row.status != null ? String(row.status) : null,
|
||||||
official_url: row.official_url != null ? String(row.official_url) : null,
|
official_url: row.official_url != null ? String(row.official_url) : null,
|
||||||
|
cover_image_url: row.cover_image_url != null ? String(row.cover_image_url) : null,
|
||||||
start_time: row.start_time != null ? String(row.start_time) : null,
|
start_time: row.start_time != null ? String(row.start_time) : null,
|
||||||
cluster_schedule: row.cluster_schedule != null ? String(row.cluster_schedule) : null,
|
cluster_schedule: row.cluster_schedule != null ? String(row.cluster_schedule) : null,
|
||||||
bib_pickup: row.bib_pickup != null ? String(row.bib_pickup) : null,
|
bib_pickup: row.bib_pickup != null ? String(row.bib_pickup) : null,
|
||||||
@@ -108,7 +110,19 @@ function createMockPool(): Pool {
|
|||||||
if (!existing) {
|
if (!existing) {
|
||||||
return emptyResult();
|
return emptyResult();
|
||||||
}
|
}
|
||||||
|
const setMatch = sql.match(/UPDATE races SET (.+) WHERE id =/);
|
||||||
const updated = { ...existing, updated_at: new Date() };
|
const updated = { ...existing, updated_at: new Date() };
|
||||||
|
const setColumns =
|
||||||
|
setMatch?.[1]
|
||||||
|
.split(",")
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter((part) => !part.startsWith("updated_at"))
|
||||||
|
.map((part) => part.split("=")[0]?.trim())
|
||||||
|
.filter((col): col is string => Boolean(col)) ?? [];
|
||||||
|
|
||||||
|
setColumns.forEach((col, index) => {
|
||||||
|
(updated as unknown as Record<string, unknown>)[col] = p[index] ?? null;
|
||||||
|
});
|
||||||
store.set(id, updated);
|
store.set(id, updated);
|
||||||
return {
|
return {
|
||||||
rows: [updated as unknown as T],
|
rows: [updated as unknown as T],
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export interface RaceRow {
|
|||||||
distance_km: string;
|
distance_km: string;
|
||||||
status: string | null;
|
status: string | null;
|
||||||
official_url: string | null;
|
official_url: string | null;
|
||||||
|
cover_image_url: string | null;
|
||||||
start_time: string | null;
|
start_time: string | null;
|
||||||
cluster_schedule: string | null;
|
cluster_schedule: string | null;
|
||||||
bib_pickup: string | null;
|
bib_pickup: string | null;
|
||||||
@@ -28,6 +29,7 @@ export interface RaceDto {
|
|||||||
distanceKm: number;
|
distanceKm: number;
|
||||||
status: string | null;
|
status: string | null;
|
||||||
officialUrl: string | null;
|
officialUrl: string | null;
|
||||||
|
coverImageUrl: string | null;
|
||||||
startTime: string | null;
|
startTime: string | null;
|
||||||
clusterSchedule: string | null;
|
clusterSchedule: string | null;
|
||||||
bibPickup: string | null;
|
bibPickup: string | null;
|
||||||
@@ -64,6 +66,7 @@ export function rowToDto(row: RaceRow): RaceDto {
|
|||||||
distanceKm: parseFloat(row.distance_km),
|
distanceKm: parseFloat(row.distance_km),
|
||||||
status: row.status,
|
status: row.status,
|
||||||
officialUrl: row.official_url,
|
officialUrl: row.official_url,
|
||||||
|
coverImageUrl: row.cover_image_url,
|
||||||
startTime: row.start_time,
|
startTime: row.start_time,
|
||||||
clusterSchedule: row.cluster_schedule,
|
clusterSchedule: row.cluster_schedule,
|
||||||
bibPickup: row.bib_pickup,
|
bibPickup: row.bib_pickup,
|
||||||
@@ -83,6 +86,7 @@ const FIELD_MAP: Record<string, string> = {
|
|||||||
distanceKm: "distance_km",
|
distanceKm: "distance_km",
|
||||||
status: "status",
|
status: "status",
|
||||||
officialUrl: "official_url",
|
officialUrl: "official_url",
|
||||||
|
coverImageUrl: "cover_image_url",
|
||||||
startTime: "start_time",
|
startTime: "start_time",
|
||||||
clusterSchedule: "cluster_schedule",
|
clusterSchedule: "cluster_schedule",
|
||||||
bibPickup: "bib_pickup",
|
bibPickup: "bib_pickup",
|
||||||
|
|||||||
103
backend/src/raceCoverImage.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
const IMAGE_META_KEYS = new Set([
|
||||||
|
"og:image",
|
||||||
|
"og:image:url",
|
||||||
|
"twitter:image",
|
||||||
|
"twitter:image:src",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const FETCH_TIMEOUT_MS = 5_000;
|
||||||
|
|
||||||
|
function getAttribute(tag: string, name: string): string | null {
|
||||||
|
const pattern = new RegExp(`${name}\\s*=\\s*["']([^"']+)["']`, "i");
|
||||||
|
return tag.match(pattern)?.[1] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHttpUrl(value: string, baseUrl: string): string | null {
|
||||||
|
try {
|
||||||
|
const url = new URL(value, baseUrl);
|
||||||
|
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRuncRunUrl(value: string): boolean {
|
||||||
|
try {
|
||||||
|
const hostname = new URL(value).hostname.toLowerCase();
|
||||||
|
return hostname === "runc.run" || hostname.endsWith(".runc.run");
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRuncIntroImage(html: string, baseUrl: string): string | null {
|
||||||
|
const introMatch = html.match(/<div\b[^>]*class=["'][^"']*\brun-intro__image\b[^"']*["'][^>]*>[\s\S]*?<img\b[^>]*>/i);
|
||||||
|
if (!introMatch) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const src = getAttribute(introMatch[0], "src");
|
||||||
|
return src ? toHttpUrl(src, baseUrl) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMetaImage(html: string, baseUrl: string): string | null {
|
||||||
|
const tags = html.match(/<meta\b[^>]*>/gi) ?? [];
|
||||||
|
|
||||||
|
for (const tag of tags) {
|
||||||
|
const key = (getAttribute(tag, "property") || getAttribute(tag, "name") || "").toLowerCase();
|
||||||
|
if (!IMAGE_META_KEYS.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = getAttribute(tag, "content");
|
||||||
|
if (!content) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageUrl = toHttpUrl(content, baseUrl);
|
||||||
|
if (imageUrl) {
|
||||||
|
return imageUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractRaceCoverImageFromHtml(html: string, pageUrl: string): string | null {
|
||||||
|
if (isRuncRunUrl(pageUrl)) {
|
||||||
|
const runcImage = findRuncIntroImage(html, pageUrl);
|
||||||
|
if (runcImage) {
|
||||||
|
return runcImage;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return findMetaImage(html, pageUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function extractRaceCoverImage(officialUrl: string): Promise<string | null> {
|
||||||
|
const normalizedUrl = toHttpUrl(officialUrl, officialUrl);
|
||||||
|
if (!normalizedUrl) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(normalizedUrl, {
|
||||||
|
redirect: "follow",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const html = await response.text();
|
||||||
|
return extractRaceCoverImageFromHtml(html, response.url || normalizedUrl);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Router, Request, Response } from "express";
|
import { Router, Request, Response } from "express";
|
||||||
import { pool } from "../db";
|
import { pool } from "../db";
|
||||||
import { rowToDto, bodyToColumns, RaceRow } from "../mappers/race";
|
import { rowToDto, bodyToColumns, RaceRow } from "../mappers/race";
|
||||||
|
import { extractRaceCoverImage } from "../raceCoverImage";
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
@@ -117,7 +118,15 @@ router.post("/races", async (req: Request, res: Response) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { columns, values } = bodyToColumns(body);
|
const payload = { ...body };
|
||||||
|
const hasManualCover = typeof payload.coverImageUrl === "string" && payload.coverImageUrl.trim() !== "";
|
||||||
|
const hasOfficialUrl = typeof payload.officialUrl === "string" && payload.officialUrl.trim() !== "";
|
||||||
|
|
||||||
|
if (!hasManualCover && hasOfficialUrl) {
|
||||||
|
payload.coverImageUrl = await extractRaceCoverImage(payload.officialUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { columns, values } = bodyToColumns(payload);
|
||||||
columns.unshift("id");
|
columns.unshift("id");
|
||||||
values.unshift(body.id);
|
values.unshift(body.id);
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
|||||||
import { test } from "node:test";
|
import { test } from "node:test";
|
||||||
import request from "supertest";
|
import request from "supertest";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
|
import { extractRaceCoverImageFromHtml } from "../src/raceCoverImage";
|
||||||
|
|
||||||
const app = createApp();
|
const app = createApp();
|
||||||
|
|
||||||
@@ -45,3 +46,124 @@ test("GET /api/races/:id returns not_found", async () => {
|
|||||||
assert.equal(res.body.error, "not_found");
|
assert.equal(res.body.error, "not_found");
|
||||||
assert.ok(Array.isArray(res.body.details));
|
assert.ok(Array.isArray(res.body.details));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("extractRaceCoverImageFromHtml prefers runc.run intro image", () => {
|
||||||
|
const html = `
|
||||||
|
<meta property="og:image" content="https://example.com/og.jpg">
|
||||||
|
<div class="run-intro__image">
|
||||||
|
<div class="run-intro__image-left-shadow"></div>
|
||||||
|
<img src="/uploads/race_landing_header_backgrounds/header.jpg" alt="">
|
||||||
|
<div class="run-intro__image-right-shadow"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
extractRaceCoverImageFromHtml(html, "https://aprilrun5km.runc.run/"),
|
||||||
|
"https://aprilrun5km.runc.run/uploads/race_landing_header_backgrounds/header.jpg",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("extractRaceCoverImageFromHtml reads Open Graph and Twitter images", () => {
|
||||||
|
assert.equal(
|
||||||
|
extractRaceCoverImageFromHtml(
|
||||||
|
'<meta property="og:image" content="/cover.png">',
|
||||||
|
"https://example.com/race",
|
||||||
|
),
|
||||||
|
"https://example.com/cover.png",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
extractRaceCoverImageFromHtml(
|
||||||
|
'<meta name="twitter:image" content="https://cdn.example.com/twitter.jpg">',
|
||||||
|
"https://example.com/race",
|
||||||
|
),
|
||||||
|
"https://cdn.example.com/twitter.jpg",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("POST /api/races stores manual coverImageUrl", async () => {
|
||||||
|
const coverImageUrl = "https://example.com/manual.jpg";
|
||||||
|
const res = await request(app)
|
||||||
|
.post("/api/races")
|
||||||
|
.send({
|
||||||
|
id: "2026-06-01-manual-cover",
|
||||||
|
date: "2026-06-01",
|
||||||
|
title: "Manual Cover",
|
||||||
|
distanceKm: 10,
|
||||||
|
officialUrl: "https://example.com/race",
|
||||||
|
coverImageUrl,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
assert.equal(res.body.coverImageUrl, coverImageUrl);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("POST /api/races auto extracts coverImageUrl from officialUrl", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
globalThis.fetch = async () =>
|
||||||
|
new Response('<meta property="og:image" content="/auto.jpg">', {
|
||||||
|
status: 200,
|
||||||
|
headers: { "content-type": "text/html" },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await request(app)
|
||||||
|
.post("/api/races")
|
||||||
|
.send({
|
||||||
|
id: "2026-06-02-auto-cover",
|
||||||
|
date: "2026-06-02",
|
||||||
|
title: "Auto Cover",
|
||||||
|
distanceKm: 21.1,
|
||||||
|
officialUrl: "https://example.com/race",
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
assert.equal(res.body.coverImageUrl, "https://example.com/auto.jpg");
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("POST /api/races succeeds when cover extraction fails", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
globalThis.fetch = async () => {
|
||||||
|
throw new Error("network down");
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await request(app)
|
||||||
|
.post("/api/races")
|
||||||
|
.send({
|
||||||
|
id: "2026-06-03-cover-fail",
|
||||||
|
date: "2026-06-03",
|
||||||
|
title: "Cover Fail",
|
||||||
|
distanceKm: 5,
|
||||||
|
officialUrl: "https://example.com/race",
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
assert.equal(res.body.coverImageUrl, null);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("PATCH /api/races/:id updates coverImageUrl explicitly", async () => {
|
||||||
|
const id = "2026-06-04-patch-cover";
|
||||||
|
await request(app)
|
||||||
|
.post("/api/races")
|
||||||
|
.send({
|
||||||
|
id,
|
||||||
|
date: "2026-06-04",
|
||||||
|
title: "Patch Cover",
|
||||||
|
distanceKm: 10,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const coverImageUrl = "https://example.com/patched.jpg";
|
||||||
|
const res = await request(app)
|
||||||
|
.patch(`/api/races/${id}`)
|
||||||
|
.send({ coverImageUrl })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert.equal(res.body.coverImageUrl, coverImageUrl);
|
||||||
|
});
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ GET /api/races?year=2026&month=5
|
|||||||
"distanceKm": 42.195,
|
"distanceKm": 42.195,
|
||||||
"status": "planned",
|
"status": "planned",
|
||||||
"officialUrl": null,
|
"officialUrl": null,
|
||||||
|
"coverImageUrl": null,
|
||||||
"startTime": null,
|
"startTime": null,
|
||||||
"clusterSchedule": null,
|
"clusterSchedule": null,
|
||||||
"bibPickup": null,
|
"bibPickup": null,
|
||||||
@@ -124,6 +125,7 @@ GET /api/races?year=2026&month=5
|
|||||||
"distanceKm": 10,
|
"distanceKm": 10,
|
||||||
"status": "planned",
|
"status": "planned",
|
||||||
"officialUrl": "https://example.com",
|
"officialUrl": "https://example.com",
|
||||||
|
"coverImageUrl": "https://example.com/cover.jpg",
|
||||||
"startTime": "09:30",
|
"startTime": "09:30",
|
||||||
"clusterSchedule": null,
|
"clusterSchedule": null,
|
||||||
"bibPickup": null,
|
"bibPickup": null,
|
||||||
@@ -167,7 +169,7 @@ GET /api/races?year=2026&month=5
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Допустимые поля:** `date`, `title`, `distanceKm`, `status`, `officialUrl`, `startTime`, `clusterSchedule`, `bibPickup`, `bibNumber`, `finishTime`, `finishPlace`, `notes`.
|
**Допустимые поля:** `date`, `title`, `distanceKm`, `status`, `officialUrl`, `coverImageUrl`, `startTime`, `clusterSchedule`, `bibPickup`, `bibNumber`, `finishTime`, `finishPlace`, `notes`.
|
||||||
|
|
||||||
**Ответ 200:** обновлённый объект `Race`.
|
**Ответ 200:** обновлённый объект `Race`.
|
||||||
|
|
||||||
@@ -207,6 +209,7 @@ GET /api/races?year=2026&month=5
|
|||||||
| `distanceKm` | number | да | да | Дистанция в км |
|
| `distanceKm` | number | да | да | Дистанция в км |
|
||||||
| `status` | string \| null | нет | да | `"planned"` / `"registered"` / `"completed"` |
|
| `status` | string \| null | нет | да | `"planned"` / `"registered"` / `"completed"` |
|
||||||
| `officialUrl` | string \| null | нет | да | URL организатора |
|
| `officialUrl` | string \| null | нет | да | URL организатора |
|
||||||
|
| `coverImageUrl` | string \| null | нет | да | URL обложки забега. При `POST` может быть найден автоматически по `officialUrl`, если не передан вручную |
|
||||||
| `startTime` | string \| null | нет | да | Время старта, напр. `"09:30"` или `"09:30:00"` (часы:минуты:секунды) |
|
| `startTime` | string \| null | нет | да | Время старта, напр. `"09:30"` или `"09:30:00"` (часы:минуты:секунды) |
|
||||||
| `clusterSchedule` | string \| null | нет | да | Расписание кластеров |
|
| `clusterSchedule` | string \| null | нет | да | Расписание кластеров |
|
||||||
| `bibPickup` | string \| null | нет | да | Выдача номеров |
|
| `bibPickup` | string \| null | нет | да | Выдача номеров |
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
<html lang="ru">
|
<html lang="ru">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Календарь стартов</title>
|
<title>Календарь стартов</title>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
4
frontend/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "calendar-run-frontend",
|
"name": "calendar-run-frontend",
|
||||||
"version": "0.4.0",
|
"version": "0.6.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "calendar-run-frontend",
|
"name": "calendar-run-frontend",
|
||||||
"version": "0.4.0",
|
"version": "0.6.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "calendar-run-frontend",
|
"name": "calendar-run-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.4.0",
|
"version": "0.6.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
24
frontend/public/favicon.svg
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Календарь стартов">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="bg" x1="12" y1="4" x2="52" y2="60" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop offset="0" stop-color="#1168d8" />
|
||||||
|
<stop offset="1" stop-color="#071927" />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width="64" height="64" rx="16" fill="url(#bg)" />
|
||||||
|
<path
|
||||||
|
d="M18 20h28a5 5 0 0 1 5 5v21a5 5 0 0 1-5 5H18a5 5 0 0 1-5-5V25a5 5 0 0 1 5-5Z"
|
||||||
|
fill="#ffffff"
|
||||||
|
/>
|
||||||
|
<path d="M13 29h38" stroke="#d6e1ea" stroke-width="4" />
|
||||||
|
<path d="M23 14v11M41 14v11" stroke="#b9f24a" stroke-width="5" stroke-linecap="round" />
|
||||||
|
<path
|
||||||
|
d="M22 41c5-8 13-8 18 0M22 41h18"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1168d8"
|
||||||
|
stroke-width="5"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
<circle cx="44" cy="44" r="5" fill="#ff6f5e" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 890 B |
BIN
frontend/public/images/race-half.jpg
Normal file
|
After Width: | Height: | Size: 87 KiB |
BIN
frontend/public/images/race-marathon.jpg
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
frontend/public/images/race-night.jpg
Normal file
|
After Width: | Height: | Size: 78 KiB |
BIN
frontend/public/images/race-short.jpg
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
frontend/public/images/race-trail.jpg
Normal file
|
After Width: | Height: | Size: 176 KiB |
BIN
frontend/public/images/runner-hero.jpg
Normal file
|
After Width: | Height: | Size: 135 KiB |
@@ -23,6 +23,7 @@ function normalizeRace(input: unknown): Race {
|
|||||||
race?.status === "registered" ||
|
race?.status === "registered" ||
|
||||||
race?.status === "completed") &&
|
race?.status === "completed") &&
|
||||||
isNullableString(race?.officialUrl) &&
|
isNullableString(race?.officialUrl) &&
|
||||||
|
isNullableString(race?.coverImageUrl) &&
|
||||||
isNullableString(race?.startTime) &&
|
isNullableString(race?.startTime) &&
|
||||||
isNullableString(race?.clusterSchedule) &&
|
isNullableString(race?.clusterSchedule) &&
|
||||||
isNullableString(race?.bibPickup) &&
|
isNullableString(race?.bibPickup) &&
|
||||||
@@ -48,6 +49,7 @@ function normalizeRace(input: unknown): Race {
|
|||||||
distanceKm: race.distanceKm,
|
distanceKm: race.distanceKm,
|
||||||
status: race.status,
|
status: race.status,
|
||||||
officialUrl: race.officialUrl,
|
officialUrl: race.officialUrl,
|
||||||
|
coverImageUrl: race.coverImageUrl,
|
||||||
startTime: race.startTime,
|
startTime: race.startTime,
|
||||||
clusterSchedule: race.clusterSchedule,
|
clusterSchedule: race.clusterSchedule,
|
||||||
bibPickup: race.bibPickup,
|
bibPickup: race.bibPickup,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export interface Race {
|
|||||||
distanceKm: number;
|
distanceKm: number;
|
||||||
status: RaceStatus | null;
|
status: RaceStatus | null;
|
||||||
officialUrl: string | null;
|
officialUrl: string | null;
|
||||||
|
coverImageUrl: string | null;
|
||||||
startTime: string | null;
|
startTime: string | null;
|
||||||
clusterSchedule: string | null;
|
clusterSchedule: string | null;
|
||||||
bibPickup: string | null;
|
bibPickup: string | null;
|
||||||
@@ -30,6 +31,7 @@ export interface CreateRacePayload {
|
|||||||
distanceKm: number;
|
distanceKm: number;
|
||||||
status?: RaceStatus | null;
|
status?: RaceStatus | null;
|
||||||
officialUrl?: string | null;
|
officialUrl?: string | null;
|
||||||
|
coverImageUrl?: string | null;
|
||||||
startTime?: string | null;
|
startTime?: string | null;
|
||||||
clusterSchedule?: string | null;
|
clusterSchedule?: string | null;
|
||||||
bibPickup?: string | null;
|
bibPickup?: string | null;
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
import { NavLink, Outlet } from "react-router-dom";
|
import { Link, NavLink, Outlet } from "react-router-dom";
|
||||||
import { AppShellFooter } from "./AppShellFooter";
|
import { AppShellFooter } from "./AppShellFooter";
|
||||||
|
|
||||||
export function AppLayout(): JSX.Element {
|
export function AppLayout(): JSX.Element {
|
||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<header className="app-shell__header">
|
<header className="app-shell__header">
|
||||||
<div className="app-shell__brand">Календарь стартов</div>
|
<Link className="app-shell__brand" to="/">
|
||||||
|
Календарь стартов
|
||||||
|
</Link>
|
||||||
<nav className="app-shell__nav" aria-label="Основная навигация">
|
<nav className="app-shell__nav" aria-label="Основная навигация">
|
||||||
<NavLink
|
<NavLink
|
||||||
to="/"
|
to="/"
|
||||||
|
|||||||
197
frontend/src/components/DatePickerField.tsx
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { buildMonthCells, toYmd, WEEKDAY_LABELS_SHORT_RU } from "../lib";
|
||||||
|
|
||||||
|
const MONTH_NAMES_RU = [
|
||||||
|
"Январь",
|
||||||
|
"Февраль",
|
||||||
|
"Март",
|
||||||
|
"Апрель",
|
||||||
|
"Май",
|
||||||
|
"Июнь",
|
||||||
|
"Июль",
|
||||||
|
"Август",
|
||||||
|
"Сентябрь",
|
||||||
|
"Октябрь",
|
||||||
|
"Ноябрь",
|
||||||
|
"Декабрь",
|
||||||
|
];
|
||||||
|
|
||||||
|
interface DatePickerFieldProps {
|
||||||
|
value: string;
|
||||||
|
name: string;
|
||||||
|
required?: boolean;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseYmd(value: string): { year: number; monthIndex: number; day: number } | null {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const year = Number(value.slice(0, 4));
|
||||||
|
const monthIndex = Number(value.slice(5, 7)) - 1;
|
||||||
|
const day = Number(value.slice(8, 10));
|
||||||
|
|
||||||
|
if (!Number.isInteger(year) || !Number.isInteger(monthIndex) || !Number.isInteger(day)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (monthIndex < 0 || monthIndex > 11) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { year, monthIndex, day };
|
||||||
|
}
|
||||||
|
|
||||||
|
function getInitialVisibleMonth(value: string): { year: number; monthIndex: number } {
|
||||||
|
const parsed = parseYmd(value);
|
||||||
|
if (parsed) {
|
||||||
|
return { year: parsed.year, monthIndex: parsed.monthIndex };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
return { year: now.getFullYear(), monthIndex: now.getMonth() };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DatePickerField(props: DatePickerFieldProps): JSX.Element {
|
||||||
|
const { value, name, required, onChange } = props;
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const [visibleMonth, setVisibleMonth] = useState(() => getInitialVisibleMonth(value));
|
||||||
|
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const parsed = parseYmd(value);
|
||||||
|
if (!parsed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setVisibleMonth({ year: parsed.year, monthIndex: parsed.monthIndex });
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePointerDown(event: MouseEvent): void {
|
||||||
|
if (rootRef.current?.contains(event.target as Node)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeyDown(event: KeyboardEvent): void {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("mousedown", handlePointerDown);
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", handlePointerDown);
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
};
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
|
const selected = parseYmd(value);
|
||||||
|
const todayYmd = toYmd(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
|
||||||
|
const cells = useMemo(
|
||||||
|
() => buildMonthCells(visibleMonth.year, visibleMonth.monthIndex),
|
||||||
|
[visibleMonth],
|
||||||
|
);
|
||||||
|
const monthTitle = `${MONTH_NAMES_RU[visibleMonth.monthIndex]} ${visibleMonth.year}`;
|
||||||
|
|
||||||
|
function shiftMonth(delta: number): void {
|
||||||
|
setVisibleMonth((prev) => {
|
||||||
|
const next = new Date(Date.UTC(prev.year, prev.monthIndex + delta, 1));
|
||||||
|
return { year: next.getUTCFullYear(), monthIndex: next.getUTCMonth() };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="date-picker" ref={rootRef}>
|
||||||
|
<div className="date-picker__control">
|
||||||
|
<input
|
||||||
|
className="race-form__input date-picker__input"
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
name={name}
|
||||||
|
value={value}
|
||||||
|
onChange={(event) => {
|
||||||
|
onChange(event.target.value);
|
||||||
|
}}
|
||||||
|
onFocus={() => setIsOpen(true)}
|
||||||
|
placeholder="2026-05-03"
|
||||||
|
autoComplete="off"
|
||||||
|
required={required}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="date-picker__toggle"
|
||||||
|
type="button"
|
||||||
|
aria-label="Открыть календарь"
|
||||||
|
aria-expanded={isOpen}
|
||||||
|
onClick={() => setIsOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
▾
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isOpen ? (
|
||||||
|
<div className="date-picker__popover" role="dialog" aria-label="Выбор даты">
|
||||||
|
<div className="date-picker__header">
|
||||||
|
<button
|
||||||
|
className="date-picker__nav"
|
||||||
|
type="button"
|
||||||
|
aria-label="Предыдущий месяц"
|
||||||
|
onClick={() => shiftMonth(-1)}
|
||||||
|
>
|
||||||
|
‹
|
||||||
|
</button>
|
||||||
|
<p className="date-picker__title">{monthTitle}</p>
|
||||||
|
<button
|
||||||
|
className="date-picker__nav"
|
||||||
|
type="button"
|
||||||
|
aria-label="Следующий месяц"
|
||||||
|
onClick={() => shiftMonth(1)}
|
||||||
|
>
|
||||||
|
›
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="date-picker__weekdays" aria-hidden>
|
||||||
|
{WEEKDAY_LABELS_SHORT_RU.map((weekday) => (
|
||||||
|
<span key={weekday} className="date-picker__weekday">
|
||||||
|
{weekday}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="date-picker__cells">
|
||||||
|
{cells.map((day, idx) => {
|
||||||
|
if (day === null) {
|
||||||
|
return <span key={`empty-${idx}`} className="date-picker__cell date-picker__cell--empty" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ymd = toYmd(visibleMonth.year, visibleMonth.monthIndex, day);
|
||||||
|
const isSelected =
|
||||||
|
selected?.year === visibleMonth.year &&
|
||||||
|
selected.monthIndex === visibleMonth.monthIndex &&
|
||||||
|
selected.day === day;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={ymd}
|
||||||
|
className={`date-picker__day${isSelected ? " date-picker__day--selected" : ""}${ymd === todayYmd ? " date-picker__day--today" : ""}`}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
onChange(ymd);
|
||||||
|
setIsOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{day}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -55,16 +55,38 @@ export function PaceTrendChart(props: PaceTrendChartProps): JSX.Element {
|
|||||||
.join(" ");
|
.join(" ");
|
||||||
|
|
||||||
const last = series[series.length - 1]!;
|
const last = series[series.length - 1]!;
|
||||||
|
const best = series.reduce((currentBest, item) => (item.minutes < currentBest.minutes ? item : currentBest), series[0]!);
|
||||||
|
const dotPoints = series.map((s, i) => {
|
||||||
|
const x = pad + (n === 1 ? innerW / 2 : (i / (n - 1)) * innerW);
|
||||||
|
const norm = (maxM - s.minutes) / range;
|
||||||
|
const y = pad + (1 - norm) * innerH;
|
||||||
|
return { x, y, id: s.race.id };
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="pace-chart">
|
<div className="pace-chart">
|
||||||
<svg className="pace-chart__svg" viewBox={`0 0 ${w} ${h}`} role="img" aria-label="Динамика времени на дистанции">
|
<svg className="pace-chart__svg" viewBox={`0 0 ${w} ${h}`} role="img" aria-label="Динамика времени на дистанции">
|
||||||
|
<line className="pace-chart__grid-line" x1={pad} y1={pad} x2={w - pad} y2={pad} />
|
||||||
|
<line className="pace-chart__grid-line" x1={pad} y1={h - pad} x2={w - pad} y2={h - pad} />
|
||||||
<polyline className="pace-chart__line" fill="none" points={points} />
|
<polyline className="pace-chart__line" fill="none" points={points} />
|
||||||
|
{dotPoints.map((point, index) => (
|
||||||
|
<circle
|
||||||
|
key={point.id}
|
||||||
|
className={index === dotPoints.length - 1 ? "pace-chart__dot pace-chart__dot--last" : "pace-chart__dot"}
|
||||||
|
cx={point.x}
|
||||||
|
cy={point.y}
|
||||||
|
r="1.6"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</svg>
|
</svg>
|
||||||
<p className="pace-chart__caption">
|
<div className="pace-chart__stats">
|
||||||
Последний пункт: {formatRaceDate(last.race.date)} — {last.race.finishTime} (
|
<p className="pace-chart__caption">
|
||||||
{last.minutes.toFixed(1)} мин)
|
Последний: {formatRaceDate(last.race.date)} · {last.race.finishTime} · {last.minutes.toFixed(1)} мин
|
||||||
</p>
|
</p>
|
||||||
|
<p className="pace-chart__caption pace-chart__caption--best">
|
||||||
|
Лучший: {formatRaceDate(best.race.date)} · {best.race.finishTime} · {best.minutes.toFixed(1)} мин
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { useCallback, useMemo, useRef, useState } from "react";
|
import { useCallback, useMemo, useRef, useState } from "react";
|
||||||
import { Link, useNavigate } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import type { Race } from "../api";
|
import type { Race } from "../api";
|
||||||
import { buildMonthCells, groupRacesByYmd, toYmd, WEEKDAY_LABELS_SHORT_RU } from "../lib";
|
import { buildMonthCells, groupRacesByYmd, isRaceDateInPast, toYmd, WEEKDAY_LABELS_SHORT_RU } from "../lib";
|
||||||
|
|
||||||
const MONTH_NAMES_RU_SHORT = [
|
const MONTH_NAMES_RU_SHORT = [
|
||||||
"янв.",
|
"янв.",
|
||||||
"февр.",
|
"февр.",
|
||||||
"мар.",
|
"мар.",
|
||||||
"апр.",
|
"апр.",
|
||||||
"мая",
|
"май",
|
||||||
"июн.",
|
"июн.",
|
||||||
"июл.",
|
"июл.",
|
||||||
"авг.",
|
"авг.",
|
||||||
@@ -20,6 +20,13 @@ const MONTH_NAMES_RU_SHORT = [
|
|||||||
|
|
||||||
const POPOVER_LEAVE_MS = 140;
|
const POPOVER_LEAVE_MS = 140;
|
||||||
|
|
||||||
|
function toLocalYmd(date: Date): string {
|
||||||
|
const y = date.getFullYear();
|
||||||
|
const m = String(date.getMonth() + 1).padStart(2, "0");
|
||||||
|
const d = String(date.getDate()).padStart(2, "0");
|
||||||
|
return `${y}-${m}-${d}`;
|
||||||
|
}
|
||||||
|
|
||||||
interface RacesCalendarProps {
|
interface RacesCalendarProps {
|
||||||
displayYear: number;
|
displayYear: number;
|
||||||
monthFilter: string;
|
monthFilter: string;
|
||||||
@@ -77,6 +84,8 @@ function CalendarMonthBlock(props: {
|
|||||||
setOpenYmd: (v: string | null) => void;
|
setOpenYmd: (v: string | null) => void;
|
||||||
scheduleClose: () => void;
|
scheduleClose: () => void;
|
||||||
cancelClose: () => void;
|
cancelClose: () => void;
|
||||||
|
onMonthSelect?: (monthIndex: number) => void;
|
||||||
|
todayYmd: string;
|
||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const {
|
const {
|
||||||
year,
|
year,
|
||||||
@@ -88,6 +97,8 @@ function CalendarMonthBlock(props: {
|
|||||||
setOpenYmd,
|
setOpenYmd,
|
||||||
scheduleClose,
|
scheduleClose,
|
||||||
cancelClose,
|
cancelClose,
|
||||||
|
onMonthSelect,
|
||||||
|
todayYmd,
|
||||||
} = props;
|
} = props;
|
||||||
const cells = useMemo(() => buildMonthCells(year, monthIndex), [year, monthIndex]);
|
const cells = useMemo(() => buildMonthCells(year, monthIndex), [year, monthIndex]);
|
||||||
const title = `${MONTH_NAMES_RU_SHORT[monthIndex]} ${year}`;
|
const title = `${MONTH_NAMES_RU_SHORT[monthIndex]} ${year}`;
|
||||||
@@ -96,7 +107,21 @@ function CalendarMonthBlock(props: {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={blockClass}>
|
<div className={blockClass}>
|
||||||
<h3 className="races-cal__month-title">{title}</h3>
|
<h3 className="races-cal__month-title">
|
||||||
|
{onMonthSelect ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="races-cal__month-title-button"
|
||||||
|
onClick={() => {
|
||||||
|
onMonthSelect(monthIndex);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
title
|
||||||
|
)}
|
||||||
|
</h3>
|
||||||
<div className="races-cal__weekdays" aria-hidden>
|
<div className="races-cal__weekdays" aria-hidden>
|
||||||
{WEEKDAY_LABELS_SHORT_RU.map((d) => (
|
{WEEKDAY_LABELS_SHORT_RU.map((d) => (
|
||||||
<span key={d} className="races-cal__weekday">
|
<span key={d} className="races-cal__weekday">
|
||||||
@@ -113,14 +138,25 @@ function CalendarMonthBlock(props: {
|
|||||||
const dayRaces = racesByYmd.get(ymd) ?? [];
|
const dayRaces = racesByYmd.get(ymd) ?? [];
|
||||||
const hasRaces = dayRaces.length > 0;
|
const hasRaces = dayRaces.length > 0;
|
||||||
const isOpen = openYmd === ymd;
|
const isOpen = openYmd === ymd;
|
||||||
|
const isPast = isRaceDateInPast(ymd);
|
||||||
|
const isToday = ymd === todayYmd;
|
||||||
|
const cellClassName = [
|
||||||
|
"races-cal__cell",
|
||||||
|
hasRaces ? "races-cal__cell--has-race" : "",
|
||||||
|
isOpen ? "races-cal__cell--open" : "",
|
||||||
|
isPast ? "races-cal__cell--past" : "",
|
||||||
|
isToday ? "races-cal__cell--today" : "",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={ymd}
|
key={ymd}
|
||||||
className={`races-cal__cell${hasRaces ? " races-cal__cell--has-race" : ""}${isOpen ? " races-cal__cell--open" : ""}`}
|
className={cellClassName}
|
||||||
onMouseEnter={() => {
|
onMouseEnter={() => {
|
||||||
cancelClose();
|
cancelClose();
|
||||||
setOpenYmd(ymd);
|
setOpenYmd(hasRaces ? ymd : null);
|
||||||
}}
|
}}
|
||||||
onMouseLeave={scheduleClose}
|
onMouseLeave={scheduleClose}
|
||||||
>
|
>
|
||||||
@@ -132,7 +168,7 @@ function CalendarMonthBlock(props: {
|
|||||||
}}
|
}}
|
||||||
onFocus={() => {
|
onFocus={() => {
|
||||||
cancelClose();
|
cancelClose();
|
||||||
setOpenYmd(ymd);
|
setOpenYmd(hasRaces ? ymd : null);
|
||||||
}}
|
}}
|
||||||
onBlur={(e) => {
|
onBlur={(e) => {
|
||||||
const next = e.relatedTarget as Node | null;
|
const next = e.relatedTarget as Node | null;
|
||||||
@@ -144,7 +180,7 @@ function CalendarMonthBlock(props: {
|
|||||||
>
|
>
|
||||||
{day}
|
{day}
|
||||||
</button>
|
</button>
|
||||||
{isOpen ? (
|
{isOpen && hasRaces ? (
|
||||||
<DayPopover
|
<DayPopover
|
||||||
ymd={ymd}
|
ymd={ymd}
|
||||||
races={dayRaces}
|
races={dayRaces}
|
||||||
@@ -182,12 +218,13 @@ export function RacesCalendar(props: RacesCalendarProps): JSX.Element {
|
|||||||
}, [cancelClose]);
|
}, [cancelClose]);
|
||||||
|
|
||||||
const racesByYmd = useMemo(() => groupRacesByYmd(races), [races]);
|
const racesByYmd = useMemo(() => groupRacesByYmd(races), [races]);
|
||||||
|
const todayYmd = useMemo(() => toLocalYmd(new Date()), []);
|
||||||
|
|
||||||
const focusedMonthIndex = monthFilter === "" ? null : parseInt(monthFilter, 10) - 1;
|
const focusedMonthIndex = monthFilter === "" ? null : parseInt(monthFilter, 10) - 1;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="races-cal">
|
<div className="races-cal">
|
||||||
<p className="races-cal__hint">Наведите на дату — краткая информация. Клик — страница дня.</p>
|
<p className="races-cal__hint">Наведите на дату с забегом — краткая информация. Клик — страница дня.</p>
|
||||||
{focusedMonthIndex === null || Number.isNaN(focusedMonthIndex) ? (
|
{focusedMonthIndex === null || Number.isNaN(focusedMonthIndex) ? (
|
||||||
<div className="races-cal__year">
|
<div className="races-cal__year">
|
||||||
{MONTH_NAMES_RU_SHORT.map((_, mi) => (
|
{MONTH_NAMES_RU_SHORT.map((_, mi) => (
|
||||||
@@ -202,6 +239,11 @@ export function RacesCalendar(props: RacesCalendarProps): JSX.Element {
|
|||||||
setOpenYmd={setOpenYmd}
|
setOpenYmd={setOpenYmd}
|
||||||
scheduleClose={scheduleClose}
|
scheduleClose={scheduleClose}
|
||||||
cancelClose={cancelClose}
|
cancelClose={cancelClose}
|
||||||
|
onMonthSelect={(mi) => {
|
||||||
|
onMonthFilterChange(String(mi + 1));
|
||||||
|
setOpenYmd(null);
|
||||||
|
}}
|
||||||
|
todayYmd={todayYmd}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -240,6 +282,7 @@ export function RacesCalendar(props: RacesCalendarProps): JSX.Element {
|
|||||||
setOpenYmd={setOpenYmd}
|
setOpenYmd={setOpenYmd}
|
||||||
scheduleClose={scheduleClose}
|
scheduleClose={scheduleClose}
|
||||||
cancelClose={cancelClose}
|
cancelClose={cancelClose}
|
||||||
|
todayYmd={todayYmd}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
export { DatePickerField } from "./DatePickerField";
|
||||||
export { PaceTrendChart } from "./PaceTrendChart";
|
export { PaceTrendChart } from "./PaceTrendChart";
|
||||||
export { RacesCalendar } from "./RacesCalendar";
|
export { RacesCalendar } from "./RacesCalendar";
|
||||||
export { StartTimeSelects } from "./StartTimeSelects";
|
export { StartTimeSelects } from "./StartTimeSelects";
|
||||||
|
|||||||
@@ -2,16 +2,20 @@ import type { Race } from "../api";
|
|||||||
|
|
||||||
export const WEEKDAY_LABELS_SHORT_RU: string[] = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"];
|
export const WEEKDAY_LABELS_SHORT_RU: string[] = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"];
|
||||||
|
|
||||||
/** Monday-based week: Mon=0 … Sun=6 */
|
/** Monday-based week: Mon=0 ... Sun=6 */
|
||||||
|
function mondayIndexFromJsDay(jsDay: number): number {
|
||||||
|
return (jsDay + 6) % 7;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Monday-based week: Mon=0 ... Sun=6 */
|
||||||
export function mondayIndexFromDate(d: Date): number {
|
export function mondayIndexFromDate(d: Date): number {
|
||||||
return (d.getDay() + 6) % 7;
|
return mondayIndexFromJsDay(d.getDay());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Grid cells for one month: `null` = empty, `1..31` = day of month. Padded to full weeks, at least 6 rows. */
|
/** Grid cells for one month: `null` = empty, `1..31` = day of month. Padded to full weeks, at least 6 rows. */
|
||||||
export function buildMonthCells(year: number, monthIndex: number): (number | null)[] {
|
export function buildMonthCells(year: number, monthIndex: number): (number | null)[] {
|
||||||
const first = new Date(year, monthIndex, 1);
|
const lead = mondayIndexFromJsDay(new Date(Date.UTC(year, monthIndex, 1)).getUTCDay());
|
||||||
const lead = mondayIndexFromDate(first);
|
const dim = new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
|
||||||
const dim = new Date(year, monthIndex + 1, 0).getDate();
|
|
||||||
const cells: (number | null)[] = [];
|
const cells: (number | null)[] = [];
|
||||||
for (let i = 0; i < lead; i += 1) {
|
for (let i = 0; i < lead; i += 1) {
|
||||||
cells.push(null);
|
cells.push(null);
|
||||||
|
|||||||
@@ -16,3 +16,5 @@ export {
|
|||||||
} from "./raceMetrics";
|
} from "./raceMetrics";
|
||||||
|
|
||||||
export { buildMonthCells, groupRacesByYmd, toYmd, WEEKDAY_LABELS_SHORT_RU } from "./calendarUtils";
|
export { buildMonthCells, groupRacesByYmd, toYmd, WEEKDAY_LABELS_SHORT_RU } from "./calendarUtils";
|
||||||
|
export { getRaceVisual } from "./raceVisuals";
|
||||||
|
export type { RaceVisualVariant } from "./raceVisuals";
|
||||||
|
|||||||
215
frontend/src/lib/raceVisuals.ts
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
import type { Race } from "../api";
|
||||||
|
|
||||||
|
export type RaceVisualVariant = "short" | "half" | "marathon" | "trail" | "night";
|
||||||
|
export type RaceVisualFit = "cover" | "contain";
|
||||||
|
|
||||||
|
interface RaceVisual {
|
||||||
|
variant: RaceVisualVariant;
|
||||||
|
imageSrc: string;
|
||||||
|
fallbackSrc: string;
|
||||||
|
imageFit: RaceVisualFit;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OfficialRaceVisual {
|
||||||
|
keywords: string[];
|
||||||
|
imageSrc: string;
|
||||||
|
imageFit?: RaceVisualFit;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FALLBACK_VISUALS: Record<RaceVisualVariant, RaceVisual> = {
|
||||||
|
short: {
|
||||||
|
variant: "short",
|
||||||
|
imageSrc: "/images/race-short.jpg",
|
||||||
|
fallbackSrc: "/images/race-short.jpg",
|
||||||
|
imageFit: "cover",
|
||||||
|
label: "Городской темп",
|
||||||
|
},
|
||||||
|
half: {
|
||||||
|
variant: "half",
|
||||||
|
imageSrc: "/images/race-half.jpg",
|
||||||
|
fallbackSrc: "/images/race-half.jpg",
|
||||||
|
imageFit: "cover",
|
||||||
|
label: "Полумарафон",
|
||||||
|
},
|
||||||
|
marathon: {
|
||||||
|
variant: "marathon",
|
||||||
|
imageSrc: "/images/race-marathon.jpg",
|
||||||
|
fallbackSrc: "/images/race-marathon.jpg",
|
||||||
|
imageFit: "cover",
|
||||||
|
label: "Марафон",
|
||||||
|
},
|
||||||
|
trail: {
|
||||||
|
variant: "trail",
|
||||||
|
imageSrc: "/images/race-trail.jpg",
|
||||||
|
fallbackSrc: "/images/race-trail.jpg",
|
||||||
|
imageFit: "cover",
|
||||||
|
label: "Трейл",
|
||||||
|
},
|
||||||
|
night: {
|
||||||
|
variant: "night",
|
||||||
|
imageSrc: "/images/race-night.jpg",
|
||||||
|
fallbackSrc: "/images/race-night.jpg",
|
||||||
|
imageFit: "cover",
|
||||||
|
label: "Ночной старт",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const OFFICIAL_VISUALS: OfficialRaceVisual[] = [
|
||||||
|
{
|
||||||
|
keywords: ["забег апрель"],
|
||||||
|
imageSrc: "https://aprilrun5km.runc.run/uploads/page_card_photos/AprilRun_photo_1.jpg",
|
||||||
|
label: "Забег Апрель",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["быстрый пес"],
|
||||||
|
imageSrc: "https://fastdogxc.runc.run/uploads/page_card_photos/Dog_spring_2026-5.jpg",
|
||||||
|
label: "Кросс",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["лисья гора"],
|
||||||
|
imageSrc: "https://foxhillxc.runc.run/uploads/page_card_photos/Fox_Spring_2026-0.jpg",
|
||||||
|
label: "Кросс",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["казанский марафон"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild3961-6436-4462-b738-356665613039/Frame_2131327895.png",
|
||||||
|
imageFit: "contain",
|
||||||
|
label: "Казанский марафон",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["мышкинский полумарафон", "по шести холмам"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6133-6137-4865-b166-623532313531/photo.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["забег.рф", "забег рф"],
|
||||||
|
imageSrc: "https://xn--80acghh.xn--p1ai/zabeg.jpg",
|
||||||
|
label: "ЗаБег.РФ",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["переславский марафон", "александровские версты"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6432-3338-4533-b262-633339353335/photo_1.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["красочный забег"],
|
||||||
|
imageSrc: "https://colorrun5km.runc.run/uploads/page_card_photos/ColorRun2026-1.jpg",
|
||||||
|
label: "Красочный забег",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["здорово кострома", "здорово, кострома"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6139-3539-4661-b232-386230336431/kostroma.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["ночной забег москва"],
|
||||||
|
imageSrc: "https://nightrun10km.runc.run/uploads/page_card_photos/NightRun_2026-9.jpg",
|
||||||
|
label: "Ночной забег",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["белые ночи"],
|
||||||
|
imageSrc: "https://wnmarathon.runc.run/uploads/page_card_photos/WN_photo_01.jpg",
|
||||||
|
label: "Белые ночи",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["сергиевым путем", "сергиевым путём"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6236-3466-4239-b666-393061326338/serg.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["ночной забег нижний новгород"],
|
||||||
|
imageSrc: "https://rrweb.russiarunning.com/-x740/generalimages/0531a1b8-3876-4620-8961-2fa374e474e5.png",
|
||||||
|
imageFit: "contain",
|
||||||
|
label: "Ночной забег",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["suvorov extreme"],
|
||||||
|
imageSrc: "https://goldenultra.ru/grut/files/photos/100.jpg",
|
||||||
|
label: "Трейл",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["рыбинский полумарафон", "великий хлебный путь"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6130-3230-4332-b932-366166366633/photo.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["ярославский полумарафон", "золотое кольцо"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild6331-6333-4635-b635-376262373361/photo.jpg",
|
||||||
|
label: "Золотое кольцо",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keywords: ["моя столица"],
|
||||||
|
imageSrc: "https://static.tildacdn.com/tild3263-3036-4639-b830-653365663832/-min.jpg",
|
||||||
|
imageFit: "contain",
|
||||||
|
label: "Моя столица",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function normalizeTitle(value: string): string {
|
||||||
|
return value
|
||||||
|
.toLowerCase()
|
||||||
|
.replaceAll("ё", "е")
|
||||||
|
.replace(/[«»|]/g, " ")
|
||||||
|
.replace(/[^\p{L}\p{N}.&]+/gu, " ")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFallbackRaceVisual(race: Race): RaceVisual {
|
||||||
|
const title = normalizeTitle(race.title);
|
||||||
|
|
||||||
|
if (title.includes("ночной")) {
|
||||||
|
return FALLBACK_VISUALS.night;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
title.includes("trail") ||
|
||||||
|
title.includes("extreme") ||
|
||||||
|
title.includes("suvorov") ||
|
||||||
|
title.includes("трейл") ||
|
||||||
|
title.includes("экстрим")
|
||||||
|
) {
|
||||||
|
return FALLBACK_VISUALS.trail;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Math.abs(race.distanceKm - 42.2) < 0.8) {
|
||||||
|
return FALLBACK_VISUALS.marathon;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Math.abs(race.distanceKm - 21.1) < 0.4) {
|
||||||
|
return FALLBACK_VISUALS.half;
|
||||||
|
}
|
||||||
|
|
||||||
|
return FALLBACK_VISUALS.short;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRaceVisual(race: Race): RaceVisual {
|
||||||
|
const fallback = getFallbackRaceVisual(race);
|
||||||
|
|
||||||
|
if (race.coverImageUrl) {
|
||||||
|
return {
|
||||||
|
...fallback,
|
||||||
|
imageSrc: race.coverImageUrl,
|
||||||
|
fallbackSrc: fallback.imageSrc,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = normalizeTitle(race.title);
|
||||||
|
const official = OFFICIAL_VISUALS.find((visual) =>
|
||||||
|
visual.keywords.some((keyword) => title.includes(normalizeTitle(keyword))),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!official) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...fallback,
|
||||||
|
imageSrc: official.imageSrc,
|
||||||
|
fallbackSrc: fallback.imageSrc,
|
||||||
|
imageFit: official.imageFit ?? fallback.imageFit,
|
||||||
|
label: official.label,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
import type { Race } from "../api";
|
import type { Race } from "../api";
|
||||||
import { ApiError, getRaces } from "../api";
|
import { ApiError, getRaces } from "../api";
|
||||||
import { PaceTrendChart } from "../components";
|
import { PaceTrendChart } from "../components";
|
||||||
@@ -61,26 +62,14 @@ export function DashboardPage(): JSX.Element {
|
|||||||
|
|
||||||
const dashboardMetrics = useMemo(() => {
|
const dashboardMetrics = useMemo(() => {
|
||||||
const { upcoming, past } = splitRacesByDate(races);
|
const { upcoming, past } = splitRacesByDate(races);
|
||||||
const completed = races.filter((race) => race.status === "completed");
|
|
||||||
|
|
||||||
const nextRace = upcoming[0] ?? null;
|
const nextRace = upcoming[0] ?? null;
|
||||||
const lastResult = past.find((race) => race.status === "completed") ?? null;
|
const lastResult = past.find((race) => race.status === "completed") ?? null;
|
||||||
|
|
||||||
let personalRecord: Race | null = null;
|
const lastPersonalRecord =
|
||||||
let personalRecordSeconds = Number.POSITIVE_INFINITY;
|
past.find(
|
||||||
|
(race) => race.status === "completed" && parseFinishTimeToSeconds(race.finishTime) !== null,
|
||||||
for (const race of completed) {
|
) ?? null;
|
||||||
const finishSeconds = parseFinishTimeToSeconds(race.finishTime);
|
|
||||||
if (!finishSeconds) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidate = finishSeconds / race.distanceKm;
|
|
||||||
if (candidate < personalRecordSeconds) {
|
|
||||||
personalRecordSeconds = candidate;
|
|
||||||
personalRecord = race;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const seasonRaces = races.filter((race) => parseRaceDate(race.date).getFullYear() === currentYear);
|
const seasonRaces = races.filter((race) => parseRaceDate(race.date).getFullYear() === currentYear);
|
||||||
@@ -89,7 +78,7 @@ export function DashboardPage(): JSX.Element {
|
|||||||
return {
|
return {
|
||||||
nextRace,
|
nextRace,
|
||||||
lastResult,
|
lastResult,
|
||||||
personalRecord,
|
lastPersonalRecord,
|
||||||
seasonTotal: seasonRaces.length,
|
seasonTotal: seasonRaces.length,
|
||||||
seasonCompletedCount: seasonCompleted.length,
|
seasonCompletedCount: seasonCompleted.length,
|
||||||
};
|
};
|
||||||
@@ -143,6 +132,11 @@ export function DashboardPage(): JSX.Element {
|
|||||||
.sort((left, right) => right.year - left.year || left.title.localeCompare(right.title, "ru-RU"));
|
.sort((left, right) => right.year - left.year || left.title.localeCompare(right.title, "ru-RU"));
|
||||||
}, [races]);
|
}, [races]);
|
||||||
|
|
||||||
|
const seasonProgress =
|
||||||
|
dashboardMetrics.seasonTotal > 0
|
||||||
|
? Math.round((dashboardMetrics.seasonCompletedCount / dashboardMetrics.seasonTotal) * 100)
|
||||||
|
: 0;
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<section className="page page--dashboard" aria-busy="true">
|
<section className="page page--dashboard" aria-busy="true">
|
||||||
@@ -163,60 +157,125 @@ export function DashboardPage(): JSX.Element {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="page page--dashboard">
|
<section className="page page--dashboard">
|
||||||
<h1 className="page__title">Обзор</h1>
|
<section className="dashboard-hero" aria-label="Обзор сезона">
|
||||||
<p className="page__subtitle">Ключевые метрики по вашему календарю стартов.</p>
|
<div className="dashboard-hero__content">
|
||||||
|
<p className="dashboard-hero__eyebrow">Календарь сезона</p>
|
||||||
|
<h1 className="dashboard-hero__title">Беговой штаб</h1>
|
||||||
|
<p className="dashboard-hero__text">
|
||||||
|
Планируйте старты, держите фокус на ближайшей гонке и сравнивайте прогресс по дистанциям.
|
||||||
|
</p>
|
||||||
|
<div className="dashboard-hero__actions">
|
||||||
|
<Link className="btn btn--primary" to="/races">
|
||||||
|
Смотреть старты
|
||||||
|
</Link>
|
||||||
|
<Link className="btn btn--secondary dashboard-hero__secondary" to="/races/new">
|
||||||
|
Добавить старт
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dashboard-hero__panel">
|
||||||
|
<p className="dashboard-hero__panel-label">Ближайший старт</p>
|
||||||
|
{dashboardMetrics.nextRace ? (
|
||||||
|
<Link className="dashboard-hero__race-link" to={`/races/${dashboardMetrics.nextRace.id}`}>
|
||||||
|
<span className="dashboard-hero__race-title">{dashboardMetrics.nextRace.title}</span>
|
||||||
|
<span className="dashboard-hero__race-meta">
|
||||||
|
{formatRaceDate(dashboardMetrics.nextRace.date)} · {formatDistance(dashboardMetrics.nextRace.distanceKm)}
|
||||||
|
</span>
|
||||||
|
<span className="dashboard-hero__race-countdown">
|
||||||
|
{getRaceCountdownLabel(dashboardMetrics.nextRace.date)}
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<p className="dashboard-hero__empty">Запланируйте первый старт сезона.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div className="dashboard-grid" aria-label="Ключевые метрики">
|
<div className="dashboard-grid" aria-label="Ключевые метрики">
|
||||||
<article className="dashboard-card">
|
<article
|
||||||
<h2 className="dashboard-card__title">Ближайший старт</h2>
|
className={`dashboard-card dashboard-card--accent-blue${dashboardMetrics.nextRace ? " dashboard-card--linked" : ""}`}
|
||||||
|
>
|
||||||
{dashboardMetrics.nextRace ? (
|
{dashboardMetrics.nextRace ? (
|
||||||
<>
|
<Link
|
||||||
|
className="dashboard-card__link-surface"
|
||||||
|
to={`/races/${dashboardMetrics.nextRace.id}`}
|
||||||
|
aria-label={`Ближайший старт: ${dashboardMetrics.nextRace.title}`}
|
||||||
|
>
|
||||||
|
<h2 className="dashboard-card__title">Ближайший старт</h2>
|
||||||
<p className="dashboard-card__value">{dashboardMetrics.nextRace.title}</p>
|
<p className="dashboard-card__value">{dashboardMetrics.nextRace.title}</p>
|
||||||
<p className="dashboard-card__meta">
|
<p className="dashboard-card__meta">
|
||||||
{formatRaceDate(dashboardMetrics.nextRace.date)} · {formatDistance(dashboardMetrics.nextRace.distanceKm)}
|
{formatRaceDate(dashboardMetrics.nextRace.date)} ·{" "}
|
||||||
|
{formatDistance(dashboardMetrics.nextRace.distanceKm)}
|
||||||
</p>
|
</p>
|
||||||
<p className="dashboard-card__hint">{getRaceCountdownLabel(dashboardMetrics.nextRace.date)}</p>
|
<p className="dashboard-card__hint">{getRaceCountdownLabel(dashboardMetrics.nextRace.date)}</p>
|
||||||
</>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
<p className="dashboard-card__empty">Нет запланированных стартов.</p>
|
<>
|
||||||
|
<h2 className="dashboard-card__title">Ближайший старт</h2>
|
||||||
|
<p className="dashboard-card__empty">Нет запланированных стартов.</p>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
<article className="dashboard-card">
|
<article
|
||||||
<h2 className="dashboard-card__title">Последний результат</h2>
|
className={`dashboard-card dashboard-card--accent-coral${dashboardMetrics.lastResult ? " dashboard-card--linked" : ""}`}
|
||||||
|
>
|
||||||
{dashboardMetrics.lastResult ? (
|
{dashboardMetrics.lastResult ? (
|
||||||
<>
|
<Link
|
||||||
|
className="dashboard-card__link-surface"
|
||||||
|
to={`/races/${dashboardMetrics.lastResult.id}`}
|
||||||
|
aria-label={`Последний результат: ${dashboardMetrics.lastResult.title}`}
|
||||||
|
>
|
||||||
|
<h2 className="dashboard-card__title">Последний результат</h2>
|
||||||
<p className="dashboard-card__value">{dashboardMetrics.lastResult.finishTime ?? "время не указано"}</p>
|
<p className="dashboard-card__value">{dashboardMetrics.lastResult.finishTime ?? "время не указано"}</p>
|
||||||
<p className="dashboard-card__meta">
|
<p className="dashboard-card__meta">
|
||||||
{dashboardMetrics.lastResult.title} · {formatDistance(dashboardMetrics.lastResult.distanceKm)}
|
{dashboardMetrics.lastResult.title} · {formatDistance(dashboardMetrics.lastResult.distanceKm)}
|
||||||
</p>
|
</p>
|
||||||
<p className="dashboard-card__hint">{formatRaceDate(dashboardMetrics.lastResult.date)}</p>
|
<p className="dashboard-card__hint">{formatRaceDate(dashboardMetrics.lastResult.date)}</p>
|
||||||
</>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
<p className="dashboard-card__empty">Пока нет завершённых стартов.</p>
|
|
||||||
)}
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article className="dashboard-card">
|
|
||||||
<h2 className="dashboard-card__title">Личный рекорд</h2>
|
|
||||||
{dashboardMetrics.personalRecord ? (
|
|
||||||
<>
|
<>
|
||||||
<p className="dashboard-card__value">{dashboardMetrics.personalRecord.finishTime ?? "время не указано"}</p>
|
<h2 className="dashboard-card__title">Последний результат</h2>
|
||||||
<p className="dashboard-card__meta">
|
<p className="dashboard-card__empty">Пока нет завершённых стартов.</p>
|
||||||
{dashboardMetrics.personalRecord.title} · {formatDistance(dashboardMetrics.personalRecord.distanceKm)}
|
|
||||||
</p>
|
|
||||||
<p className="dashboard-card__hint">Лучший темп среди завершённых стартов.</p>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
|
||||||
<p className="dashboard-card__empty">Недостаточно данных для личного рекорда.</p>
|
|
||||||
)}
|
)}
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
<article className="dashboard-card">
|
<article
|
||||||
|
className={`dashboard-card dashboard-card--accent-lime${dashboardMetrics.lastPersonalRecord ? " dashboard-card--linked" : ""}`}
|
||||||
|
>
|
||||||
|
{dashboardMetrics.lastPersonalRecord ? (
|
||||||
|
<Link
|
||||||
|
className="dashboard-card__link-surface"
|
||||||
|
to={`/races/${dashboardMetrics.lastPersonalRecord.id}`}
|
||||||
|
aria-label={`Последний личный рекорд: ${dashboardMetrics.lastPersonalRecord.title}`}
|
||||||
|
>
|
||||||
|
<h2 className="dashboard-card__title">Последний личный рекорд</h2>
|
||||||
|
<p className="dashboard-card__value">
|
||||||
|
{dashboardMetrics.lastPersonalRecord.finishTime ?? "время не указано"}
|
||||||
|
</p>
|
||||||
|
<p className="dashboard-card__meta">
|
||||||
|
{dashboardMetrics.lastPersonalRecord.title} ·{" "}
|
||||||
|
{formatDistance(dashboardMetrics.lastPersonalRecord.distanceKm)}
|
||||||
|
</p>
|
||||||
|
<p className="dashboard-card__hint">{formatRaceDate(dashboardMetrics.lastPersonalRecord.date)}</p>
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<h2 className="dashboard-card__title">Последний личный рекорд</h2>
|
||||||
|
<p className="dashboard-card__empty">Нет завершённых стартов с финишным временем.</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="dashboard-card dashboard-card--season dashboard-card--accent-violet">
|
||||||
<h2 className="dashboard-card__title">Сезон</h2>
|
<h2 className="dashboard-card__title">Сезон</h2>
|
||||||
<p className="dashboard-card__value">{dashboardMetrics.seasonTotal}</p>
|
<p className="dashboard-card__value">{dashboardMetrics.seasonTotal}</p>
|
||||||
<p className="dashboard-card__meta">стартов в этом году</p>
|
<p className="dashboard-card__meta">стартов в этом году</p>
|
||||||
<p className="dashboard-card__hint">Завершено: {dashboardMetrics.seasonCompletedCount}</p>
|
<p className="dashboard-card__hint">Завершено: {dashboardMetrics.seasonCompletedCount}</p>
|
||||||
|
<div className="dashboard-card__progress" aria-label={`Сезон завершен на ${seasonProgress}%`}>
|
||||||
|
<span style={{ width: `${seasonProgress}%` }} />
|
||||||
|
</div>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,14 @@ import { useEffect, useMemo, useState } from "react";
|
|||||||
import { Link, useParams } from "react-router-dom";
|
import { Link, useParams } from "react-router-dom";
|
||||||
import type { Race } from "../api";
|
import type { Race } from "../api";
|
||||||
import { ApiError, getRaces } from "../api";
|
import { ApiError, getRaces } from "../api";
|
||||||
import { formatDistance, formatRaceDate, getRaceStatusClassName, getRaceStatusLabel, sortByDateAsc } from "../lib";
|
import {
|
||||||
|
formatDistance,
|
||||||
|
formatRaceDate,
|
||||||
|
getRaceStatusClassName,
|
||||||
|
getRaceStatusLabel,
|
||||||
|
getRaceVisual,
|
||||||
|
sortByDateAsc,
|
||||||
|
} from "../lib";
|
||||||
|
|
||||||
function getErrorMessage(error: unknown): string {
|
function getErrorMessage(error: unknown): string {
|
||||||
if (error instanceof ApiError) {
|
if (error instanceof ApiError) {
|
||||||
@@ -70,24 +77,33 @@ export function RaceDayPage(): JSX.Element {
|
|||||||
if (!validYmd) {
|
if (!validYmd) {
|
||||||
return (
|
return (
|
||||||
<section className="page page--race-day">
|
<section className="page page--race-day">
|
||||||
<h1 className="page__title">Некорректная дата</h1>
|
<div className="race-day-hero">
|
||||||
<p className="page__subtitle">
|
<p className="race-day-hero__eyebrow">Страница дня</p>
|
||||||
|
<h1 className="page__title">Некорректная дата</h1>
|
||||||
<Link className="page-link" to="/races">
|
<Link className="page-link" to="/races">
|
||||||
Вернуться к календарю стартов
|
Вернуться к календарю стартов
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="page page--race-day">
|
<section className="page page--race-day">
|
||||||
<p className="page__subtitle">
|
<section className="race-day-hero" aria-label="Старты дня">
|
||||||
<Link className="page-link" to="/races">
|
<Link className="page-link" to="/races">
|
||||||
← Календарь стартов
|
← Календарь стартов
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
<p className="race-day-hero__eyebrow">Старты дня</p>
|
||||||
<h1 className="page__title">{heading}</h1>
|
<h1 className="page__title">{heading}</h1>
|
||||||
|
<p className="page__subtitle">
|
||||||
|
{isLoading
|
||||||
|
? "Загружаем расписание..."
|
||||||
|
: races.length > 0
|
||||||
|
? `Запланировано стартов: ${races.length}`
|
||||||
|
: "Проверьте расписание или добавьте старт на эту дату."}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
{errorMessage ? (
|
{errorMessage ? (
|
||||||
<p className="page__subtitle page__subtitle--error" role="alert">
|
<p className="page__subtitle page__subtitle--error" role="alert">
|
||||||
@@ -107,19 +123,40 @@ export function RaceDayPage(): JSX.Element {
|
|||||||
|
|
||||||
{!isLoading && races.length > 0 ? (
|
{!isLoading && races.length > 0 ? (
|
||||||
<ul className="race-day__list">
|
<ul className="race-day__list">
|
||||||
{races.map((race) => (
|
{races.map((race) => {
|
||||||
<li key={race.id} className="race-day__item">
|
const visual = getRaceVisual(race);
|
||||||
<Link className="race-day__link" to={`/races/${race.id}`}>
|
|
||||||
{race.title}
|
return (
|
||||||
</Link>
|
<li key={race.id} className="race-day__item">
|
||||||
<span className="race-day__meta">
|
<Link className="race-day__link" to={`/races/${race.id}`}>
|
||||||
{formatDistance(race.distanceKm)} ·{" "}
|
<img
|
||||||
<span className={getRaceStatusClassName(race.status, race.date)}>
|
className={`race-day__image${
|
||||||
{getRaceStatusLabel(race.status, race.date)}
|
visual.imageFit === "contain" ? " race-day__image--contain" : ""
|
||||||
</span>
|
}`}
|
||||||
</span>
|
src={visual.imageSrc}
|
||||||
</li>
|
alt=""
|
||||||
))}
|
loading="lazy"
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
onError={(event) => {
|
||||||
|
event.currentTarget.onerror = null;
|
||||||
|
event.currentTarget.classList.remove("race-day__image--contain");
|
||||||
|
event.currentTarget.src = visual.fallbackSrc;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="race-day__body">
|
||||||
|
<span className="race-day__kicker">{visual.label}</span>
|
||||||
|
<span className="race-day__title">{race.title}</span>
|
||||||
|
<span className="race-day__meta">
|
||||||
|
{formatDistance(race.distanceKm)} ·{" "}
|
||||||
|
<span className={getRaceStatusClassName(race.status, race.date)}>
|
||||||
|
{getRaceStatusLabel(race.status, race.date)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
getPaceLabel,
|
getPaceLabel,
|
||||||
getRaceStatusClassName,
|
getRaceStatusClassName,
|
||||||
getRaceStatusLabel,
|
getRaceStatusLabel,
|
||||||
|
getRaceVisual,
|
||||||
raceNeedsResultEntry,
|
raceNeedsResultEntry,
|
||||||
} from "../lib";
|
} from "../lib";
|
||||||
import type { Race } from "../api";
|
import type { Race } from "../api";
|
||||||
@@ -139,18 +140,40 @@ export function RaceDetailsPage(): JSX.Element {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isCompleted = race.status === "completed";
|
const isCompleted = race.status === "completed";
|
||||||
|
const visual = getRaceVisual(race);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="page page--race-details">
|
<section className="page page--race-details">
|
||||||
<div className="race-details-header">
|
<section className={`race-details-hero race-details-hero--${visual.variant}`} aria-label="Карточка старта">
|
||||||
<div className="race-details-header__main">
|
<img
|
||||||
|
className={`race-details-hero__image${
|
||||||
|
visual.imageFit === "contain" ? " race-details-hero__image--contain" : ""
|
||||||
|
}`}
|
||||||
|
src={visual.imageSrc}
|
||||||
|
alt=""
|
||||||
|
loading="eager"
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
onError={(event) => {
|
||||||
|
event.currentTarget.onerror = null;
|
||||||
|
event.currentTarget.classList.remove("race-details-hero__image--contain");
|
||||||
|
event.currentTarget.src = visual.fallbackSrc;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="race-details-hero__shade" aria-hidden="true" />
|
||||||
|
<div className="race-details-hero__content">
|
||||||
|
<Link className="race-details-hero__back" to="/races">
|
||||||
|
← Календарь стартов
|
||||||
|
</Link>
|
||||||
|
<p className="race-details-hero__eyebrow">{visual.label}</p>
|
||||||
<h1 className="page__title">{race.title}</h1>
|
<h1 className="page__title">{race.title}</h1>
|
||||||
<p className="page__subtitle">
|
<p className="page__subtitle">
|
||||||
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
||||||
</p>
|
</p>
|
||||||
|
<span className={getRaceStatusClassName(race.status, race.date)}>
|
||||||
|
{getRaceStatusLabel(race.status, race.date)}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<span className={getRaceStatusClassName(race.status, race.date)}>{getRaceStatusLabel(race.status, race.date)}</span>
|
</section>
|
||||||
</div>
|
|
||||||
|
|
||||||
{raceNeedsResultEntry(race) ? (
|
{raceNeedsResultEntry(race) ? (
|
||||||
<p className="race-details-past-hint" role="status">
|
<p className="race-details-past-hint" role="status">
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||||
import { ApiError, createRace, getRaceById, updateRace } from "../api";
|
import { ApiError, createRace, getRaceById, updateRace } from "../api";
|
||||||
import type { CreateRacePayload, Race, RaceStatus, UpdateRacePayload } from "../api";
|
import type { CreateRacePayload, Race, RaceStatus, UpdateRacePayload } from "../api";
|
||||||
import { StartTimeSelects } from "../components/StartTimeSelects";
|
import { DatePickerField, StartTimeSelects } from "../components";
|
||||||
import { isRaceDateInPast } from "../lib";
|
import { isRaceDateInPast, parseFinishTimeToSeconds } from "../lib";
|
||||||
|
|
||||||
function slugify(text: string): string {
|
function slugify(text: string): string {
|
||||||
return text
|
return text
|
||||||
@@ -31,6 +31,7 @@ interface FormData {
|
|||||||
distanceKm: string;
|
distanceKm: string;
|
||||||
status: string;
|
status: string;
|
||||||
officialUrl: string;
|
officialUrl: string;
|
||||||
|
coverImageUrl: string;
|
||||||
startTime: string;
|
startTime: string;
|
||||||
clusterSchedule: string;
|
clusterSchedule: string;
|
||||||
bibPickup: string;
|
bibPickup: string;
|
||||||
@@ -46,6 +47,7 @@ const EMPTY_FORM: FormData = {
|
|||||||
distanceKm: "",
|
distanceKm: "",
|
||||||
status: "planned",
|
status: "planned",
|
||||||
officialUrl: "",
|
officialUrl: "",
|
||||||
|
coverImageUrl: "",
|
||||||
startTime: "",
|
startTime: "",
|
||||||
clusterSchedule: "",
|
clusterSchedule: "",
|
||||||
bibPickup: "",
|
bibPickup: "",
|
||||||
@@ -63,6 +65,7 @@ function raceToFormData(race: Race): FormData {
|
|||||||
distanceKm: String(race.distanceKm),
|
distanceKm: String(race.distanceKm),
|
||||||
status: race.status ?? "",
|
status: race.status ?? "",
|
||||||
officialUrl: race.officialUrl ?? "",
|
officialUrl: race.officialUrl ?? "",
|
||||||
|
coverImageUrl: race.coverImageUrl ?? "",
|
||||||
startTime: race.startTime ?? "",
|
startTime: race.startTime ?? "",
|
||||||
clusterSchedule: race.clusterSchedule ?? "",
|
clusterSchedule: race.clusterSchedule ?? "",
|
||||||
bibPickup: race.bibPickup ?? "",
|
bibPickup: race.bibPickup ?? "",
|
||||||
@@ -93,6 +96,17 @@ function validateForm(form: FormData): string[] {
|
|||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isRaceDateTodayOrPast(date: string): boolean {
|
||||||
|
if (!date.trim()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const today = new Date();
|
||||||
|
const y = today.getFullYear();
|
||||||
|
const m = String(today.getMonth() + 1).padStart(2, "0");
|
||||||
|
const d = String(today.getDate()).padStart(2, "0");
|
||||||
|
return isRaceDateInPast(date) || date.slice(0, 10) === `${y}-${m}-${d}`;
|
||||||
|
}
|
||||||
|
|
||||||
export function RaceFormPage(): JSX.Element {
|
export function RaceFormPage(): JSX.Element {
|
||||||
const { raceId } = useParams<{ raceId: string }>();
|
const { raceId } = useParams<{ raceId: string }>();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -151,7 +165,16 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
const handleChange = useCallback(
|
const handleChange = useCallback(
|
||||||
(event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
(event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||||
const { name, value } = event.target;
|
const { name, value } = event.target;
|
||||||
setForm((prev) => ({ ...prev, [name]: value }));
|
setForm((prev) => {
|
||||||
|
const next = { ...prev, [name]: value };
|
||||||
|
if (name === "finishTime") {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed !== "" && parseFinishTimeToSeconds(trimmed) !== null) {
|
||||||
|
return { ...next, status: "completed" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
@@ -170,10 +193,16 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const statusValue: RaceStatus | null =
|
const finishTrimmed = form.finishTime.trim();
|
||||||
|
const hasParsedFinish =
|
||||||
|
finishTrimmed !== "" && parseFinishTimeToSeconds(finishTrimmed) !== null;
|
||||||
|
let statusValue: RaceStatus | null =
|
||||||
form.status === "planned" || form.status === "registered" || form.status === "completed"
|
form.status === "planned" || form.status === "registered" || form.status === "completed"
|
||||||
? form.status
|
? form.status
|
||||||
: null;
|
: null;
|
||||||
|
if (hasParsedFinish) {
|
||||||
|
statusValue = "completed";
|
||||||
|
}
|
||||||
|
|
||||||
if (isEditMode && raceId) {
|
if (isEditMode && raceId) {
|
||||||
const payload: UpdateRacePayload = {
|
const payload: UpdateRacePayload = {
|
||||||
@@ -182,6 +211,7 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
distanceKm: parseFloat(form.distanceKm),
|
distanceKm: parseFloat(form.distanceKm),
|
||||||
status: statusValue,
|
status: statusValue,
|
||||||
officialUrl: emptyToNull(form.officialUrl),
|
officialUrl: emptyToNull(form.officialUrl),
|
||||||
|
coverImageUrl: emptyToNull(form.coverImageUrl),
|
||||||
startTime: emptyToNull(form.startTime),
|
startTime: emptyToNull(form.startTime),
|
||||||
clusterSchedule: emptyToNull(form.clusterSchedule),
|
clusterSchedule: emptyToNull(form.clusterSchedule),
|
||||||
bibPickup: emptyToNull(form.bibPickup),
|
bibPickup: emptyToNull(form.bibPickup),
|
||||||
@@ -202,6 +232,7 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
distanceKm: parseFloat(form.distanceKm),
|
distanceKm: parseFloat(form.distanceKm),
|
||||||
status: statusValue,
|
status: statusValue,
|
||||||
officialUrl: emptyToNull(form.officialUrl),
|
officialUrl: emptyToNull(form.officialUrl),
|
||||||
|
coverImageUrl: emptyToNull(form.coverImageUrl),
|
||||||
startTime: emptyToNull(form.startTime),
|
startTime: emptyToNull(form.startTime),
|
||||||
clusterSchedule: emptyToNull(form.clusterSchedule),
|
clusterSchedule: emptyToNull(form.clusterSchedule),
|
||||||
bibPickup: emptyToNull(form.bibPickup),
|
bibPickup: emptyToNull(form.bibPickup),
|
||||||
@@ -228,6 +259,7 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const hideOrgScheduleFields = isEditMode && isRaceDateInPast(form.date);
|
const hideOrgScheduleFields = isEditMode && isRaceDateInPast(form.date);
|
||||||
|
const showResultFields = isRaceDateTodayOrPast(form.date);
|
||||||
const pageTitle = isEditMode ? "Редактирование старта" : "Новый старт";
|
const pageTitle = isEditMode ? "Редактирование старта" : "Новый старт";
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
@@ -259,17 +291,17 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
<fieldset className="race-form__group">
|
<fieldset className="race-form__group">
|
||||||
<legend className="race-form__legend">Основная информация</legend>
|
<legend className="race-form__legend">Основная информация</legend>
|
||||||
|
|
||||||
<label className="race-form__field">
|
<div className="race-form__field">
|
||||||
<span className="race-form__label">Дата *</span>
|
<span className="race-form__label">Дата *</span>
|
||||||
<input
|
<DatePickerField
|
||||||
className="race-form__input"
|
|
||||||
type="date"
|
|
||||||
name="date"
|
name="date"
|
||||||
value={form.date}
|
value={form.date}
|
||||||
onChange={handleChange}
|
onChange={(next) => {
|
||||||
|
setForm((prev) => ({ ...prev, date: next }));
|
||||||
|
}}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</label>
|
</div>
|
||||||
|
|
||||||
<label className="race-form__field">
|
<label className="race-form__field">
|
||||||
<span className="race-form__label">Название *</span>
|
<span className="race-form__label">Название *</span>
|
||||||
@@ -331,6 +363,18 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<label className="race-form__field">
|
||||||
|
<span className="race-form__label">URL обложки</span>
|
||||||
|
<input
|
||||||
|
className="race-form__input"
|
||||||
|
type="url"
|
||||||
|
name="coverImageUrl"
|
||||||
|
value={form.coverImageUrl}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="https://…"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
{hideOrgScheduleFields ? null : (
|
{hideOrgScheduleFields ? null : (
|
||||||
<div className="race-form__field">
|
<div className="race-form__field">
|
||||||
<span className="race-form__label">Время старта</span>
|
<span className="race-form__label">Время старта</span>
|
||||||
@@ -382,33 +426,35 @@ export function RaceFormPage(): JSX.Element {
|
|||||||
</label>
|
</label>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
<fieldset className="race-form__group">
|
{showResultFields ? (
|
||||||
<legend className="race-form__legend">Результаты</legend>
|
<fieldset className="race-form__group">
|
||||||
|
<legend className="race-form__legend">Результаты</legend>
|
||||||
|
|
||||||
<label className="race-form__field">
|
<label className="race-form__field">
|
||||||
<span className="race-form__label">Финишное время</span>
|
<span className="race-form__label">Финишное время</span>
|
||||||
<input
|
<input
|
||||||
className="race-form__input"
|
className="race-form__input"
|
||||||
type="text"
|
type="text"
|
||||||
name="finishTime"
|
name="finishTime"
|
||||||
value={form.finishTime}
|
value={form.finishTime}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
placeholder="1:45:30"
|
placeholder="1:45:30"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="race-form__field">
|
<label className="race-form__field">
|
||||||
<span className="race-form__label">Место на финише</span>
|
<span className="race-form__label">Место на финише</span>
|
||||||
<input
|
<input
|
||||||
className="race-form__input"
|
className="race-form__input"
|
||||||
type="text"
|
type="text"
|
||||||
name="finishPlace"
|
name="finishPlace"
|
||||||
value={form.finishPlace}
|
value={form.finishPlace}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
placeholder="12/340"
|
placeholder="12/340"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<fieldset className="race-form__group">
|
<fieldset className="race-form__group">
|
||||||
<legend className="race-form__legend">Дополнительно</legend>
|
<legend className="race-form__legend">Дополнительно</legend>
|
||||||
|
|||||||
@@ -6,10 +6,12 @@ import { RacesCalendar } from "../components/RacesCalendar";
|
|||||||
import {
|
import {
|
||||||
formatDistance,
|
formatDistance,
|
||||||
formatRaceDate,
|
formatRaceDate,
|
||||||
|
getRaceVisual,
|
||||||
getRaceStatusClassName,
|
getRaceStatusClassName,
|
||||||
getRaceStatusLabel,
|
getRaceStatusLabel,
|
||||||
raceNeedsResultEntry,
|
parseRaceDate,
|
||||||
splitRacesByDate,
|
sortByDateAsc,
|
||||||
|
sortByDateDesc,
|
||||||
} from "../lib";
|
} from "../lib";
|
||||||
|
|
||||||
const MONTH_OPTIONS: { value: string; label: string }[] = [
|
const MONTH_OPTIONS: { value: string; label: string }[] = [
|
||||||
@@ -68,16 +70,41 @@ function RaceList(props: { title: string; races: Race[] }): JSX.Element {
|
|||||||
{races.length > 0 ? (
|
{races.length > 0 ? (
|
||||||
<ul className="race-list__items">
|
<ul className="race-list__items">
|
||||||
{races.map((race) => {
|
{races.map((race) => {
|
||||||
const needsResult = raceNeedsResultEntry(race);
|
const visual = getRaceVisual(race);
|
||||||
if (needsResult) {
|
const parsedDate = parseRaceDate(race.date);
|
||||||
return (
|
const day = parsedDate.toLocaleDateString("ru-RU", { day: "2-digit" });
|
||||||
<li key={race.id} className="race-card race-card--action">
|
const month = parsedDate.toLocaleDateString("ru-RU", { month: "short" });
|
||||||
<Link
|
|
||||||
className="race-card__link-surface"
|
return (
|
||||||
to={`/races/${race.id}/edit`}
|
<li key={race.id} className={`race-card race-card--action race-card--poster race-card--${visual.variant}`}>
|
||||||
aria-label={`${race.title}, внести результат`}
|
<Link
|
||||||
>
|
className="race-card__link-surface"
|
||||||
|
to={`/races/${race.id}`}
|
||||||
|
aria-label={`Старт: ${race.title}`}
|
||||||
|
>
|
||||||
|
<div className="race-card__image-wrap">
|
||||||
|
<img
|
||||||
|
className={`race-card__image${
|
||||||
|
visual.imageFit === "contain" ? " race-card__image--contain" : ""
|
||||||
|
}`}
|
||||||
|
src={visual.imageSrc}
|
||||||
|
alt=""
|
||||||
|
loading="lazy"
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
onError={(event) => {
|
||||||
|
event.currentTarget.onerror = null;
|
||||||
|
event.currentTarget.classList.remove("race-card__image--contain");
|
||||||
|
event.currentTarget.src = visual.fallbackSrc;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="race-card__date-badge">
|
||||||
|
<span>{day}</span>
|
||||||
|
<span>{month}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="race-card__content">
|
||||||
<div className="race-card__main">
|
<div className="race-card__main">
|
||||||
|
<p className="race-card__kicker">{visual.label}</p>
|
||||||
<p className="race-card__title">
|
<p className="race-card__title">
|
||||||
<span className="race-card__title-text">{race.title}</span>
|
<span className="race-card__title-text">{race.title}</span>
|
||||||
</p>
|
</p>
|
||||||
@@ -85,28 +112,14 @@ function RaceList(props: { title: string; races: Race[] }): JSX.Element {
|
|||||||
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className={getRaceStatusClassName(race.status, race.date)}>
|
<div className="race-card__footer">
|
||||||
{getRaceStatusLabel(race.status, race.date)}
|
<span className={getRaceStatusClassName(race.status, race.date)}>
|
||||||
</span>
|
{getRaceStatusLabel(race.status, race.date)}
|
||||||
</Link>
|
</span>
|
||||||
</li>
|
<span className="race-card__cta">Открыть</span>
|
||||||
);
|
</div>
|
||||||
}
|
</div>
|
||||||
return (
|
</Link>
|
||||||
<li key={race.id} className="race-card">
|
|
||||||
<div className="race-card__main">
|
|
||||||
<p className="race-card__title">
|
|
||||||
<Link className="race-card__link" to={`/races/${race.id}`}>
|
|
||||||
{race.title}
|
|
||||||
</Link>
|
|
||||||
</p>
|
|
||||||
<p className="race-card__meta">
|
|
||||||
{formatRaceDate(race.date)} · {formatDistance(race.distanceKm)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<span className={getRaceStatusClassName(race.status, race.date)}>
|
|
||||||
{getRaceStatusLabel(race.status, race.date)}
|
|
||||||
</span>
|
|
||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -208,7 +221,32 @@ export function RacesPage(): JSX.Element {
|
|||||||
};
|
};
|
||||||
}, [listQuery]);
|
}, [listQuery]);
|
||||||
|
|
||||||
const { upcoming, past } = useMemo(() => splitRacesByDate(races), [races]);
|
const { upcoming, completed } = useMemo(
|
||||||
|
() => ({
|
||||||
|
upcoming: sortByDateAsc(races.filter((race) => race.status !== "completed")),
|
||||||
|
completed: sortByDateDesc(races.filter((race) => race.status === "completed")),
|
||||||
|
}),
|
||||||
|
[races],
|
||||||
|
);
|
||||||
|
const statusMessage = useMemo(() => {
|
||||||
|
if (errorMessage && !isLoading) {
|
||||||
|
return errorMessage;
|
||||||
|
}
|
||||||
|
if (isLoading) {
|
||||||
|
return "Загружаем данные...";
|
||||||
|
}
|
||||||
|
if (viewMode === "calendar" && monthFilter === "") {
|
||||||
|
return "Выберите месяц, чтобы увидеть его крупным планом.";
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}, [errorMessage, isLoading, monthFilter, viewMode]);
|
||||||
|
const statusClassName = [
|
||||||
|
"races-status__message",
|
||||||
|
!statusMessage ? "races-status__message--empty" : "",
|
||||||
|
errorMessage && !isLoading ? "races-status__message--error" : "",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
|
||||||
if (errorMessage && races.length === 0 && !isLoading) {
|
if (errorMessage && races.length === 0 && !isLoading) {
|
||||||
return (
|
return (
|
||||||
@@ -221,82 +259,82 @@ export function RacesPage(): JSX.Element {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="page page--races">
|
<section className="page page--races">
|
||||||
<h1 className="page__title">Календарь стартов</h1>
|
<section className="races-hero" aria-label="Календарь стартов">
|
||||||
<p className="page__subtitle">Будущие и прошедшие старты в одном месте.</p>
|
<div className="races-hero__content">
|
||||||
|
<p className="races-hero__eyebrow">Сезонная афиша</p>
|
||||||
|
<h1 className="page__title">Календарь стартов</h1>
|
||||||
|
<p className="page__subtitle">Будущие и прошедшие старты в одном месте.</p>
|
||||||
|
<div className="races-view-toggle" role="group" aria-label="Вид отображения">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`races-view-toggle__btn${viewMode === "list" ? " races-view-toggle__btn--active" : ""}`}
|
||||||
|
onClick={handleViewList}
|
||||||
|
>
|
||||||
|
Список
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`races-view-toggle__btn${viewMode === "calendar" ? " races-view-toggle__btn--active" : ""}`}
|
||||||
|
onClick={handleViewCalendar}
|
||||||
|
>
|
||||||
|
Календарь
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="races-hero__filters">
|
||||||
|
<div className="races-filter" role="search" aria-label="Фильтр по дате">
|
||||||
|
<label className="races-filter__field">
|
||||||
|
<span className="races-filter__label">Год</span>
|
||||||
|
<select
|
||||||
|
className="races-filter__select"
|
||||||
|
value={viewMode === "list" ? yearFilter : yearFilter || String(displayYear)}
|
||||||
|
onChange={(event) => {
|
||||||
|
setYearFilter(event.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{viewMode === "list" ? <option value="">Все года</option> : null}
|
||||||
|
{yearSelectOptions().map((y) => (
|
||||||
|
<option key={y} value={String(y)}>
|
||||||
|
{y}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="races-filter__field">
|
||||||
|
<span className="races-filter__label">Месяц</span>
|
||||||
|
<select
|
||||||
|
className="races-filter__select"
|
||||||
|
value={monthFilter}
|
||||||
|
onChange={(event) => {
|
||||||
|
setMonthFilter(event.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{MONTH_OPTIONS.map((opt) => (
|
||||||
|
<option key={opt.value || "all"} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div className="races-view-toggle" role="group" aria-label="Вид отображения">
|
<div className="races-status" aria-live="polite">
|
||||||
<button
|
<p
|
||||||
type="button"
|
className={statusClassName}
|
||||||
className={`races-view-toggle__btn${viewMode === "list" ? " races-view-toggle__btn--active" : ""}`}
|
role={errorMessage && !isLoading ? "alert" : undefined}
|
||||||
onClick={handleViewList}
|
aria-busy={isLoading || undefined}
|
||||||
|
aria-hidden={!statusMessage || undefined}
|
||||||
>
|
>
|
||||||
Список
|
{statusMessage || "\u00a0"}
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`races-view-toggle__btn${viewMode === "calendar" ? " races-view-toggle__btn--active" : ""}`}
|
|
||||||
onClick={handleViewCalendar}
|
|
||||||
>
|
|
||||||
Календарь
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{errorMessage && !isLoading ? (
|
|
||||||
<p className="page__subtitle page__subtitle--error" role="alert" style={{ marginTop: "var(--space-4)" }}>
|
|
||||||
{errorMessage}
|
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div className="races-filter" role="search" aria-label="Фильтр по дате">
|
|
||||||
<label className="races-filter__field">
|
|
||||||
<span className="races-filter__label">Год</span>
|
|
||||||
<select
|
|
||||||
className="races-filter__select"
|
|
||||||
value={viewMode === "list" ? yearFilter : yearFilter || String(displayYear)}
|
|
||||||
onChange={(event) => {
|
|
||||||
setYearFilter(event.target.value);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{viewMode === "list" ? <option value="">Все года</option> : null}
|
|
||||||
{yearSelectOptions().map((y) => (
|
|
||||||
<option key={y} value={String(y)}>
|
|
||||||
{y}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<label className="races-filter__field">
|
|
||||||
<span className="races-filter__label">Месяц</span>
|
|
||||||
<select
|
|
||||||
className="races-filter__select"
|
|
||||||
value={monthFilter}
|
|
||||||
onChange={(event) => {
|
|
||||||
setMonthFilter(event.target.value);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{MONTH_OPTIONS.map((opt) => (
|
|
||||||
<option key={opt.value || "all"} value={opt.value}>
|
|
||||||
{opt.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{viewMode === "calendar" && monthFilter === "" ? (
|
|
||||||
<p className="page__subtitle races-cal__filter-hint">Выберите месяц, чтобы увидеть его крупным планом.</p>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<p className="page__subtitle" aria-busy="true">
|
|
||||||
Загружаем данные...
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{viewMode === "list" ? (
|
{viewMode === "list" ? (
|
||||||
<div className="race-lists">
|
<div className="race-lists">
|
||||||
<RaceList title="Будущие" races={upcoming} />
|
<RaceList title="Будущие" races={upcoming} />
|
||||||
<RaceList title="Прошедшие" races={past} />
|
<RaceList title="Завершенные" races={completed} />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="races-cal-wrap">
|
<div className="races-cal-wrap">
|
||||||
|
|||||||
@@ -1,20 +1,26 @@
|
|||||||
:root {
|
:root {
|
||||||
--color-bg: #f3f5f7;
|
--color-bg: #edf3f6;
|
||||||
|
--color-bg-deep: #071927;
|
||||||
--color-surface: #ffffff;
|
--color-surface: #ffffff;
|
||||||
--color-text: #13202b;
|
--color-surface-soft: #f7fafc;
|
||||||
--color-text-muted: #5d6b77;
|
--color-text: #0e1f2d;
|
||||||
--color-accent: #1f7ae0;
|
--color-text-muted: #647483;
|
||||||
--color-border: #dce2e8;
|
--color-accent: #1168d8;
|
||||||
--color-success: #2f9e63;
|
--color-accent-strong: #0c48a0;
|
||||||
--color-warning: #c0821f;
|
--color-lime: #b9f24a;
|
||||||
--color-error: #cc3a3a;
|
--color-coral: #ff6f5e;
|
||||||
|
--color-violet: #6d5dfc;
|
||||||
|
--color-border: #d6e1ea;
|
||||||
|
--color-success: #168657;
|
||||||
|
--color-warning: #b77716;
|
||||||
|
--color-error: #c43333;
|
||||||
|
|
||||||
--font-family-base: "Inter", "Segoe UI", Arial, sans-serif;
|
--font-family-base: "Inter", "Segoe UI", Arial, sans-serif;
|
||||||
--font-size-h1: 2rem;
|
--font-size-h1: 2.35rem;
|
||||||
--font-size-h2: 1.5rem;
|
--font-size-h2: 1.35rem;
|
||||||
--font-size-body: 1rem;
|
--font-size-body: 1rem;
|
||||||
--font-size-caption: 0.875rem;
|
--font-size-caption: 0.875rem;
|
||||||
--line-height-base: 1.5;
|
--line-height-base: 1.45;
|
||||||
|
|
||||||
--space-1: 0.25rem;
|
--space-1: 0.25rem;
|
||||||
--space-2: 0.5rem;
|
--space-2: 0.5rem;
|
||||||
@@ -25,8 +31,10 @@
|
|||||||
--space-8: 2rem;
|
--space-8: 2rem;
|
||||||
|
|
||||||
--radius-sm: 0.375rem;
|
--radius-sm: 0.375rem;
|
||||||
--radius-md: 0.75rem;
|
--radius-md: 0.625rem;
|
||||||
--radius-lg: 1rem;
|
--radius-lg: 0.75rem;
|
||||||
|
|
||||||
--shadow-card-lift: 0 6px 20px rgba(19, 32, 43, 0.12);
|
--shadow-card: 0 10px 30px rgba(14, 31, 45, 0.08);
|
||||||
|
--shadow-card-lift: 0 16px 34px rgba(14, 31, 45, 0.16);
|
||||||
|
--shadow-hero: 0 22px 60px rgba(7, 25, 39, 0.24);
|
||||||
}
|
}
|
||||||
|
|||||||