fix(graph): add all roads
This commit is contained in:
+101
-155
@@ -88,73 +88,59 @@ function graphLineId(extractId: string): string {
|
||||
return `${GRAPH_PREFIX}-${extractId}-line`;
|
||||
}
|
||||
|
||||
function attachGraphTiles(map: MapLibreMap, access: Access, sources: SourceItem[]): string | null {
|
||||
if (!map.isStyleLoaded()) {
|
||||
return "Стиль карты ещё грузится — повтори через секунду.";
|
||||
}
|
||||
function readyGraphSources(sources: SourceItem[]): SourceItem[] {
|
||||
return sources.filter((item) => item.graphReady !== false);
|
||||
}
|
||||
|
||||
clearGraphLayers(map);
|
||||
const ready = sources.filter((item) => item.graphReady !== false);
|
||||
function styleWithGraph(style: StyleSpecification, access: Access, extracts: SourceItem[]): StyleSpecification {
|
||||
const ready = readyGraphSources(extracts);
|
||||
if (ready.length === 0) {
|
||||
return "У выбранных округов граф ещё не собран. Синхронизируй extract.";
|
||||
return style;
|
||||
}
|
||||
|
||||
const sources = { ...style.sources };
|
||||
const layers = [...(style.layers ?? [])];
|
||||
for (const item of ready) {
|
||||
const sourceId = graphSourceId(item.id);
|
||||
map.addSource(sourceId, {
|
||||
sources[sourceId] = {
|
||||
type: "vector",
|
||||
tiles: [graphTilesUrl(access, item.id)],
|
||||
minzoom: GRAPH_MIN_ZOOM,
|
||||
maxzoom: GRAPH_MAX_ZOOM
|
||||
});
|
||||
map.addLayer({
|
||||
id: graphCasingId(item.id),
|
||||
type: "line",
|
||||
source: sourceId,
|
||||
"source-layer": "roads",
|
||||
paint: {
|
||||
"line-color": "#1a1208",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 10, 3.2, 14, 6],
|
||||
"line-opacity": 0.85
|
||||
};
|
||||
layers.push(
|
||||
{
|
||||
id: graphCasingId(item.id),
|
||||
type: "line",
|
||||
source: sourceId,
|
||||
"source-layer": "roads",
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: {
|
||||
"line-color": "#1a1208",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 10, 3.2, 14, 6],
|
||||
"line-opacity": 0.85
|
||||
}
|
||||
},
|
||||
{
|
||||
id: graphLineId(item.id),
|
||||
type: "line",
|
||||
source: sourceId,
|
||||
"source-layer": "roads",
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: {
|
||||
"line-color": "#ffb45a",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6],
|
||||
"line-opacity": 1
|
||||
}
|
||||
}
|
||||
});
|
||||
map.addLayer({
|
||||
id: graphLineId(item.id),
|
||||
type: "line",
|
||||
source: sourceId,
|
||||
"source-layer": "roads",
|
||||
paint: {
|
||||
"line-color": "#ffb45a",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6],
|
||||
"line-opacity": 1
|
||||
}
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
return { ...style, sources, layers };
|
||||
}
|
||||
|
||||
function clearGraphLayers(map: MapLibreMap | null): void {
|
||||
if (!map) {
|
||||
return;
|
||||
}
|
||||
|
||||
const style = map.getStyle();
|
||||
if (!style) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const layer of [...(style.layers ?? [])]) {
|
||||
if (layer.id.startsWith(`${GRAPH_PREFIX}-`)) {
|
||||
map.removeLayer(layer.id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const id of Object.keys(style.sources ?? {})) {
|
||||
if (id.startsWith(`${GRAPH_PREFIX}-`)) {
|
||||
map.removeSource(id);
|
||||
}
|
||||
}
|
||||
function isGraphRequestError(message: string): boolean {
|
||||
return message.includes(GRAPH_PREFIX) || /\/graph\/[\w-]+\/\d+\/\d+\/\d+\.pbf/i.test(message);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
@@ -175,10 +161,9 @@ 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<GraphMeta | null>(null);
|
||||
const [graphEnabled, setGraphEnabled] = useState(false);
|
||||
const [graphEnabled, setGraphEnabled] = useState(true);
|
||||
const [access, setAccess] = useState<Access>(() => {
|
||||
const stored = readAccess();
|
||||
persistAccess(stored);
|
||||
@@ -188,16 +173,13 @@ export function App() {
|
||||
const [tokenDraft, setTokenDraft] = useState(access.token);
|
||||
const accessRef = useRef(access);
|
||||
accessRef.current = access;
|
||||
const graphEnabledRef = useRef(graphEnabled);
|
||||
graphEnabledRef.current = graphEnabled;
|
||||
const selectedSourcesRef = useRef<SourceItem[]>([]);
|
||||
const personal = isPersonal(access);
|
||||
|
||||
const selectedSources = sources.filter((item) => selectedSourceIds.includes(item.id));
|
||||
selectedSourcesRef.current = selectedSources;
|
||||
const source = selectedSources[0] ?? sources[0];
|
||||
const graphSources = selectedSources.filter((item) => item.graphReady !== false);
|
||||
const graphSources = readyGraphSources(selectedSources);
|
||||
const graphSource = graphSources[0] ?? selectedSources[0] ?? sources[0];
|
||||
const graphKey = graphEnabled ? graphSources.map((item) => item.id).join(",") : "";
|
||||
|
||||
const updateHud = useCallback((map: MapLibreMap) => {
|
||||
const center = map.getCenter();
|
||||
@@ -254,12 +236,13 @@ export function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}`;
|
||||
const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}|g:${graphKey}`;
|
||||
if (mapRef.current && styleKeyRef.current === styleKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const style = await fetchJson<StyleSpecification>(styleUrl(access, styleName, selectedSourceIds));
|
||||
const baseStyle = await fetchJson<StyleSpecification>(styleUrl(access, styleName, selectedSourceIds));
|
||||
const style = graphEnabled ? styleWithGraph(baseStyle, access, selectedSources) : baseStyle;
|
||||
const hashed = cameraFromHash();
|
||||
const center = hashed ? [hashed.lon, hashed.lat] : (source?.center ?? [37.6173, 55.7558]);
|
||||
const zoom = hashed ? hashed.zoom : 6;
|
||||
@@ -282,38 +265,27 @@ export function App() {
|
||||
map.resize();
|
||||
updateHud(map);
|
||||
syncGotoFromMap(map);
|
||||
if (graphEnabledRef.current) {
|
||||
const err = attachGraphTiles(map, accessRef.current, selectedSourcesRef.current);
|
||||
if (err) {
|
||||
setGraphError(err);
|
||||
}
|
||||
}
|
||||
});
|
||||
map.on("error", (event) => {
|
||||
const message = event.error?.message;
|
||||
if (message) {
|
||||
setBanner(message);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
if (isGraphRequestError(message)) {
|
||||
setGraphError(message);
|
||||
return;
|
||||
}
|
||||
setBanner(message);
|
||||
});
|
||||
mapRef.current = map;
|
||||
} else {
|
||||
mapRef.current.setStyle(style, { diff: false });
|
||||
mapRef.current.once("idle", () => {
|
||||
const current = mapRef.current;
|
||||
if (!current || !graphEnabledRef.current) {
|
||||
return;
|
||||
}
|
||||
const err = attachGraphTiles(current, accessRef.current, selectedSourcesRef.current);
|
||||
if (err) {
|
||||
setGraphError(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
styleKeyRef.current = styleKey;
|
||||
const pending = selectedSources.find((item) => item.status !== "Ready");
|
||||
setBanner(pending ? sourceBanner(pending) : "");
|
||||
}, [access, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]);
|
||||
}, [access, graphEnabled, graphKey, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const [sourceList, syncStatus] = await Promise.all([
|
||||
@@ -351,6 +323,39 @@ export function App() {
|
||||
void loadStyle().catch((err: unknown) => setBanner(err instanceof Error ? err.message : "Ошибка стиля"));
|
||||
}, [loadStyle]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!personal || !graphEnabled) {
|
||||
setGraphMeta(null);
|
||||
return;
|
||||
}
|
||||
const first = graphSources[0];
|
||||
if (!first) {
|
||||
setGraphMeta(null);
|
||||
if (selectedSourceIds.length > 0) {
|
||||
setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
void fetchJson<GraphMeta>(graphMetaUrl(access, first.id))
|
||||
.then((meta) => {
|
||||
if (!cancelled) {
|
||||
setGraphMeta(meta);
|
||||
setGraphError("");
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) {
|
||||
setGraphMeta(null);
|
||||
setGraphError(err instanceof Error ? err.message : "Не удалось прочитать метаданные графа");
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [access, graphEnabled, graphKey, personal, selectedSourceIds.length]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
mapRef.current?.remove();
|
||||
@@ -418,64 +423,6 @@ export function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const clearGraph = () => {
|
||||
graphEnabledRef.current = false;
|
||||
setGraphEnabled(false);
|
||||
clearGraphLayers(mapRef.current);
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
};
|
||||
|
||||
const loadGraph = async () => {
|
||||
if (!personal) {
|
||||
setGraphError("Нужны slug и токен.");
|
||||
return;
|
||||
}
|
||||
const map = mapRef.current;
|
||||
if (!map) {
|
||||
setGraphError("Карта ещё не готова.");
|
||||
return;
|
||||
}
|
||||
if (graphSources.length === 0) {
|
||||
setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract.");
|
||||
return;
|
||||
}
|
||||
|
||||
setGraphLoading(true);
|
||||
setGraphError("");
|
||||
try {
|
||||
const meta = await fetchJson<GraphMeta>(graphMetaUrl(access, graphSources[0].id));
|
||||
const waitStyle = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (map.isStyleLoaded()) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
map.once("idle", () => resolve());
|
||||
});
|
||||
await waitStyle();
|
||||
const err = attachGraphTiles(map, access, selectedSources);
|
||||
if (err) {
|
||||
setGraphError(err);
|
||||
setGraphEnabled(false);
|
||||
graphEnabledRef.current = false;
|
||||
return;
|
||||
}
|
||||
graphEnabledRef.current = true;
|
||||
setGraphEnabled(true);
|
||||
setGraphMeta(meta);
|
||||
setBanner("");
|
||||
} catch (err: unknown) {
|
||||
clearGraphLayers(map);
|
||||
setGraphEnabled(false);
|
||||
graphEnabledRef.current = false;
|
||||
setGraphMeta(null);
|
||||
setGraphError(err instanceof Error ? err.message : "Не удалось подключить тайлы графа");
|
||||
} finally {
|
||||
setGraphLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const mixedStatus = selectedSources.some((item) => item.status === "Failed")
|
||||
? "Failed"
|
||||
: selectedSources.every((item) => item.status === "Ready")
|
||||
@@ -541,7 +488,8 @@ export function App() {
|
||||
const next = { slug: slugDraft.trim(), token: tokenDraft.trim() };
|
||||
persistAccess(next);
|
||||
styleKeyRef.current = null;
|
||||
clearGraph();
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
setAccess(next);
|
||||
}}
|
||||
>
|
||||
@@ -556,7 +504,8 @@ export function App() {
|
||||
setTokenDraft("");
|
||||
persistAccess({ slug: "", token: "" });
|
||||
styleKeyRef.current = null;
|
||||
clearGraph();
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
setAccess({ slug: "", token: "" });
|
||||
}}
|
||||
>
|
||||
@@ -617,27 +566,24 @@ export function App() {
|
||||
<summary>Граф дорог</summary>
|
||||
<div className="graph-panel">
|
||||
<p className="graph-panel__hint">
|
||||
Векторные тайлы <code>graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code>
|
||||
Тайлы <code>/graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code> вшиты в стиль как vector source,
|
||||
слой <code>roads</code>, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}
|
||||
{graphSources.length > 0
|
||||
? ` — ${graphSources.map((item) => `«${item.name}»`).join(", ")}`
|
||||
: graphSource
|
||||
? ` («${graphSource.name}»)`
|
||||
: ""}
|
||||
. Слой <code>roads</code>, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}. Оранжевые линии поверх OSM.
|
||||
. Оранжевые линии поверх OSM.
|
||||
</p>
|
||||
<div className="graph-panel__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--accent"
|
||||
disabled={graphLoading || !personal || graphEnabled}
|
||||
onClick={() => void loadGraph()}
|
||||
>
|
||||
{graphLoading ? "Подключение…" : "Показать граф"}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={!graphEnabled} onClick={clearGraph}>
|
||||
Снять слой
|
||||
</button>
|
||||
</div>
|
||||
<label className="graph-panel__toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={graphEnabled}
|
||||
disabled={!personal}
|
||||
onChange={(e) => setGraphEnabled(e.target.checked)}
|
||||
/>
|
||||
Показывать тайлы графа
|
||||
</label>
|
||||
{graphError ? <p className="error">{graphError}</p> : null}
|
||||
{graphMeta ? (
|
||||
<dl>
|
||||
|
||||
+22
-3
@@ -76,16 +76,35 @@ export function graphTilesUrl(access: Access, sourceId: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
const TILE_PLACEHOLDERS: Record<string, string> = {
|
||||
"{z}": "__TS_Z__",
|
||||
"{x}": "__TS_X__",
|
||||
"{y}": "__TS_Y__"
|
||||
};
|
||||
|
||||
export function rewriteServiceUrl(url: string, access: Access): string {
|
||||
const resolved = new URL(url, `${API_ORIGIN}/`);
|
||||
let masked = url;
|
||||
for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) {
|
||||
masked = masked.replaceAll(token, sentinel);
|
||||
}
|
||||
|
||||
const resolved = new URL(masked, `${API_ORIGIN}/`);
|
||||
const isService = resolved.pathname.startsWith("/u/") || resolved.pathname.startsWith("/api/");
|
||||
if (!isService) {
|
||||
return resolved.href;
|
||||
return restoreTilePlaceholders(resolved.href);
|
||||
}
|
||||
|
||||
if (isPersonal(access) && resolved.pathname.startsWith("/u/") && !resolved.searchParams.has("token")) {
|
||||
resolved.searchParams.set("token", access.token);
|
||||
}
|
||||
|
||||
return `${API_ORIGIN}${resolved.pathname}${resolved.search}`;
|
||||
return restoreTilePlaceholders(`${API_ORIGIN}${resolved.pathname}${resolved.search}`);
|
||||
}
|
||||
|
||||
function restoreTilePlaceholders(url: string): string {
|
||||
let restored = url;
|
||||
for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) {
|
||||
restored = restored.replaceAll(sentinel, token);
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
+12
-3
@@ -364,10 +364,19 @@ button:disabled { opacity: 0.55; cursor: wait; }
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.graph-panel__actions {
|
||||
.graph-panel__toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
font-size: 0.86rem;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.graph-panel__toggle input {
|
||||
width: 1.05rem;
|
||||
height: 1.05rem;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.graph-panel__bbox {
|
||||
|
||||
Reference in New Issue
Block a user