diff --git a/context/2026-09-21_11-35-00_cabinet-graph-section.md b/context/2026-09-21_11-35-00_cabinet-graph-section.md new file mode 100644 index 0000000..51ba308 --- /dev/null +++ b/context/2026-09-21_11-35-00_cabinet-graph-section.md @@ -0,0 +1,5 @@ +# Кабинет: раздел Граф + инструкции + +Нав «Граф» → `/graph`: выбор округа, bbox, токен, превью метаданных/рёбер, копируемые URL. +Инструкции: отдельный блок (meta/nodes/edges, curl, fetch+пагинация). +`GET /api/v1/sources` → `graphReady`. diff --git a/src/TileServer.Application/Extracts/ExtractService.cs b/src/TileServer.Application/Extracts/ExtractService.cs index fa5a4c9..98e2a0f 100644 --- a/src/TileServer.Application/Extracts/ExtractService.cs +++ b/src/TileServer.Application/Extracts/ExtractService.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Options; using TileServer.Application.Configuration; +using TileServer.Application.Graph; using TileServer.Application.Tiles; using TileServer.Domain; using TileServer.Domain.Exceptions; @@ -12,6 +13,7 @@ public sealed class ExtractService( IExtractCatalog catalog, IExtractStateStore stateStore, ITileStore tileStore, + IRoadGraphStore roadGraphStore, IOptions options) : IExtractService { public async Task> ListAsync(string baseUrl, CancellationToken ct) @@ -88,6 +90,7 @@ public sealed class ExtractService( state.BuiltAt, state.PbfBytes, state.LastError, - bounds); + bounds, + roadGraphStore.Exists(extract.Id)); } } diff --git a/src/TileServer.Application/Extracts/IExtractService.cs b/src/TileServer.Application/Extracts/IExtractService.cs index 3fb9976..e5ab0e3 100644 --- a/src/TileServer.Application/Extracts/IExtractService.cs +++ b/src/TileServer.Application/Extracts/IExtractService.cs @@ -17,7 +17,8 @@ public sealed record ExtractResponse( DateTimeOffset? BuiltAt, long? PbfBytes, string? LastError, - TilesetBounds? Bounds); + TilesetBounds? Bounds, + bool GraphReady); public sealed record TilesetBounds(double MinLon, double MinLat, double MaxLon, double MaxLat); diff --git a/web/src/App.tsx b/web/src/App.tsx index d4fc7a2..a94b700 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -8,6 +8,7 @@ import { StylesPage } from "./features/styles/StylesPage"; import { StyleEditorPage } from "./features/styles/StyleEditorPage"; import { TokensPage } from "./features/tokens/TokensPage"; import { GuidesPage } from "./features/guides/GuidesPage"; +import { GraphPage } from "./features/graph/GraphPage"; import { CookieBanner } from "./legal/CookieBanner"; import { LegalPage } from "./legal/LegalPage"; @@ -66,6 +67,14 @@ export function App() { } /> + + + + } + /> = { + items: T[]; + nextAfter?: number | null; +}; + +function formatNumber(value: number): string { + return value.toLocaleString("ru-RU"); +} + +function CopyField({ label, value }: { label: string; value: string }) { + const [copied, setCopied] = useState(false); + return ( +
+
+ {label} + +
+
{value}
+
+ ); +} + +function defaultBbox(center: number[] | undefined): string { + const lon = center?.[0] ?? 37.6173; + const lat = center?.[1] ?? 55.7558; + const d = 0.08; + return `${(lon - d).toFixed(4)},${(lat - d).toFixed(4)},${(lon + d).toFixed(4)},${(lat + d).toFixed(4)}`; +} + +export function GraphPage() { + const { user } = useAuth(); + const [sources, setSources] = useState([]); + const [sourceId, setSourceId] = useState(""); + const [bbox, setBbox] = useState("37.5373,55.6758,37.6973,55.8358"); + const [token, setToken] = useState(() => getPreviewToken() ?? ""); + const [meta, setMeta] = useState(null); + const [edges, setEdges] = useState([]); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + const [creating, setCreating] = useState(false); + + const source = sources.find((item) => item.id === sourceId) ?? sources[0]; + const slug = user?.slug ?? "{slug}"; + const origin = window.location.origin; + const activeToken = token.trim() || "ts_…"; + + const urls = useMemo(() => { + const id = source?.id ?? "central-fed-district"; + const q = `token=${encodeURIComponent(activeToken)}`; + return { + meta: `${origin}/u/${slug}/graph/${id}?${q}`, + nodes: `${origin}/u/${slug}/graph/${id}/nodes?bbox=${bbox}&${q}`, + edges: `${origin}/u/${slug}/graph/${id}/edges?bbox=${bbox}&limit=50&${q}` + }; + }, [origin, slug, source?.id, bbox, activeToken]); + + useEffect(() => { + void api + .sources() + .then((list) => { + const enabled = list.filter((item) => item.enabled); + setSources(enabled); + setSourceId((current) => { + if (current && enabled.some((item) => item.id === current)) { + return current; + } + return enabled[0]?.id ?? ""; + }); + const first = enabled[0]; + if (first) { + setBbox(defaultBbox(first.center)); + } + }) + .catch((err: unknown) => setError(err instanceof Error ? err.message : "Не удалось загрузить источники")); + }, []); + + const loadGraph = useCallback(async () => { + if (!user || !source) { + return; + } + const secret = token.trim(); + if (!secret) { + setError("Нужен токен — создайте в «Токены» или вставьте сюда."); + return; + } + + setLoading(true); + setError(null); + const q = `token=${encodeURIComponent(secret)}`; + const metaUrl = `${origin}/u/${user.slug}/graph/${source.id}?${q}`; + const edgesUrl = `${origin}/u/${user.slug}/graph/${source.id}/edges?bbox=${encodeURIComponent(bbox)}&limit=50&${q}`; + try { + const metaRes = await fetch(metaUrl); + if (!metaRes.ok) { + const text = await metaRes.text(); + throw new Error(text || `${metaRes.status} ${metaRes.statusText}`); + } + const nextMeta = (await metaRes.json()) as GraphMeta; + setMeta(nextMeta); + + const edgesRes = await fetch(edgesUrl); + if (!edgesRes.ok) { + const text = await edgesRes.text(); + throw new Error(text || `${edgesRes.status} ${edgesRes.statusText}`); + } + const page = (await edgesRes.json()) as GraphPage; + setEdges(page.items ?? []); + } catch (err: unknown) { + setMeta(null); + setEdges([]); + setError(err instanceof Error ? err.message : "Не удалось загрузить граф"); + } finally { + setLoading(false); + } + }, [user, source, token, origin, bbox]); + + return ( +
+ + + +
+
+ { + const next = e.target.value; + setSourceId(next); + const item = sources.find((s) => s.id === next); + setBbox(defaultBbox(item?.center)); + setMeta(null); + setEdges([]); + }} + > + {sources.map((item) => ( + + ))} + + setBbox(e.target.value.trim())} + /> +
+
+ { + const value = e.target.value.trim(); + setToken(value); + if (value.startsWith("ts_")) { + setPreviewToken(value); + } + }} + placeholder="ts_…" + /> + + {!token ? ( + + ) : null} +
+ {source?.graphReady === false ? ( +

+ Для «{source.name}» граф ещё не собран. Дождитесь sync или вызовите{" "} + POST /api/v1/sync/{source.id} — тайлы пересобирать не обязательно. +

+ ) : null} +
+ +
+ + + +

+ Примеры кода и контракт ответа — в Инструкциях, блок «Граф дорог». +

+
+ + {meta ? ( +
+
+
+
Extract
+
{meta.extractId}
+
+
+
Узлы
+
{formatNumber(meta.nodeCount)}
+
+
+
Рёбра
+
{formatNumber(meta.edgeCount)}
+
+
+
Собран
+
{new Date(meta.builtAt).toLocaleString("ru-RU")}
+
+
+
+ ) : null} + + {edges.length > 0 ? ( +
+ + + + + + + + + + + + + {edges.map((edge) => ( + + + + + + + + + ))} + +
idfrom → tohighwayимямoneway
{edge.id} + {edge.fromId} → {edge.toId} + {edge.highway}{edge.name ?? "—"}{Math.round(edge.lengthM)}{edge.oneway ? "да" : "нет"}
+
+ ) : null} +
+ ); +} diff --git a/web/src/features/graph/graph.css b/web/src/features/graph/graph.css new file mode 100644 index 0000000..79fa3f5 --- /dev/null +++ b/web/src/features/graph/graph.css @@ -0,0 +1,86 @@ +.graph-page { + width: min(960px, 100%); + margin: 0 auto; + padding-bottom: var(--space-8); +} + +.graph-page__row { + align-items: end; +} + +.graph-page__hint { + margin: var(--space-3) 0 0; + color: var(--secondary-label); + font-size: var(--text-footnote); +} + +.graph-page__hint code { + font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; +} + +.graph-copy { + margin: 0 0 var(--space-3); + border-radius: var(--radius-lg); + overflow: hidden; + background: #11161c; + color: #e8eef4; +} + +.graph-copy figcaption { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 12px; + font-size: var(--text-caption1); + letter-spacing: 0.04em; + text-transform: uppercase; + color: rgb(232 238 244 / 55%); + border-bottom: 1px solid rgb(255 255 255 / 8%); +} + +.graph-copy button { + border: 0; + background: transparent; + color: #3cd68c; + cursor: pointer; + text-transform: none; + letter-spacing: 0; +} + +.graph-copy pre { + margin: 0; + padding: 12px 14px 14px; + overflow: auto; + font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; + font-size: 12.5px; + line-height: 1.45; + white-space: pre-wrap; + word-break: break-all; +} + +.graph-meta { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); + gap: var(--space-3); + margin: 0; +} + +.graph-meta div { + padding: var(--space-3); + border-radius: var(--radius-lg); + background: var(--grouped-background); +} + +.graph-meta dt { + margin: 0 0 4px; + font-size: var(--text-caption1); + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--secondary-label); +} + +.graph-meta dd { + margin: 0; + font-size: var(--text-title3); + letter-spacing: -0.02em; +} diff --git a/web/src/features/guides/GuidesPage.tsx b/web/src/features/guides/GuidesPage.tsx index 06cdc73..a2fb73b 100644 --- a/web/src/features/guides/GuidesPage.tsx +++ b/web/src/features/guides/GuidesPage.tsx @@ -38,6 +38,7 @@ export function GuidesPage() { const source = sources[0]?.id ?? "central-fed-district"; const origin = window.location.origin; const slug = user?.slug ?? "{slug}"; + const tokenSuffix = token ? `token=${token}` : "token=ts_…"; useEffect(() => { void api @@ -46,10 +47,11 @@ export function GuidesPage() { .catch((err: unknown) => setError(err instanceof Error ? err.message : "Не удалось загрузить источники")); }, []); - const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${source}${token ? `&token=${token}` : "&token=ts_…"}`; - const tilesUrl = `${origin}/u/${slug}/tiles/${source}/{z}/{x}/{y}.pbf?token=${token ?? "ts_…"}`; - const graphUrl = `${origin}/u/${slug}/graph/${source}?token=${token ?? "ts_…"}`; - const graphEdgesUrl = `${origin}/u/${slug}/graph/${source}/edges?bbox=37.5,55.7,37.7,55.8&token=${token ?? "ts_…"}`; + const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${source}&${tokenSuffix}`; + const tilesUrl = `${origin}/u/${slug}/tiles/${source}/{z}/{x}/{y}.pbf?${tokenSuffix}`; + const graphUrl = `${origin}/u/${slug}/graph/${source}?${tokenSuffix}`; + const graphNodesUrl = `${origin}/u/${slug}/graph/${source}/nodes?bbox=37.5,55.7,37.7,55.8&${tokenSuffix}`; + const graphEdgesUrl = `${origin}/u/${slug}/graph/${source}/edges?bbox=37.5,55.7,37.7,55.8&limit=100&${tokenSuffix}`; const html = useMemo( () => ` @@ -79,6 +81,31 @@ const map = new maplibregl.Map({ [styleUrl] ); + const graphFetch = useMemo( + () => `const token = "ts_…"; +const source = "${source}"; +const bbox = "37.5,55.7,37.7,55.8"; // minLon,minLat,maxLon,maxLat, сторона ≤ 2° + +const meta = await fetch(\`/u/${slug}/graph/\${source}?token=\${token}\`).then((r) => r.json()); +// { extractId, nodeCount, edgeCount, bounds, builtAt, links } + +let after = 0; +const edges = []; +for (;;) { + const page = await fetch( + \`/u/${slug}/graph/\${source}/edges?bbox=\${bbox}&after=\${after}&limit=5000&token=\${token}\` + ).then((r) => r.json()); + edges.push(...page.items); + if (page.nextAfter == null) break; + after = page.nextAfter; +} +// page.items[]: { id, fromId, toId, highway, name, oneway, lengthM } +// oneway=false → ребро двустороннее (ездить можно в обе стороны)`, + [slug, source] + ); + + const graphCurl = `curl -s "${graphEdgesUrl}"`; + return (
  • 1. Токен -

    В разделе «Токены» создайте ключ. Он показывается один раз и дальше уходит только в query token= или Bearer.

    +

    + В разделе Токены создайте ключ. Он показывается один раз и дальше уходит только в + query token= или Bearer. +

    {!token ? (
  • - 3. URL + 3. URL карты

    MapLibre просит style JSON. Сервер сам подставит тайлы с тем же токеном.

  • @@ -136,20 +166,31 @@ const map = new maplibregl.Map({
  • 5. Граф дорог

    - После sync рядом с тайлами лежит SQLite-граф (highway=*, рёбра между перекрёстками). Отдаётся только с - токеном. Узлы/рёбра — по bbox (≤ 2°), пагинация after. + На sync из того же PBF собирается SQLite-граф (highway motorway…service): узлы — перекрёстки, + рёбра — сегменты с lengthM и oneway. Смотреть и дергать API — в разделе{" "} + Граф.

  • +

    Карта

    item.id).join(",") || "central-fed-district,volga-fed-district"}${token ? `&token=${token}` : "&token=ts_…"}`} + value={`${origin}/u/${slug}/styles/osm-bright?source=${sources.map((item) => item.id).join(",") || "central-fed-district,volga-fed-district"}&${tokenSuffix}`} /> - - + +

    Граф дорог

    +

    + Только с токеном. Выгрузка всего округа целиком запрещена: всегда указывайте bbox (сторона ≤ 2°), + дальше листайте через after / nextAfter. +

    + + + + +

    HTML

    diff --git a/web/src/features/guides/guides.css b/web/src/features/guides/guides.css index 8271bbb..bedba15 100644 --- a/web/src/features/guides/guides.css +++ b/web/src/features/guides/guides.css @@ -14,6 +14,17 @@ letter-spacing: -0.02em; } +.guides__lead { + margin: 0 var(--gutter) var(--space-4); + color: var(--secondary-label); + font-size: var(--text-subhead); +} + +.guides__lead code { + font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; + font-size: 0.92em; +} + .guide-steps { list-style: none; margin: 0 var(--gutter) var(--space-5); diff --git a/web/src/features/tokens/TokensPage.tsx b/web/src/features/tokens/TokensPage.tsx index 902479e..1021e03 100644 --- a/web/src/features/tokens/TokensPage.tsx +++ b/web/src/features/tokens/TokensPage.tsx @@ -25,7 +25,7 @@ export function TokensPage() {
    diff --git a/web/src/features/usage/DashboardPage.tsx b/web/src/features/usage/DashboardPage.tsx index 7513f17..cfd983e 100644 --- a/web/src/features/usage/DashboardPage.tsx +++ b/web/src/features/usage/DashboardPage.tsx @@ -66,7 +66,8 @@ export function DashboardPage() { />

    - Примеры кода, HTML и живая карта — в разделе Инструкции. + Примеры кода — в Инструкциях. Граф дорог — в разделе{" "} + Граф.