diff --git a/context/2026-09-21_12-45-00_web-demo-graph.md b/context/2026-09-21_12-45-00_web-demo-graph.md new file mode 100644 index 0000000..02f7644 --- /dev/null +++ b/context/2026-09-21_12-45-00_web-demo-graph.md @@ -0,0 +1,3 @@ +# web-demo: проверка графа + +Панель «Граф дорог»: bbox из viewport (≤ 2°), meta/nodes/edges по токену, оранжевый GeoJSON-слой на карте. В чекбоксах округов пометка «нет графа». Починен пропавший `formatStatus`. diff --git a/context/2026-09-21_13-20-00_demo-graph-coords.md b/context/2026-09-21_13-20-00_demo-graph-coords.md new file mode 100644 index 0000000..7795dc9 --- /dev/null +++ b/context/2026-09-21_13-20-00_demo-graph-coords.md @@ -0,0 +1,5 @@ +# web-demo: граф не рисовался + +Узлы и рёбра пагинировались отдельно (LIMIT 5000 по разным id) — join на клиенте давал 0 LineString при ненулевом ответе API. + +Фикс: edges отдают fromLon/fromLat/toLon/toLat. Демо рисует по координатам рёбра, слой поверх стиля, счётчик «нарисовано». Нужен деплой API. diff --git a/src/TileServer.Domain/Graph/RoadGraphModels.cs b/src/TileServer.Domain/Graph/RoadGraphModels.cs index fd7607a..60f9ea3 100644 --- a/src/TileServer.Domain/Graph/RoadGraphModels.cs +++ b/src/TileServer.Domain/Graph/RoadGraphModels.cs @@ -18,6 +18,10 @@ public sealed record RoadGraphEdge( string Highway, string? Name, bool Oneway, - double LengthM); + double LengthM, + double FromLon, + double FromLat, + double ToLon, + double ToLat); public sealed record RoadGraphPage(IReadOnlyList Items, long? NextAfter); diff --git a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs index 924d574..b8d5e23 100644 --- a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs +++ b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs @@ -129,7 +129,8 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger(items, next); diff --git a/web-demo/src/App.tsx b/web-demo/src/App.tsx index 5587091..d0f619e 100644 --- a/web-demo/src/App.tsx +++ b/web-demo/src/App.tsx @@ -3,6 +3,9 @@ import maplibregl, { type Map as MapLibreMap, type StyleSpecification } from "ma import "maplibre-gl/dist/maplibre-gl.css"; import { API_ORIGIN, + graphEdgesUrl, + graphMetaUrl, + graphNodesUrl, isPersonal, persistAccess, readAccess, @@ -12,7 +15,16 @@ import { stylesListUrl, type Access } from "./access"; -import { fetchJson, type SourceItem, type StyleItem, type SyncStatus } from "./api"; +import { + fetchJson, + type GraphEdge, + type GraphMeta, + type GraphNode, + type GraphPage, + type SourceItem, + type StyleItem, + type SyncStatus +} from "./api"; const STATUS_LABELS: Record = { Pending: "ожидание", @@ -23,6 +35,15 @@ const STATUS_LABELS: Record = { Failed: "ошибка" }; +const GRAPH_SOURCE = "demo-road-graph"; +const GRAPH_LAYER = "demo-road-graph-line"; +const GRAPH_CASING = "demo-road-graph-casing"; +const MAX_BBOX_SPAN = 2; + +function formatStatus(value?: string): string { + return STATUS_LABELS[value ?? ""] ?? value ?? "—"; +} + function sourceBanner(item: SourceItem): string { if (item.status === "Failed") { const detail = item.lastError?.trim(); @@ -37,6 +58,10 @@ function formatDate(value?: string | null): string { return value ? new Date(value).toLocaleString("ru-RU") : "нет"; } +function formatNumber(value: number): string { + return value.toLocaleString("ru-RU"); +} + function parseNumber(value: string): number | null { const parsed = Number(value.trim().replace(",", ".")); return Number.isFinite(parsed) ? parsed : null; @@ -56,6 +81,125 @@ function cameraFromHash(): { zoom: number; lat: number; lon: number } | null { return { zoom, lat, lon }; } +/** Clamp map viewport to API max span (2°) around center. */ +function bboxFromMap(map: MapLibreMap): string { + const bounds = map.getBounds(); + const center = map.getCenter(); + let west = bounds.getWest(); + let east = bounds.getEast(); + let south = bounds.getSouth(); + let north = bounds.getNorth(); + if (east - west > MAX_BBOX_SPAN) { + const half = MAX_BBOX_SPAN / 2; + west = center.lng - half; + east = center.lng + half; + } + if (north - south > MAX_BBOX_SPAN) { + const half = MAX_BBOX_SPAN / 2; + south = center.lat - half; + north = center.lat + half; + } + return `${west.toFixed(5)},${south.toFixed(5)},${east.toFixed(5)},${north.toFixed(5)}`; +} + +function edgesToGeoJson(nodes: GraphNode[], edges: GraphEdge[]): GeoJSON.FeatureCollection { + const byId = new Map(nodes.map((node) => [node.id, node])); + const features: GeoJSON.Feature[] = []; + for (const edge of edges) { + const from = hasCoords(edge.fromLon, edge.fromLat) + ? { lon: edge.fromLon as number, lat: edge.fromLat as number } + : byId.get(edge.fromId); + const to = hasCoords(edge.toLon, edge.toLat) + ? { lon: edge.toLon as number, lat: edge.toLat as number } + : byId.get(edge.toId); + if (!from || !to) { + continue; + } + features.push({ + type: "Feature", + properties: { + id: edge.id, + highway: edge.highway, + name: edge.name ?? "", + oneway: edge.oneway, + lengthM: edge.lengthM + }, + geometry: { + type: "LineString", + coordinates: [ + [from.lon, from.lat], + [to.lon, to.lat] + ] + } + }); + } + return { type: "FeatureCollection", features }; +} + +function hasCoords(lon?: number, lat?: number): boolean { + return Number.isFinite(lon) && Number.isFinite(lat); +} + +function ensureGraphLayers(map: MapLibreMap, data: GeoJSON.FeatureCollection): void { + const paint = () => { + if (map.loaded() === false || !map.isStyleLoaded()) { + map.once("idle", paint); + return; + } + + const existing = map.getSource(GRAPH_SOURCE) as maplibregl.GeoJSONSource | undefined; + if (existing) { + existing.setData(data); + } else { + map.addSource(GRAPH_SOURCE, { type: "geojson", data }); + map.addLayer({ + id: GRAPH_CASING, + type: "line", + source: GRAPH_SOURCE, + paint: { + "line-color": "#1a1208", + "line-width": 5.5, + "line-opacity": 0.85 + } + }); + map.addLayer({ + id: GRAPH_LAYER, + type: "line", + source: GRAPH_SOURCE, + paint: { + "line-color": "#ffb45a", + "line-width": 3.2, + "line-opacity": 1 + } + }); + } + + if (map.getLayer(GRAPH_CASING)) { + map.moveLayer(GRAPH_CASING); + } + if (map.getLayer(GRAPH_LAYER)) { + map.moveLayer(GRAPH_LAYER); + } + }; + + paint(); +} + +function clearGraphLayers(map: MapLibreMap | null): void { + if (!map) { + return; + } + if (map.getLayer(GRAPH_LAYER)) { + map.removeLayer(GRAPH_LAYER); + } + if (map.getLayer(GRAPH_CASING)) { + map.removeLayer(GRAPH_CASING); + } + if (map.getSource(GRAPH_SOURCE)) { + map.removeSource(GRAPH_SOURCE); + } +} + export function App() { const mapEl = useRef(null); const mapRef = useRef(null); @@ -74,6 +218,14 @@ export function App() { const [gotoError, setGotoError] = useState(""); const [banner, setBanner] = useState(""); const [syncing, setSyncing] = useState(false); + const [graphLoading, setGraphLoading] = useState(false); + const [graphError, setGraphError] = useState(""); + const [graphMeta, setGraphMeta] = useState(null); + const [graphEdgeCount, setGraphEdgeCount] = useState(0); + const [graphNodeCount, setGraphNodeCount] = useState(0); + const [graphBbox, setGraphBbox] = useState(""); + const [graphSample, setGraphSample] = useState([]); + const [graphDrawn, setGraphDrawn] = useState(0); const [access, setAccess] = useState(() => { const stored = readAccess(); persistAccess(stored); @@ -87,6 +239,8 @@ export function App() { const selectedSources = sources.filter((item) => selectedSourceIds.includes(item.id)); const source = selectedSources[0] ?? sources[0]; + const graphSource = + selectedSources.find((item) => item.graphReady !== false) ?? selectedSources[0] ?? sources[0]; const updateHud = useCallback((map: MapLibreMap) => { const center = map.getCenter(); @@ -180,7 +334,14 @@ export function App() { }); mapRef.current = map; } else { + clearGraphLayers(mapRef.current); mapRef.current.setStyle(style, { diff: false }); + setGraphMeta(null); + setGraphEdgeCount(0); + setGraphNodeCount(0); + setGraphSample([]); + setGraphDrawn(0); + setGraphBbox(""); } styleKeyRef.current = styleKey; @@ -291,6 +452,70 @@ export function App() { } }; + const clearGraph = () => { + clearGraphLayers(mapRef.current); + setGraphMeta(null); + setGraphEdgeCount(0); + setGraphNodeCount(0); + setGraphSample([]); + setGraphDrawn(0); + setGraphBbox(""); + setGraphError(""); + }; + + const loadGraph = async () => { + if (!personal) { + setGraphError("Нужны slug и токен."); + return; + } + const map = mapRef.current; + if (!map || !graphSource) { + setGraphError("Карта или источник ещё не готовы."); + return; + } + if (graphSource.graphReady === false) { + setGraphError(`Граф «${graphSource.name}» ещё не собран. Синхронизируй extract.`); + return; + } + + const bbox = bboxFromMap(map); + setGraphLoading(true); + setGraphError(""); + try { + const [meta, nodesPage, edgesPage] = await Promise.all([ + fetchJson(graphMetaUrl(access, graphSource.id)), + fetchJson>(graphNodesUrl(access, graphSource.id, bbox, 0, 5000)), + fetchJson>(graphEdgesUrl(access, graphSource.id, bbox, 0, 5000)) + ]); + const nodes = nodesPage.items ?? []; + const edges = edgesPage.items ?? []; + const geo = edgesToGeoJson(nodes, edges); + ensureGraphLayers(map, geo); + setGraphMeta(meta); + setGraphNodeCount(nodes.length); + setGraphEdgeCount(edges.length); + setGraphDrawn(geo.features.length); + setGraphSample(edges.slice(0, 8)); + setGraphBbox(bbox); + setBanner(""); + if (edges.length === 0) { + setGraphError("В этом кадре API вернул 0 рёбер. Приблизь карту (зум 13+, Москва) или собери граф через sync."); + } else if (geo.features.length === 0) { + setGraphError( + "Рёбра есть, но без координат на карте. Задеплой API: edges должны отдавать fromLon/fromLat/toLon/toLat." + ); + } + } catch (err: unknown) { + clearGraphLayers(map); + setGraphMeta(null); + setGraphSample([]); + setGraphDrawn(0); + setGraphError(err instanceof Error ? err.message : "Не удалось загрузить граф"); + } finally { + setGraphLoading(false); + } + }; + const mixedStatus = selectedSources.some((item) => item.status === "Failed") ? "Failed" : selectedSources.every((item) => item.status === "Ready") @@ -356,6 +581,7 @@ export function App() { const next = { slug: slugDraft.trim(), token: tokenDraft.trim() }; persistAccess(next); styleKeyRef.current = null; + clearGraph(); setAccess(next); }} > @@ -370,6 +596,7 @@ export function App() { setTokenDraft(""); persistAccess({ slug: "", token: "" }); styleKeyRef.current = null; + clearGraph(); setAccess({ slug: "", token: "" }); }} > @@ -383,7 +610,7 @@ export function App() { {sources.map((item) => { const checked = selectedSourceIds.includes(item.id); return ( -