Merge remote-tracking branch 'liketrek/dev' into resolve/native-apps

# Conflicts:
#	client/scripts/size-baseline.json
#	client/src/components/Planner/useTripExport.ts
#	client/src/components/Settings/AboutTab.tsx
#	client/src/components/Settings/useAccountSettings.ts
This commit is contained in:
Maurice
2026-11-05 13:07:08 +01:00
1732 changed files with 75060 additions and 7223 deletions
@@ -1,8 +1,10 @@
import L from 'leaflet';
import { useCallback, useEffect } from 'react';
import { useMap } from 'react-leaflet';
import { frameLng } from '../../utils/lngFrame';
import { MAX_ZOOM_RASTER, type ViewportPadding } from '../../utils/mapViewport';
import { ASSISTANT_CAMERA_MS, centreOf, coverPadding, useCameraRequest, useUserMoveClock } from './assistantCamera';
import { useLngFrame } from './lngFrameContext';
import type { AssistantCamera } from './mapViewContract';
interface AssistantCameraControllerProps {
@@ -18,12 +20,17 @@ interface AssistantCameraControllerProps {
*/
export function AssistantCameraController({ camera, padding }: AssistantCameraControllerProps) {
const map = useMap();
// The points are framed the way the map draws them (#2975).
const frame = useLngFrame();
const getContainer = useCallback(() => map.getContainer(), [map]);
const userMovedAt = useUserMoveClock(getContainer, true);
const request = useCameraRequest(camera, userMovedAt);
useEffect(() => {
request((next) => {
request((camera) => {
const next = frame
? { ...camera, points: camera.points.map(([lat, lng]) => [lat, frameLng(frame, lng)] as [number, number]) }
: camera;
const duration = ASSISTANT_CAMERA_MS / 1000;
if (next.mode === 'pan') {
const centre = centreOf(next.points);
@@ -39,7 +46,7 @@ export function AssistantCameraController({ camera, padding }: AssistantCameraCo
duration,
});
});
}, [map, padding, request]);
}, [map, padding, request, frame]);
return null;
}
@@ -1,7 +1,9 @@
import L from 'leaflet';
import { useEffect, useLayoutEffect, useRef } from 'react';
import { useMap } from 'react-leaflet';
import { frameLng } from '../../utils/lngFrame';
import { GHOST_SIZE, mountGhosts, setGhostHot, type GhostHandlers } from './assistantGhostMarker';
import { useLngFrame } from './lngFrameContext';
import type { AssistantGhost } from './mapViewContract';
interface AssistantGhostLayerProps {
@@ -22,6 +24,8 @@ const GHOST_Z_OFFSET = 900;
*/
export function AssistantGhostLayer({ ghosts, hoveredId, onHover, onClick }: AssistantGhostLayerProps) {
const map = useMap();
// Pinned where the map draws the trip, in its longitude frame (#2975).
const frame = useLngFrame();
const handlers = useRef<GhostHandlers>({ onHover, onClick });
useLayoutEffect(() => {
handlers.current = { onHover, onClick };
@@ -36,7 +40,11 @@ export function AssistantGhostLayer({ ghosts, hoveredId, onHover, onClick }: Ass
const icon = L.divIcon({ html: el, className: 'trek-ghost-pin', iconSize: [GHOST_SIZE, GHOST_SIZE] });
const label = document.createElement('span');
label.textContent = ghost.name;
const marker = L.marker([ghost.lat, ghost.lng], { icon, keyboard: false, zIndexOffset: GHOST_Z_OFFSET })
const marker = L.marker([ghost.lat, frameLng(frame, ghost.lng)], {
icon,
keyboard: false,
zIndexOffset: GHOST_Z_OFFSET,
})
.bindTooltip(label, { direction: 'top', offset: [0, -GHOST_SIZE / 2], className: 'map-tooltip' })
.addTo(map);
return { remove: () => marker.remove() };
@@ -48,7 +56,7 @@ export function AssistantGhostLayer({ ghosts, hoveredId, onHover, onClick }: Ass
mounted.dispose();
elements.current = new Map();
};
}, [ghosts, map]);
}, [ghosts, map, frame]);
useEffect(() => {
setGhostHot(elements.current, hoveredId);
@@ -1,8 +1,11 @@
import type { FeatureGroup as LeafletFeatureGroup, LeafletMouseEvent } from 'leaflet';
import { useEffect, useRef } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import { CircleMarker, FeatureGroup, Polyline, Tooltip } from 'react-leaflet';
import type { AssistantRouteLine } from '../../types/assistantMap';
import { frameLine, frameLng, type LngFrame } from '../../utils/lngFrame';
import { onRealWorld } from '../../utils/worldCopy';
import { useLngFrame } from './lngFrameContext';
/** A rim under the line, the line, and the invisible fat line that takes the pointer. */
const CASING_WEIGHT = 7;
@@ -38,7 +41,10 @@ function GhostLine({ line, onHover, onPoint }: { line: AssistantRouteLine } & Li
if (line.hot) group.current?.bringToFront();
}, [line.hot]);
const opacity = line.dim ? DIM_OPACITY : 1;
const point = (event: LeafletMouseEvent) => onPoint?.(line.ref, event.latlng.lat, event.latlng.lng);
const point = (event: LeafletMouseEvent) => {
const at = onRealWorld(event.latlng);
onPoint?.(line.ref, at.lat, at.lng);
};
return (
<FeatureGroup ref={group}>
<Polyline
@@ -122,11 +128,25 @@ interface AssistantGhostLineLayerProps extends LineHandlers {
* under its pins. The twin of
* useAssistantGhostLinesGL.
*/
/** A line drawn in the map's longitude frame, with the trip it proposes changes to (#2975). */
function inFrame(frame: LngFrame, line: AssistantRouteLine): AssistantRouteLine {
const at = ([lat, lng]: [number, number]): [number, number] => [lat, frameLng(frame, lng)];
return {
...line,
lines: line.lines.map((part) => frameLine(frame, part)),
ends: line.ends && { start: at(line.ends.start), end: line.ends.end && at(line.ends.end) },
stops: line.stops?.map((stop) => ({ ...stop, lng: frameLng(frame, stop.lng) })),
tints: line.tints?.map((tint) => ({ ...tint, line: frameLine(frame, tint.line) })),
};
}
export function AssistantGhostLineLayer({ lines, onHover, onPoint }: AssistantGhostLineLayerProps) {
if (!lines?.length) return null;
const frame = useLngFrame();
const drawn = useMemo(() => (frame && lines ? lines.map((line) => inFrame(frame, line)) : lines), [frame, lines]);
if (!drawn?.length) return null;
return (
<>
{lines.map((line) => (
{drawn.map((line) => (
<GhostLine key={line.id} line={line} onHover={onHover} onPoint={onPoint} />
))}
</>
+8 -4
View File
@@ -4,11 +4,14 @@ import L from 'leaflet'
import { useTranslation } from '../../i18n/TranslationContext'
import type { Poi } from './poiCategories'
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
pois: Poi[]; enabled: boolean; onPoiClick?: (poi: Poi) => void; children: ReactNode[]
}) {
const map = useMap()
const frame = useLngFrame()
const { t } = useTranslation()
const [zoom, setZoom] = useState(() => map.getZoom())
const popup = useRef<L.Popup | null>(null)
@@ -18,20 +21,21 @@ export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
map.on('zoomend', update)
return () => { map.off('zoomend', update) }
}, [map])
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, poi.lng]), zoom) : [], [pois, enabled, map, zoom])
// Measured and placed where the map draws them, in its longitude frame (#2975).
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, frameLng(frame, poi.lng)]), zoom) : [], [pois, enabled, map, zoom, frame])
const markers = new Map(pois.map((poi, index) => [poi.osm_id, children[index]]))
if (!enabled) return <>{children}</>
return <>{groups.map(group => {
if (group.pois.length === 1) return markers.get(group.pois[0].osm_id)
const label = t('roadtrip.poi.found', { count: group.pois.length })
return <Marker key={`poi-cluster-${group.pois[0].osm_id}`} position={[group.lat, group.lng]} alt={label}
return <Marker key={`poi-cluster-${group.pois[0].osm_id}`} position={[group.lat, frameLng(frame, group.lng)]} alt={label}
icon={L.divIcon({ className: '', html: poiClusterMarkup(group.pois.length), iconSize: [38, 38], iconAnchor: [19, 19] })}
zIndexOffset={600} eventHandlers={{ click: () => {
if (map.getZoom() >= POI_CLUSTER_DETAIL_ZOOM) {
popup.current?.remove()
popup.current = L.popup({ className: 'map-tooltip', maxWidth: 300 }).setLatLng([group.lat, group.lng])
popup.current = L.popup({ className: 'map-tooltip', maxWidth: 300 }).setLatLng([group.lat, frameLng(frame, group.lng)])
.setContent(poiClusterList(group.pois, poi => { popup.current?.remove(); onPoiClick?.(poi) })).openOn(map)
} else map.fitBounds(group.pois.map(poi => [poi.lat, poi.lng] as [number, number]), { padding: [70, 70], maxZoom: POI_CLUSTER_DETAIL_ZOOM })
} else map.fitBounds(group.pois.map(poi => [poi.lat, frameLng(frame, poi.lng)] as [number, number]), { padding: [70, 70], maxZoom: POI_CLUSTER_DETAIL_ZOOM })
} }} />
})}</>
}
@@ -1,5 +1,7 @@
import { useMemo } from 'react'
import { Polyline } from 'react-leaflet'
import { useLngFrame } from './lngFrameContext'
import { frameLine } from '../../utils/lngFrame'
import type { DawarichTrack } from '@trek/shared'
import {
DAWARICH_TRAIL_CASING,
@@ -37,7 +39,10 @@ export default function DawarichTrailLayer({
/** The `trek-track-casing` pane, when the renderer supports panes. */
casingPane?: string
}) {
const segments = useMemo(() => trailSegments(track, selectedDate, hiddenDates), [track, selectedDate, hiddenDates])
const frame = useLngFrame()
// Drawn in the map's longitude frame, with the trip it was recorded on (#2975).
const segments = useMemo(() => trailSegments(track, selectedDate, hiddenDates)
.map(segment => (frame ? { ...segment, points: frameLine(frame, segment.points) } : segment)), [track, selectedDate, hiddenDates, frame])
if (segments.length === 0) return null
return (
+5 -1
View File
@@ -4,10 +4,14 @@ import L from 'leaflet'
import { useTranslation } from '../../i18n/TranslationContext'
import { hazardPopup, hazardFeature } from './hazardPopup'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
export default function HazardLayers({ hazards }: { hazards: RoadtripHazard[] }) {
const { t } = useTranslation()
return <>{hazards.map(hazard => <GeoJSON key={`${hazard.id}-${hazard.updatedAt}`} data={hazardFeature(hazard)}
const frame = useLngFrame()
return <>{hazards.map(hazard => <GeoJSON key={`${hazard.id}-${hazard.updatedAt}-${frame?.seam ?? ''}`} data={hazardFeature(hazard)}
coordsToLatLng={coords => L.latLng(coords[1], frameLng(frame, coords[0]))}
style={{ color: 'var(--warning)', weight: 2, fillOpacity: 0.16 }}
pointToLayer={(_, point) => L.circleMarker(point, { radius: 7, color: 'var(--warning)', fillOpacity: 0.65 })}
onEachFeature={(_, layer) => layer.bindPopup(hazardPopup(hazard, t('roadtrip.hazards.note'), t('roadtrip.hazards.point')), { className: 'map-tooltip trek-hazard-popup', maxWidth: 320 })}
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react'
import { Circle, Polygon, Polyline, Tooltip, useMap } from 'react-leaflet'
import { pluginsApi, type PluginMapLayer, type PluginMapLayerFeature } from '../../api/client'
import { useLngFrame } from './lngFrameContext'
import { frameLine, frameLng } from '../../utils/lngFrame'
/**
* Host-rendered overlay for the `mapLayerProvider` plugin hook. A plugin returns
@@ -47,6 +49,7 @@ function pathOptions(f: PluginMapLayerFeature, pane: string | undefined) {
export function PluginMapLayers({ tripId }: { tripId?: number | string }) {
const map = useMap()
const frame = useLngFrame()
const [layers, setLayers] = useState<PluginMapLayer[]>([])
// Whether our dedicated below-overlay pane exists. Pane support is a Leaflet
// optimization — if the map has no pane API (e.g. a minimal renderer), the
@@ -73,6 +76,7 @@ export function PluginMapLayers({ tripId }: { tripId?: number | string }) {
if (layers.length === 0) return null
const pane = hasPane ? PANE : undefined
// Drawn in the map's longitude frame, with the trip (#2975).
return (
<>
@@ -80,13 +84,13 @@ export function PluginMapLayers({ tripId }: { tripId?: number | string }) {
const key = `${layer.pluginId}:${layer.id}:${i}`
const tooltip = f.label ? <Tooltip sticky>{f.label}</Tooltip> : null
if (f.type === 'polyline' && f.points) {
return <Polyline key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polyline>
return <Polyline key={key} positions={frameLine(frame, f.points)} pathOptions={pathOptions(f, pane)}>{tooltip}</Polyline>
}
if (f.type === 'polygon' && f.points) {
return <Polygon key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polygon>
return <Polygon key={key} positions={frameLine(frame, f.points)} pathOptions={pathOptions(f, pane)}>{tooltip}</Polygon>
}
if (f.type === 'circle' && f.center && f.radiusM) {
return <Circle key={key} center={f.center} radius={f.radiusM} pathOptions={pathOptions(f, pane)}>{tooltip}</Circle>
return <Circle key={key} center={frame ? [f.center[0], frameLng(frame, f.center[1])] : f.center} radius={f.radiusM} pathOptions={pathOptions(f, pane)}>{tooltip}</Circle>
}
return null
}))}
@@ -2,6 +2,8 @@ import { useEffect, useMemo, useState } from 'react'
import { Marker, Popup } from 'react-leaflet'
import L from 'leaflet'
import { pluginsApi, type PluginMapMarker } from '../../api/client'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
/**
* Host-rendered overlay for the `mapMarkerProvider` plugin hook (#587). A plugin
@@ -33,6 +35,8 @@ function markerIcon(tone: PluginMapMarker['tone']): L.DivIcon {
export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
const [markers, setMarkers] = useState<PluginMapMarker[]>([])
// Drawn in the map's longitude frame, with the trip (#2975).
const frame = useLngFrame()
useEffect(() => {
if (tripId == null) { setMarkers([]); return }
@@ -54,7 +58,7 @@ export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
return (
<>
{markers.map(mk => (
<Marker key={`${mk.pluginId}:${mk.id}`} position={[mk.lat, mk.lng]} icon={icons.get(mk.tone)!}>
<Marker key={`${mk.pluginId}:${mk.id}`} position={[mk.lat, frameLng(frame, mk.lng)]} icon={icons.get(mk.tone)!}>
{(mk.label || mk.popupText || mk.url) && (
<Popup>
<div style={{ minWidth: 120, fontSize: 13 }}>
+13 -4
View File
@@ -1185,9 +1185,14 @@ describe('MapView map event wiring', () => {
it('FE-COMP-MAPVIEW-046: a map-click handler is attached and detached again', () => {
const onMapClick = vi.fn()
const { unmount } = render(<MapView onMapClick={onMapClick} />)
expect(mapMock.on).toHaveBeenCalledWith('click', onMapClick)
const bound = mapMock.on.mock.calls.find(c => c[0] === 'click')?.[1]
expect(bound).toEqual(expect.any(Function))
// A click on the real world reaches the caller as the very event the map fired.
const event = { latlng: { lat: 48, lng: 2 } }
bound(event)
expect(onMapClick).toHaveBeenCalledWith(event)
unmount()
expect(mapMock.off).toHaveBeenCalledWith('click', onMapClick)
expect(mapMock.off).toHaveBeenCalledWith('click', bound)
})
it('FE-COMP-MAPVIEW-047: without a click handler nothing is bound', () => {
@@ -1198,9 +1203,13 @@ describe('MapView map event wiring', () => {
it('FE-COMP-MAPVIEW-048: a context-menu handler is attached and detached again', () => {
const onMapContextMenu = vi.fn()
const { unmount } = render(<MapView onMapContextMenu={onMapContextMenu} />)
expect(mapMock.on).toHaveBeenCalledWith('contextmenu', onMapContextMenu)
const bound = mapMock.on.mock.calls.find(c => c[0] === 'contextmenu')?.[1]
expect(bound).toEqual(expect.any(Function))
const event = { latlng: { lat: 48, lng: 2 } }
bound(event)
expect(onMapContextMenu).toHaveBeenCalledWith(event)
unmount()
expect(mapMock.off).toHaveBeenCalledWith('contextmenu', onMapContextMenu)
expect(mapMock.off).toHaveBeenCalledWith('contextmenu', bound)
})
it('FE-COMP-MAPVIEW-049: changing the center prop moves the camera there', () => {
+46 -99
View File
@@ -3,7 +3,7 @@ import DOM from 'react-dom'
import { categoryIconSvg } from './categoryIconSvg'
import { MapContainer, TileLayer, Marker, Polyline, CircleMarker, Circle, useMap, Tooltip } from 'react-leaflet'
import MarkerClusterGroup from 'react-leaflet-cluster'
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
import { makeMarkerDraggable, makePoiDraggable } from './markerDrag'
import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
import RoadtripViaMarkers from './RoadtripViaMarkers'
import PlannerWaypointMarker from './PlannerWaypointMarker'
@@ -121,7 +121,8 @@ function RouteViaMarker({ via, controls, eventHandlers, children }: {
via: RouteVia; controls?: DayBoundaryControls; eventHandlers?: L.LeafletEventHandlerFnMap; children?: React.ReactNode
}) {
const [marker, setMarker] = useState<L.Marker | null>(null)
return <Marker ref={setMarker} position={[via.lat, via.lng]} icon={via.nightPause ? nightPauseIcon(via) : routeViaIcon(via.tone)}
const frame = useLngFrame()
return <Marker ref={setMarker} position={[via.lat, frameLng(frame, via.lng)]} icon={via.nightPause ? nightPauseIcon(via) : routeViaIcon(via.tone)}
alt={via.nightPause ? via.label : undefined} zIndexOffset={800} eventHandlers={eventHandlers}>
{children}
{via.nightPause && <NightPauseDrag marker={marker} via={via} controls={controls} />}
@@ -298,59 +299,6 @@ function CameraHoverGuard({ movingRef, onMoveStart, onZoom }: { movingRef: { cur
return null
}
/**
* Takes a corridor hit dropped anywhere on the map and reports where it landed.
*
* The container rather than the drawn route: a polyline is a real element here but not in
* the GL renderers, and the drop coordinate answers "where on the drive" just as well
* once the caller projects it onto the routed geometry — one behaviour for all three.
*/
function PoiDropTarget({ onPoiDropOnRoute }: { onPoiDropOnRoute?: (osmId: string, lat: number, lng: number) => void }) {
const map = useMap()
useEffect(() => {
if (!onPoiDropOnRoute) return
const container = map.getContainer()
const onDragOver = (e: DragEvent) => {
if (!draggedPoiId(e)) return
e.preventDefault()
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'
}
const onDrop = (e: DragEvent) => {
const osmId = draggedPoiId(e)
if (!osmId) return
e.preventDefault()
const rect = container.getBoundingClientRect()
const at = map.containerPointToLatLng([e.clientX - rect.left, e.clientY - rect.top])
onPoiDropOnRoute(osmId, at.lat, at.lng)
}
container.addEventListener('dragover', onDragOver)
container.addEventListener('drop', onDrop)
return () => {
container.removeEventListener('dragover', onDragOver)
container.removeEventListener('drop', onDrop)
}
}, [map, onPoiDropOnRoute])
return null
}
// Emits the current viewport bbox on pan/zoom so the POI-explore pill can fetch
// OSM places for the visible area, with the zoom an overlay's minimum is read against.
function ViewportController({ onViewportChange }: { onViewportChange?: MapViewProps['onViewportChange'] }) {
const map = useMap()
useEffect(() => {
if (!onViewportChange) return
const emit = () => {
const b = map.getBounds()
onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() }, map.getZoom())
}
map.whenReady(emit) // ensure the first bbox is captured once the map is laid out
map.on('moveend', emit)
map.on('zoomend', emit)
return () => { map.off('moveend', emit); map.off('zoomend', emit) }
}, [map, onViewportChange])
return null
}
function MapCameraSnapshot({ onChange }: { onChange: (center: [number, number], zoom: number) => void }) {
const map = useMap()
useEffect(() => {
@@ -377,6 +325,7 @@ interface SelectionControllerProps {
function SelectionController({ follow, places, selectedPlaceId, dayPlaces, selectedPlace, paddingOpts }: SelectionControllerProps) {
const map = useMap()
const frame = useLngFrame()
const prev = useRef(null)
useEffect(() => {
@@ -387,7 +336,7 @@ function SelectionController({ follow, places, selectedPlaceId, dayPlaces, selec
// would cover it). Reuses the same paddingOpts the fit-bounds path uses.
const selected = selectedPlaceTarget(selectedPlaceId, places, dayPlaces, selectedPlace)
if (selected?.lat != null && selected?.lng != null) {
const latlng: [number, number] = [selected.lat, selected.lng]
const latlng: [number, number] = [selected.lat, frameLng(frame, selected.lng)]
const tl = paddingOpts.paddingTopLeft as [number, number] | undefined
const br = paddingOpts.paddingBottomRight as [number, number] | undefined
if (tl && br && typeof map.project === 'function' && typeof map.unproject === 'function') {
@@ -399,7 +348,7 @@ function SelectionController({ follow, places, selectedPlaceId, dayPlaces, selec
}
}
prev.current = selectedPlaceId
}, [selectedPlaceId, places, dayPlaces, selectedPlace, map, follow])
}, [selectedPlaceId, places, dayPlaces, selectedPlace, map, follow, frame])
return null
}
@@ -411,14 +360,15 @@ interface MapControllerProps {
function MapController({ center, zoom }: MapControllerProps) {
const map = useMap()
const frame = useLngFrame()
const prevCenter = useRef(center)
useEffect(() => {
if (prevCenter.current[0] !== center[0] || prevCenter.current[1] !== center[1]) {
map.setView(center, zoom)
map.setView([center[0], frameLng(frame, center[1])], zoom)
prevCenter.current = center
}
}, [center, zoom, map])
}, [center, zoom, map, frame])
return null
}
@@ -456,10 +406,12 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
const prevFocusKey = useRef(focusKey)
const built = useRef(false)
const frame = useLngFrame()
const fitTo = useCallback((coords: [number, number][], padding: L.FitBoundsOptions = paddingOpts) => {
if (coords.length === 0) return
try {
const bounds = L.latLngBounds(coords)
// In the map's longitude frame, so a trip across the Pacific is framed across the Pacific (#2975).
const bounds = L.latLngBounds(frame ? coords.map(([lat, lng]) => [lat, frameLng(frame, lng)] as [number, number]) : coords)
if (bounds.isValid()) {
/*
* The padding already reserves the day panel's height at the bottom
@@ -478,7 +430,7 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
map.fitBounds(bounds, { maxZoom: 16, animate: true, ...padding })
}
} catch {}
}, [map, paddingOpts])
}, [map, paddingOpts, frame])
// New fitKey (initial trip fit or a day selection): fit to the destinations now
// and arm a one-shot re-fit for when the route arrives.
@@ -535,10 +487,6 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
return null
}
interface MapClickHandlerProps {
onClick: ((e: L.LeafletMouseEvent) => void) | null
}
const TRACK_CASING_PANE = 'trek-track-casing'
/**
@@ -561,26 +509,6 @@ function TrackCasingPane({ onReady }: { onReady: (ready: boolean) => void }) {
return null
}
function MapClickHandler({ onClick }: MapClickHandlerProps) {
const map = useMap()
useEffect(() => {
if (!onClick) return
map.on('click', onClick)
return () => { map.off('click', onClick) }
}, [map, onClick])
return null
}
function MapContextMenuHandler({ onContextMenu }: { onContextMenu: ((e: L.LeafletMouseEvent) => void) | null }) {
const map = useMap()
useEffect(() => {
if (!onContextMenu) return
map.on('contextmenu', onContextMenu)
return () => { map.off('contextmenu', onContextMenu) }
}, [map, onContextMenu])
return null
}
// Travel times are shown in the day sidebar (per-segment connectors), not on the map.
import { useMarkerThumbs } from './useMarkerThumbs'
@@ -594,9 +522,15 @@ import { useIsPhone } from '../../mobile/useIsPhone'
// identically. Heading is shown as a rotated conic SVG when available.
import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation'
import { selectedPlaceTarget } from './selectedPlaceTarget'
import { LngFrameProvider, useLngFrame, useTripLngFrame } from './lngFrameContext'
import { frameLine, frameLng } from '../../utils/lngFrame'
import { LngFrameFollower, MapClickHandler, MapContextMenuHandler, PoiDropTarget, ViewportController } from './leafletMapBridges'
function LeafletLocationLayer({ position, mode }: { position: GeoPosition | null; mode: TrackingMode }) {
function LeafletLocationLayer({ position: fix, mode }: { position: GeoPosition | null; mode: TrackingMode }) {
const map = useMap()
const frame = useLngFrame()
// Drawn on the trip's world copy (#2975); every field but the longitude is the fix itself.
const position = useMemo(() => (fix && frame ? { ...fix, lng: frameLng(frame, fix.lng) } : fix), [fix, frame])
// When the user is in follow mode, keep the map centred on the dot.
// setView (no animation) is what Google Maps does during navigation —
@@ -711,7 +645,8 @@ const MemoMarker = memo(function MemoMarker({
// differs, and the cluster group answers a moved child by taking it out and putting
// it back — which collapses an open fan. A fresh array literal here did that on
// every render the marker took part in.
const position = useMemo<[number, number]>(() => [place.lat, place.lng], [place.lat, place.lng])
const frame = useLngFrame()
const position = useMemo<[number, number]>(() => [place.lat, frameLng(frame, place.lng)], [place.lat, place.lng, frame])
const register = useCallback((marker: unknown) => { onRegister(place.id, marker) }, [onRegister, place.id])
return (
<Marker
@@ -835,11 +770,15 @@ export const MapView = memo(function MapView({
*/
const isGcjBasemap = !tourRaster && basemap.kind === 'raster' && isGcj02Basemap(basemap.url)
const gcjCrs = useMemo(() => crsForBasemap(isGcjBasemap), [isGcjBasemap])
// Leaflet draws a layer on one world copy only, so a trip across the antimeridian is
// drawn in a longitude frame that keeps it on one copy (#2975). Null for every other
// trip, and then each layer below draws exactly what it always drew.
const lngFrame = useTripLngFrame(places, dayPlaces, reservations)
const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => (
<Marker
key={`poi-${poi.osm_id}`}
alt={poi.name}
position={[poi.lat, poi.lng]}
position={[poi.lat, frameLng(lngFrame, poi.lng)]}
icon={createPoiIcon(poi, poi.brand_wikidata)}
zIndexOffset={500}
eventHandlers={{
@@ -858,7 +797,7 @@ export const MapView = memo(function MapView({
>
<Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip"><PoiTooltipBody poi={poi} /></Tooltip>
</Marker>
)), [pois, onPoiClick, onPoiDropOnRoute])
)), [pois, onPoiClick, onPoiDropOnRoute, lngFrame])
const visibleReservations = useMemo(() => (
visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay })
), [reservations, visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay])
@@ -892,8 +831,11 @@ export const MapView = memo(function MapView({
const framed = computeMapViewport(dayPlaces.length > 0 ? dayPlaces : places, {
tileSize: TILE_SIZE_RASTER,
padding: paddingBox,
// With a longitude frame the trip lies on one copy, so it can be framed the short way.
wrapsWorld: lngFrame !== null,
})
return { center: framed?.center ?? center, zoom: framed?.zoom ?? zoom, framed: framed !== null }
const opening: [number, number] | undefined = framed ? [framed.center[0], frameLng(lngFrame, framed.center[1])] : undefined
return { center: opening ?? center, zoom: framed?.zoom ?? zoom, framed: framed !== null }
})
const cameraSnapshotRef = useRef<{ center: [number, number]; zoom: number } | null>(null)
const saveCameraSnapshot = useCallback((cameraCenter: [number, number], cameraZoom: number) => {
@@ -947,7 +889,8 @@ export const MapView = memo(function MapView({
// Flattened [lat,lng] points of the selected day's route, so the bounds fit can
// include the full polyline once it has been computed.
const routeCoords = useMemo<[number, number][]>(() => (route || []).flat() as [number, number][], [route])
const framedRoute = useMemo(() => (lngFrame && route ? route.map(seg => frameLine(lngFrame, seg)) : route), [route, lngFrame])
const routeCoords = useMemo<[number, number][]>(() => (framedRoute || []).flat() as [number, number][], [framedRoute])
const photoUrls = useMarkerThumbs(places)
const isTouchDevice = typeof window !== 'undefined' && navigator.maxTouchPoints > 0
@@ -1015,9 +958,9 @@ export const MapView = memo(function MapView({
const gpxTracks = useMemo(() => places.flatMap(place => {
const geometry = parseRenderableRouteGeometry(place.route_geometry)
if (!geometry) return []
const coords: [number, number][] = geometry.map(([lat, lng]) => [lat, lng])
const coords: [number, number][] = frameLine(lngFrame, geometry.map(([lat, lng]) => [lat, lng] as [number, number]))
return [{ place, coords, cased: hasManualTrackColor(place), color: resolveTrackColor(place) }]
}), [places])
}), [places, lngFrame])
// Keeps the click handler out of the track lines' memo (TrackLines): `handleMarkerClick`
// changes on every selection, and depending on it would redraw all tracks.
@@ -1053,6 +996,7 @@ export const MapView = memo(function MapView({
return (
<>
<div className="w-full h-full relative">
<LngFrameProvider value={lngFrame}>
<MapContainer
// The datum is in the element's identity, because react-leaflet builds the
// map once and Leaflet cannot change a CRS afterwards. Settings can arrive
@@ -1125,6 +1069,8 @@ export const MapView = memo(function MapView({
/>
)}
{/* First, so a fit or a camera request in the same commit starts from the trip's world copy. */}
<LngFrameFollower />
<MapController center={center} zoom={zoom} />
{hasViewBaseLayer && <MapCameraSnapshot onChange={saveCameraSnapshot} />}
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} />
@@ -1142,7 +1088,7 @@ export const MapView = memo(function MapView({
{/* Apple-Maps style: darker-blue casing under a bright-blue core, rounded.
When the route can be reshaped an invisible band wider than both takes the click. */}
{route && route.length > 0 && route.flatMap((seg, i) => seg.length < 2 ? [] : routeWalking?.[i] ? [
{framedRoute && framedRoute.length > 0 && framedRoute.flatMap((seg, i) => seg.length < 2 ? [] : routeWalking?.[i] ? [
// Walked, so dashed and without the casing: the drive is the solid line (#2532).
<Polyline
key={`${i}-walk`}
@@ -1174,7 +1120,7 @@ export const MapView = memo(function MapView({
{(accessLines ?? []).map((spur, i) => (
<Polyline
key={`access-${i}`}
positions={spur.line}
positions={frameLine(lngFrame, spur.line)}
pathOptions={{ color: '#0a84ff', weight: 3, opacity: 0.85, dashArray: '2 7', lineCap: 'round' }}
interactive={false}
/>
@@ -1190,13 +1136,13 @@ export const MapView = memo(function MapView({
return [
<Polyline
key={`alt-${alt.index}-casing`}
positions={alt.coordinates}
positions={frameLine(lngFrame, alt.coordinates)}
pathOptions={{ color: ALT_CASING, weight: active ? 9 : 8, opacity: 0.9, lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>,
<Polyline
key={`alt-${alt.index}`}
positions={alt.coordinates}
positions={frameLine(lngFrame, alt.coordinates)}
pathOptions={{
color: alt.color,
weight: active ? 6 : 4,
@@ -1213,7 +1159,7 @@ export const MapView = memo(function MapView({
// The drive time on the road itself, the way Apple labels them.
<Marker
key={`alt-${alt.index}-label`}
position={[alt.at.lat, alt.at.lng]}
position={[alt.at.lat, frameLng(lngFrame, alt.at.lng)]}
zIndexOffset={600}
icon={alternativeLabelIcon(alt.label, alt.note, alt.labelBg, active)}
eventHandlers={onChooseAlternative ? {
@@ -1249,7 +1195,7 @@ export const MapView = memo(function MapView({
{routeProfileFocus && (
<CircleMarker
center={[routeProfileFocus.lat, routeProfileFocus.lng]}
center={[routeProfileFocus.lat, frameLng(lngFrame, routeProfileFocus.lng)]}
radius={8}
pathOptions={{ className: 'tour-profile-focus-marker', color: 'var(--bg-card)', weight: 3, fillColor: 'var(--text-muted)', fillOpacity: 1 }}
interactive={false}
@@ -1301,6 +1247,7 @@ export const MapView = memo(function MapView({
<AssistantMapLeaflet assistant={assistant} padding={paddingBox} markerEl={assistantMarkerEl} />
<PluginMapLayers tripId={tripId} />
</MapContainer>
</LngFrameProvider>
{isMobile && <LocationButton
mode={trackingMode}
error={trackingError}
+29 -122
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useMemo, useState, useCallback } from 'react'
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
import { makeMarkerDraggable, makePoiDraggable } from './markerDrag'
import { useStableVias } from './viaMarkerState'
import { usePlannerWaypointMarkersGL } from './usePlannerWaypointMarkersGL'
import { carryAssistantMarks, useAssistantMapGL } from './useAssistantMapGL'
@@ -49,17 +49,13 @@ import { buildPoiPopupHtml } from './placePopup'
import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client'
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
import { onRealWorld } from '../../utils/worldCopy'
import { bindPoiDropTarget } from './poiDropTarget'
import { selectedPlaceTarget } from './selectedPlaceTarget'
import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers'
// Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich
// HTML photo markers *and* cluster them natively, so we feed the place points
// into a clustered GeoJSON source. The cluster bubbles render as GL circles +
// a count label; the individual rich HTML markers are then only drawn for the
// points the source reports as currently unclustered. Grouping is always on,
// matching the Leaflet map's MarkerClusterGroup.
const PLACE_CLUSTER_SOURCE_ID = 'trip-place-clusters'
const PLACE_UNCLUSTERED_LAYER_ID = 'trip-place-unclustered-hit'
import {
PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID, PLACE_CLUSTER_SOURCE_ID,
addPlaceClusterLayers, drawClusterBubbles, expandCluster,
} from './placeClusterLayers'
type PlaceWithCoords = Place & { lat: number; lng: number }
@@ -112,72 +108,6 @@ interface Props extends MapViewProps {
gl: any
}
/**
* How eagerly place markers merge into a cluster.
*
* The overview band the Leaflet map clusters in as well (`CLUSTER_UNTIL_ZOOM` there),
* kept as plain numbers rather than shared constants so the GL bundle does not have to
* carry Leaflet for them. Above the cutoff supercluster hands every point back on its
* own, and the stops that share a coordinate are folded together at the pin level
* instead — see the reconcile below.
*/
const CLUSTER_RADIUS = 20
const CLUSTER_MAX_ZOOM = 8
/** The cluster source and the three layers over it. Extracted so the rebuild on a mode
* change and the initial build cannot drift apart. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function addPlaceClusterLayers(map: any): void {
map.addSource(PLACE_CLUSTER_SOURCE_ID, {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] },
cluster: true,
clusterRadius: CLUSTER_RADIUS,
clusterMaxZoom: CLUSTER_MAX_ZOOM,
})
map.addLayer({
id: PLACE_CLUSTER_CIRCLE_LAYER_ID,
type: 'circle',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['has', 'point_count'],
paint: {
'circle-color': '#111827',
'circle-opacity': 0.97,
'circle-radius': ['step', ['get', 'point_count'], 18, 10, 21, 50, 24],
'circle-stroke-width': 2.5,
'circle-stroke-color': 'rgba(255,255,255,0.9)',
},
})
map.addLayer({
id: PLACE_CLUSTER_COUNT_LAYER_ID,
type: 'symbol',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['has', 'point_count'],
layout: {
'text-field': ['get', 'point_count_abbreviated'],
'text-size': 12,
'text-allow-overlap': true,
},
paint: {
'text-color': '#ffffff',
'text-halo-color': 'rgba(17,24,39,0.35)',
'text-halo-width': 1,
},
})
map.addLayer({
id: PLACE_UNCLUSTERED_LAYER_ID,
type: 'circle',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['!', ['has', 'point_count']],
paint: {
'circle-radius': 24,
'circle-opacity': 0,
'circle-stroke-opacity': 0,
},
})
}
function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement {
// A stop that interrupts the drive gets its own small disc, decided before the photo
// branch: the brand logo a fuel search comes back with is exactly what this replaces.
@@ -612,6 +542,8 @@ export function MapViewGL({
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markersRef = useRef<Map<number, PlacePin>>(new Map())
/** The count bubbles, one per cluster the source currently reports. */
const clusterPinsRef = useRef<PlacePin[]>([])
// Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin).
const pinLayerRef = useRef<HTMLDivElement | null>(null)
const locationMarkerRef = useRef<LocationMarkerHandle | null>(null)
@@ -642,6 +574,7 @@ export function MapViewGL({
// in the same frame the canvas draws, or the ones left out swim against the ones in.
const repositionPins = useCallback(() => {
markersRef.current.forEach(pin => pin.reposition())
clusterPinsRef.current.forEach(pin => pin.reposition())
poiMarkersRef.current.forEach(pin => pin.reposition())
pluginMarkersRef.current.forEach(pin => pin.reposition())
routeViaMarkersRef.current.forEach(pin => pin.reposition())
@@ -794,7 +727,7 @@ export function MapViewGL({
return
}
const rect = map.getContainer().getBoundingClientRect()
const at = map.unproject([e.clientX - rect.left, e.clientY - rect.top])
const at = onRealWorld(map.unproject([e.clientX - rect.left, e.clientY - rect.top]))
viaHandlersRef.current.onMoveVia?.(via.day_id, via.id, at.lat, at.lng)
}
// The browser fires this when the captured element is torn out of the DOM,
@@ -994,7 +927,8 @@ export function MapViewGL({
// trip reloads for a gesture the user made once. The picker is a modal
// choice about that leg; dropping a via mid-choice is not offered anywhere.
if (e.point && map.queryRenderedFeatures?.(e.point, { layers: ['route-alt-hit'] })?.length) return
onRouteClick(e.lngLat.lat, e.lngLat.lng)
const at = onRealWorld(e.lngLat)
onRouteClick(at.lat, at.lng)
}
const enter = () => { map.getCanvas().style.cursor = 'copy' }
const leave = () => { map.getCanvas().style.cursor = '' }
@@ -1013,35 +947,12 @@ export function MapViewGL({
}
}, [mapReady, onRouteClick])
/**
* The map takes the drop, not the drawn route: in a GL renderer the line lives in the
* canvas and has no element to aim at. The coordinate under the pointer says just as
* much once it is projected onto the routed geometry, and it works the same in all
* three renderers.
*/
// A POI dropped on the map lands on the drive (see poiDropTarget.ts).
useEffect(() => {
const map = mapRef.current
const container = map?.getContainer?.()
if (!container || !mapReady || !onPoiDropOnRoute) return
const onDragOver = (e: DragEvent) => {
if (!draggedPoiId(e)) return
e.preventDefault()
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'
}
const onDrop = (e: DragEvent) => {
const osmId = draggedPoiId(e)
if (!osmId) return
e.preventDefault()
const rect = container.getBoundingClientRect()
const at = map.unproject([e.clientX - rect.left, e.clientY - rect.top])
onPoiDropOnRoute(osmId, at.lat, at.lng)
}
container.addEventListener('dragover', onDragOver)
container.addEventListener('drop', onDrop)
return () => {
container.removeEventListener('dragover', onDragOver)
container.removeEventListener('drop', onDrop)
}
return bindPoiDropTarget(container, (x, y) => map.unproject([x, y]), onPoiDropOnRoute)
}, [mapReady, onPoiDropOnRoute])
const onViewportChangeRef = useRef(onViewportChange)
onViewportChangeRef.current = onViewportChange
@@ -1304,21 +1215,7 @@ export function MapViewGL({
? map.queryRenderedFeatures(e.point, { layers: [PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID] })
: []
const feature = features?.[0]
const clusterId = feature?.properties?.cluster_id
const coordinates = feature?.geometry?.coordinates
if (clusterId == null || !Array.isArray(coordinates)) return
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as any
const easeToZoom = (nextZoom: number) => {
try { map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 }) } catch { /* noop */ }
}
try {
const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err: Error | null, nextZoom: number) => {
if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom)
})
if (typeof maybeZoom === 'number') easeToZoom(maybeZoom)
else if (maybeZoom && typeof maybeZoom.then === 'function') maybeZoom.then(easeToZoom).catch(() => {})
} catch { /* noop */ }
expandCluster(map, feature?.properties?.cluster_id, feature?.geometry?.coordinates)
}
const setClusterCursor = () => {
const canvas = typeof map.getCanvas === 'function' ? map.getCanvas() : null
@@ -1426,7 +1323,7 @@ export function MapViewGL({
&& map.queryRenderedFeatures(e.point, { layers: ['trip-route-hit'] }).length > 0
) return
if (isTourLayerHit(map, e.point)) return // a picked via ferrata or paddle obstacle opens its card instead
onClickRefs.current.map?.({ latlng: { lat: e.lngLat.lat, lng: e.lngLat.lng } })
onClickRefs.current.map?.({ latlng: onRealWorld({ lat: e.lngLat.lat, lng: e.lngLat.lng }) })
})
// Emit the viewport (pan/zoom + once on first idle) for the POI-explore pill.
const emitViewport = () => reportGlViewport(map, onViewportChangeRef.current)
@@ -1459,7 +1356,7 @@ export function MapViewGL({
// timer — dedupe so the form doesn't open twice.
if (Date.now() - lastContextFire < 700) return false
lastContextFire = Date.now()
onClickRefs.current.context?.({ latlng: { lat: lngLat.lat, lng: lngLat.lng }, originalEvent })
onClickRefs.current.context?.({ latlng: onRealWorld({ lat: lngLat.lat, lng: lngLat.lng }), originalEvent })
return true
}
// MapLibre swallows the map contextmenu at the end of a right-button
@@ -1704,8 +1601,17 @@ export function MapViewGL({
source.setData(buildPlaceClusterData(places) as any)
const placesById = new Map<number, PlaceWithCoords>(validPlaces.map(place => [place.id, place]))
let raf: number | null = null
const dropClusterPins = () => {
clusterPinsRef.current.forEach(pin => pin.remove())
clusterPinsRef.current = []
}
const reconcileClusterPins = () => {
dropClusterPins()
clusterPinsRef.current = drawClusterBubbles(map, (el, lng, lat) => attachPin(map, gl, pinLayerRef.current, el, lng, lat))
}
const runReconcile = () => {
raf = null
reconcileClusterPins()
const features = map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['!', ['has', 'point_count']] }) || []
const seen = new Set<number>()
const visiblePlaces: PlaceWithCoords[] = []
@@ -1752,6 +1658,7 @@ export function MapViewGL({
return () => {
if (raf !== null) cancelAnimationFrame(raf)
dropClusterPins()
map.off('moveend', scheduleReconcile)
map.off('zoomend', scheduleReconcile)
map.off('idle', scheduleReconcile)
@@ -2055,7 +1962,7 @@ export function MapViewGL({
const fitPoints = routeCoords.length > 0 ? [...routeCoords, ...markerPoints] : markerPoints
if (fitPoints.length === 0) return
const bounds = new gl.LngLatBounds()
fitPoints.forEach(([lat, lng]) => bounds.extend([lng, lat]))
alongShortestArc(fitPoints).forEach(([lat, lng]) => bounds.extend([lng, lat]))
let fitted = false
const run = () => {
try {
+7 -3
View File
@@ -3,25 +3,29 @@ import { useMap } from 'react-leaflet'
import type L from 'leaflet'
import type { RouteVia } from '../../types'
import { bindDayBoundaryDrag, type DayBoundaryControls } from './dayBoundaryDrag'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
export function NightPauseDrag({ marker, via, controls }: { marker: L.Marker | null; via: RouteVia; controls?: DayBoundaryControls }) {
const map = useMap()
// The route is drawn in the map's longitude frame (#2975), so its points are measured there too.
const frame = useLngFrame()
useEffect(() => {
const el = marker?.getElement()
if (!marker || !el || !controls) return
return bindDayBoundaryDrag(el, via, controls, {
project: (lat, lng) => {
const point = map.latLngToContainerPoint([lat, lng])
const point = map.latLngToContainerPoint([lat, frameLng(frame, lng)])
const rect = map.getContainer().getBoundingClientRect()
return { x: point.x + rect.left, y: point.y + rect.top }
},
setPosition: (lat, lng) => { marker.setLatLng([lat, lng]) },
setPosition: (lat, lng) => { marker.setLatLng([lat, frameLng(frame, lng)]) },
lock: () => {
const enabled = map.dragging.enabled()
map.dragging.disable()
return () => { if (enabled) map.dragging.enable() }
},
})
}, [map, marker, via, controls])
}, [map, marker, via, controls, frame])
return null
}
@@ -1,6 +1,9 @@
import L from 'leaflet';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Marker, Tooltip, useMap } from 'react-leaflet';
import { frameLng } from '../../utils/lngFrame';
import { onRealWorld } from '../../utils/worldCopy';
import { useLngFrame } from './lngFrameContext';
import { MAP_LABEL_BADGE_CLASS } from './mapHoverLabel';
import { plannerPinBadge, plannerPinShape, type PlannerPinPoint } from './plannerPinShape';
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
@@ -45,7 +48,11 @@ export default function PlannerWaypointMarker({
useLayoutEffect(() => {
handlersRef.current = { onClick, onMove };
}, [onClick, onMove]);
const position = useMemo(() => [point.lat, point.lng] as [number, number], [point.lat, point.lng]);
const frame = useLngFrame();
const position = useMemo(
() => [point.lat, frameLng(frame, point.lng)] as [number, number],
[point.lat, point.lng, frame]
);
const { label, shaping, stageEnd } = point;
const icon = useMemo(
() => plannerWaypointIcon(pinCss, { label, shaping, stageEnd }, index, selected, !!onMove),
@@ -67,7 +74,7 @@ export default function PlannerWaypointMarker({
if (!element) return;
return wirePlannerWaypointDrag({
element,
initial: { lat: point.lat, lng: point.lng },
initial: { lat: position[0], lng: position[1] },
coordinateAt: (clientX, clientY) => {
const rect = map.getContainer().getBoundingClientRect();
const at = map.containerPointToLatLng([clientX - rect.left, clientY - rect.top]);
@@ -76,9 +83,13 @@ export default function PlannerWaypointMarker({
setPosition: ({ lat, lng }) => {
marker.setLatLng([lat, lng]);
},
onCommit: ({ lat, lng }) => handlersRef.current.onMove?.(point.id, lat, lng) ?? false,
// Saved on the real world, whichever copy of it the pin was dragged on (#2976).
onCommit: (at) => {
const { lat, lng } = onRealWorld(at);
return handlersRef.current.onMove?.(point.id, lat, lng) ?? false;
},
});
}, [map, marker, onMove, point.id, point.lat, point.lng]);
}, [map, marker, onMove, point.id, position]);
return (
<Marker
@@ -9,6 +9,8 @@ import { useSettingsStore } from '../../store/settingsStore'
import { hopIsVisible, labelFloorPx } from '../../utils/reservationRoutes'
import { TRANSPORT_COLOR, TRANSPORT_META, transportHop, type TransportHop, type TransportType } from './transportHops'
import type { Reservation } from '../../types'
import { frameLine } from '../../utils/lngFrame'
import { useLngFrame } from './lngFrameContext'
const ENDPOINT_PANE = 'reservation-endpoints'
@@ -48,11 +50,13 @@ function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
/** What a hop will draw: the road it was routed along when there is one, else its arcs. */
function linesFor(item: TransportItem, roadRoutes: Map<number, [number, number][]> | undefined): [number, number][][] {
const road = roadRoutes?.get(item.res.id)
return road && road.length >= 2 ? [road] : item.arcs
return road && road.length >= 2 ? [frameLine(item.frame, road)] : item.arcs
}
interface TransportItem extends TransportHop {
transitSegs: TransitMapSegment[]
/** The map's longitude frame the hop was drawn in (#2975), for the road route that arrives later. */
frame: ReturnType<typeof useLngFrame>
}
interface Props {
@@ -75,16 +79,19 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
zoomend: () => setZoom(map.getZoom()),
})
const showEndpointLabels = useSettingsStore(s => s.settings.map_booking_labels) === true
const frame = useLngFrame()
const items = useMemo<TransportItem[]>(() => {
const out: TransportItem[] = []
for (const r of reservations) {
const hop = transportHop(r, true)
const hop = transportHop(r, true, frame)
if (!hop) continue
out.push({ ...hop, transitSegs: hop.type === 'transit' ? getTransitMapSegments(r) : [] })
const segs = hop.type === 'transit' ? getTransitMapSegments(r) : []
const transitSegs = frame ? segs.map(seg => ({ ...seg, coords: frameLine(frame, seg.coords) })) : segs
out.push({ ...hop, transitSegs, frame })
}
return out
}, [reservations])
}, [reservations, frame])
const visibleItems = useMemo(() => {
const project = (p: readonly [number, number]) => map.latLngToContainerPoint([p[0], p[1]])
@@ -3,6 +3,9 @@ import { Marker, Tooltip, useMap } from 'react-leaflet'
import L from 'leaflet'
import { useTranslation } from '../../i18n/TranslationContext'
import { useStableVias } from './viaMarkerState'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
import { onRealWorld } from '../../utils/worldCopy'
import type { RoadtripVia } from '@trek/shared'
/**
@@ -64,12 +67,14 @@ export default function RoadtripViaMarkers({
return () => { map.off('zoomend', update) }
}, [map])
const frame = useLngFrame()
const markers = useMemo(() => vias.map(via => ({
via,
position: [via.lat, via.lng] as [number, number],
position: [via.lat, frameLng(frame, via.lng)] as [number, number],
handlers: {
dragend: (e: { target: { getLatLng: () => { lat: number; lng: number } } }) => {
const at = e.target.getLatLng()
// Saved on the real world, whichever copy of it the handle was dragged on (#2976).
const at = onRealWorld(e.target.getLatLng())
handlersRef.current.onMoveVia?.(via.day_id, via.id, at.lat, at.lng)
},
// Right-click rather than a delete handle: a 12px dot has no room for one,
@@ -79,7 +84,7 @@ export default function RoadtripViaMarkers({
handlersRef.current.onRemoveVia?.(via.day_id, via.id)
},
},
})), [vias])
})), [vias, frame])
if (!markers.length || !zoomedIn) return null
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../../../tests/helpers/msw/server'
import { pluginsApi, type PluginRouteResult } from '../../api/client'
@@ -15,8 +15,8 @@ import {
calculateAlternatives,
avoidedClasses,
routeEngineFor,
osrmLegSegment,
} from './RouteCalculator'
import { legSegment } from './routeText'
// Every route now goes to the FOSSGIS per-profile hosts. The car-only project-osrm.org
// demo ignored the profile in the URL, so walking routes followed the road network.
@@ -387,6 +387,12 @@ function pluginRouteResult(over: Partial<PluginRouteResult> = {}): PluginRouteRe
}
}
// FOSSGIS: OSRM routes the days and Valhalla only what OSRM cannot. Where Valhalla routes
// every day is valhallaDayRoute.test.ts.
beforeEach(() => {
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_valhalla_provider: 'fossgis' } }))
})
afterEach(() => {
vi.restoreAllMocks()
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
@@ -426,6 +432,23 @@ describe('calculateRouteWithLegs', () => {
expect(second).toBe(first)
})
it('FE-COMP-ROUTECALCULATOR-035b: a route answered once is still there after a reload, without asking the router (#2794)', async () => {
let hits = 0
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
const wps = freshWaypoints()
const first = await calculateRouteWithLegs(wps)
const { offlineDb } = await import('../../db/offlineDb')
await vi.waitFor(async () => expect(await offlineDb.routeCache.count()).toBeGreaterThan(0))
// A reload: the module, and with it the cache in memory, starts over.
vi.resetModules()
const reloaded = await import('./RouteCalculator')
const again = await reloaded.calculateRouteWithLegs(wps)
expect(hits).toBe(1)
expect(again).toEqual(first)
})
it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
const wps = freshWaypoints()
@@ -896,7 +919,8 @@ describe('calculateAlternatives', () => {
it('FE-COMP-ROUTECALCULATOR-053: an instance with its own OSRM is never sent to the public Valhalla', async () => {
let valhallaCalls = 0
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_base_url: 'https://osrm.example.org' } }))
// No routing service chosen: the own OSRM alone decides.
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_base_url: 'https://osrm.example.org', routing_valhalla_provider: '' } }))
server.use(
http.get('https://osrm.example.org/route/v1/driving/:coords', ({ request }) => {
const exclude = new URL(request.url).searchParams.get('exclude')
@@ -1215,11 +1239,11 @@ describe('a trip that avoids something', () => {
})
})
describe('osrmLegSegment', () => {
describe('legSegment', () => {
const waypoints = [{ lat: 48, lng: 2 }, { lat: 50, lng: 4 }, { lat: 52, lng: 6 }]
it('spans waypoint i to i + 1 with the label at the midpoint', () => {
const seg = osrmLegSegment({ distance: 1500, duration: 600 }, 1, waypoints)
const seg = legSegment({ distance: 1500, duration: 600 }, 1, waypoints)
expect(seg.from).toEqual([50, 4])
expect(seg.to).toEqual([52, 6])
expect(seg.mid).toEqual([51, 5])
@@ -1228,7 +1252,7 @@ describe('osrmLegSegment', () => {
})
it('formats driving as measured and walking at 5 km/h', () => {
const seg = osrmLegSegment({ distance: 5000, duration: 600 }, 0, waypoints)
const seg = legSegment({ distance: 5000, duration: 600 }, 0, waypoints)
expect(seg.drivingText).toBe('10 min')
expect(seg.walkingText).toBe('1 h 0 min')
expect(seg.durationText).toBeUndefined()
@@ -1236,6 +1260,6 @@ describe('osrmLegSegment', () => {
it('writes short metric distances in metres', () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
expect(osrmLegSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
expect(legSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
})
})
+141 -309
View File
@@ -1,10 +1,13 @@
import { useSettingsStore } from '../../store/settingsStore'
import { pluginsApi } from '../../api/client'
import type { DistanceUnit, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { formatDistance } from '../../utils/units'
import { countRoute } from './routeUsageCounter'
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
import { EXCLUDABLE_CLASSES, valhallaDayAlternatives, valhallaDayRoute, valhallaExcluding } from './valhallaDayRoute'
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
// FOSSGIS hosts OSRM with real per-profile routing (car/foot/bike) — the
@@ -196,10 +199,6 @@ function retryAfterMs(response: Response): number | null {
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
}
// Cache route responses keyed by the exact waypoint list. Routes are stable, so
// this avoids re-hitting the public OSRM demo server on every day switch / reorder.
const routeCache = new Map<string, RouteWithLegs>()
const ROUTE_CACHE_MAX = 200
/**
* A route profile is either one of the built-in OSRM profiles or a plugin profile
@@ -216,12 +215,15 @@ export function parsePluginProfile(profile: string): { pluginId: string; profile
return { pluginId: rest.slice(0, slash), profileId: rest.slice(slash + 1) }
}
/**
* Which engine priced a route: OSRM, the second engine that weighs road classes away, or
* a route provider plugin. Their figures are three different speed models, so a figure
* from one read against a figure from another measures the models, not the roads.
*/
export type RouteEngine = 'osrm' | 'valhalla' | 'plugin'
/** One of the three profiles both engines know, or null for a plugin's own. */
function builtInProfile(profile: RouteProfileKey): 'driving' | 'walking' | 'cycling' | null {
switch (profile) {
case 'driving': return 'driving'
case 'walking': return 'walking'
case 'cycling': return 'cycling'
default: return null
}
}
/**
* The classes a request really weighs away, in a stable order, and none when it cannot.
@@ -237,10 +239,75 @@ export function avoidedClasses(profile: RouteProfileKey, avoid: readonly AvoidCl
: []
}
/** The engine `calculateRouteWithLegs` hands a request with this profile and avoidance to. */
/**
* The engine a request with this profile and avoidance is planned with: Valhalla for every
* day where it routes the days, and for a day that avoids something wherever it can; OSRM
* for the rest. Planned, not promised: a day Valhalla cannot answer, or one asked while
* the relay rests, is drawn by OSRM, and the answer says so in its `engine`.
*/
export function routeEngineFor(profile: RouteProfileKey, avoid: readonly AvoidClass[]): RouteEngine {
if (parsePluginProfile(profile)) return 'plugin'
return avoidedClasses(profile, avoid).length ? 'valhalla' : 'osrm'
if (avoidedClasses(profile, avoid).length) return 'valhalla'
return builtInProfile(profile) && valhallaPlansDays() ? 'valhalla' : 'osrm'
}
/** The profile Valhalla routes a request under, or null where `routeEngineFor` gives it to another engine. */
function valhallaProfile(profile: RouteProfileKey, avoid: readonly AvoidClass[]): 'driving' | 'walking' | 'cycling' | null {
return routeEngineFor(profile, avoid) === 'valhalla' ? builtInProfile(profile) : null
}
/**
* Where a Valhalla answer is kept: beside the OSRM key, which keeps the shape it always
* had. A day that weighs classes away keeps the key it has had since only Valhalla could
* answer one, so the days a device already holds stay found; a day that avoids nothing
* names the engine instead.
*/
function valhallaKey(plainKey: string, avoiding: readonly AvoidClass[]): string {
return avoiding.length ? `${plainKey}:avoid=${avoiding.join(',')}` : `${plainKey}:valhalla`
}
/**
* OSRM's answer for a day Valhalla could not route. A day that avoided nothing is then
* routed as it always was, without a word. One that avoided something says that nothing
* was avoided, with the reason, so the rail flags the day instead of implying the setting
* held on a road nobody weighed.
*/
function withFallbackNoted(plain: RouteWithLegs, avoiding: AvoidClass[]): RouteWithLegs {
const drawn = withEngine(plain, 'osrm')
return avoiding.length ? { ...drawn, avoidance: { asked: avoiding, achieved: [], fellBack: true } } : drawn
}
/**
* A kept route with the engine that drew it. A key holds one engine's answers only, so an
* entry kept before answers named their engine is that key's.
*/
function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
return route.engine ? route : { ...route, engine }
}
/**
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
{ profile, avoiding, keys, signal }: {
profile: 'driving' | 'walking' | 'cycling'
avoiding: AvoidClass[]
keys: { valhalla: string; plain: string; coords: string }
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
cacheRoute(keys.valhalla, routed)
return routed
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -470,31 +537,11 @@ export async function calculateSegments(
if (data.code !== 'Ok' || !data.routes?.[0]) throw new Error('No route found')
const legs = data.routes[0].legs
return legs.map((leg: OsrmLeg, i: number): RouteSegment => osrmLegSegment(leg, i, waypoints))
return legs.map((leg: OsrmLeg, i: number): RouteSegment => legSegment(leg, i, waypoints))
}
interface OsrmLeg { distance: number; duration: number }
/**
* The connector data for OSRM leg i, which runs from waypoint i to waypoint i + 1:
* both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
* the driving time OSRM measured.
*/
export function osrmLegSegment(leg: OsrmLeg, i: number, waypoints: Waypoint[]): RouteSegment {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(walkingDuration),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
}
}
/**
* One OSRM call per waypoint-run that returns BOTH the real road geometry (for the
* map) and per-leg distance/duration (for the sidebar connectors). Results are cached
@@ -516,6 +563,7 @@ export async function calculateRouteWithLegs(
return { coordinates: [], distance: 0, duration: 0, legs: [] }
}
const valhallaDay = valhallaProfile(profile, avoid)
const avoiding = avoidedClasses(profile, avoid)
const coords = waypoints.map((p) => `${p.lng},${p.lat}`).join(';')
@@ -523,38 +571,37 @@ export async function calculateRouteWithLegs(
// part of the key — otherwise switching km↔mi would return stale text (#1300).
// A plugin route is trip-/day-specific (it may return different charging stops for
// the same coordinates on a different day), so its key includes tripId/dayId;
// the built-in OSRM profiles are context-free and leave those out.
// the built-in profiles are context-free and leave those out.
//
// The engine belongs in the key because the two price roads differently: a day OSRM
// drew handed out as Valhalla's after the admin switched engines would keep the old
// times on every device that held it, and the other way round. An OSRM answer keeps
// the key it always had, so the routes already kept on a device stay good.
//
// The avoidance belongs in the key for two reasons pointing opposite ways. Without it
// turning the switch on returns the tolled route out of cache in under a millisecond,
// so nothing on screen changes and it reads as a broken toggle. And the leak the other
// way is worse: this Map is shared with the ordinary day planner, the studio and the
// booking geometry, none of which ask for avoidance, so an avoid-routed answer stored
// under the plain key would hand them a road nobody drives and a second engine's
// times. So the avoiding key only ever holds a Valhalla answer: when Valhalla cannot
// answer and OSRM drives the request after all, that answer is filed under the plain
// key, where it is exactly what an ordinary caller would have got. Filed under the
// avoiding key it stood in for the avoided road until the next reload, however soon
// Valhalla came back.
// under the plain key would hand them a road nobody drives. So the Valhalla keys only
// ever hold a Valhalla answer: when Valhalla cannot answer and OSRM drives the request
// after all, that answer is filed under the OSRM key, where it is exactly what an
// ordinary caller would have got. Filed under the Valhalla key it stood in for the
// weighed road until the next reload, however soon Valhalla came back.
const pluginScope = profile.startsWith('plugin:') ? `:${tripId ?? ''}:${dayId ?? ''}` : ''
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
const cacheKey = `${plainKey}${avoidScope}`
const cached = routeCache.get(cacheKey)
if (cached) return cached
// Which engine the day is planned with does not follow the relay's rest, so a day kept
// from Valhalla is still found while the relay rests, offline above all.
const cacheKey = valhallaDay ? valhallaKey(plainKey, avoiding) : plainKey
// A plugin route stays in memory: its answer depends on the trip and the day,
// and may carry live data such as charging stops. The rest is kept on the device
// too, so a trip that shows its whole route opens drawn (#2794).
const cached = pluginScope ? routeInMemory(cacheKey) : await storedRoute(cacheKey)
if (cached) return withEngine(cached, routeEngineFor(profile, avoid))
if (avoiding.length) {
const routed = await routeAvoidingWithLegs(waypoints, avoiding, signal)
if (routed) {
cacheRoute(cacheKey, routed)
return routed
}
// Null is a Valhalla that could not answer at all. OSRM keeps the day drawn rather
// than blank, and the answer says that nothing was avoided, with the reason, so the
// rail flags the day instead of implying the setting held on a road nobody weighed.
const plain = routeCache.get(plainKey) ?? await osrmWithLegs(waypoints, coords, profile, signal)
cacheRoute(plainKey, plain)
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
if (valhallaDay) {
const keys = { valhalla: cacheKey, plain: plainKey, coords }
return valhallaOrOsrmDay(waypoints, { profile: valhallaDay, avoiding, keys, signal })
}
// Plugin profile (`plugin:<id>/<profile>`): the server invokes that routeProvider
@@ -569,33 +616,20 @@ export async function calculateRouteWithLegs(
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
}, { signal })
if (!route) throw new Error('No route found')
const legs: RouteSegment[] = route.legs.map((leg, i): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
durationText: formatDuration(leg.duration),
...(leg.note ? { noteText: leg.note } : {}),
}
})
const legs = route.legs.map((leg, i): RouteSegment => ({
...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
...(leg.note ? { noteText: leg.note } : {}),
}))
const result: RouteWithLegs = {
coordinates: route.coordinates,
distance: route.distance,
duration: route.duration,
legs,
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
engine: 'plugin',
}
routeCache.set(cacheKey, result)
if (routeCache.size > ROUTE_CACHE_MAX) {
const oldest = routeCache.keys().next().value
if (oldest !== undefined) routeCache.delete(oldest)
}
rememberRoute(cacheKey, result)
return result
}
@@ -629,79 +663,13 @@ async function osrmWithLegs(
// The day plan's connectors also show the leg's own duration line.
const legs: RouteSegment[] = (route.legs || []).map(
(leg: OsrmLeg, i: number): RouteSegment => ({
...osrmLegSegment(leg, i, waypoints),
...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
})
)
const snapped = readSnapped(data, waypoints)
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
}
/** Store a route and drop the oldest once the cache is over its cap. */
function cacheRoute(key: string, route: RouteWithLegs): void {
routeCache.set(key, route)
if (routeCache.size > ROUTE_CACHE_MAX) {
const oldest = routeCache.keys().next().value
if (oldest !== undefined) routeCache.delete(oldest)
}
}
/**
* A whole chain from the second engine, weighted away from some road classes.
*
* Shaped exactly like the OSRM answer above so the callers never branch on which engine
* spoke — same leg list, same formatted text, same snap positions. What it adds is
* `avoidance`: what was asked for against what the road actually turned out to be, which
* is the only honest way to label a weighting that can fail.
*
* Null rather than a throw when it cannot answer, so the caller falls through to OSRM
* and the day stays drawn.
*/
async function routeAvoidingWithLegs(
waypoints: Waypoint[],
avoid: AvoidClass[],
signal?: AbortSignal,
): Promise<RouteWithLegs | null> {
const sample = {
profile: 'driving' as const,
surface: 'legs' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: waypoints.length,
km: waypoints.slice(1).reduce((sum, point, i) => sum + haversineKm(waypoints[i], point), 0),
}
const run = await valhallaRun(waypoints, 'driving', avoid, signal)
// Counted by hand because the adapter speaks to a different engine with a different
// verb, and the counter exists to answer "how much routing does this instance do" —
// an engine it cannot see is exactly the traffic that would go missing from it.
if (!signal?.aborted) countRoute({ ...sample, failed: !run })
if (!run) return null
const legs: RouteSegment[] = run.legs.map((leg, i): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
return {
mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
from,
to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
durationText: formatDuration(leg.duration),
}
})
return {
coordinates: run.total.coordinates,
distance: run.total.distance,
duration: run.total.duration,
legs,
snapped: run.snapped,
avoidance: { asked: avoid, achieved: avoid.filter(cls => legAvoids(run.total, cls)) },
hasFerry: run.total.hasFerry,
}
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}), engine: 'osrm' }
}
/**
@@ -735,75 +703,6 @@ function readSnapped(data: unknown, waypoints: Waypoint[]): SnappedWaypoint[] |
return out
}
function getDistanceUnit(): DistanceUnit {
return useSettingsStore.getState().settings.distance_unit === 'imperial' ? 'imperial' : 'metric'
}
function formatRouteDistance(meters: number): string {
const unit = getDistanceUnit()
if (unit === 'metric' && meters < 1000) {
return `${Math.round(meters)} m`
}
return formatDistance(meters / 1000, unit)
}
function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
if (h > 0) {
return `${h} h ${m} min`
}
return `${m} min`
}
/** One way of driving a leg, as a router offers it. */
export interface RouteAlternative {
coordinates: [number, number][]
distance: number
duration: number
/** Where this route differs most from the first one — the point that would pin it. */
divergence: { lat: number; lng: number } | null
/** Set when this way exists because a road class was left out of it. */
avoids?: AvoidClass
/**
* Which engine priced this route. Absent means OSRM, which is what answers every route
* of a trip that avoids nothing, except the avoidance offer on a default install.
*
* It exists because the engines do not agree on speed: measured over twelve European
* legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
* sign depends on the region: Valhalla is faster on Spanish autovía and slower through
* a city. So a figure from one of them subtracted from a figure from the other is not a
* difference in driving time, it is the gap between two speed models, and the reader
* has no way of telling the two apart.
*/
engine?: RouteEngine
/** Whether the way crosses by ferry, where the engine that drew it says so. */
hasFerry?: boolean
}
/** What two routes are compared by: their line, and their figures where there is none. */
export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>
/**
* Road classes worth asking the router to leave out, in the order they are tried.
*
* OSRM's own alternative search is conservative: it only offers a second road when the
* detour is short enough and shares little enough with the first, so on a long motorway
* run it usually answers with exactly one route — while a perfectly good, slower way over
* the B-roads exists and is what somebody opening "other ways" is looking for. Excluding
* a class asks a different question and reliably produces that road.
*
* Only for driving: the foot and bike profiles have no excludable classes, and asking
* anyway earns an `InvalidOptions` for nothing.
*
* Ferry is on the list for Valhalla's sake and skipped on the OSRM path below. OSRM
* does carry a ferry class, but on a leg where a ferry is the only crossing it answers
* NoRoute rather than the long way round, which is not an alternative anybody can use.
* Valhalla weights it instead and drives around, which is the whole point.
*/
const EXCLUDABLE_CLASSES = ['motorway', 'toll', 'ferry'] as const
/**
* Hosts that have already answered "I do not do exclude", by base URL.
*
@@ -851,49 +750,6 @@ async function routeExcluding(
return osrmExcluding(from, to, profile, exclude, signal)
}
/**
* The same leg from Valhalla, weighted away from one class, or null.
*
* The check that makes this honest is `legAvoids`: `use_tolls: 0` is a preference, so
* between two points with no untolled connection the answer is still a tolled road.
* Offering that as "No tolls" would put a lie on the map, so it is dropped and the
* OSRM attempt gets its turn.
*/
async function valhallaExcluding(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling',
exclude: AvoidClass,
signal?: AbortSignal,
): Promise<RouteAlternative | null> {
if (!valhallaAvailable()) return null
const sample = {
profile,
surface: 'alternatives' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: 2,
km: haversineKm(from, to),
}
const leg = await valhallaRouteAvoiding(from, to, profile, exclude, signal)
// Counted here rather than in the adapter, so the adapter stays a format translator
// and every routing request an instance makes still lands in the one counter.
if (!signal?.aborted) countRoute({ ...sample, failed: !leg })
if (!leg || !legAvoids(leg, exclude)) return null
return valhallaOffer(leg)
}
/** A Valhalla leg as an offer, carrying the engine that priced it and what it crosses. */
function valhallaOffer(leg: ValhallaLeg): RouteAlternative {
return {
coordinates: leg.coordinates,
distance: leg.distance,
duration: leg.duration,
divergence: null,
engine: 'valhalla',
hasFerry: leg.hasFerry,
}
}
/** The same leg from OSRM with the class excluded outright, or null. */
async function osrmExcluding(
from: Waypoint,
@@ -941,20 +797,25 @@ async function osrmExcluding(
* onto this road on every future request, without storing a polyline that would go stale
* with the next OSM update.
*
* `avoid` is the classes the trip weighs away. A driving leg of such a trip is routed by
* Valhalla, so its offers come from Valhalla too, weighed the same way, and never from
* OSRM: a list holding both engines is what offered a road the rail was not on as the
* quicker one, and clicking it changed nothing.
* `avoid` is the classes the trip weighs away. A leg Valhalla routes, because it routes
* the days or because the trip avoids something, gets its offers from Valhalla too,
* weighed the same way, and never from OSRM: a list holding both engines is what offered
* a road the rail was not on as the quicker one, and clicking it changed nothing.
*/
export async function calculateAlternatives(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling' = 'driving',
{ signal, limit = 3, avoid = [] }: { signal?: AbortSignal; limit?: number; avoid?: readonly AvoidClass[] } = {},
{ signal, limit = 3, avoid = [], engine = routeEngineFor(profile, avoid) }: {
signal?: AbortSignal
limit?: number
avoid?: readonly AvoidClass[]
/** The engine that drew the leg, where it is known; the planned one otherwise. */
engine?: RouteEngine
} = {},
): Promise<RouteAlternative[]> {
const avoiding = avoidedClasses(profile, avoid)
const routes = avoiding.length
? await alternativesAvoiding(from, to, avoiding, limit, signal)
const routes = engine === 'valhalla'
? await alternativesFromValhalla(from, to, profile, avoidedClasses(profile, avoid), { limit, signal })
: await alternativesFromOsrm(from, to, profile, limit, signal)
if (!routes.length) return routes
@@ -966,54 +827,25 @@ export async function calculateAlternatives(
}
/**
* The offers for a leg of a trip that weighs classes away, every one of them Valhalla's.
* The offers for a leg of a day Valhalla routes, every one of them Valhalla's.
*
* Throws when Valhalla has nothing to say, so the picker reports a router that is not
* answering. Quietly offering OSRM's roads instead is the very mix this path exists to end.
*
* One way back gets the question the OSRM path asks too: the same drive with one more
* class left out, only of those the trip does not already avoid, and only where the road
* that comes back really is without it. Paced like the pieces of a split day, because the
* public instance allows one request a second.
* A day that weighs classes away has no other engine to ask: this throws when Valhalla has
* nothing to say, so the picker reports a router that is not answering. Quietly offering
* OSRM's roads instead is the very mix this path exists to end. A day that avoids nothing
* went to OSRM whole when Valhalla did not answer it, so its offers do the same.
*/
async function alternativesAvoiding(
async function alternativesFromValhalla(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling',
avoiding: AvoidClass[],
limit: number,
signal?: AbortSignal,
{ limit, signal }: { limit: number; signal?: AbortSignal },
): Promise<RouteAlternative[]> {
const sample = {
profile: 'driving' as const,
surface: 'alternatives' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: 2,
km: haversineKm(from, to),
}
const answered = await valhallaAlternates(from, to, 'driving', avoiding, Math.max(0, limit - 1), signal)
if (!signal?.aborted) countRoute({ ...sample, failed: !answered })
if (!answered?.length) throw new Error('No route found')
const routes: RouteAlternative[] = []
for (const leg of answered) {
const offer = valhallaOffer(leg)
if (!routes.some(r => sameRoad(r, offer))) routes.push(offer)
}
if (routes.length >= 2) return routes
for (const cls of EXCLUDABLE_CLASSES) {
if (avoiding.includes(cls)) continue
await valhallaSpacing(signal)
if (signal?.aborted) break
const run = await valhallaRun([from, to], 'driving', [...avoiding, cls], signal)
if (!signal?.aborted) countRoute({ ...sample, failed: !run })
if (!run || !legAvoids(run.total, cls)) continue
const detour = valhallaOffer(run.total)
if (routes.some(r => sameRoad(r, detour))) continue
routes.push({ ...detour, avoids: cls })
break
}
return routes
const asking = avoiding.length > 0 || valhallaRoutesDays()
const offered = asking ? await valhallaDayAlternatives(from, to, profile, avoiding, { limit, signal }) : null
if (offered) return offered
if (avoiding.length) throw new Error('No route found')
return alternativesFromOsrm(from, to, profile, limit, signal)
}
/** The offers for a leg of a trip that avoids nothing: OSRM's, and one avoidance offer. */
+4 -1
View File
@@ -1,4 +1,5 @@
import { Polyline } from 'react-leaflet';
import { onRealWorld } from '../../utils/worldCopy';
/**
* P2A-03: an invisible band along a route segment on the Leaflet map, wider
@@ -31,7 +32,9 @@ export function RouteHitBand({
click: (e: { latlng: { lat: number; lng: number }; originalEvent: MouseEvent }) => {
// Stops the map's own click, which would otherwise open the add-place menu underneath the new via.
e.originalEvent.stopPropagation();
onRouteClick(e.latlng.lat, e.latlng.lng);
// The via is saved on the real world, whichever copy of it the route was clicked on (#2976).
const at = onRealWorld(e.latlng);
onRouteClick(at.lat, at.lng);
},
}}
/>
@@ -100,6 +100,9 @@ describe('TripRouteOverviewPanel', () => {
expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted')
expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1)
// The short figures read as floors, the trip's and the day's, not as measurements (#2876).
expect(screen.getAllByText('map.overview.distanceAtLeast')).toHaveLength(2)
expect(screen.getByText('140.5 km')).toBeInTheDocument()
})
it('FE-MAP-TROU-010: does not call a leg unrouted while the round is still running', () => {
@@ -2,7 +2,7 @@ import { AlertTriangle, Route } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { MapTogglePill } from './MapTogglePill'
import { routeModeIcon } from '../Planner/routeModes'
import { formatDistance } from '../../utils/units'
import { routeDistanceLabel } from './tripRouteLabels'
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
import type { DistanceUnit } from '../../types'
@@ -65,7 +65,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
{/* Same tier as the label beside it: the two read as one line rather than as a
heading with a number stuck under it. */}
<span className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600 }}>
{formatDistance(overview.totalDistance / 1000, unit)}
{routeDistanceLabel(overview.totalDistance, unrouted, unit, t)}
{/* Still routing: the number is a partial sum, and saying so beats a total
that silently grows while you read it. */}
{overview.loading && <span className="text-content-muted" style={{ fontWeight: 400 }}>{' '}…</span>}
@@ -112,7 +112,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
/>
)}
<span className="text-content-muted" style={{ flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>
{formatDistance(day.distance / 1000, unit)}
{routeDistanceLabel(day.distance, dayUnrouted, unit, t)}
</span>
</>
)
+11 -2
View File
@@ -4,6 +4,7 @@ import { useMap } from 'react-leaflet';
import { useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
import { bboxOnRealWorld } from '../../utils/worldCopy';
/**
* The part of the planner's map on screen, told to the assistant after every
@@ -54,7 +55,11 @@ export function useReportViewLeaflet(): void {
if (tripId === null) return;
const read = () => {
const b = map.getBounds();
report(tripId, { south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() });
// On the real world, whichever world copy (or longitude frame, #2975) the map shows.
report(
tripId,
bboxOnRealWorld({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
);
};
read();
map.on('moveend', read);
@@ -87,7 +92,11 @@ export function useReportViewGL(mapRef: { readonly current: unknown }, mapReady:
const read = () => {
const b = getBounds();
if (typeof b?.getSouth !== 'function') return;
report(tripId, { south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() });
// On the real world, whichever world copy (or longitude frame, #2975) the map shows.
report(
tripId,
bboxOnRealWorld({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
);
};
read();
on('moveend', read);
@@ -169,6 +169,45 @@ describe('buildDayRouteRuns', () => {
expect(hotelBookendOf(run[0], run[1])).toBe('morning')
})
it("FE-MAP-DRP-017: the morning after a night away starts at the side trip's hotel, not the room kept at home", () => {
// The first hotel stays booked over the whole trip and comes first in the list; the
// side trip's hotel holds the night before. The day used to start with a 716 km drive
// from the kept room to the side trip's first stop.
const days = [1, 2, 3, 4, 5].map(n => buildDay({ id: n, day_number: n }))
const kept = { id: 1, trip_id: 1, place_lat: 13.7466, place_lng: 100.5393, start_day_id: 1, end_day_id: 5 } as unknown as Accommodation
const away = { id: 2, trip_id: 1, place_lat: 18.7883, place_lng: 98.9853, start_day_id: 2, end_day_id: 3 } as unknown as Accommodation
const runs = buildDayRouteRuns(3, inputs({
days,
assignments: { '3': [buildAssignment({ day_id: 3, order_index: 0, place: buildPlace({ lat: 18.8048, lng: 98.9216, place_time: '10:00' }) })] },
accommodations: [kept, away],
optimizeFromAccommodation: true,
}))
expect(runs[0][0]).toMatchObject({ lat: 18.7883, lng: 98.9853, hotel: 'morning' })
expect(runs.flat().some(p => p.hotel === 'morning' && p.lat === 13.7466)).toBe(false)
})
it('FE-MAP-DRP-018: a taxi that leaves from the hotel adds no road from the hotel to itself', () => {
const days = [1, 2, 3].map(n => buildDay({ id: n, day_number: n }))
const hotel = { id: 1, trip_id: 1, place_lat: 13.7466, place_lng: 100.5393, start_day_id: 1, end_day_id: 3 } as unknown as Accommodation
const taxi = {
id: 9, trip_id: 1, type: 'taxi', title: 'Taxi', status: 'confirmed', day_id: 2, end_day_id: 2,
reservation_time: '2026-12-02T09:00', reservation_end_time: '2026-12-02T09:40',
endpoints: [
{ role: 'from', sequence: 0, name: 'Hotel', lat: 13.7466, lng: 100.5393 },
{ role: 'to', sequence: 1, name: 'Museum', lat: 13.7516, lng: 100.4927 },
],
} as unknown as Reservation
const runs = buildDayRouteRuns(2, inputs({
days,
assignments: { '2': [buildAssignment({ day_id: 2, order_index: 0, place: buildPlace({ lat: 13.7563, lng: 100.5018, place_time: '12:00' }) })] },
reservations: [taxi],
accommodations: [hotel],
optimizeFromAccommodation: true,
}))
const zeroLength = runs.filter(run => run.length === 2 && run[0].lat === run[1].lat && run[0].lng === run[1].lng)
expect(zeroLength).toEqual([])
})
it('FE-MAP-DRP-008: a day that is not in the trip has no route', () => {
expect(buildDayRouteRuns(99, inputs({ assignments: { '1': [at(48.86, 2.35, 0)] } }))).toEqual([])
})
+4 -1
View File
@@ -196,7 +196,10 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
const role: CarrierEdge = side === 'first'
? (e.from ? 'departure' : 'arrival')
: (e.to ? 'arrival' : 'departure')
return { isPlace: false, time: null, carrierEdge: e.carrier ? role : null }
// The booking's own point at this edge of the day, as the sidebar passes it: a taxi
// that starts or ends at the hotel then adds no zero-length leg to it.
const point = side === 'first' ? (e.from ?? e.to) : (e.to ?? e.from)
return { isPlace: false, time: null, carrierEdge: e.carrier ? role : null, lat: point?.lat, lng: point?.lng }
}
// A carrier with a located endpoint today means the day changes geography by
// air/rail/sea — the check-in hotel is then the day's destination and the
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { greatCircle, unwrapLngs, geodesicArcs } from './flightGeodesy'
import { tripLngFrame } from '../../utils/lngFrame'
const YVR: [number, number] = [49.19, -123.18]
const ICN: [number, number] = [37.46, 126.44]
@@ -61,3 +62,29 @@ describe('flightGeodesy (#1411)', () => {
expect(unwrapLngs(pts)).toEqual(pts)
})
})
describe('flightGeodesy in a longitude frame (#2975)', () => {
const LAX: [number, number] = [33.94, -118.41]
const AKL: [number, number] = [-37.01, 174.79]
const frame = tripLngFrame([LAX[1], AKL[1]])
it('draws LAX to Auckland as one arc on one world copy, between the two pins as the frame places them', () => {
expect(frame).not.toBeNull()
const arcs = geodesicArcs([LAX[0], LAX[1] + 360], AKL, true, frame)
expect(arcs).toHaveLength(1)
const [arc] = arcs
expect(maxConsecutiveDeltaLng(arc)).toBeLessThan(180)
expect(arc[0][1]).toBeCloseTo(LAX[1] + 360, 5)
expect(arc[arc.length - 1][1]).toBeCloseTo(AKL[1], 5)
})
it('still copies an arc that leaves the frame, so both of its ends keep a line', () => {
const arcs = geodesicArcs(FRA, JFK, true, { seam: -30 })
expect(arcs).toHaveLength(2)
expect(arcs[1][0][1]).toBeCloseTo(arcs[0][0][1] + 360, 10)
})
it('without a frame draws what it drew before', () => {
expect(geodesicArcs(YVR, ICN, true, null)).toEqual(geodesicArcs(YVR, ICN, true))
})
})
+12 -4
View File
@@ -1,6 +1,8 @@
// Great-circle geometry for transport routes (flights, cruises, ferries),
// shared by the Leaflet and Mapbox/MapLibre renderers (#1411).
import { frameLine, type LngFrame } from '../../utils/lngFrame'
const toRad = (d: number) => d * Math.PI / 180
const toDeg = (r: number) => r * 180 / Math.PI
@@ -51,11 +53,17 @@ export function unwrapLngs(points: [number, number][]): [number, number][] {
* copies), a ±360-shifted duplicate keeps both halves visible in the
* standard [-180, 180] view; GL maps repeat features themselves
* (renderWorldCopies), so the duplicate would just double the line opacity.
*
* Given a longitude frame (Leaflet, a trip across the antimeridian, #2975), the
* arc starts at `a` as the frame draws it, and the duplicate is only needed
* when the arc leaves the frame rather than the plain world.
*/
export function geodesicArcs(a: [number, number], b: [number, number], wrapCopies: boolean): [number, number][][] {
const arc = unwrapLngs(greatCircle(a, b))
const crosses = arc.some(([, lng]) => lng < -180 || lng > 180)
export function geodesicArcs(a: [number, number], b: [number, number], wrapCopies: boolean, frame: LngFrame | null = null): [number, number][][] {
const arc = frame ? frameLine(frame, greatCircle(a, b)) : unwrapLngs(greatCircle(a, b))
const west = frame ? frame.seam : -180
const east = west + 360
const crosses = arc.some(([, lng]) => lng < west || lng > east)
if (!crosses || !wrapCopies) return [arc]
const shift = arc.some(([, lng]) => lng < -180) ? 360 : -360
const shift = arc.some(([, lng]) => lng < west) ? 360 : -360
return [arc, arc.map(([lat, lng]) => [lat, lng + shift] as [number, number])]
}
+7 -1
View File
@@ -1,3 +1,4 @@
import { bboxOnRealWorld } from '../../utils/worldCopy';
import { rasterTileZoom } from './glRasterLayers';
import type { MapViewProps } from './mapViewContract';
@@ -16,6 +17,11 @@ interface ViewportSource {
export function reportGlViewport(map: ViewportSource, report: MapViewProps['onViewportChange']): void {
const bounds = map.getBounds();
if (!report || !bounds) return;
const bbox = { south: bounds.getSouth(), west: bounds.getWest(), north: bounds.getNorth(), east: bounds.getEast() };
const bbox = bboxOnRealWorld({
south: bounds.getSouth(),
west: bounds.getWest(),
north: bounds.getNorth(),
east: bounds.getEast(),
});
report(bbox, rasterTileZoom(map.getZoom()));
}
@@ -0,0 +1,120 @@
// The Leaflet map's bridges to the page: the events it hands out, with their
// points on the real world (#2976), and the view kept on the world copy the
// trip is drawn on (#2975).
import { wrapLongitude } from '@trek/shared';
import L from 'leaflet';
import { useEffect, useRef } from 'react';
import { useMap } from 'react-leaflet';
import { frameLng, type LngFrame } from '../../utils/lngFrame';
import { bboxOnRealWorld } from '../../utils/worldCopy';
import { useLngFrame } from './lngFrameContext';
import type { MapViewProps } from './mapViewContract';
import { bindPoiDropTarget } from './poiDropTarget';
/**
* Takes a corridor hit dropped anywhere on the map and reports where it landed.
*
* The container rather than the drawn route: a polyline is a real element here but not in
* the GL renderers, and the drop coordinate answers "where on the drive" just as well
* once the caller projects it onto the routed geometry — one behaviour for all three.
*/
export function PoiDropTarget({
onPoiDropOnRoute,
}: {
onPoiDropOnRoute?: (osmId: string, lat: number, lng: number) => void;
}) {
const map = useMap();
useEffect(() => {
if (!onPoiDropOnRoute) return;
return bindPoiDropTarget(map.getContainer(), (x, y) => map.containerPointToLatLng([x, y]), onPoiDropOnRoute);
}, [map, onPoiDropOnRoute]);
return null;
}
// Emits the current viewport bbox on pan/zoom so the POI-explore pill can fetch
// OSM places for the visible area, with the zoom an overlay's minimum is read against.
export function ViewportController({ onViewportChange }: { onViewportChange?: MapViewProps['onViewportChange'] }) {
const map = useMap();
useEffect(() => {
if (!onViewportChange) return;
const emit = () => {
const b = map.getBounds();
// A view of a world copy (or of a trip drawn past the antimeridian) asks for the real places there.
onViewportChange(
bboxOnRealWorld({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() }),
map.getZoom()
);
};
map.whenReady(emit); // ensure the first bbox is captured once the map is laid out
map.on('moveend', emit);
map.on('zoomend', emit);
return () => {
map.off('moveend', emit);
map.off('zoomend', emit);
};
}, [map, onViewportChange]);
return null;
}
/**
* Moves the view along when the longitude frame changes under it (#2975): the trip
* is then drawn one world further east or west, and a view left where it was would
* look at an empty copy. One jump of a whole world, so nothing on screen changes.
*/
export function LngFrameFollower() {
const map = useMap();
const frame = useLngFrame();
const prev = useRef<LngFrame | null>(frame);
useEffect(() => {
const before = prev.current;
prev.current = frame;
if (before === frame || typeof map.getCenter !== 'function') return;
const center = map.getCenter();
// Without a frame the trip is back on the real world, and so is the view.
const target = frame ? frameLng(frame, center.lng) : wrapLongitude(center.lng);
const shift = target - center.lng;
if (shift !== 0) map.setView([center.lat, target], map.getZoom(), { animate: false });
}, [frame, map]);
return null;
}
interface MapClickHandlerProps {
onClick: ((e: L.LeafletMouseEvent) => void) | null;
}
/**
* The event as the map reports it, with its point moved from a repeated world copy
* back onto the real world: a right-click on the copy east of it said 274.9 for
* -85.1, and the place was saved there (#2976).
*/
function onRealWorldEvent(e: L.LeafletMouseEvent): L.LeafletMouseEvent {
const lng = wrapLongitude(e.latlng.lng);
return lng === e.latlng.lng ? e : { ...e, latlng: L.latLng(e.latlng.lat, lng) };
}
export function MapClickHandler({ onClick }: MapClickHandlerProps) {
const map = useMap();
useEffect(() => {
if (!onClick) return;
const handle = (e: L.LeafletMouseEvent) => onClick(onRealWorldEvent(e));
map.on('click', handle);
return () => {
map.off('click', handle);
};
}, [map, onClick]);
return null;
}
export function MapContextMenuHandler({ onContextMenu }: { onContextMenu: ((e: L.LeafletMouseEvent) => void) | null }) {
const map = useMap();
useEffect(() => {
if (!onContextMenu) return;
const handle = (e: L.LeafletMouseEvent) => onContextMenu(onRealWorldEvent(e));
map.on('contextmenu', handle);
return () => {
map.off('contextmenu', handle);
};
}, [map, onContextMenu]);
return null;
}
@@ -0,0 +1,51 @@
// The longitude frame of the Leaflet map, for every layer that draws in it (#2975).
// See utils/lngFrame.ts for what the frame is and why only Leaflet needs it.
import { createContext, useContext, useMemo, useState } from 'react';
import type { Place, Reservation } from '../../types';
import { tripLngFrame, type LngFrame } from '../../utils/lngFrame';
const LngFrameContext = createContext<LngFrame | null>(null);
export const LngFrameProvider = LngFrameContext.Provider;
/** The frame the map draws in, or null when it draws the plain world. */
export function useLngFrame(): LngFrame | null {
return useContext(LngFrameContext);
}
type Located = Pick<Place, 'lng'>;
function tripLngs(
places: readonly Located[],
dayPlaces: readonly Located[],
reservations: readonly Reservation[]
): number[] {
const lngs: number[] = [];
for (const p of places) if (typeof p.lng === 'number') lngs.push(p.lng);
for (const p of dayPlaces) if (typeof p.lng === 'number') lngs.push(p.lng);
for (const r of reservations) for (const e of r.endpoints ?? []) if (typeof e.lng === 'number') lngs.push(e.lng);
return lngs;
}
/**
* The frame for a trip: its places, the day's places and every endpoint of every
* booking, shown or not, so switching a day or a booking on and off does not move
* the seam. The frame in use is handed back in, which keeps it while it still fits.
*/
export function useTripLngFrame(
places: readonly Located[],
dayPlaces: readonly Located[],
reservations: readonly Reservation[]
): LngFrame | null {
const [current, setCurrent] = useState<LngFrame | null>(() =>
tripLngFrame(tripLngs(places, dayPlaces, reservations))
);
const next = useMemo(
() => tripLngFrame(tripLngs(places, dayPlaces, reservations), current),
[places, dayPlaces, reservations, current]
);
// Derived state, adjusted during render: the next render already draws in the new frame.
if (next !== current) setCurrent(next);
return next;
}
@@ -97,6 +97,8 @@ describe('attachLocationMarker', () => {
expect(root.children).toHaveLength(3)
// The cone starts hidden — there is no heading until the first fix.
expect((root.children[1] as HTMLElement).style.display).toBe('none')
// The GL marker class owns `position`; an inline one would drop it into the flow.
expect(root.style.position).toBe('')
})
it('FE-COMP-LOCMARKERGL-003: adds the accuracy source and fill layer when the map is already loaded', () => {
@@ -13,7 +13,9 @@ type MarkerConstructor = new (options?: { element?: HTMLElement; anchor?: string
// and mapbox doesn't get confused about which element to position.
function buildLocationEl(): { root: HTMLDivElement; cone: HTMLDivElement } {
const root = document.createElement('div')
root.style.cssText = 'width:28px;height:28px;position:relative;pointer-events:none;'
// No inline `position`: the GL marker class keeps the root absolute, which the
// children's insets resolve against (see the note on markers in MapViewGL).
root.style.cssText = 'width:28px;height:28px;pointer-events:none;'
// Accuracy pulse behind the dot
const pulse = document.createElement('div')
pulse.style.cssText = `
+2 -1
View File
@@ -1,5 +1,6 @@
import L from 'leaflet'
import { STACK_RADIUS_PX } from './coincidentPlaces'
import { clusterBubbleSize } from './placeClusterLayers'
/** Up to here the map is an overview, where stops merge to keep the world readable. */
export const CLUSTER_UNTIL_ZOOM = 9
@@ -66,7 +67,7 @@ export interface ClusterLike {
/** A count bubble sized by its count, styled by `.marker-cluster-custom` in index.css. */
export function createClusterIcon(cluster: ClusterLike) {
const count = cluster.getChildCount()
const size = count < 10 ? 36 : count < 50 ? 42 : 48
const size = clusterBubbleSize(count)
return L.divIcon({
html: `<div class="marker-cluster-custom" style="width:${size}px;height:${size}px;"><span>${count}</span></div>`,
className: 'marker-cluster-wrapper',
@@ -0,0 +1,86 @@
import { describe, expect, it, vi } from 'vitest';
import {
type ClusterMap,
PLACE_CLUSTER_SOURCE_ID,
addPlaceClusterLayers,
clusterBubbleSize,
createClusterBubble,
drawClusterBubbles,
} from './placeClusterLayers';
function fakeMap(features: unknown[], expansionZoom: unknown = 11) {
const source = { getClusterExpansionZoom: vi.fn(() => expansionZoom) };
const map = {
addSource: vi.fn(),
addLayer: vi.fn(),
getSource: vi.fn((id: string) => (id === PLACE_CLUSTER_SOURCE_ID ? source : undefined)),
easeTo: vi.fn(),
querySourceFeatures: vi.fn((_id: string, query: { filter: unknown[] }) =>
query.filter[0] === 'has' ? features : []
),
};
return { map: map as unknown as ClusterMap & typeof map, source };
}
describe('cluster bubbles', () => {
it('FE-COMP-PLACECLUSTER-001: a bubble grows in three steps with its count', () => {
expect([1, 9, 10, 49, 50, 500].map(clusterBubbleSize)).toEqual([36, 36, 42, 42, 48, 48]);
});
it('FE-COMP-PLACECLUSTER-002: the GL bubble is the Leaflet markup inside a bare wrapper the pin can move', () => {
const wrapper = createClusterBubble(38);
expect(wrapper.className).toBe('');
const bubble = wrapper.firstElementChild as HTMLElement;
expect(bubble.className).toBe('marker-cluster-custom');
expect(bubble.style.width).toBe('42px');
expect(bubble.style.height).toBe('42px');
expect(bubble.textContent).toBe('38');
});
it('FE-COMP-PLACECLUSTER-003: the canvas circle and count stay as an invisible hit area', () => {
const { map } = fakeMap([]);
addPlaceClusterLayers(map);
expect(map.addSource).toHaveBeenCalledWith(PLACE_CLUSTER_SOURCE_ID, expect.objectContaining({ cluster: true }));
const layers = map.addLayer.mock.calls.map(([layer]) => layer as { id: string; paint: Record<string, unknown> });
expect(layers.find((l) => l.id === 'trip-place-clusters-circle')?.paint['circle-opacity']).toBe(0);
expect(layers.find((l) => l.id === 'trip-place-clusters-count')?.paint['text-opacity']).toBe(0);
});
it('FE-COMP-PLACECLUSTER-004: one bubble per cluster, placed at its centre, that zooms in on a click', () => {
const cluster = { properties: { cluster_id: 5, point_count: 12 }, geometry: { coordinates: [139.7, 35.6] } };
const { map, source } = fakeMap([
cluster,
cluster, // the same cluster crossing a tile edge
{ properties: { cluster_id: 6 }, geometry: { coordinates: [1, 1] } }, // no count
{ properties: { cluster_id: 7, point_count: 3 } }, // no geometry
]);
const placed: { el: HTMLElement; lng: number; lat: number }[] = [];
const pins = drawClusterBubbles(map, (el, lng, lat) => {
placed.push({ el, lng, lat });
return lng;
});
expect(pins).toEqual([139.7]);
expect(placed[0].el.textContent).toBe('12');
expect(placed[0].lat).toBe(35.6);
const onMapClick = vi.fn();
document.body.appendChild(placed[0].el);
document.body.addEventListener('click', onMapClick);
placed[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
document.body.removeEventListener('click', onMapClick);
placed[0].el.remove();
// The click is the bubble's: the map underneath never sees it.
expect(onMapClick).not.toHaveBeenCalled();
expect(source.getClusterExpansionZoom).toHaveBeenCalledWith(5, expect.any(Function));
expect(map.easeTo).toHaveBeenCalledWith({ center: [139.7, 35.6], zoom: 11, duration: 350 });
});
it('FE-COMP-PLACECLUSTER-005: a source that reports nothing draws nothing', () => {
const { map } = fakeMap([]);
map.querySourceFeatures.mockReturnValue(null as never);
expect(drawClusterBubbles(map, () => 1)).toEqual([]);
});
});
@@ -5,3 +5,169 @@
*/
export const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle';
export const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count';
// Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich
// HTML photo markers *and* cluster them natively, so we feed the place points
// into a clustered GeoJSON source. The source decides what is clustered; the
// bubbles are drawn as DOM (`drawClusterBubbles`) and the individual rich HTML
// markers only for the points the source reports as currently unclustered.
// Grouping is always on, matching the Leaflet map's MarkerClusterGroup.
export const PLACE_CLUSTER_SOURCE_ID = 'trip-place-clusters';
const PLACE_UNCLUSTERED_LAYER_ID = 'trip-place-unclustered-hit';
/**
* How eagerly place markers merge into a cluster.
*
* The overview band the Leaflet map clusters in as well (`CLUSTER_UNTIL_ZOOM` there),
* kept as plain numbers rather than shared constants so the GL bundle does not have to
* carry Leaflet for them. Above the cutoff supercluster hands every point back on its
* own, and the stops that share a coordinate are folded together at the pin level
* instead — see the reconcile in MapViewGL.
*/
const CLUSTER_RADIUS = 20;
const CLUSTER_MAX_ZOOM = 8;
/** The part of either SDK's map the cluster code calls. */
export interface ClusterMap {
addSource: (id: string, source: object) => void;
addLayer: (layer: object) => void;
getSource: (id: string) => unknown;
easeTo: (options: { center: unknown[]; zoom: number; duration: number }) => void;
querySourceFeatures: (id: string, options: { filter: unknown[] }) => ClusterFeature[] | null | undefined;
}
interface ClusterFeature {
properties?: { cluster_id?: unknown; point_count?: unknown } | null;
geometry?: { coordinates?: unknown };
}
interface ClusterSource {
getClusterExpansionZoom?: (id: unknown, done: (err: Error | null, zoom: number) => void) => unknown;
}
/** The cluster source and the three layers over it. Extracted so the rebuild on a mode
* change and the initial build cannot drift apart. */
export function addPlaceClusterLayers(map: Pick<ClusterMap, 'addSource' | 'addLayer'>): void {
map.addSource(PLACE_CLUSTER_SOURCE_ID, {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] },
cluster: true,
clusterRadius: CLUSTER_RADIUS,
clusterMaxZoom: CLUSTER_MAX_ZOOM,
});
// Invisible: the bubble the user sees is DOM (createClusterBubble), these two
// layers stay as the hit area the track and route layers check a click against.
map.addLayer({
id: PLACE_CLUSTER_CIRCLE_LAYER_ID,
type: 'circle',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['has', 'point_count'],
paint: {
'circle-opacity': 0,
'circle-stroke-opacity': 0,
'circle-radius': ['step', ['get', 'point_count'], 18, 10, 21, 50, 24],
},
});
map.addLayer({
id: PLACE_CLUSTER_COUNT_LAYER_ID,
type: 'symbol',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['has', 'point_count'],
layout: {
'text-field': ['get', 'point_count_abbreviated'],
'text-size': 12,
'text-allow-overlap': true,
},
paint: { 'text-opacity': 0 },
});
map.addLayer({
id: PLACE_UNCLUSTERED_LAYER_ID,
type: 'circle',
source: PLACE_CLUSTER_SOURCE_ID,
filter: ['!', ['has', 'point_count']],
paint: {
'circle-radius': 24,
'circle-opacity': 0,
'circle-stroke-opacity': 0,
},
});
}
/** Eases the map in to the zoom a cluster falls apart at. Both SDKs answer that
* question, one through a callback and one through a promise. */
export function expandCluster(
map: Pick<ClusterMap, 'getSource' | 'easeTo'>,
clusterId: unknown,
coordinates: unknown
): void {
if (clusterId == null || !Array.isArray(coordinates)) return;
const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as ClusterSource | undefined;
const easeToZoom = (nextZoom: number) => {
try {
map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 });
} catch {
/* noop */
}
};
try {
const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err, nextZoom) => {
if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom);
});
if (typeof maybeZoom === 'number') easeToZoom(maybeZoom);
else if (maybeZoom instanceof Promise) maybeZoom.then(easeToZoom).catch(() => {});
} catch {
/* noop */
}
}
/**
* Puts one count bubble on the map per cluster the source currently reports, through
* `place` (the caller's pin factory), and returns what `place` handed back. A cluster
* crossing a tile edge comes back once per tile, so bubbles are keyed by cluster id.
*/
export function drawClusterBubbles<T>(map: ClusterMap, place: (el: HTMLElement, lng: number, lat: number) => T): T[] {
const pins: T[] = [];
const seen = new Set<unknown>();
for (const feature of map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['has', 'point_count'] }) ?? []) {
const clusterId = feature?.properties?.cluster_id;
const count = feature?.properties?.point_count;
const coordinates = feature?.geometry?.coordinates;
if (typeof count !== 'number' || !Array.isArray(coordinates) || seen.has(clusterId)) continue;
seen.add(clusterId);
const el = createClusterBubble(count);
el.addEventListener('click', (ev) => {
ev.stopPropagation();
expandCluster(map, clusterId, coordinates);
});
pins.push(place(el, coordinates[0], coordinates[1]));
}
return pins;
}
/** A count bubble's diameter in pixels: both renderers size their bubbles by it. */
export function clusterBubbleSize(count: number): number {
return count < 10 ? 36 : count < 50 ? 42 : 48;
}
/**
* A count bubble as DOM, styled by `.marker-cluster-custom` in index.css.
*
* The GL map draws its bubbles with this element rather than as canvas text, so they
* read in the app's own font and get the same hover the Leaflet map has. A canvas
* symbol layer can only use the glyphs the map style ships and knows no `:hover`.
* The bubble sits in a bare wrapper because the pin positions its element through
* `transform`, which would otherwise override the hover's scale.
*/
export function createClusterBubble(count: number): HTMLDivElement {
const size = clusterBubbleSize(count);
const bubble = document.createElement('div');
bubble.className = 'marker-cluster-custom';
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
const label = document.createElement('span');
label.textContent = String(count);
bubble.appendChild(label);
const wrapper = document.createElement('div');
wrapper.appendChild(bubble);
return wrapper;
}
@@ -0,0 +1,39 @@
// A corridor hit dropped anywhere on the map, for every renderer.
//
// The map takes the drop, not the drawn route: in a GL renderer the line lives in the
// canvas and has no element to aim at, and the coordinate under the pointer says just
// as much once the caller projects it onto the routed geometry. The point goes out on
// the real world, whichever world copy it was dropped on (#2976).
import { onRealWorld } from '../../utils/worldCopy';
import { draggedPoiId } from './markerDrag';
/** Where a point of the container lies, in the renderer's own coordinates. */
type PointAt = (x: number, y: number) => { lat: number; lng: number };
/** Listens for POI drops on `container` and reports each one; returns the cleanup. */
export function bindPoiDropTarget(
container: HTMLElement,
pointAt: PointAt,
onPoiDropOnRoute: (osmId: string, lat: number, lng: number) => void
): () => void {
const onDragOver = (e: DragEvent) => {
if (!draggedPoiId(e)) return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
};
const onDrop = (e: DragEvent) => {
const osmId = draggedPoiId(e);
if (!osmId) return;
e.preventDefault();
const rect = container.getBoundingClientRect();
const at = onRealWorld(pointAt(e.clientX - rect.left, e.clientY - rect.top));
onPoiDropOnRoute(osmId, at.lat, at.lng);
};
container.addEventListener('dragover', onDragOver);
container.addEventListener('drop', onDrop);
return () => {
container.removeEventListener('dragover', onDragOver);
container.removeEventListener('drop', onDrop);
};
}
+41
View File
@@ -0,0 +1,41 @@
import { routeCacheRepo } from '../../repo/routeCacheRepo';
import type { RouteWithLegs } from '../../types';
/**
* Route answers by RouteCalculator's cache key (profile, unit, waypoints,
* avoided roads). Routes are stable, so this keeps the router from being asked
* again on every day switch or reorder: in memory for this visit, and on the
* device for the next one, so a trip that shows its whole route opens drawn
* instead of routing every leg again, one a second (#2794).
*/
const inMemory = new Map<string, RouteWithLegs>();
const MEMORY_MAX = 200;
/** Keeps a route for this visit only, dropping the oldest past the limit. */
export function rememberRoute(key: string, route: RouteWithLegs): void {
inMemory.set(key, route);
if (inMemory.size > MEMORY_MAX) {
const oldest = inMemory.keys().next().value;
if (oldest !== undefined) inMemory.delete(oldest);
}
}
/** The route this visit already holds, without asking the device. */
export function routeInMemory(key: string): RouteWithLegs | undefined {
return inMemory.get(key);
}
/** Keeps a route the router just answered, in memory and on the device. */
export function cacheRoute(key: string, route: RouteWithLegs): void {
rememberRoute(key, route);
void routeCacheRepo.put(key, route);
}
/** The route kept in memory, else the one kept on the device, which then stays in memory too. */
export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
const held = inMemory.get(key);
if (held) return held;
const kept = await routeCacheRepo.get<RouteWithLegs>(key);
if (kept) rememberRoute(key, kept);
return kept;
}
+52
View File
@@ -0,0 +1,52 @@
import { useSettingsStore } from '../../store/settingsStore';
import type { DistanceUnit, RouteSegment, Waypoint } from '../../types';
import { formatDistance } from '../../utils/units';
/** The unit a route's texts are written in, which is why it is part of the route cache key. */
export function getDistanceUnit(): DistanceUnit {
return useSettingsStore.getState().settings.distance_unit === 'imperial' ? 'imperial' : 'metric';
}
/** A routed distance as the connectors show it: metres below a kilometre, else the user's unit. */
export function formatRouteDistance(meters: number): string {
const unit = getDistanceUnit();
if (unit === 'metric' && meters < 1000) {
return `${Math.round(meters)} m`;
}
return formatDistance(meters / 1000, unit);
}
/** A routed time in hours and minutes, the minutes rounded down. */
export function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) {
return `${h} h ${m} min`;
}
return `${m} min`;
}
/**
* The connector data for leg i of a routed chain, which runs from waypoint i to waypoint
* i + 1: both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
* the time the engine measured. The same for every engine, so a day reads alike whichever
* of them drew it.
*/
export function legSegment(
leg: { distance: number; duration: number },
i: number,
waypoints: Waypoint[]
): RouteSegment {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng];
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng];
return {
mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
from,
to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
};
}
+30
View File
@@ -0,0 +1,30 @@
import type { RouteAvoidClass, RouteEngine } from '../../types';
/** One way of driving a leg, as a router offers it. */
export interface RouteAlternative {
coordinates: [number, number][];
distance: number;
duration: number;
/** Where this route differs most from the first one — the point that would pin it. */
divergence: { lat: number; lng: number } | null;
/** Set when this way exists because a road class was left out of it. */
avoids?: RouteAvoidClass;
/**
* Which engine priced this route. Absent means OSRM, which answers every route of a
* trip that avoids nothing where Valhalla does not route the days, except the
* avoidance offer.
*
* It exists because the engines do not agree on speed: measured over twelve European
* legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
* sign depends on the region: Valhalla is faster on Spanish autovía and slower through
* a city. So a figure from one of them subtracted from a figure from the other is not a
* difference in driving time, it is the gap between two speed models, and the reader
* has no way of telling the two apart.
*/
engine?: RouteEngine;
/** Whether the way crosses by ferry, where the engine that drew it says so. */
hasFerry?: boolean;
}
/** What two routes are compared by: their line, and their figures where there is none. */
export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>;
@@ -88,6 +88,20 @@ describe('transportHop', () => {
expect(transportHop(r, false)!.arcs[0].length).toBeGreaterThan(2);
});
it("draws the waypoints and arcs in the map's longitude frame, so the pins sit on the line (#2975)", () => {
const r = booking('flight', [
endpoint({ role: 'from', lat: 33.94, lng: -118.41 }),
endpoint({ role: 'to', sequence: 1, lat: -37.01, lng: 174.79 }),
]);
const hop = transportHop(r, true, { seam: 28 });
if (!hop) throw new Error('a flight with two located ends draws a hop');
expect(hop.from.lng).toBeCloseTo(241.59, 5);
expect(hop.to.lng).toBeCloseTo(174.79, 5);
expect(hop.arcs).toHaveLength(1);
expect(hop.arcs[0][0][1]).toBeCloseTo(241.59, 5);
expect(hop.arcs[0][hop.arcs[0].length - 1][1]).toBeCloseTo(174.79, 5);
});
it('draws ferries and cruises as arcs but a cable car as a straight line', () => {
expect(TRANSPORT_META.ferry.geodesic).toBe(true);
expect(TRANSPORT_META.cruise.geodesic).toBe(true);
+9 -5
View File
@@ -7,6 +7,7 @@
import { Bike, Bus, CableCar, Car, CarTaxiFront, Plane, Route, Sailboat, Ship, Train, TramFront } from 'lucide-react';
import type { Reservation, ReservationEndpoint } from '../../types';
import { haversineKm } from '../../utils/geo';
import { frameLine, frameLng, type LngFrame } from '../../utils/lngFrame';
import { geodesicArcs } from './flightGeodesy';
export type TransportType =
@@ -144,14 +145,17 @@ export interface TransportHop {
* antimeridian also gets a copy shifted by 360 degrees: Leaflet needs that, while a
* GL map repeats features across world copies itself, so there one continuous arc
* is enough (a shifted duplicate would sit on the wrapped copy and double the opacity).
* `frame` is Leaflet's longitude frame (#2975): the arcs and the waypoints come back
* drawn in it, so a pin and the line that ends at it are on the same world copy.
*/
export function transportHop(r: Reservation, wrapArcs: boolean): TransportHop | null {
export function transportHop(r: Reservation, wrapArcs: boolean, frame: LngFrame | null = null): TransportHop | null {
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) return null;
// Ordered waypoints (from · stops · to). A single-leg booking has exactly two.
const waypoints = (r.endpoints || [])
const sorted = (r.endpoints || [])
.filter((e) => e.role === 'from' || e.role === 'to' || e.role === 'stop')
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
const waypoints = frame ? sorted.map((e) => ({ ...e, lng: frameLng(frame, e.lng) })) : sorted;
if (waypoints.length < 2) return null;
const from = waypoints[0];
const to = waypoints[waypoints.length - 1];
@@ -164,12 +168,12 @@ export function transportHop(r: Reservation, wrapArcs: boolean): TransportHop |
const a = waypoints[i];
const b = waypoints[i + 1];
const segArcs = isGeo
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], wrapArcs)
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], wrapArcs, frame)
: [
[
frameLine(frame, [
[a.lat, a.lng],
[b.lat, b.lng],
] as [number, number][],
] as [number, number][]),
];
arcs.push(...segArcs);
distanceKm += haversineKm(a, b);
@@ -78,31 +78,61 @@ describe('tripRouteGeometry', () => {
expect(calculateRouteWithLegs).not.toHaveBeenCalled()
})
it('FE-MAP-TRG-005: the deadline gives back what answered and leaves the rest as straight lines', async () => {
neverAnswers()
// The PDF used to route under an 8 s deadline: with a second between two requests that
// is about seven legs, so a month-long trip printed most of its days as straight lines
// and a total that looked final, and every export routed a few more days (#2876).
it('FE-MAP-TRG-005: a long trip is routed to its last leg, and says how far it has got', async () => {
const days = Array.from({ length: 12 }, (_, i) => buildDay({ id: i + 1, day_number: i + 1 }))
const assignments: AssignmentsMap = Object.fromEntries(days.map(day => [
String(day.id),
[at(48 + day.id / 10, 2.35, 0, day.id), at(48 + day.id / 10, 2.45, 1, day.id)],
]))
vi.useFakeTimers()
try {
const pending = routeTrip(input, { profile: 'driving', tripId: 7, timeoutMs: 8000 })
await vi.advanceTimersByTimeAsync(8100)
vi.mocked(calculateRouteWithLegs).mockImplementation(() => new Promise(resolve => {
setTimeout(() => resolve({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] }), 100)
}))
const onProgress = vi.fn<(done: number, total: number) => void>()
const pending = routeTrip({ ...input, days, assignments }, { profile: 'driving', tripId: 7, onProgress })
await vi.advanceTimersByTimeAsync(12 * 1200)
const summary = await pending
// The shape of the trip survives...
expect(summary.lines).toHaveLength(2)
expect(summary.lines[0]).toEqual([[48.86, 2.35], [48.90, 2.42]])
// ...and nothing that never answered is counted.
expect(summary.totalDistance).toBe(0)
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(12)
expect(summary.unroutedLegs).toBe(0)
expect(summary.totalDistance).toBe(120000)
expect(onProgress.mock.calls[0]).toEqual([0, 12])
expect(onProgress.mock.calls.map(([done]) => done)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
expect(onProgress.mock.calls.every(([, total]) => total === 12)).toBe(true)
} finally {
vi.useRealTimers()
}
})
it('FE-MAP-TRG-006: a caller\'s own abort cuts the routing short too', async () => {
it("FE-MAP-TRG-006: a caller's own abort cuts the routing short, and what never answered is counted", async () => {
neverAnswers()
const controller = new AbortController()
const pending = routeTrip(input, { profile: 'driving', tripId: 7, timeoutMs: 60_000, signal: controller.signal })
const pending = routeTrip(input, { profile: 'driving', tripId: 7, signal: controller.signal })
controller.abort()
await expect(pending).resolves.toMatchObject({ totalDistance: 0 })
await expect(pending).resolves.toMatchObject({ totalDistance: 0, unroutedLegs: 2 })
})
it('FE-MAP-TRG-014: a host that never answers costs one leg its road, not the whole round', async () => {
neverAnswers()
vi.useFakeTimers()
try {
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
await vi.advanceTimersByTimeAsync(30_000)
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1100 + 30_000)
const summary = await pending
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
expect(summary.lines).toHaveLength(2)
expect(summary.unroutedLegs).toBe(2)
} finally {
vi.useRealTimers()
}
})
// The public OSRM hosts allow about one request a second. Every leg of every day at
+35 -20
View File
@@ -29,7 +29,7 @@ export interface TripOverviewDay {
modes: string[]
/**
* Legs drawn as a straight line because the router gave no road for them: not asked
* yet while the round is running, refused or cut off by the deadline once it is over.
* yet while the round is running, refused, timed out or skipped by the caller once it is over.
* Those legs add nothing to `distance`, so a day with any of them reads too short.
*/
unroutedLegs?: number
@@ -56,7 +56,7 @@ export interface TripRouteSummary {
interface Chunk { points: DayRoutePoint[]; mode: string; waypoints: { lat: number; lng: number }[]; stopAt: number[] }
/** The day inputs plus the road trip's vias, which bend a day the way it was picked there (#2580). */
interface TripRouteInputs extends DayRouteInputs {
export interface TripRouteInputs extends DayRouteInputs {
/** The stored day lists the vias are anchored in, hidden rows included. Absent: `assignments`. */
storedAssignments?: AssignmentsMap
viasByDay?: Record<number, readonly RoadtripVia[]>
@@ -187,6 +187,15 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
const REQUEST_SPACING_MS = 1100
/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */
const CACHE_HIT_MS = 60
/**
* The longest one leg may take, its rate-limit retries included. The OSRM request has no
* deadline of its own, and a round that waits for every leg must not hang on a host that
* accepted the connection and never answered.
*/
const LEG_TIMEOUT_MS = 30_000
/** How far a routing round has got: legs answered or given up on, out of all it asks. */
export type TripRouteProgress = (done: number, total: number) => void
/**
* Ask the router for every leg of every day, one at a time.
@@ -206,13 +215,15 @@ const CACHE_HIT_MS = 60
*/
export async function routeTripLegs(
plan: TripRoutePlanDay[],
{ tripId, signal, onAnswer, unit }: {
{ tripId, signal, onAnswer, onProgress, unit }: {
tripId: number | null
signal?: AbortSignal
/** The unit a leg bent through vias has its text written again in. */
unit?: DistanceUnit
/** Called after each answer, for a caller that wants to draw as they arrive. */
onAnswer?: (routed: Answer[][][]) => void
/** Called once before the first leg and again after every leg, answered or not. */
onProgress?: TripRouteProgress
},
): Promise<Answer[][][]> {
const routed = emptyAnswers(plan)
@@ -222,25 +233,34 @@ export async function routeTripLegs(
chunks.forEach((chunk, c) => {
tasks.push(async () => {
if (signal?.aborted) return
const leg = new AbortController()
const abortLeg = () => leg.abort()
const timer = setTimeout(abortLeg, LEG_TIMEOUT_MS)
signal?.addEventListener('abort', abortLeg, { once: true })
try {
const answer = await calculateRouteWithRetries(
chunk.waypoints,
{ signal, profile: chunk.mode, tripId, dayId: day.id },
{ signal: leg.signal, profile: chunk.mode, tripId, dayId: day.id },
)
routed[d][r][c] = { coordinates: answer.coordinates, legs: foldViaLegs(answer.legs, chunk.stopAt, unit) }
onAnswer?.(routed)
} catch {
// Refused for good, or aborted: the leg keeps its straight line.
// Refused for good, timed out or aborted: the leg keeps its straight line.
} finally {
clearTimeout(timer)
signal?.removeEventListener('abort', abortLeg)
}
})
})
})
})
onProgress?.(0, tasks.length)
for (let i = 0; i < tasks.length; i++) {
if (signal?.aborted) break
const startedAt = performance.now()
await tasks[i]()
onProgress?.(i + 1, tasks.length)
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, signal)
}
@@ -250,30 +270,25 @@ export async function routeTripLegs(
/**
* The whole thing end to end, for a caller with no need to draw the intermediate state.
*
* `timeoutMs` stops waiting rather than stopping the work: legs that answered are kept
* and the rest stay straight lines, which is what makes this usable from an export
* somebody is standing in front of. A month-long trip with a cold cache is a few hundred
* requests against a shared router, and no document is worth that wait.
* Waits for every leg: a cold month-long trip is a few minutes against a shared router,
* which is why `onProgress` exists, and the pacing, the retry limit and the per-leg
* timeout keep that wait finite. A document printed after a deadline looked finished
* while most of its days were straight lines (#2876). The caller's `signal` is the only
* way to stop early; the legs that answered by then are kept, the rest stay straight
* lines and are counted in `unroutedLegs`.
*/
export async function routeTrip(
input: TripRouteInputs,
{ profile, tripId, signal, timeoutMs, unit }: {
{ profile, tripId, signal, unit, onProgress }: {
profile: RouteProfileKey
tripId: number | null
signal?: AbortSignal
timeoutMs?: number
unit?: DistanceUnit
onProgress?: TripRouteProgress
},
): Promise<TripRouteSummary> {
const plan = planTripRoute(input, profile)
if (!plan.length) return summariseTripRoute([])
const deadline = timeoutMs ? new AbortController() : null
const timer = deadline ? setTimeout(() => deadline.abort(), timeoutMs) : null
if (deadline && signal) signal.addEventListener('abort', () => deadline.abort(), { once: true })
try {
const routed = await routeTripLegs(plan, { tripId, signal: deadline?.signal ?? signal, unit })
return summariseTripRoute(assembleTripRoute(plan, routed))
} finally {
if (timer) clearTimeout(timer)
}
const routed = await routeTripLegs(plan, { tripId, signal, unit, onProgress })
return summariseTripRoute(assembleTripRoute(plan, routed))
}
@@ -0,0 +1,18 @@
import type { DistanceUnit } from '../../types';
import { formatDistance } from '../../utils/units';
type Translate = (key: string, params?: Record<string, string | number>) => string;
/**
* A day's or the trip's distance as the overview panel and the PDF print it.
*
* A leg the router gave no road for is drawn straight and adds nothing to the sum, so a
* figure with such legs in it is a floor, and a figure made of nothing but such legs is
* no figure at all. "0 m" for a day of driving read as a measurement (#2876). One wording
* for the screen and the document, so the two cannot drift apart again.
*/
export function routeDistanceLabel(meters: number, unroutedLegs: number, unit: DistanceUnit, t: Translate): string {
const distance = formatDistance(meters / 1000, unit);
if (unroutedLegs <= 0) return distance;
return meters > 0 ? t('map.overview.distanceAtLeast', { distance }) : t('map.overview.notRouted');
}
@@ -1,6 +1,7 @@
import { useEffect, useLayoutEffect, useRef } from 'react';
import type { AssistantRouteLine } from '../../types/assistantMap';
import { onRealWorld } from '../../utils/worldCopy';
import { mapHoverLabel } from './mapHoverLabel';
import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers';
@@ -245,12 +246,15 @@ export function useAssistantGhostLinesGL({ mapRef, mapReady, lines, onHover, onP
return;
}
handlers.current.onHover?.(ref);
handlers.current.onPoint?.(ref, event.lngLat.lat, event.lngLat.lng);
const at = onRealWorld(event.lngLat);
handlers.current.onPoint?.(ref, at.lat, at.lng);
};
const leave = () => handlers.current.onHover?.(null);
const click = (event: LayerEvent) => {
const ref = refOf(event);
if (ref !== null && !onPlanPin(map, event)) handlers.current.onPoint?.(ref, event.lngLat.lat, event.lngLat.lng);
if (ref === null || onPlanPin(map, event)) return;
const at = onRealWorld(event.lngLat);
handlers.current.onPoint?.(ref, at.lat, at.lng);
};
const stop = (event: LayerEvent) => {
const name = event.features?.[0]?.properties?.label;
@@ -1,5 +1,6 @@
import { useEffect, useLayoutEffect, useRef } from 'react';
import { onRealWorld } from '../../utils/worldCopy';
import { bindPinHoverLabel, mapHoverLabel } from './mapHoverLabel';
import type { MapViewProps } from './mapViewContract';
import { plannerPinBadge, plannerPinShape } from './plannerPinShape';
@@ -102,7 +103,7 @@ export function usePlannerWaypointMarkersGL<Pin extends PlannerWaypointPin>({
coordinateAt: (clientX, clientY) => {
const rect = map.getContainer().getBoundingClientRect();
const at = map.unproject([clientX - rect.left, clientY - rect.top]);
return { lat: at.lat, lng: at.lng };
return onRealWorld({ lat: at.lat, lng: at.lng });
},
setPosition: ({ lat, lng }) => pin.setLngLat([lng, lat]),
onCommit: ({ lat, lng }) =>
@@ -0,0 +1,331 @@
import { encodePolyline6 } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { useSettingsStore } from '../../store/settingsStore';
import type { Settings, Waypoint } from '../../types';
import { calculateAlternatives, calculateRouteWithLegs, routeEngineFor } from './RouteCalculator';
import { resetValhallaTurns } from './valhallaRoute';
const RELAY = '/api/routing/valhalla/route';
const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de/route';
const OWN_VALHALLA = 'https://valhalla.example.org';
const OSRM = {
driving: 'https://routing.openstreetmap.de/routed-car/route/v1/driving',
walking: 'https://routing.openstreetmap.de/routed-foot/route/v1/foot',
cycling: 'https://routing.openstreetmap.de/routed-bike/route/v1/bike',
} as const;
const PROFILES = [
['driving', 'auto'],
['walking', 'pedestrian'],
['cycling', 'bicycle'],
] as const;
type Point = { lat: number; lon: number };
type RouteBody = { locations: Point[]; costing: string; costing_options: unknown; alternates?: number };
let seed = 0;
/** Points no other test asked for, so neither route cache answers in their place. */
function freshDay(count: number): Waypoint[] {
seed += 1;
return Array.from({ length: count }, (_, i) => ({ lat: 40 + seed / 100, lng: 5 + i / 100 }));
}
/** Valhalla's trip through some points: one leg per pair, two kilometres and five minutes each. */
function valhallaTrip(points: Point[]) {
const legs = points.slice(1).map((to, i) => ({
shape: encodePolyline6([points[i], to]),
summary: { length: 2, time: 300, has_toll: false, has_highway: false, has_ferry: false },
}));
return { legs, summary: { length: 2 * legs.length, time: 300 * legs.length } };
}
/** OSRM's answer for a request's coordinates: one leg per pair, a kilometre and two minutes each. */
function osrmAnswer(coords: string) {
const points = coords.split(';').map((pair) => pair.split(',').map(Number));
const legs = points.slice(1).map(() => ({ distance: 1000, duration: 120 }));
return {
code: 'Ok',
routes: [{ geometry: { coordinates: points }, distance: 1000 * legs.length, duration: 120 * legs.length, legs }],
waypoints: points.map((location) => ({ location, distance: 0 })),
};
}
interface Traffic {
relay: RouteBody[];
fossgis: RouteBody[];
own: RouteBody[];
osrm: string[];
}
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
function listen(relay: (body: RouteBody) => Response = answered): Traffic {
const traffic: Traffic = { relay: [], fossgis: [], own: [], osrm: [] };
const valhalla =
(asked: RouteBody[], answer: (body: RouteBody) => Response) =>
async ({ request }: { request: Request }) => {
const body = (await request.json()) as RouteBody;
asked.push(body);
return answer(body);
};
server.use(
http.post(RELAY, valhalla(traffic.relay, relay)),
http.post(FOSSGIS_VALHALLA, valhalla(traffic.fossgis, answered)),
http.post(`${OWN_VALHALLA}/route`, valhalla(traffic.own, answered)),
...Object.values(OSRM).map((base) =>
http.get(`${base}/:coords`, ({ request, params }) => {
traffic.osrm.push(request.url);
return HttpResponse.json(osrmAnswer(String(params.coords)));
})
)
);
return traffic;
}
const choose = (patch: Partial<Settings>) =>
useSettingsStore.setState((st) => ({ settings: { ...st.settings, ...patch } }));
afterEach(() => {
choose({ routing_valhalla_provider: '', valhalla_base_url: '', routing_base_url: '' });
resetValhallaTurns();
vi.restoreAllMocks();
});
describe('which engine routes a day', () => {
it.each(PROFILES)('VDAY-ENGINE-001: the TREK services and an own Valhalla route every %s day', (profile) => {
choose({ routing_valhalla_provider: 'trek' });
expect([routeEngineFor(profile, []), routeEngineFor(profile, ['toll'])]).toEqual(['valhalla', 'valhalla']);
choose({ routing_valhalla_provider: '', valhalla_base_url: OWN_VALHALLA });
expect([routeEngineFor(profile, []), routeEngineFor(profile, ['toll'])]).toEqual(['valhalla', 'valhalla']);
choose({ routing_valhalla_provider: 'custom' });
expect(routeEngineFor(profile, [])).toBe('valhalla');
});
it.each(PROFILES)('VDAY-ENGINE-002: with FOSSGIS a %s day goes to Valhalla only to avoid by car', (profile) => {
choose({ routing_valhalla_provider: 'fossgis' });
expect(routeEngineFor(profile, [])).toBe('osrm');
expect(routeEngineFor(profile, ['toll'])).toBe(profile === 'driving' ? 'valhalla' : 'osrm');
});
it('VDAY-ENGINE-003: an own OSRM alone keeps every day, and a plugin its own', () => {
choose({ routing_base_url: 'https://osrm.example.org' });
expect(PROFILES.map(([profile]) => routeEngineFor(profile, ['toll']))).toEqual(['osrm', 'osrm', 'osrm']);
choose({ routing_valhalla_provider: 'trek' });
expect(routeEngineFor('plugin:ev/fast', [])).toBe('plugin');
});
it('VDAY-ENGINE-004: while the relay rests the days stay planned with Valhalla, and OSRM draws them and says so', async () => {
const traffic = listen(() => HttpResponse.json({ error: 'resting' }, { status: 503 }));
expect((await calculateRouteWithLegs(freshDay(2), { profile: 'driving' })).engine).toBe('osrm');
expect((await calculateRouteWithLegs(freshDay(2), { profile: 'driving' })).engine).toBe('osrm');
expect(routeEngineFor('driving', [])).toBe('valhalla');
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 2]);
});
});
describe('a day where Valhalla routes the days', () => {
it.each(PROFILES)('VDAY-001: a %s day goes to the relay as %s, OSRM never asked', async (profile, costing) => {
const traffic = listen();
const route = await calculateRouteWithLegs(freshDay(3), { profile });
expect(traffic.relay.map((body) => [body.costing, body.costing_options, body.locations.length])).toEqual([
[costing, { [costing]: {} }, 3],
]);
expect(traffic.osrm).toEqual([]);
expect(traffic.fossgis).toEqual([]);
expect([route.distance, route.duration, route.legs.length, route.snapped?.length]).toEqual([4000, 600, 2, 3]);
expect(route.legs[0]).toMatchObject({ distanceText: '2 km', durationText: '5 min' });
expect(route).not.toHaveProperty('avoidance');
expect(route.engine).toBe('valhalla');
});
it('VDAY-002: the relay takes twenty locations a request, an own Valhalla too', async () => {
let traffic = listen();
await calculateRouteWithLegs(freshDay(12), { profile: 'driving' });
expect(traffic.relay.map((body) => body.locations.length)).toEqual([12]);
choose({ valhalla_base_url: OWN_VALHALLA });
traffic = listen();
const route = await calculateRouteWithLegs(freshDay(25), { profile: 'cycling' });
const asked = traffic.own.map((body) => body.locations);
expect(asked.map((locations) => locations.length)).toEqual([20, 6]);
expect(asked[1][0]).toEqual(asked[0][19]);
expect(route.legs).toHaveLength(24);
expect(traffic.relay).toEqual([]);
});
it('VDAY-003: where the relay cannot answer, OSRM routes the whole day and FOSSGIS is never asked', async () => {
const refusals: Array<() => Response> = [
() => HttpResponse.json({ error: 'Unauthorized' }, { status: 401 }),
() => HttpResponse.json({ error: 'Forbidden' }, { status: 403 }),
() => HttpResponse.json({ error: 'Too large' }, { status: 413 }),
() => HttpResponse.json({ error: 'Too many routing requests' }, { status: 429 }),
() => HttpResponse.json({ error: 'down' }, { status: 500 }),
() => HttpResponse.json({ error: 'The TREK routing service is resting' }, { status: 503 }),
() => HttpResponse.json({ error: 'Expected number, received string' }, { status: 400 }),
() => HttpResponse.json({ error_code: 442, error: 'No path could be found for input' }, { status: 400 }),
() => HttpResponse.error(),
];
for (const refusal of refusals) {
resetValhallaTurns();
const traffic = listen(refusal);
const route = await calculateRouteWithLegs(freshDay(3), { profile: 'walking' });
expect([route.distance, route.legs.length]).toEqual([2000, 2]);
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([1, 0, 1]);
expect(traffic.osrm[0]).toContain(OSRM.walking);
expect(route).not.toHaveProperty('avoidance');
expect(route.engine).toBe('osrm');
}
});
it('VDAY-004: a relay that does not answer in time hands the day to OSRM as well', async () => {
const timeout = AbortSignal.timeout.bind(AbortSignal);
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) =>
ms === 12_000 ? AbortSignal.abort(new DOMException('signal timed out', 'TimeoutError')) : timeout(ms)
);
const traffic = listen();
const route = await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
expect(route.distance).toBe(1000);
expect([traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 1]);
});
it('VDAY-004c: a day the relay ran out of time on goes to OSRM alone, and the next day asks the relay again', async () => {
let slow = true;
const traffic = listen((body) =>
slow
? HttpResponse.json({ error: 'The TREK routing service took too long for this route' }, { status: 504 })
: answered(body)
);
const fallen = await calculateRouteWithLegs(freshDay(3), { profile: 'cycling' });
expect([fallen.distance, fallen.engine]).toEqual([2000, 'osrm']);
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([1, 0, 1]);
slow = false;
const next = await calculateRouteWithLegs(freshDay(3), { profile: 'cycling' });
expect([next.distance, next.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
it('VDAY-004b: an own Valhalla that does not answer in time hands the day to OSRM without a second wait', async () => {
choose({ valhalla_base_url: OWN_VALHALLA });
const timeout = AbortSignal.timeout.bind(AbortSignal);
const deadlines = vi
.spyOn(AbortSignal, 'timeout')
.mockImplementation((ms) =>
ms === 12_000 ? AbortSignal.abort(new DOMException('signal timed out', 'TimeoutError')) : timeout(ms)
);
const traffic = listen();
const route = await calculateRouteWithLegs(freshDay(3), { profile: 'cycling' });
expect([route.distance, route.engine]).toEqual([2000, 'osrm']);
expect(deadlines.mock.calls.filter(([ms]) => ms === 12_000)).toHaveLength(1);
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 0, 1]);
});
it('VDAY-005: an own Valhalla that cannot answer leaves the day to OSRM', async () => {
choose({ valhalla_base_url: OWN_VALHALLA });
const traffic = listen();
server.use(http.post(`${OWN_VALHALLA}/route`, () => HttpResponse.json({ error: 'down' }, { status: 502 })));
const route = await calculateRouteWithLegs(freshDay(3), { profile: 'driving' });
expect(route.distance).toBe(2000);
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 0, 1]);
});
it('VDAY-006: a day that avoids something keeps FOSSGIS behind the relay and its ten locations', async () => {
const traffic = listen(() => HttpResponse.json({ error: 'resting' }, { status: 503 }));
const route = await calculateRouteWithLegs(freshDay(12), { profile: 'driving', avoid: ['toll'] });
expect(traffic.relay).toHaveLength(1);
expect(traffic.fossgis.map((body) => body.locations.length)).toEqual([10, 3]);
expect(traffic.osrm).toEqual([]);
expect(route.avoidance).toEqual({ asked: ['toll'], achieved: ['toll'] });
});
it('VDAY-007: with FOSSGIS chosen, a day that avoids nothing is OSRM’s as before', async () => {
choose({ routing_valhalla_provider: 'fossgis' });
const traffic = listen();
const route = await calculateRouteWithLegs(freshDay(3), { profile: 'cycling' });
expect(route.distance).toBe(2000);
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 0, 1]);
});
});
describe('the route cache keeps the engine apart', () => {
it('VDAY-CACHE-001: a day kept from one engine is not handed out as the other’s', async () => {
const points = freshDay(3);
choose({ routing_valhalla_provider: 'trek' });
const traffic = listen();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
choose({ routing_valhalla_provider: 'fossgis' });
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
choose({ routing_valhalla_provider: 'trek' });
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
});
it('VDAY-CACHE-002: OSRM standing in is not filed as the Valhalla day, so the relay is asked again once it is back', async () => {
const points = freshDay(3);
let up = false;
const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
up = true;
resetValhallaTurns();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
});
describe('the route cache while the relay rests', () => {
it('VDAY-CACHE-003: a day kept from Valhalla is still found while the relay rests, as it is offline', async () => {
const points = freshDay(3);
let up = true;
const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
up = false;
await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
const kept = await calculateRouteWithLegs(points, { profile: 'driving' });
expect([kept.distance, kept.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
it('VDAY-CACHE-004: a day that avoids something keeps its key, whichever Valhalla answered it', async () => {
const points = freshDay(3);
const traffic = listen();
await calculateRouteWithLegs(points, { profile: 'driving', avoid: ['toll'] });
choose({ routing_valhalla_provider: 'fossgis' });
const kept = await calculateRouteWithLegs(points, { profile: 'driving', avoid: ['toll'] });
expect(kept.engine).toBe('valhalla');
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([1, 0, 0]);
});
});
describe('other ways for a leg Valhalla routes', () => {
const from = { lat: 47, lng: 9 };
const to = { lat: 47, lng: 9.2 };
it('VDAY-ALT-001: the offers come from the relay, weighed like the day, and OSRM is not asked', async () => {
const traffic = listen((body) => {
const detour = [body.locations[0], { lat: 47.3, lon: 9.1 }, body.locations[1]];
return HttpResponse.json({ trip: valhallaTrip(body.locations), alternates: [{ trip: valhallaTrip(detour) }] });
});
const routes = await calculateAlternatives(from, to, 'driving');
expect(traffic.relay.map((body) => [body.costing, body.alternates])).toEqual([['auto', 2]]);
expect(routes.map((route) => route.engine)).toEqual(['valhalla', 'valhalla']);
expect(routes[1].divergence).not.toBeNull();
expect(traffic.osrm).toEqual([]);
});
it('VDAY-ALT-002: where the relay cannot answer, the offers are OSRM’s like the day', async () => {
const traffic = listen(() => HttpResponse.json({ error: 'resting' }, { status: 503 }));
const routes = await calculateAlternatives(from, to, 'walking');
expect(routes).toHaveLength(1);
expect(routes[0].engine).toBeUndefined();
expect(traffic.fossgis).toEqual([]);
expect(traffic.osrm[0]).toContain('alternatives=3');
});
});
@@ -0,0 +1,173 @@
import { sameRoad } from '@trek/shared';
import { useSettingsStore } from '../../store/settingsStore';
import type { RouteSegment, RouteWithLegs, Waypoint } from '../../types';
import { haversineKm } from '../../utils/geo';
import { formatDuration, legSegment } from './routeText';
import type { RouteAlternative } from './routeTypes';
import { countRoute } from './routeUsageCounter';
import {
legAvoids,
valhallaAvailable,
valhallaDayAlternates,
valhallaDayRun,
valhallaRouteAvoiding,
valhallaSpacing,
type AvoidClass,
type ValhallaLeg,
} from './valhallaRoute';
type Profile = 'driving' | 'walking' | 'cycling';
/**
* Road classes worth asking the router to leave out, in the order they are tried.
*
* OSRM's own alternative search is conservative: it only offers a second road when the
* detour is short enough and shares little enough with the first, so on a long motorway
* run it usually answers with exactly one route, while a perfectly good, slower way over
* the B-roads exists and is what somebody opening "other ways" is looking for. Excluding
* a class asks a different question and reliably produces that road.
*
* Only for driving: the foot and bike profiles have no excludable classes, and asking
* anyway earns an `InvalidOptions` for nothing.
*
* Ferry is on the list for Valhalla's sake and skipped on the OSRM path. OSRM does carry
* a ferry class, but on a leg where a ferry is the only crossing it answers NoRoute
* rather than the long way round, which is not an alternative anybody can use. Valhalla
* weights it instead and drives around, which is the whole point.
*/
export const EXCLUDABLE_CLASSES = ['motorway', 'toll', 'ferry'] as const;
/**
* What the usage counter is told about a question to this engine. Counted by hand
* because it speaks to a different engine with a different verb, and the counter exists
* to answer "how much routing does this instance do": an engine it cannot see is exactly
* the traffic that would go missing from it.
*/
function usage(profile: Profile, surface: 'legs' | 'alternatives', points: readonly Waypoint[]) {
let km = 0;
for (let i = 1; i < points.length; i++) km += haversineKm(points[i - 1], points[i]);
const selfHosted = !!useSettingsStore.getState().settings.routing_base_url?.trim();
return { profile, surface, selfHosted, waypoints: points.length, km };
}
/**
* A whole day from Valhalla, shaped exactly like the OSRM answer so the callers never
* branch on which engine spoke: same leg list, same formatted text, same snap positions.
*
* A day that weighs classes away adds `avoidance`: what was asked for against what the
* road actually turned out to be, which is the only honest way to label a weighting that
* can fail. A day that avoids nothing has no such question and leaves it out.
*
* Null rather than a throw when it cannot answer, so the caller routes the whole day
* with OSRM and the day stays drawn.
*/
export async function valhallaDayRoute(
waypoints: Waypoint[],
profile: Profile,
avoid: AvoidClass[],
signal?: AbortSignal
): Promise<RouteWithLegs | null> {
const sample = usage(profile, 'legs', waypoints);
const run = await valhallaDayRun(waypoints, profile, avoid, signal);
if (!signal?.aborted) countRoute({ ...sample, failed: !run });
if (!run) return null;
const legs = run.legs.map((leg, i): RouteSegment => ({
...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
}));
return {
coordinates: run.total.coordinates,
distance: run.total.distance,
duration: run.total.duration,
legs,
snapped: run.snapped,
...(avoid.length
? { avoidance: { asked: avoid, achieved: avoid.filter((cls) => legAvoids(run.total, cls)) } }
: {}),
hasFerry: run.total.hasFerry,
engine: 'valhalla',
};
}
/** A Valhalla leg as an offer, carrying the engine that priced it and what it crosses. */
function valhallaOffer(leg: ValhallaLeg): RouteAlternative {
return {
coordinates: leg.coordinates,
distance: leg.distance,
duration: leg.duration,
divergence: null,
engine: 'valhalla',
hasFerry: leg.hasFerry,
};
}
/**
* The same leg from Valhalla, weighted away from one class, or null.
*
* The check that makes this honest is `legAvoids`: `use_tolls: 0` is a preference, so
* between two points with no untolled connection the answer is still a tolled road.
* Offering that as "No tolls" would put a lie on the map, so it is dropped and the
* OSRM attempt gets its turn.
*/
export async function valhallaExcluding(
from: Waypoint,
to: Waypoint,
profile: Profile,
exclude: AvoidClass,
signal?: AbortSignal
): Promise<RouteAlternative | null> {
if (!valhallaAvailable()) return null;
const sample = usage(profile, 'alternatives', [from, to]);
const leg = await valhallaRouteAvoiding(from, to, profile, exclude, signal);
if (!signal?.aborted) countRoute({ ...sample, failed: !leg });
if (!leg || !legAvoids(leg, exclude)) return null;
return valhallaOffer(leg);
}
/**
* The offers for one leg of a day Valhalla routes, every one of them Valhalla's and
* weighed the way the day was, or null when it has nothing to say. Quietly offering
* OSRM's roads beside a Valhalla day is the mix that offered a road the rail was not on
* as the quicker one, and clicking it changed nothing.
*
* Where the router offers a single way, a driving leg gets the question the OSRM path
* asks too: the same drive with one more class left out, only of those the day does not
* already avoid, and only where the road that comes back really is without it. Paced
* like the pieces of a split day, because the public instance allows one request a second.
*/
export async function valhallaDayAlternatives(
from: Waypoint,
to: Waypoint,
profile: Profile,
avoiding: AvoidClass[],
{ limit, signal }: { limit: number; signal?: AbortSignal }
): Promise<RouteAlternative[] | null> {
const sample = usage(profile, 'alternatives', [from, to]);
const answered = await valhallaDayAlternates(from, to, profile, avoiding, { count: Math.max(0, limit - 1), signal });
if (!signal?.aborted) countRoute({ ...sample, failed: !answered });
if (!answered?.length) return null;
const routes: RouteAlternative[] = [];
for (const leg of answered) {
const offer = valhallaOffer(leg);
if (!routes.some((r) => sameRoad(r, offer))) routes.push(offer);
}
if (routes.length >= 2 || profile !== 'driving') return routes;
for (const cls of EXCLUDABLE_CLASSES) {
if (avoiding.includes(cls)) continue;
await valhallaSpacing(signal);
if (signal?.aborted) break;
const run = await valhallaDayRun([from, to], 'driving', [...avoiding, cls], signal);
if (!signal?.aborted) countRoute({ ...sample, failed: !run });
if (!run || !legAvoids(run.total, cls)) continue;
const detour = valhallaOffer(run.total);
if (routes.some((r) => sameRoad(r, detour))) continue;
routes.push({ ...detour, avoids: cls });
break;
}
return routes;
}
@@ -0,0 +1,45 @@
import type { FerrySpan } from './valhallaRoute';
/** One step of a Valhalla leg, with the fields the ferry spans are read from. */
export interface ValhallaManeuver {
type?: number;
ferry?: boolean;
begin_shape_index?: number;
end_shape_index?: number;
time?: number;
length?: number;
}
/** Valhalla's maneuver type for boarding a ferry; the maneuver also carries `ferry: true` for its crossing. */
const FERRY_ENTER = 28;
/**
* CW-12: the stretches of a leg the router takes by boat, read off its
* maneuvers: a crossing is the maneuver that boards the ferry, from the point
* it starts at to the one it ends at, with its own length and time. Measured
* on Venice, the San Tomà to Ca' Rezzonico line came back as one maneuver of
* type 28, ferry true, 1.236 km and 745 s over shape points 24 to 46, then the
* walk off it. Crossings that touch are one. A leg the summary says has a
* ferry but whose maneuvers do not say where is taken whole, without a time:
* the crossing is somewhere on it, and none of it is counted as walked.
*/
export function ferrySpansOf(maneuvers: ValhallaManeuver[] | undefined, points: number): FerrySpan[] {
const spans: FerrySpan[] = [];
for (const maneuver of maneuvers ?? []) {
if (maneuver.ferry !== true && maneuver.type !== FERRY_ENTER) continue;
const from = Number(maneuver.begin_shape_index);
const to = Number(maneuver.end_shape_index);
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to <= from || to >= points) continue;
const metres = Number.isFinite(maneuver.length) ? Number(maneuver.length) * 1000 : 0;
const seconds = Number.isFinite(maneuver.time) ? Number(maneuver.time) : null;
const previous = spans[spans.length - 1];
if (previous && previous.to === from) {
previous.to = to;
previous.metres += metres;
previous.seconds = previous.seconds === null || seconds === null ? null : previous.seconds + seconds;
} else {
spans.push({ from, to, metres, seconds });
}
}
return spans.length || points < 2 ? spans : [{ from: 0, to: points - 1, metres: 0, seconds: null }];
}
+233 -19
View File
@@ -5,6 +5,8 @@ import { useSettingsStore } from '../../store/settingsStore'
import { valhallaBase, valhallaAvailable, valhallaTurn, resetValhallaTurns, valhallaRouteAvoiding, valhallaRun, valhallaRunOnFoot, valhallaAlternates, alternatesFrom, runFrom, legAvoids, valhallaTraceAttributes } from './valhallaRoute'
const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de/route'
/** The relay to the TREK services' Valhalla, the base asked when nothing else is configured. */
const TREK_VALHALLA = '/api/routing/valhalla'
/**
* A real polyline6, encoded from three known points and verified by decoding it back.
@@ -36,7 +38,7 @@ const setSettings = (patch: Record<string, string>) =>
useSettingsStore.setState(st => ({ settings: { ...st.settings, ...patch } }))
afterEach(() => {
setSettings({ routing_base_url: '', valhalla_base_url: '' })
setSettings({ routing_base_url: '', valhalla_base_url: '', routing_valhalla_provider: '' })
resetValhallaTurns()
})
@@ -92,11 +94,20 @@ const HAMBURG = { lat: 53.5511, lng: 9.9937 }
const BERLIN = { lat: 52.52, lng: 13.405 }
describe('valhallaBase', () => {
it('VALHALLA-BASE-001: falls back to the public instance when nothing is configured', () => {
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
it('VALHALLA-BASE-001: asks the TREK services through the relay when nothing is configured', () => {
expect(valhallaBase()).toBe(TREK_VALHALLA)
expect(valhallaAvailable()).toBe(true)
})
it('VALHALLA-BASE-005: keeps the admin choice of a routing service', () => {
setSettings({ routing_valhalla_provider: 'fossgis', valhalla_base_url: 'https://v.example.org' })
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
setSettings({ routing_valhalla_provider: 'custom' })
expect(valhallaBase()).toBe('https://v.example.org')
setSettings({ routing_valhalla_provider: 'trek', valhalla_base_url: '', routing_base_url: 'https://osrm.example.org' })
expect(valhallaBase()).toBe(TREK_VALHALLA)
})
it('VALHALLA-BASE-002: uses the configured instance and drops its trailing slashes', () => {
setSettings({ valhalla_base_url: 'https://valhalla.example.org//' })
expect(valhallaBase()).toBe('https://valhalla.example.org')
@@ -123,9 +134,9 @@ describe('runFrom', () => {
it('VALHALLA-PARSE-001: decodes the shape as polyline6 and converts km to metres', () => {
const leg = total(answer())
expect(leg).not.toBeNull()
expect(leg!.coordinates).toEqual(SHAPE_POINTS)
expect(leg!.distance).toBeCloseTo(295700, 0)
expect(leg!.duration).toBe(11460)
expect(leg?.coordinates).toEqual(SHAPE_POINTS)
expect(leg?.distance).toBeCloseTo(295700, 0)
expect(leg?.duration).toBe(11460)
})
it('VALHALLA-PARSE-002: carries the flags through as booleans', () => {
@@ -153,15 +164,15 @@ describe('runFrom', () => {
summary: { length: 150, time: 5400, has_toll: true, has_highway: true, has_ferry: false },
},
}
const run = runFrom(chain)!
expect(run.legs.map(l => l.distance)).toEqual([100000, 50000])
expect(run.legs.map(l => l.hasToll)).toEqual([false, true])
expect(run.total.distance).toBe(150000)
expect(run.total.duration).toBe(5400)
const run = runFrom(chain)
expect(run?.legs.map(l => l.distance)).toEqual([100000, 50000])
expect(run?.legs.map(l => l.hasToll)).toEqual([false, true])
expect(run?.total.distance).toBe(150000)
expect(run?.total.duration).toBe(5400)
// One tolled leg makes the drive tolled. `every` here would call a day with a
// single toll booth in it toll-free.
expect(run.total.hasToll).toBe(true)
expect(run.total.coordinates).toHaveLength(SHAPE_POINTS.length * 2)
expect(run?.total.hasToll).toBe(true)
expect(run?.total.coordinates).toHaveLength(SHAPE_POINTS.length * 2)
})
it('VALHALLA-PARSE-007: several legs with no summaries of their own are refused', () => {
@@ -217,7 +228,7 @@ describe('valhallaRouteAvoiding', () => {
})
)
const leg = await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
expect(leg!.distance).toBeCloseTo(295700, 0)
expect(leg?.distance).toBeCloseTo(295700, 0)
expect(body).toMatchObject({
costing: 'auto',
costing_options: { auto: { use_tolls: 0 } },
@@ -353,6 +364,7 @@ describe('valhallaRun over a whole day', () => {
costing: 'pedestrian',
costing_options: { pedestrian: { max_hiking_difficulty: difficulty, use_ferry: 0 } },
directions_options: { units: 'kilometers' },
directions_type: 'maneuvers',
})
})
@@ -367,8 +379,8 @@ describe('valhallaRun over a whole day', () => {
const run = await valhallaRun(stops(6), 'driving', [])
expect(calls).toBe(1)
expect(run!.legs).toHaveLength(5)
expect(run!.total.distance).toBe(50000)
expect(run?.legs).toHaveLength(5)
expect(run?.total.distance).toBe(50000)
})
it('VALHALLA-RUN-008: forwards caller-specific costing options only when supplied', async () => {
@@ -403,8 +415,8 @@ describe('valhallaRun over a whole day', () => {
// takes the remaining five. Nine pairs plus four.
expect(sizes).toEqual([10, 5])
// Thirteen pairs across two requests, none lost and none counted twice.
expect(run!.legs).toHaveLength(13)
expect(run!.total.distance).toBe(130000)
expect(run?.legs).toHaveLength(13)
expect(run?.total.distance).toBe(130000)
})
it('VALHALLA-RUN-003: never sends more than ten locations, however long the day', async () => {
@@ -453,11 +465,58 @@ describe('valhallaRun over a whole day', () => {
const run = await valhallaRun(stops(14), 'driving', ['toll'])
expect(run!.legs).toHaveLength(13)
expect(run?.legs).toHaveLength(13)
// First piece, second piece refused, second piece again.
expect(calls).toBe(3)
})
it('VALHALLA-RUN-009: asks the relay twenty locations at a time with no pause between the pieces', async () => {
const sizes: number[] = []
let fossgis = 0
server.use(
http.post('/api/routing/valhalla/:action', async ({ request }) => {
const body = await request.json() as { locations: unknown[] }
sizes.push(body.locations.length)
return HttpResponse.json(chain(body.locations.length - 1))
}),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(chain(1)) }),
)
const started = Date.now()
const avoiding = await valhallaRun(stops(14), 'driving', ['toll'])
const long = await valhallaRun(stops(25), 'driving', ['toll'])
expect(avoiding?.legs).toHaveLength(13)
expect(long?.legs).toHaveLength(24)
expect(sizes).toEqual([14, 20, 6])
// The pause between pieces was 1.1 s; the relay and an own Valhalla are not paced.
expect(Date.now() - started).toBeLessThan(1000)
expect(fossgis).toBe(0)
})
it('VALHALLA-RUN-010: a day cut for the relay that the relay cannot answer is cut again in tens for FOSSGIS', async () => {
const relayed: number[] = []
const sizes: number[] = []
server.use(
http.post('/api/routing/valhalla/:action', async ({ request }) => {
relayed.push(((await request.json()) as { locations: unknown[] }).locations.length)
return HttpResponse.json({ error: 'down' }, { status: 502 })
}),
http.post(FOSSGIS_VALHALLA, async ({ request }) => {
const body = await request.json() as { locations: unknown[] }
sizes.push(body.locations.length)
return HttpResponse.json(chain(body.locations.length - 1))
}),
)
const run = await valhallaRun(stops(14), 'driving', ['toll'])
expect(run?.legs).toHaveLength(13)
expect(relayed).toEqual([14])
// FOSSGIS never saw the piece of fourteen it would have refused with error 150.
expect(sizes).toEqual([10, 5])
})
it('VALHALLA-RUN-005: fewer than two points is nothing to route', async () => {
let calls = 0
server.use(http.post(FOSSGIS_VALHALLA, () => { calls++; return HttpResponse.json(chain(1)) }))
@@ -705,3 +764,158 @@ describe('crossings by boat on a walk (CW-12)', () => {
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toBeNull()
})
})
describe('through the TREK services (routing relay)', () => {
const RELAY = '/api/routing/valhalla/:action'
it('VALHALLA-RELAY-001: asks the relay first, and FOSSGIS is not asked while it answers', async () => {
const relayed: Array<{ action: string; body: Record<string, unknown> }> = []
let fossgis = 0
server.use(
http.post(RELAY, async ({ params, request }) => {
relayed.push({ action: String(params.action), body: await request.json() as Record<string, unknown> })
return HttpResponse.json(answer({ has_toll: false }))
}),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
const leg = await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
expect(leg).not.toBeNull()
expect(leg?.distance).toBeCloseTo(295700, 0)
expect(relayed).toHaveLength(1)
expect(relayed[0].action).toBe('route')
expect(relayed[0].body).toMatchObject({
costing: 'auto',
costing_options: { auto: { use_tolls: 0 } },
directions_type: 'maneuvers',
})
expect(fossgis).toBe(0)
})
it('VALHALLA-RELAY-009: a question the relay ran out of time on has no answer, without resting the relay or asking FOSSGIS', async () => {
let relayCalls = 0
let fossgis = 0
server.use(
http.post(RELAY, () => {
relayCalls++
return HttpResponse.json({ error: 'The TREK routing service took too long for this route' }, { status: 504 })
}),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'cycling', 'ferry')).resolves.toBeNull()
// Asked once: the relay would only run out of time on it again.
expect([relayCalls, fossgis]).toEqual([1, 0])
expect(valhallaBase()).toBe(TREK_VALHALLA)
server.use(http.post(RELAY, () => { relayCalls++; return HttpResponse.json(answer()) }))
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')).resolves.not.toBeNull()
expect([relayCalls, fossgis]).toEqual([2, 0])
})
it('VALHALLA-RELAY-002: turns to FOSSGIS without a word where the relay cannot answer, and leaves it alone a while', async () => {
for (const status of [401, 429, 503]) {
resetValhallaTurns()
let relayCalls = 0
let fossgis = 0
server.use(
http.post(RELAY, () => { relayCalls++; return HttpResponse.json({ error: 'no' }, { status }) }),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')).resolves.not.toBeNull()
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now() + 2000)
await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'ferry')
vi.useRealTimers()
expect([status, relayCalls, fossgis]).toEqual([status, 1, 2])
}
})
it('VALHALLA-RELAY-003: asks the relay again once the rest is over', async () => {
let relayCalls = 0
server.use(
http.post(RELAY, () => { relayCalls++; return HttpResponse.json({ error: 'no' }, { status: 503 }) }),
http.post(FOSSGIS_VALHALLA, () => HttpResponse.json(answer())),
)
await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
expect(relayCalls).toBe(1)
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now() + 11 * 60_000)
expect(valhallaBase()).toBe(TREK_VALHALLA)
vi.useRealTimers()
})
it("VALHALLA-RELAY-004: reads Valhalla's own refusal through the relay as no way, without asking FOSSGIS", async () => {
let fossgis = 0
server.use(
http.post(RELAY, () => HttpResponse.json({ error_code: 442, error: 'No path could be found for input' }, { status: 400 })),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
const points = [HAMBURG, BERLIN]
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toEqual({ noPath: true })
expect(fossgis).toBe(0)
expect(valhallaBase()).toBe(TREK_VALHALLA)
})
it('VALHALLA-RELAY-005: describes a line through the relay as a polyline', async () => {
const bodies: Record<string, unknown>[] = []
server.use(http.post(RELAY, async ({ request }) => {
bodies.push(await request.json() as Record<string, unknown>)
return HttpResponse.json({ edges: [] })
}))
await expect(valhallaTraceAttributes(SHAPE_POINTS)).resolves.toEqual({ edges: [] })
expect(bodies[0]).not.toHaveProperty('shape')
expect(bodies[0]).toMatchObject({ encoded_polyline: expect.any(String), costing: 'bicycle', shape_match: 'map_snap' })
})
it('VALHALLA-RELAY-006: reads a 400 without error_code, and a route the server does not have, as the relay unable to answer', async () => {
const refusals = [
() => HttpResponse.json({ error: 'Expected number, received string' }, { status: 400 }),
() => new HttpResponse('Not Found', { status: 404 }),
() => HttpResponse.json({ error: 'Method Not Allowed' }, { status: 405 }),
]
for (const refusal of refusals) {
resetValhallaTurns()
let fossgis = 0
server.use(
http.post(RELAY, refusal),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')).resolves.not.toBeNull()
expect(fossgis).toBe(1)
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
}
})
it('VALHALLA-RELAY-007: rests the relay as long as its Retry-After says, at most an hour', async () => {
for (const [retryAfter, restMs] of [['30', 30_000], ['86400', 60 * 60_000]] as const) {
resetValhallaTurns()
server.use(
http.post(RELAY, () => HttpResponse.json({ error: 'spent' }, { status: 429, headers: { 'Retry-After': retryAfter } })),
http.post(FOSSGIS_VALHALLA, () => HttpResponse.json(answer())),
)
await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now() + restMs - 1000)
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
vi.setSystemTime(Date.now() + 2000)
expect(valhallaBase()).toBe(TREK_VALHALLA)
vi.useRealTimers()
}
})
it('VALHALLA-RELAY-008: gives up on a relay that does not answer in time and asks FOSSGIS', async () => {
const timeout = AbortSignal.timeout.bind(AbortSignal)
const spy = vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms =>
ms === 12_000 ? AbortSignal.abort(new DOMException('signal timed out', 'TimeoutError')) : timeout(ms))
let fossgis = 0
server.use(
http.post(RELAY, () => HttpResponse.json(answer())),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')).resolves.not.toBeNull()
expect(spy).toHaveBeenCalledWith(12_000)
expect(fossgis).toBe(1)
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
spy.mockRestore()
})
})
+348 -122
View File
@@ -1,5 +1,15 @@
import {
resolveValhallaProvider,
VALHALLA_COSTING,
VALHALLA_RELAY_MAX_LOCATIONS,
valhallaRoutesEveryDay,
type ValhallaProvider,
type ValhallaRelayAction,
} from '@trek/shared'
import { valhallaRelayRepo } from '../../repo/valhallaRelayRepo'
import { useSettingsStore } from '../../store/settingsStore'
import { decodePolyline } from './transitGeometry'
import { ferrySpansOf, type ValhallaManeuver } from './valhallaFerries'
import { haversineKm } from '../../utils/geo'
import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
@@ -16,7 +26,8 @@ import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
* module is the adapter: same question, different engine, answer shaped like the OSRM
* one so the callers do not have to care which engine spoke.
*
* Deliberately NOT a replacement for the OSRM path. Three measured reasons:
* On the public instance it is deliberately NOT a replacement for the OSRM path. Three
* measured reasons:
* - it caps at ten locations, and following a track sends a day's stops plus up to
* nine anchors, so the bundled requests would start failing;
* - it refuses a point it cannot bind to a road, where OSRM still snaps one. The
@@ -31,13 +42,41 @@ import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
* subtracting one engine's figure from the other's, which is what an offer beside
* a route invites, measures the gap between two speed models and nothing else.
*
* Which leaves exactly the shape this module serves: two points, one avoidance, asked
* on demand, drawn as an offer next to the route rather than replacing it.
* Which leaves exactly the shape this module serves there: two points, one avoidance,
* asked on demand, drawn as an offer next to the route rather than replacing it.
*
* The TREK services' Valhalla and an own one take twenty locations and no pace of one a
* second, so with either of them this engine routes every day (`valhallaDayRun`), and a
* day it cannot answer goes to OSRM whole. The third reason holds on every host, which
* is why one day is never routed by both.
*/
/** The public instance, matching how the OSRM defaults are shipped rather than configured. */
const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de'
/**
* The TREK services' Valhalla, reached through this server's relay: same origin, so no
* connect-src to add, and the installation key stays on the server.
*/
const TREK_VALHALLA = '/api/routing/valhalla'
/**
* How long this tab leaves the relay alone after it could not answer: signed out on a
* shared page, the allowance spent, the services down. FOSSGIS answers meanwhile.
*/
const RELAY_REST_MS = 10 * 60_000
/** The longest Retry-After of the relay this tab follows; a longer one is asked about again after it. */
const RELAY_MAX_WAIT_MS = 60 * 60_000
/**
* How long a route or a height question may take through the relay or at an own Valhalla.
* The server gives the TREK Valhalla ten seconds; this leaves room for its 504 to arrive
* first. Where the relay itself hangs, FOSSGIS answers soon after; where an own Valhalla
* does, OSRM routes the day, rather than the day waiting as long as the browser would.
*/
const ASK_TIMEOUT_MS = 12_000
/**
* How far Valhalla may look for a road under a point, in metres.
*
@@ -48,13 +87,6 @@ const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de'
*/
const SNAP_RADIUS_M = 50
/** TREK's profile names against Valhalla's costing models. */
const COSTING: Record<'driving' | 'walking' | 'cycling', string> = {
driving: 'auto',
walking: 'pedestrian',
cycling: 'bicycle',
}
/** What a caller tunes in the costing model: a weighting, a switch, or a bicycle type by name. */
export type CostingOptions = Record<string, number | string | boolean>
@@ -77,17 +109,18 @@ const AVOID_OPTION: Record<AvoidClass, string> = {
export type AvoidClass = RouteAvoidClass
/**
* Locations one request may carry. The eleventh answers
* `{"error_code":150,"error":"Exceeded max locations: 10"}` with HTTP 400.
* Locations one request to the public instance may carry. The eleventh answers
* `{"error_code":150,"error":"Exceeded max locations: 10"}` with HTTP 400. The TREK
* Valhalla and an own one take `VALHALLA_RELAY_MAX_LOCATIONS`.
*/
const MAX_LOCATIONS = 10
/**
* Pause between the pieces of a split day, in milliseconds.
* The pace of the public instance, in milliseconds between two questions.
*
* The public instance allows about one request a second per client, and a day long
* enough to be split is exactly the case that would fire two back to back. Matches the
* 1100 ms the road trip rail already leaves between its own days.
* It allows about one request a second per client, and a day long enough to be split is
* exactly the case that would fire two back to back; `valhallaTurn` holds every question
* to it there. Matches the 1100 ms the road trip rail already leaves between its own days.
*/
const CHUNK_PAUSE_MS = 1100
@@ -152,6 +185,14 @@ export interface ValhallaNoPath {
const NO_PATH_CODES = new Set([170, 171, 442])
const NO_PATH: ValhallaNoPath = { noPath: true }
/** A host that let a question run out its deadline, apart from one that refused it. */
const TOO_SLOW = { tooSlow: true } as const
type TooSlow = typeof TOO_SLOW
function tooSlow(answer: unknown): answer is TooSlow {
return answer === TOO_SLOW
}
/** A routed chain: one leg per pair of consecutive waypoints, plus the whole of it. */
export interface ValhallaRun {
legs: ValhallaLeg[]
@@ -169,21 +210,59 @@ export interface ValhallaRun {
snapped: SnappedWaypoint[]
}
/** Until when this tab asks FOSSGIS instead of a relay that could not answer. */
let relayRestingUntil = 0
/**
* The instance's Valhalla, or null when it should not ask one.
*
* Blank falls back to the public instance, the same reading `routing_base_url` gets —
* The admin's choice (`routing_valhalla_provider`) stands. Without one, an own Valhalla
* is asked, and otherwise the TREK services through the relay, with FOSSGIS behind it —
* with one condition. An operator who filled in their OWN router chose deliberately
* against the public hosts, usually because their instance is not supposed to talk to
* third parties at all, and quietly adding a second public host they never asked for
* would undo that choice. They lose nothing: a self-hosted OSRM built through the MLD
* third parties at all, and quietly adding a second host they never asked for would
* undo that choice. They lose nothing: a self-hosted OSRM built through the MLD
* pipeline answers `exclude` on its own, which is exactly the fallback below.
*/
export function valhallaBase(): string | null {
const { provider, own } = currentProvider()
if (provider === 'custom') return own
if (provider === 'trek') return TREK_VALHALLA
return provider === 'fossgis' ? FOSSGIS_VALHALLA : null
}
/**
* The provider as the settings choose it. Whether the TREK services can answer is the
* relay's to say; until it said no, it is asked, and `ignoreRest` reads past its no.
*/
function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
const settings = useSettingsStore.getState().settings
const configured = settings.valhalla_base_url?.trim()
if (configured) return configured.replace(/\/+$/, '')
return settings.routing_base_url?.trim() ? null : FOSSGIS_VALHALLA
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? ''
const provider = resolveValhallaProvider({
provider: settings.routing_valhalla_provider,
valhallaUrl: own,
routingUrl: settings.routing_base_url,
trekAvailable: ignoreRest || Date.now() >= relayRestingUntil,
})
return { provider, own }
}
/**
* Whether the days are asked here right now rather than of OSRM: with the TREK services
* or an own Valhalla. While the relay rests after a failure this reads as FOSSGIS, so the
* days go to OSRM until it is asked again.
*/
export function valhallaRoutesDays(): boolean {
return valhallaRoutesEveryDay(currentProvider().provider)
}
/**
* Whether the days are planned with this engine, resting relay or not. The route cache is
* keyed by it: a day this device already holds from Valhalla stays found while the relay
* rests, offline above all, where every question to it fails and it rests at once.
*/
export function valhallaPlansDays(): boolean {
return valhallaRoutesEveryDay(currentProvider(true).provider)
}
/** True when this engine can be asked at all, so callers can skip building a request. */
@@ -194,6 +273,11 @@ export function valhallaAvailable(): boolean {
/** Hosts that have already proved they are not a Valhalla, by base URL. */
const notValhalla = new Set<string>()
/** Whether a question may go to this base: a Valhalla, and the public one only where it may stand in. */
function mayAsk(base: string | null, publicFallback: boolean): base is string {
return !!base && !notValhalla.has(base) && (publicFallback || base !== FOSSGIS_VALHALLA)
}
/**
* One leg with a road class weighted away, or null when it cannot be had.
*
@@ -224,9 +308,9 @@ export async function valhallaRouteAvoiding(
* came back within two metres and under a second of the same day asked whole, because
* the shared point is routed to and from identically.
*
* The pieces go out one after another with a pause, since a day long enough to need
* splitting is exactly the one that would otherwise fire two requests inside a second
* at a host that allows one.
* The pieces go out one after another. Those that reach the public instance wait their
* turn there (`valhallaTurn`), since a day long enough to need splitting is exactly the
* one that would otherwise fire two requests inside a second at a host that allows one.
*/
export async function valhallaRun(
waypoints: Waypoint[],
@@ -235,11 +319,35 @@ export async function valhallaRun(
signal?: AbortSignal,
costingOptions: Readonly<CostingOptions> = {},
): Promise<ValhallaRun | null> {
const run = await chainRun(waypoints, profile, avoid, signal, { costingOptions, searchFilter: null })
const ask: RunAsk = { costingOptions, searchFilter: null, publicFallback: true }
const run = await chainRun(waypoints, profile, avoid, signal, ask)
if (!run || 'noPath' in run) return null
return run
}
/**
* A day of the planner or the road trip, routed here because this engine routes the
* days (`valhallaRoutesDays`) or because the day avoids something only it can avoid.
*
* A day that avoids nothing is never handed to the public instance: OSRM routes it
* there, as it always has, so where the TREK services cannot answer this is null and
* OSRM takes the whole day. A day that avoids something goes to FOSSGIS behind the
* relay as before, since OSRM cannot weigh a class away.
*/
export async function valhallaDayRun(
waypoints: Waypoint[],
profile: 'driving' | 'walking' | 'cycling',
avoid: readonly AvoidClass[],
signal?: AbortSignal,
): Promise<ValhallaRun | null> {
const run = await chainRun(waypoints, profile, avoid, signal, dayAsk(avoid))
return run && !('noPath' in run) ? run : null
}
function dayAsk(avoid: readonly AvoidClass[]): RunAsk {
return { costingOptions: {}, searchFilter: null, publicFallback: avoid.length > 0 }
}
/**
* CW-12: a chain walked on foot, every point bound off the boat lines. Measured
* on Venice: a stop by a vaporetto pier bound onto the boat line ended the
@@ -253,13 +361,24 @@ export function valhallaRunOnFoot(
costingOptions: Readonly<CostingOptions>,
searchFilter: Readonly<SearchFilter>,
): Promise<ValhallaRun | ValhallaNoPath | null> {
return chainRun(waypoints, 'walking', [], signal, { costingOptions, searchFilter })
return chainRun(waypoints, 'walking', [], signal, { costingOptions, searchFilter, publicFallback: true })
}
/** How a chain is asked for besides its profile and avoidance. */
interface RunAsk {
costingOptions: Readonly<CostingOptions>
searchFilter: Readonly<SearchFilter> | null
/** Whether FOSSGIS answers where the relay cannot; without it the question has no answer then. */
publicFallback: boolean
}
/**
* Locations one request carries: ten at the public instance, twenty at the TREK
* Valhalla and at an own one. A day cut for the relay that the relay then cannot
* answer is cut again for FOSSGIS (`chainRun`).
*/
function locationsPerRequest(base: string): number {
return base === FOSSGIS_VALHALLA ? MAX_LOCATIONS : VALHALLA_RELAY_MAX_LOCATIONS
}
async function chainRun(
@@ -270,18 +389,44 @@ async function chainRun(
ask: RunAsk,
): Promise<ValhallaRun | ValhallaNoPath | null> {
const base = valhallaBase()
if (!base || notValhalla.has(base) || waypoints.length < 2) return null
if (!mayAsk(base, ask.publicFallback) || waypoints.length < 2) return null
const size = locationsPerRequest(base)
const run = await chainRunSized(base, waypoints, { size, profile, avoid, signal, ask })
// The relay fell over during a day cut for it. It rests now, so the base reads as FOSSGIS
// and the day is asked again there in pieces of ten.
const recut = run === null && base === TREK_VALHALLA && ask.publicFallback && waypoints.length > MAX_LOCATIONS
if (recut && Date.now() < relayRestingUntil && !signal?.aborted) {
return chainRun(waypoints, profile, avoid, signal, ask)
}
return run
}
/** How one day is asked: in pieces of `size`, for this profile and these avoidances. */
interface SizedRun {
size: number
profile: 'driving' | 'walking' | 'cycling'
avoid: readonly AvoidClass[]
signal: AbortSignal | undefined
ask: RunAsk
}
async function chainRunSized(
base: string,
waypoints: Waypoint[],
{ size, profile, avoid, signal, ask }: SizedRun,
): Promise<ValhallaRun | ValhallaNoPath | null> {
const legs: ValhallaLeg[] = []
const chunks = chunkWaypoints(waypoints)
for (const [index, chunk] of chunks.entries()) {
// No pause between the pieces: a question that reaches FOSSGIS waits its turn in
// valhallaTurn, and the relay and an own Valhalla are not paced.
for (const chunk of chunkWaypoints(waypoints, size)) {
if (signal?.aborted) return null
if (index > 0) await pause(CHUNK_PAUSE_MS, signal)
// Retried per piece rather than per day. The caller retries the whole task, so a
// rate limit on the last piece of a split day would otherwise throw away the pieces
// that already answered and ask for all of them again — three times over, against a
// host that allows one request a second.
const run = await askWithRetry(base, () => requestRun(base, chunk, profile, avoid, signal, ask), signal)
const request = () => requestRun(base, chunk, profile, avoid, signal, ask)
// FOSSGIS stands in only for a piece of at most ten; a longer one is cut again instead.
const run = await askWithRetry(base, request, signal, ask.publicFallback && chunk.length <= MAX_LOCATIONS)
// A day is one answer or none. Half a day of legs would be worse than no answer:
// the schedule chains leg times blindly and cannot tell that it is missing some, so
// it would print a complete, plausible, wrong timetable rather than a gap.
@@ -314,12 +459,12 @@ function snappedFrom(legs: ValhallaLeg[], waypoints: Waypoint[]): SnappedWaypoin
})
}
/** Runs of at most ten points, each starting on the one the previous ended at. */
function chunkWaypoints(waypoints: Waypoint[]): Waypoint[][] {
if (waypoints.length <= MAX_LOCATIONS) return [waypoints]
/** Runs of at most `size` points, each starting on the one the previous ended at. */
function chunkWaypoints(waypoints: Waypoint[], size: number): Waypoint[][] {
if (waypoints.length <= size) return [waypoints]
const chunks: Waypoint[][] = []
for (let start = 0; start < waypoints.length - 1; start += MAX_LOCATIONS - 1) {
chunks.push(waypoints.slice(start, start + MAX_LOCATIONS))
for (let start = 0; start < waypoints.length - 1; start += size - 1) {
chunks.push(waypoints.slice(start, start + size))
}
return chunks
}
@@ -355,9 +500,96 @@ export async function valhallaTurn(base: string, signal?: AbortSignal): Promise<
lastPublicAskAt = Date.now()
}
/** Forget the last turn, for tests that start from a quiet host. */
/** Forget the last turn and a resting relay, for tests that start from a quiet host. */
export function resetValhallaTurns(): void {
lastPublicAskAt = 0
relayRestingUntil = 0
}
/**
* Whether the relay's answer says it cannot answer for the TREK services right now: no
* session (a shared page), no key, a body it does not take, a route this server does not
* have yet, an allowance spent, a host that is down. A 400 that carries Valhalla's
* `error_code` is its own refusal of the way and is read as such; one without is the
* relay refusing the body.
*/
async function relayCannotAnswer(response: Response): Promise<boolean> {
// 504: this one question took too long. The relay still answers the next one, and
// FOSSGIS would take as long over this one.
if (response.status === 504) return false
if (response.status === 400) {
// A body that is not JSON cannot be Valhalla's own refusal, so it reads as the relay's.
const data: unknown = await response.clone().json().catch(() => ({}))
return typeof (data as { error_code?: unknown } | null)?.error_code !== 'number'
}
return [401, 403, 404, 405, 413, 429].includes(response.status) || response.status >= 500
}
/** The relay's Retry-After in milliseconds, as seconds or an HTTP date, or null without one. */
function relayWait(response: Response): number | null {
const value = response.headers.get('Retry-After')?.trim()
if (!value) return null
if (/^\d+$/.test(value)) return Number(value) * 1000
const at = Date.parse(value)
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
}
/** A route or a height question held to `ASK_TIMEOUT_MS`; a description brings its own deadline. */
function withDeadline(action: ValhallaRelayAction, signal?: AbortSignal): AbortSignal | undefined {
if (action === 'trace_attributes') return signal
const deadline = AbortSignal.timeout(ASK_TIMEOUT_MS)
return signal ? AbortSignal.any([signal, deadline]) : deadline
}
async function askRelay(action: ValhallaRelayAction, body: object, signal?: AbortSignal): Promise<Response | null> {
let wait = RELAY_REST_MS
try {
const response = await valhallaRelayRepo.ask(action, body, withDeadline(action, signal))
if (!(await relayCannotAnswer(response))) return response
wait = Math.min(relayWait(response) ?? RELAY_REST_MS, RELAY_MAX_WAIT_MS)
} catch (err) {
if (signal?.aborted) throw err
}
relayRestingUntil = Date.now() + wait
return null
}
/**
* One question to a Valhalla, in its turn where the host is the public one. The relay
* is asked first where it is the base; where it cannot answer, the same question goes
* to FOSSGIS without a word, so a route never fails because of it. Without
* `publicFallback` it does not: the answer is then a 503 of this tab's own, and the
* caller asks OSRM.
*/
export async function valhallaPost(
base: string,
action: ValhallaRelayAction,
body: object,
signal?: AbortSignal,
{ publicFallback = true }: { publicFallback?: boolean } = {},
): Promise<Response> {
if (base === TREK_VALHALLA && Date.now() >= relayRestingUntil) {
const relayed = await askRelay(action, body, signal)
if (relayed) return relayed
}
if (base === TREK_VALHALLA && (!publicFallback || overPublicLimit(action, body))) return new Response(null, { status: 503 })
const host = base === TREK_VALHALLA ? FOSSGIS_VALHALLA : base
await valhallaTurn(host, signal)
return fetch(`${host}/${action}`, {
method: 'POST',
// A browser cannot set User-Agent, so this is the whole of what FOSSGIS asks a
// client to identify itself with. It costs a preflight, which is answered.
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify(body),
// An own Valhalla routes every day, so one that hangs would hold each of them up.
signal: host === FOSSGIS_VALHALLA ? signal : withDeadline(action, signal),
})
}
/** Whether a route carries more locations than the public instance takes, so it cannot stand in for the relay. */
function overPublicLimit(action: ValhallaRelayAction, body: object): boolean {
const locations = (body as { locations?: unknown }).locations
return action === 'route' && Array.isArray(locations) && locations.length > MAX_LOCATIONS
}
/**
@@ -375,16 +607,28 @@ export function valhallaSpacing(signal?: AbortSignal): Promise<void> {
* One question, and one more try after a pause when it earned no answer.
*
* Not when the host just proved it is not a Valhalla at all: that answer will not change
* on a second ask, and asking anyway is the request the memo exists to save.
* on a second ask, and asking anyway is the request the memo exists to save. Nor, where
* nothing may stand in for this engine, when the relay now rests or the host used up its
* whole deadline: the second ask would not leave this tab or would most likely wait as
* long again, and OSRM is waiting for the day. Nor when the relay ran out of time on
* it: the relay does not rest for that, so the second ask would wait at the same host.
*/
async function askWithRetry<T>(base: string, ask: () => Promise<T | null>, signal?: AbortSignal): Promise<T | null> {
async function askWithRetry<T>(
base: string,
ask: () => Promise<T | TooSlow | null>,
signal: AbortSignal | undefined,
publicFallback: boolean,
): Promise<T | null> {
let answer = await ask()
for (let attempt = 0; !answer && attempt < CHUNK_RETRIES && !signal?.aborted; attempt++) {
for (let attempt = 0; (!answer || tooSlow(answer)) && attempt < CHUNK_RETRIES && !signal?.aborted; attempt++) {
if (notValhalla.has(base)) break
if (!publicFallback && (tooSlow(answer) || (base === TREK_VALHALLA && Date.now() < relayRestingUntil))) break
// A question the relay ran out of time on would go to the same host again.
if (tooSlow(answer) && base === TREK_VALHALLA) break
await pause(CHUNK_PAUSE_MS, signal)
answer = await ask()
}
return answer
return tooSlow(answer) ? null : answer
}
/** The request body for a chain of waypoints, weighted away from `avoid`. */
@@ -395,7 +639,7 @@ function routeBody(
costingOptions: Readonly<CostingOptions> = {},
searchFilter: Readonly<SearchFilter> | null = null,
): Record<string, unknown> {
const costing = COSTING[profile]
const costing = VALHALLA_COSTING[profile]
// All of them in one request: the options are independent weightings, so asking to
// leave out tolls and ferries together is one question rather than two routes to
// reconcile. Measured Hamburg to Copenhagen: tolls, motorways and ferries weighted
@@ -412,22 +656,23 @@ function routeBody(
costing,
costing_options: { [costing]: options },
directions_options: { units: 'kilometers' },
// The maneuvers, where the ferry spans come from, without the narrative nothing reads.
directions_type: 'maneuvers',
}
}
/** The parsed answer to one POST, `NO_PATH` when the router found no way, or null for every other failure. */
async function postRoute(base: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
/**
* The parsed answer to one POST, `NO_PATH` when the router found no way, `TOO_SLOW` when
* it did not answer in time, or null for every other failure.
*/
async function postRoute(
base: string,
body: Record<string, unknown>,
signal: AbortSignal | undefined,
publicFallback: boolean,
): Promise<unknown> {
try {
await valhallaTurn(base, signal)
if (signal?.aborted) return null
const response = await fetch(`${base}/route`, {
method: 'POST',
// A browser cannot set User-Agent, so this is the whole of what FOSSGIS asks a
// client to identify itself with. It costs a preflight, which is answered.
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify(body),
signal,
})
const response = await valhallaPost(base, 'route', body, signal, { publicFallback })
if (!response.ok) {
// 404 and 405 mean this URL is not a Valhalla — an OSRM pointed at by mistake,
// or a proxy that swallowed the path. Every other status is about this request:
@@ -435,11 +680,13 @@ async function postRoute(base: string, body: Record<string, unknown>, signal?: A
// is the public instance's one-per-second.
if (response.status === 404 || response.status === 405) notValhalla.add(base)
if (response.status === 400 && (await refusesTheWay(response))) return NO_PATH
// The relay's word that this question ran out its deadline, read as one that timed out here.
if (response.status === 504) return TOO_SLOW
return null
}
return await response.json()
} catch {
return null
} catch (err) {
return err instanceof DOMException && err.name === 'TimeoutError' ? TOO_SLOW : null
}
}
@@ -506,22 +753,15 @@ export async function valhallaTraceAttributes(
const shape = line.filter((_, index) => index % step === 0 || index === line.length - 1).map(([lat, lon]) => ({ lat, lon }))
const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(TRACE_TIMEOUT_MS)]) : AbortSignal.timeout(TRACE_TIMEOUT_MS)
try {
await valhallaTurn(base, signal)
if (signal?.aborted) return null
const response = await fetch(`${base}/trace_attributes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify({
shape,
...TRACE_COSTING[matching],
shape_match: 'map_snap',
filters: {
attributes: traceAttributesFor(matching),
action: 'include',
},
}),
signal: bounded,
})
const response = await valhallaPost(base, 'trace_attributes', {
shape,
...TRACE_COSTING[matching],
shape_match: 'map_snap',
filters: {
attributes: traceAttributesFor(matching),
action: 'include',
},
}, bounded)
if (!response.ok) return null
return await response.json()
} catch {
@@ -529,17 +769,19 @@ export async function valhallaTraceAttributes(
}
}
/** One request, at most ten locations. */
/** One request, at most ten locations at the public instance and twenty elsewhere. */
async function requestRun(
base: string,
waypoints: Waypoint[],
profile: 'driving' | 'walking' | 'cycling',
avoid: readonly AvoidClass[],
signal: AbortSignal | undefined,
{ costingOptions, searchFilter }: RunAsk,
): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | null> {
const data = await postRoute(base, routeBody(waypoints, profile, avoid, costingOptions, searchFilter), signal)
{ costingOptions, searchFilter, publicFallback }: RunAsk,
): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | TooSlow | null> {
const body = routeBody(waypoints, profile, avoid, costingOptions, searchFilter)
const data = await postRoute(base, body, signal, publicFallback)
if (data === NO_PATH) return NO_PATH
if (tooSlow(data)) return data
return data === null ? null : runFrom(data)
}
@@ -563,13 +805,39 @@ export async function valhallaAlternates(
signal?: AbortSignal,
costingOptions: Readonly<CostingOptions> = {},
): Promise<ValhallaLeg[] | null> {
const ask: RunAsk = { costingOptions, searchFilter: null, publicFallback: true }
return alternates([from, to], profile, avoid, { count, signal, ask })
}
/**
* The offers for one leg of a day `valhallaDayRun` routes, asked the way that day was:
* a leg OSRM would otherwise drive is never asked of the public instance.
*/
export function valhallaDayAlternates(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling',
avoid: readonly AvoidClass[],
{ count, signal }: { count: number; signal?: AbortSignal },
): Promise<ValhallaLeg[] | null> {
return alternates([from, to], profile, avoid, { count, signal, ask: dayAsk(avoid) })
}
async function alternates(
[from, to]: [Waypoint, Waypoint],
profile: 'driving' | 'walking' | 'cycling',
avoid: readonly AvoidClass[],
{ count, signal, ask }: { count: number; signal: AbortSignal | undefined; ask: RunAsk },
): Promise<ValhallaLeg[] | null> {
const { costingOptions, publicFallback } = ask
const base = valhallaBase()
if (!base || notValhalla.has(base)) return null
if (!mayAsk(base, publicFallback)) return null
const body = { ...routeBody([from, to], profile, avoid, costingOptions), ...(count > 0 ? { alternates: count } : {}) }
return askWithRetry(base, async () => {
const data = await postRoute(base, body, signal)
const data = await postRoute(base, body, signal, publicFallback)
if (tooSlow(data)) return data
return data === null ? null : alternatesFrom(data)
}, signal)
}, signal, publicFallback)
}
/**
@@ -664,14 +932,6 @@ export function runFrom(data: unknown): Omit<ValhallaRun, 'snapped'> | null {
interface ValhallaSummary { [key: string]: number | boolean | undefined }
interface ValhallaManeuver {
type?: number
ferry?: boolean
begin_shape_index?: number
end_shape_index?: number
time?: number
length?: number
}
function tripOf(data: unknown) {
return (data as {
@@ -682,40 +942,6 @@ function tripOf(data: unknown) {
})?.trip
}
/** Valhalla's maneuver type for boarding a ferry; the maneuver also carries `ferry: true` for its crossing. */
const FERRY_ENTER = 28
/**
* CW-12: the stretches of a leg the router takes by boat, read off its
* maneuvers: a crossing is the maneuver that boards the ferry, from the point
* it starts at to the one it ends at, with its own length and time. Measured
* on Venice, the San Tomà to Ca' Rezzonico line came back as one maneuver of
* type 28, ferry true, 1.236 km and 745 s over shape points 24 to 46, then the
* walk off it. Crossings that touch are one. A leg the summary says has a
* ferry but whose maneuvers do not say where is taken whole, without a time:
* the crossing is somewhere on it, and none of it is counted as walked.
*/
function ferrySpansOf(maneuvers: ValhallaManeuver[] | undefined, points: number): FerrySpan[] {
const spans: FerrySpan[] = []
for (const maneuver of maneuvers ?? []) {
if (maneuver.ferry !== true && maneuver.type !== FERRY_ENTER) continue
const from = Number(maneuver.begin_shape_index)
const to = Number(maneuver.end_shape_index)
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to <= from || to >= points) continue
const metres = Number.isFinite(maneuver.length) ? Number(maneuver.length) * 1000 : 0
const seconds = Number.isFinite(maneuver.time) ? Number(maneuver.time) : null
const previous = spans[spans.length - 1]
if (previous && previous.to === from) {
previous.to = to
previous.metres += metres
previous.seconds = previous.seconds === null || seconds === null ? null : previous.seconds + seconds
} else {
spans.push({ from, to, metres, seconds })
}
}
return spans.length || points < 2 ? spans : [{ from: 0, to: points - 1, metres: 0, seconds: null }]
}
/** A summary and a shape as a leg, or null when the summary carries no numbers. */
function measured(summary: ValhallaSummary, coordinates: [number, number][]): ValhallaLeg | null {
if (!coordinates.length) return null