From 51af575c9a0e615d3172f0846579e4305b4e041d Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 4 Nov 2026 10:56:36 +0100 Subject: [PATCH] fix(map): keep places and routes on one world, and start new installs with Journey and Collections A right-click, click or drag on a repeated world copy reported the longitude it has on that copy (274.9 for -85.1). The place was saved there, the geocoder found nothing, and a route to a place on the real world ran across the whole map (#2976). Longitudes are now brought back onto [-180, 180] where the map hands them out (Leaflet and GL), where they are stored (places, booking endpoints, collection places, so REST, MCP, plugin RPC and importers alike) and before reverse geocoding. A migration moves the ones already stored. Leaflet draws a layer at its literal longitude only, so a trip from Los Angeles to Auckland had its pins at opposite ends of the world while the flight ran off the edge to the next copy (#2975). A trip that crosses the antimeridian is now drawn in one longitude frame, seamed in the widest stretch it leaves empty, so pins, routes, flights and every overlay lie on one copy and the map opens across the Pacific. Every other trip has no frame and draws exactly as before. The GL day fit also takes the short way. A new install now starts with Journey and Collections switched on, next to the trip addons (all but Road trip), Atlas, Vacay and the Naver import that already were. Existing installs keep their addons as they are. Closes #2975 Closes #2976 --- .../Ferratas/FerrataLayerLeaflet.tsx | 10 +- .../Map/AssistantCameraController.tsx | 11 +- .../components/Map/AssistantGhostLayer.tsx | 12 +- .../Map/AssistantGhostLineLayer.tsx | 28 ++- client/src/components/Map/ClusteredPois.tsx | 12 +- .../src/components/Map/DawarichTrailLayer.tsx | 7 +- client/src/components/Map/HazardLayers.tsx | 6 +- client/src/components/Map/MapPluginLayers.tsx | 10 +- .../src/components/Map/MapPluginMarkers.tsx | 6 +- client/src/components/Map/MapView.test.tsx | 17 +- client/src/components/Map/MapView.tsx | 115 ++++++++--- client/src/components/Map/MapViewGL.tsx | 17 +- client/src/components/Map/NightPauseDrag.tsx | 10 +- .../components/Map/PlannerWaypointMarker.tsx | 19 +- .../src/components/Map/ReservationOverlay.tsx | 15 +- .../src/components/Map/RoadtripViaMarkers.tsx | 11 +- client/src/components/Map/RouteHitBand.tsx | 5 +- .../src/components/Map/assistantViewport.ts | 13 +- .../src/components/Map/flightGeodesy.test.ts | 27 +++ client/src/components/Map/flightGeodesy.ts | 16 +- client/src/components/Map/glViewport.ts | 8 +- client/src/components/Map/lngFrameContext.ts | 51 +++++ .../src/components/Map/transportHops.test.ts | 13 ++ client/src/components/Map/transportHops.ts | 14 +- .../Map/useAssistantGhostLinesGL.ts | 8 +- .../Map/usePlannerWaypointMarkersGL.ts | 3 +- .../Tours/paddle/PaddleLayerLeaflet.tsx | 10 +- client/src/utils/lngFrame.test.ts | 84 ++++++++ client/src/utils/lngFrame.ts | 108 ++++++++++ client/src/utils/worldCopy.test.ts | 46 +++++ client/src/utils/worldCopy.ts | 32 +++ ...01046350_a_place_lies_on_the_real_world.ts | 43 ++++ ..._new_install_starts_with_more_addons_on.ts | 22 +++ .../CollectionPlaces.repository.ts | 4 +- .../src/db/repositories/Places.repository.ts | 11 +- .../ReservationEndpoints.repository.ts | 3 +- server/src/db/seeders/AddonSeeder.ts | 10 +- server/src/nest/maps/maps.service.ts | 14 +- server/tests/unit/db/legacy-baseline.test.ts | 2 + .../db/new-install-addons-migration.test.ts | 74 +++++++ .../db/place-real-world-migration.test.ts | 116 +++++++++++ .../repositories/longitude-on-write.test.ts | 186 ++++++++++++++++++ server/tests/unit/nest/maps.nearby.test.ts | 14 ++ shared/src/geo/longitude.spec.ts | 29 +++ shared/src/geo/longitude.ts | 23 +++ shared/src/index.ts | 1 + 46 files changed, 1194 insertions(+), 102 deletions(-) create mode 100644 client/src/components/Map/lngFrameContext.ts create mode 100644 client/src/utils/lngFrame.test.ts create mode 100644 client/src/utils/lngFrame.ts create mode 100644 client/src/utils/worldCopy.test.ts create mode 100644 client/src/utils/worldCopy.ts create mode 100644 server/src/db/migrations/Migration20200101046350_a_place_lies_on_the_real_world.ts create mode 100644 server/src/db/migrations/Migration20200101046360_a_new_install_starts_with_more_addons_on.ts create mode 100644 server/tests/unit/db/new-install-addons-migration.test.ts create mode 100644 server/tests/unit/db/place-real-world-migration.test.ts create mode 100644 server/tests/unit/db/repositories/longitude-on-write.test.ts create mode 100644 shared/src/geo/longitude.spec.ts create mode 100644 shared/src/geo/longitude.ts diff --git a/client/src/components/Ferratas/FerrataLayerLeaflet.tsx b/client/src/components/Ferratas/FerrataLayerLeaflet.tsx index b062db7be..3db4a60e9 100644 --- a/client/src/components/Ferratas/FerrataLayerLeaflet.tsx +++ b/client/src/components/Ferratas/FerrataLayerLeaflet.tsx @@ -3,6 +3,8 @@ import { useMemo, useState } from 'react'; import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet'; import { useTranslation } from '../../i18n'; +import { frameLine, frameLng } from '../../utils/lngFrame'; +import { useLngFrame } from '../Map/lngFrameContext'; import { type FerrataGroup, ferrataLabel } from './ferrataGroups'; import { FERRATA_ICON_MIN_ZOOM, FERRATA_ICON_SIZE, ferrataIconSvg, placeFerrataIcons } from './ferrataIcon'; import { ferrataPositions } from './ferrataModel'; @@ -81,6 +83,8 @@ export default function FerrataLayerLeaflet({ selectedId?: string | null; }) { const paint = useFerrataPaint(); + // Drawn in the map's longitude frame, with the trip (#2975). + const frame = useLngFrame(); const iconGroups = useIconGroups(groups); const [hovered, setHovered] = useState(null); // Rebuilt per set of ferratas and per theme: pathOptions only reach Leaflet when their reference changes. @@ -110,7 +114,7 @@ export default function FerrataLayerLeaflet({ group.segments.map((segment) => ({ group, segment, - positions: ferrataPositions(segment), + positions: frameLine(frame, ferrataPositions(segment)), casing, litCasing, line, @@ -118,7 +122,7 @@ export default function FerrataLayerLeaflet({ hit, })) ); - }, [groups, paint]); + }, [groups, paint, frame]); if (lines.length === 0) return null; const lit = (group: FerrataGroup) => group.id === hovered || group.id === selectedId; @@ -163,7 +167,7 @@ export default function FerrataLayerLeaflet({ {iconGroups.map((group) => ( 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; } diff --git a/client/src/components/Map/AssistantGhostLayer.tsx b/client/src/components/Map/AssistantGhostLayer.tsx index db3e594a2..93c3f61e2 100644 --- a/client/src/components/Map/AssistantGhostLayer.tsx +++ b/client/src/components/Map/AssistantGhostLayer.tsx @@ -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({ 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); diff --git a/client/src/components/Map/AssistantGhostLineLayer.tsx b/client/src/components/Map/AssistantGhostLineLayer.tsx index 6e0a5d0c1..7ead8b6c3 100644 --- a/client/src/components/Map/AssistantGhostLineLayer.tsx +++ b/client/src/components/Map/AssistantGhostLineLayer.tsx @@ -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 ( [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) => ( ))} diff --git a/client/src/components/Map/ClusteredPois.tsx b/client/src/components/Map/ClusteredPois.tsx index 986de81bf..cac207efa 100644 --- a/client/src/components/Map/ClusteredPois.tsx +++ b/client/src/components/Map/ClusteredPois.tsx @@ -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(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 { 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 }) } }} /> })} } diff --git a/client/src/components/Map/DawarichTrailLayer.tsx b/client/src/components/Map/DawarichTrailLayer.tsx index 33284d3fe..34db5f21d 100644 --- a/client/src/components/Map/DawarichTrailLayer.tsx +++ b/client/src/components/Map/DawarichTrailLayer.tsx @@ -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 ( diff --git a/client/src/components/Map/HazardLayers.tsx b/client/src/components/Map/HazardLayers.tsx index 3fe34d4d7..8266faa6c 100644 --- a/client/src/components/Map/HazardLayers.tsx +++ b/client/src/components/Map/HazardLayers.tsx @@ -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 => {hazards.map(hazard => 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 })} diff --git a/client/src/components/Map/MapPluginLayers.tsx b/client/src/components/Map/MapPluginLayers.tsx index ee7fee308..34efb6405 100644 --- a/client/src/components/Map/MapPluginLayers.tsx +++ b/client/src/components/Map/MapPluginLayers.tsx @@ -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([]) // 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 ? {f.label} : null if (f.type === 'polyline' && f.points) { - return {tooltip} + return {tooltip} } if (f.type === 'polygon' && f.points) { - return {tooltip} + return {tooltip} } if (f.type === 'circle' && f.center && f.radiusM) { - return {tooltip} + return {tooltip} } return null }))} diff --git a/client/src/components/Map/MapPluginMarkers.tsx b/client/src/components/Map/MapPluginMarkers.tsx index 4ac642c60..4b65c54e1 100644 --- a/client/src/components/Map/MapPluginMarkers.tsx +++ b/client/src/components/Map/MapPluginMarkers.tsx @@ -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([]) + // 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 => ( - + {(mk.label || mk.popupText || mk.url) && (
diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx index 9d172f497..e9a9e679b 100644 --- a/client/src/components/Map/MapView.test.tsx +++ b/client/src/components/Map/MapView.test.tsx @@ -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() - 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() - 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', () => { diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 1c8f1d755..b1ef0ea0e 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -50,7 +50,7 @@ import { useTransportRoutes } from '../../hooks/useTransportRoutes' import { visibleRouteReservations } from '../../utils/reservationRoutes' import { safeHexColor } from '../../utils/safeColor' import { placeMarkerLook } from './markerLook' -import { escapeHtml } from '@trek/shared' +import { escapeHtml, wrapLongitude } from '@trek/shared' import type { Day, Place, Reservation, RouteVia } from '../../types' import type { MapHoverInfo } from './mapHover' import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker' @@ -121,7 +121,8 @@ function RouteViaMarker({ via, controls, eventHandlers, children }: { via: RouteVia; controls?: DayBoundaryControls; eventHandlers?: L.LeafletEventHandlerFnMap; children?: React.ReactNode }) { const [marker, setMarker] = useState(null) - return {children} {via.nightPause && } @@ -320,7 +321,7 @@ function PoiDropTarget({ onPoiDropOnRoute }: { onPoiDropOnRoute?: (osmId: string if (!osmId) return e.preventDefault() const rect = container.getBoundingClientRect() - const at = map.containerPointToLatLng([e.clientX - rect.left, e.clientY - rect.top]) + const at = onRealWorld(map.containerPointToLatLng([e.clientX - rect.left, e.clientY - rect.top])) onPoiDropOnRoute(osmId, at.lat, at.lng) } container.addEventListener('dragover', onDragOver) @@ -341,7 +342,8 @@ function ViewportController({ onViewportChange }: { onViewportChange?: MapViewPr if (!onViewportChange) return const emit = () => { const b = map.getBounds() - onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() }, map.getZoom()) + // 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) @@ -377,6 +379,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 +390,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 +402,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 } @@ -409,16 +412,39 @@ interface MapControllerProps { zoom: number } +/** + * 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. + */ +function LngFrameFollower() { + const map = useMap() + const frame = useLngFrame() + const prev = useRef(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 +} + 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 +482,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 +506,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. @@ -561,12 +589,23 @@ function TrackCasingPane({ onReady }: { onReady: (ready: boolean) => void }) { return 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) } +} + function MapClickHandler({ onClick }: MapClickHandlerProps) { const map = useMap() useEffect(() => { if (!onClick) return - map.on('click', onClick) - return () => { map.off('click', onClick) } + const handle = (e: L.LeafletMouseEvent) => onClick(onRealWorldEvent(e)) + map.on('click', handle) + return () => { map.off('click', handle) } }, [map, onClick]) return null } @@ -575,8 +614,9 @@ function MapContextMenuHandler({ onContextMenu }: { onContextMenu: ((e: L.Leafle const map = useMap() useEffect(() => { if (!onContextMenu) return - map.on('contextmenu', onContextMenu) - return () => { map.off('contextmenu', onContextMenu) } + const handle = (e: L.LeafletMouseEvent) => onContextMenu(onRealWorldEvent(e)) + map.on('contextmenu', handle) + return () => { map.off('contextmenu', handle) } }, [map, onContextMenu]) return null } @@ -594,9 +634,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, type LngFrame } from '../../utils/lngFrame' +import { bboxOnRealWorld, onRealWorld } from '../../utils/worldCopy' -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 +757,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 ( 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) => ( - )), [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 +943,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 +1001,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 +1070,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 +1108,7 @@ export const MapView = memo(function MapView({ return ( <>
+ )} + {/* First, so a fit or a camera request in the same commit starts from the trip's world copy. */} + {hasViewBaseLayer && } 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 +1200,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). ( @@ -1190,13 +1248,13 @@ export const MapView = memo(function MapView({ return [ , + {isMobile && { map.getCanvas().style.cursor = 'copy' } const leave = () => { map.getCanvas().style.cursor = '' } @@ -964,7 +966,7 @@ export function MapViewGL({ if (!osmId) return e.preventDefault() const rect = container.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])) onPoiDropOnRoute(osmId, at.lat, at.lng) } container.addEventListener('dragover', onDragOver) @@ -1343,7 +1345,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) @@ -1376,7 +1378,8 @@ 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 }) + // A right-click on a repeated world copy still means the place on the real world (#2976). + 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 @@ -1982,7 +1985,9 @@ 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])) + // The short way across the antimeridian, as the focus fit below does: a day + // from Los Angeles to Auckland frames the Pacific, not the rest of the world (#2975). + alongShortestArc(fitPoints).forEach(([lat, lng]) => bounds.extend([lng, lat])) let fitted = false const run = () => { try { diff --git a/client/src/components/Map/NightPauseDrag.tsx b/client/src/components/Map/NightPauseDrag.tsx index 336bc2b21..c624c0411 100644 --- a/client/src/components/Map/NightPauseDrag.tsx +++ b/client/src/components/Map/NightPauseDrag.tsx @@ -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 } diff --git a/client/src/components/Map/PlannerWaypointMarker.tsx b/client/src/components/Map/PlannerWaypointMarker.tsx index 0af95908a..895a23f4a 100644 --- a/client/src/components/Map/PlannerWaypointMarker.tsx +++ b/client/src/components/Map/PlannerWaypointMarker.tsx @@ -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 ( | 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 } 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(() => { 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]]) diff --git a/client/src/components/Map/RoadtripViaMarkers.tsx b/client/src/components/Map/RoadtripViaMarkers.tsx index 484258cbb..a4cd27650 100644 --- a/client/src/components/Map/RoadtripViaMarkers.tsx +++ b/client/src/components/Map/RoadtripViaMarkers.tsx @@ -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 diff --git a/client/src/components/Map/RouteHitBand.tsx b/client/src/components/Map/RouteHitBand.tsx index f2a0ed796..e4d2c63ac 100644 --- a/client/src/components/Map/RouteHitBand.tsx +++ b/client/src/components/Map/RouteHitBand.tsx @@ -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); }, }} /> diff --git a/client/src/components/Map/assistantViewport.ts b/client/src/components/Map/assistantViewport.ts index b730e37b4..4c6d85508 100644 --- a/client/src/components/Map/assistantViewport.ts +++ b/client/src/components/Map/assistantViewport.ts @@ -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); diff --git a/client/src/components/Map/flightGeodesy.test.ts b/client/src/components/Map/flightGeodesy.test.ts index 8e2b743e5..765ece39f 100644 --- a/client/src/components/Map/flightGeodesy.test.ts +++ b/client/src/components/Map/flightGeodesy.test.ts @@ -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)) + }) +}) diff --git a/client/src/components/Map/flightGeodesy.ts b/client/src/components/Map/flightGeodesy.ts index e423a67af..2a627dc3a 100644 --- a/client/src/components/Map/flightGeodesy.ts +++ b/client/src/components/Map/flightGeodesy.ts @@ -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])] } diff --git a/client/src/components/Map/glViewport.ts b/client/src/components/Map/glViewport.ts index f9c7464d6..93136a3dd 100644 --- a/client/src/components/Map/glViewport.ts +++ b/client/src/components/Map/glViewport.ts @@ -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())); } diff --git a/client/src/components/Map/lngFrameContext.ts b/client/src/components/Map/lngFrameContext.ts new file mode 100644 index 000000000..64b513c86 --- /dev/null +++ b/client/src/components/Map/lngFrameContext.ts @@ -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(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; + +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(() => + 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; +} diff --git a/client/src/components/Map/transportHops.test.ts b/client/src/components/Map/transportHops.test.ts index 7dcc94a91..f302f818e 100644 --- a/client/src/components/Map/transportHops.test.ts +++ b/client/src/components/Map/transportHops.test.ts @@ -88,6 +88,19 @@ 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 })!; + 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); diff --git a/client/src/components/Map/transportHops.ts b/client/src/components/Map/transportHops.ts index 87949e538..4b4ca9ced 100644 --- a/client/src/components/Map/transportHops.ts +++ b/client/src/components/Map/transportHops.ts @@ -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); diff --git a/client/src/components/Map/useAssistantGhostLinesGL.ts b/client/src/components/Map/useAssistantGhostLinesGL.ts index 7d6b1151f..3fa15faf6 100644 --- a/client/src/components/Map/useAssistantGhostLinesGL.ts +++ b/client/src/components/Map/useAssistantGhostLinesGL.ts @@ -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; diff --git a/client/src/components/Map/usePlannerWaypointMarkersGL.ts b/client/src/components/Map/usePlannerWaypointMarkersGL.ts index 084546657..f6e9f723a 100644 --- a/client/src/components/Map/usePlannerWaypointMarkersGL.ts +++ b/client/src/components/Map/usePlannerWaypointMarkersGL.ts @@ -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({ 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 }) => diff --git a/client/src/components/Tours/paddle/PaddleLayerLeaflet.tsx b/client/src/components/Tours/paddle/PaddleLayerLeaflet.tsx index 1c14700cf..6fc534090 100644 --- a/client/src/components/Tours/paddle/PaddleLayerLeaflet.tsx +++ b/client/src/components/Tours/paddle/PaddleLayerLeaflet.tsx @@ -2,6 +2,8 @@ import L from 'leaflet'; import { useMemo, useState } from 'react'; import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet'; import { useTranslation } from '../../../i18n'; +import { frameLine, frameLng } from '../../../utils/lngFrame'; +import { useLngFrame } from '../../Map/lngFrameContext'; import { isPaddleItemSelected, markerSize, @@ -74,6 +76,8 @@ function useLabel() { export function PaddleLayerLeaflet({ layer }: { layer?: PaddleMapLayer }) { const label = useLabel(); const map = useMap(); + // Drawn in the map's longitude frame, with the trip (#2975). + const frame = useLngFrame(); const linePane = useLinePane(); const [zoom, setZoom] = useState(() => map.getZoom()); useMapEvents({ zoomend: () => setZoom(map.getZoom()) }); @@ -105,7 +109,7 @@ export function PaddleLayerLeaflet({ layer }: { layer?: PaddleMapLayer }) { item.line ? ( ( { + it('gives a trip that stays off the antimeridian no frame, so every layer draws as before', () => { + expect(tripLngFrame([2.35, 13.4, -3.7, 12.5])).toBeNull(); + expect(tripLngFrame([LA, -73.9, -0.1, 139.7])).toBeNull(); + expect(tripLngFrame([])).toBeNull(); + expect(tripLngFrame([LA])).toBeNull(); + }); + + it('seams a trip across the Pacific in the middle of the stretch it leaves empty', () => { + const frame = tripLngFrame([LA, -118.3, AUCKLAND, 174.76]); + expect(frame).not.toBeNull(); + expect(frame!.seam).toBeCloseTo((-118.3 + 174.76) / 2, 5); + expect(frameLng(frame, LA)).toBeCloseTo(LA + 360, 9); + expect(frameLng(frame, AUCKLAND)).toBeCloseTo(AUCKLAND, 9); + }); + + it('seams Fiji to Samoa, a few degrees apart across the date line', () => { + const frame = tripLngFrame([178.4, -171.8]); + expect(frame).not.toBeNull(); + expect(frameLng(frame, -171.8) - frameLng(frame, 178.4)).toBeCloseTo(9.8, 9); + }); + + it('leaves a trip around the world alone when re-seaming would barely narrow it', () => { + expect(tripLngFrame([-150, -90, -30, 30, 90, 150])).toBeNull(); + }); + + it('keeps the frame in use while it still fits, so a new place does not slide the map', () => { + const first = tripLngFrame([LA, AUCKLAND]); + expect(tripLngFrame([LA, AUCKLAND, 151.2], first)).toBe(first); + }); + + it('reads a longitude from a world copy where it really is', () => { + expect(tripLngFrame([LA + 360, AUCKLAND - 720])!.seam).toBeCloseTo(tripLngFrame([LA, AUCKLAND])!.seam, 9); + }); +}); + +describe('frameLng', () => { + it('draws a longitude where it is without a frame', () => { + expect(frameLng(null, LA)).toBe(LA); + expect(frameLng(null, 400)).toBe(400); + }); + + it('moves any longitude into the frame, and one already in it nowhere', () => { + const frame = { seam: 28 }; + expect(frameLng(frame, LA)).toBeCloseTo(241.6, 9); + expect(frameLng(frame, 241.6)).toBeCloseTo(241.6, 9); + expect(frameLng(frame, 28)).toBe(28); + expect(frameLng(frame, 27.9)).toBeCloseTo(387.9, 9); + }); +}); + +describe('frameLine', () => { + it('hands the line back untouched without a frame', () => { + const line: [number, number][] = [ + [0, 170], + [0, -170], + ]; + expect(frameLine(null, line)).toBe(line); + }); + + it('starts the line in the frame and keeps it one line across the antimeridian', () => { + const drawn = frameLine({ seam: 28 }, [ + [34, LA], + [0, -160], + [-20, 179], + [-37, AUCKLAND], + ]); + expect(drawn.map(([, lng]) => Math.round(lng * 10) / 10)).toEqual([241.6, 200, 179, 174.8]); + }); + + it('runs past the edge of the frame rather than jumping back across the world', () => { + const drawn = frameLine({ seam: 28 }, [ + [0, 30], + [0, 20], + ]); + expect(drawn.map(([, lng]) => lng)).toEqual([30, 20]); + }); +}); diff --git a/client/src/utils/lngFrame.ts b/client/src/utils/lngFrame.ts new file mode 100644 index 000000000..855d4608a --- /dev/null +++ b/client/src/utils/lngFrame.ts @@ -0,0 +1,108 @@ +// One stretch of longitudes to draw a trip in, for a map that does not repeat its +// layers across world copies (Leaflet) (#2975). +// +// Leaflet draws a marker at its literal longitude only, on one copy of the world. +// A trip from Los Angeles (-118) to Auckland (174.8) therefore had its pins at +// opposite ends of that copy, while the flight between them, drawn the short way +// across the Pacific, ran off the edge to the Los Angeles of the next copy. The +// frame moves the seam of the drawn world into the widest stretch of the planet +// the trip leaves empty, so the whole trip, flight included, lies on one copy: +// Los Angeles at 242, Auckland at 174.8. +// +// A trip that does not cross the antimeridian gets no frame at all, and every +// layer draws exactly what it drew before. + +import { wrapLongitude } from '@trek/shared'; + +/** The drawn world runs from `seam` to `seam + 360`. */ +export interface LngFrame { + readonly seam: number; +} + +/** Re-seam only when that narrows the trip by at least this much: a world tour stays as it is. */ +const MIN_SAVING_DEG = 45; +/** A previous seam is kept while the trip drawn with it is at most this much wider than the best. */ +const KEEP_SEAM_SLACK_DEG = 15; + +/** Width of the trip, in degrees, when the world is drawn from `seam` eastwards. */ +function spanFrom(seam: number, sorted: number[]): number { + let min = Infinity; + let max = -Infinity; + for (const lng of sorted) { + const framed = lng < seam ? lng + 360 : lng; + if (framed < min) min = framed; + if (framed > max) max = framed; + } + return max - min; +} + +/** + * The frame for these longitudes, or null when the plain world already holds the + * trip narrowly enough. `previous` is the frame in use: it is kept while it still + * works, so adding or filtering a place does not slide every layer sideways. + */ +export function tripLngFrame(lngs: readonly number[], previous: LngFrame | null = null): LngFrame | null { + const sorted = lngs + .filter(Number.isFinite) + .map(wrapLongitude) + .sort((a, b) => a - b); + if (sorted.length < 2) return null; + const last = sorted.length - 1; + + // The widest stretch with no point in it. The one across the antimeridian comes first, + // so a trip that leaves the Pacific empty keeps the plain world. + let gapSize = sorted[0] + 360 - sorted[last]; + let gapWest = sorted[last]; + let crossesAntimeridian = false; + for (let i = 0; i < last; i++) { + const size = sorted[i + 1] - sorted[i]; + if (size > gapSize) { + gapSize = size; + gapWest = sorted[i]; + crossesAntimeridian = true; + } + } + if (!crossesAntimeridian) return null; + + const plainSpan = sorted[last] - sorted[0]; + const bestSpan = 360 - gapSize; + if (plainSpan - bestSpan < MIN_SAVING_DEG) return null; + + if (previous && spanFrom(previous.seam, sorted) <= bestSpan + KEEP_SEAM_SLACK_DEG) return previous; + // The middle of the empty stretch: lines that bulge a little past a stop stay clear of it. + return { seam: gapWest + gapSize / 2 }; +} + +/** Where a longitude is drawn in the frame. Without a frame it is drawn where it is. */ +export function frameLng(frame: LngFrame | null, lng: number): number { + if (!frame) return lng; + return frame.seam + ((((lng - frame.seam) % 360) + 360) % 360); +} + +/** + * A line in the frame: its first point moved into it, every next point kept within + * half a world of the one before, so the line stays one line where it crosses the + * antimeridian or the seam. Without a frame the line is drawn as it is. + */ +export function frameLine( + frame: LngFrame | null, + line: readonly T[] +): [number, number][] { + if (!frame) return line as unknown as [number, number][]; + const out: [number, number][] = []; + let prevRaw = 0; + let prevDrawn = 0; + for (let i = 0; i < line.length; i++) { + const [lat, lng] = line[i]; + if (i === 0) { + prevDrawn = frameLng(frame, lng); + } else { + let delta = lng - prevRaw; + delta -= 360 * Math.round(delta / 360); + prevDrawn += delta; + } + prevRaw = lng; + out.push([lat, prevDrawn]); + } + return out; +} diff --git a/client/src/utils/worldCopy.test.ts b/client/src/utils/worldCopy.test.ts new file mode 100644 index 000000000..8e07d7ecb --- /dev/null +++ b/client/src/utils/worldCopy.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { bboxOnRealWorld, onRealWorld } from './worldCopy'; + +describe('onRealWorld', () => { + it('brings a right-click on the copy east of the real world back to the real point (#2976)', () => { + const at = onRealWorld({ lat: 10.14, lng: 274.921875 }); + expect(at.lat).toBe(10.14); + expect(at.lng).toBeCloseTo(-85.078125, 9); + }); + + it('brings a point on the copy west of it back too', () => { + expect(onRealWorld({ lat: 35.68, lng: -220.3 }).lng).toBeCloseTo(139.7, 9); + }); + + it('hands a point already on the real world back as it is', () => { + const point = { lat: 34, lng: -118.4, extra: 1 }; + expect(onRealWorld(point)).toBe(point); + }); + + it('keeps any other field of the point', () => { + expect(onRealWorld({ lat: 1, lng: 365, name: 'x' })).toEqual({ lat: 1, lng: 5, name: 'x' }); + }); +}); + +describe('bboxOnRealWorld', () => { + it('moves a box looking at a copy of Japan onto Japan', () => { + const box = bboxOnRealWorld({ south: 34, west: -225, north: 37, east: -215 }); + expect(box.west).toBeCloseTo(135, 9); + expect(box.east).toBeCloseTo(145, 9); + expect([box.south, box.north]).toEqual([34, 37]); + }); + + it('leaves a box on the real world alone', () => { + const box = { south: 40, west: 0, north: 50, east: 20 }; + expect(bboxOnRealWorld(box)).toBe(box); + }); + + it('keeps a box across the antimeridian across it', () => { + expect(bboxOnRealWorld({ south: -20, west: 170, north: -10, east: 190 })).toEqual({ + south: -20, + west: 170, + north: -10, + east: 190, + }); + }); +}); diff --git a/client/src/utils/worldCopy.ts b/client/src/utils/worldCopy.ts new file mode 100644 index 000000000..ee5146b85 --- /dev/null +++ b/client/src/utils/worldCopy.ts @@ -0,0 +1,32 @@ +// Coordinates the map hands out, brought back from a repeated world copy (#2976). +// +// Leaflet and MapLibre/Mapbox repeat the world sideways, and a pointer on a copy +// reports the longitude it has on that copy: 274.9 for -85.1. Anything that +// stores a point or asks a server about it wants the point on the real world. + +import { wrapLongitude } from '@trek/shared'; + +/** The same point with its longitude on the real world, in [-180, 180]. */ +export function onRealWorld(point: T): T { + const lng = wrapLongitude(point.lng); + return lng === point.lng ? point : { ...point, lng }; +} + +export interface Bbox { + south: number; + west: number; + north: number; + east: number; +} + +/** + * A viewport box moved whole by a multiple of 360 degrees so its centre lies on + * the real world. A box looking at a copy of Japan then asks for Japan. A box + * that spans the antimeridian keeps one edge past it, as it always had. + */ +export function bboxOnRealWorld(bbox: T): T { + const centre = (bbox.west + bbox.east) / 2; + const shift = wrapLongitude(centre) - centre; + if (shift === 0) return bbox; + return { ...bbox, west: bbox.west + shift, east: bbox.east + shift }; +} diff --git a/server/src/db/migrations/Migration20200101046350_a_place_lies_on_the_real_world.ts b/server/src/db/migrations/Migration20200101046350_a_place_lies_on_the_real_world.ts new file mode 100644 index 000000000..7cf77c34d --- /dev/null +++ b/server/src/db/migrations/Migration20200101046350_a_place_lies_on_the_real_world.ts @@ -0,0 +1,43 @@ +import { Migration } from '@mikro-orm/migrations'; + +/** + * The tables whose `lng` a click on a repeated world copy could have written, and + * the outbox that would still hand such a place on to the shared places index. + */ +const TABLES = ['places', 'reservation_endpoints', 'collection_places', 'place_contrib_outbox'] as const; + +interface LngRow { + id: number; + lng: number; +} + +/** Into [-180, 180], the same arithmetic as wrapLongitude in @trek/shared, kept here so this body never changes. */ +function onTheRealWorld(lng: number): number { + const wrapped = ((((lng + 180) % 360) + 360) % 360) - 180; + return wrapped === 0 ? 0 : wrapped; +} + +/** + * Brings every stored longitude back onto the real world. + * + * The map repeats the world sideways, and a right-click or a drag on one of the + * copies reported its longitude as it is on that copy: 274.9 instead of -85.1. + * Saved like that, a place sat on its copy for good, out of reach of the + * geocoder, and a day route to it ran across the whole map (#2976). New writes + * are wrapped on the way in; this moves the ones already stored to the same + * point on the real world. Only rows outside [-180, 180] are touched. + */ +export class Migration20200101046350_a_place_lies_on_the_real_world extends Migration { + override name = 'Migration20200101046350_a_place_lies_on_the_real_world'; + + override async up(): Promise { + for (const table of TABLES) { + const rows = (await this.execute( + `SELECT id, lng FROM ${table} WHERE lng IS NOT NULL AND (lng < -180 OR lng > 180)`, + )) as LngRow[]; + for (const row of rows) { + await this.execute(`UPDATE ${table} SET lng = ? WHERE id = ?`, [onTheRealWorld(row.lng), row.id]); + } + } + } +} diff --git a/server/src/db/migrations/Migration20200101046360_a_new_install_starts_with_more_addons_on.ts b/server/src/db/migrations/Migration20200101046360_a_new_install_starts_with_more_addons_on.ts new file mode 100644 index 000000000..7ea0b34f6 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046360_a_new_install_starts_with_more_addons_on.ts @@ -0,0 +1,22 @@ +import { Migration } from '@mikro-orm/migrations'; + +/** + * A new install starts with Journey and Collections switched on; an existing + * install keeps every addon exactly as its admin left it. + * + * Both rows are written off by older migrations (journey_addon, collections_addon) + * that every install runs, and the addon seeder never overwrites a row that is + * already there, so the seeder alone cannot change their start value. A database + * whose `users` table is still empty here is being set up for the first time: + * migrations run before the seeders, and the admin seeder writes the first + * account only afterwards. + */ +export class Migration20200101046360_a_new_install_starts_with_more_addons_on extends Migration { + override name = 'Migration20200101046360_a_new_install_starts_with_more_addons_on'; + + override up(): void { + this.addSql( + "UPDATE addons SET enabled = 1 WHERE id IN ('journey', 'collections') AND NOT EXISTS (SELECT 1 FROM users)", + ); + } +} diff --git a/server/src/db/repositories/CollectionPlaces.repository.ts b/server/src/db/repositories/CollectionPlaces.repository.ts index f7cc08b04..73685b7fd 100644 --- a/server/src/db/repositories/CollectionPlaces.repository.ts +++ b/server/src/db/repositories/CollectionPlaces.repository.ts @@ -3,6 +3,7 @@ import type { CollectionPlaces } from '../entities/CollectionPlaces.entity'; import type { DB } from '../kysely/db'; import type { CollectionPlaceRow } from './Collections.repository'; import { TrekRepository } from './_shared/trek-repository'; +import { wrapOptionalLongitude } from '@trek/shared'; /** * `collection_places` (Plan 3h Task 2, part B — saved places CRUD, dedup, @@ -115,7 +116,7 @@ export class CollectionPlacesRepository extends TrekRepository name: row.name, description: row.description, lat: row.lat, - lng: row.lng, + lng: wrapOptionalLongitude(row.lng), address: row.address, category: row.category_id, price: row.price, @@ -181,6 +182,7 @@ export class CollectionPlacesRepository extends TrekRepository { id }, { ...rest, + ...(rest.lng !== undefined ? { lng: wrapOptionalLongitude(rest.lng) } : {}), ...(category_id !== undefined ? { category: category_id } : {}), ...(collection_id !== undefined ? { collection: collection_id } : {}), ...(owner_id !== undefined ? { owner: owner_id } : {}), diff --git a/server/src/db/repositories/Places.repository.ts b/server/src/db/repositories/Places.repository.ts index bb7029cae..4a22e0502 100644 --- a/server/src/db/repositories/Places.repository.ts +++ b/server/src/db/repositories/Places.repository.ts @@ -1,4 +1,5 @@ import type { Places } from '../entities/Places.entity'; +import { wrapOptionalLongitude } from '@trek/shared'; import { absDifference, coalesceParam, columnRef, currentTimestamp, lowerTrim } from '../dialect/sql-functions'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; @@ -386,7 +387,7 @@ export class PlacesRepository extends TrekRepository { name: input.name, description: input.description, lat: input.lat, - lng: input.lng, + lng: wrapOptionalLongitude(input.lng), address: input.address, category: input.category_id, price: input.price, @@ -466,7 +467,7 @@ export class PlacesRepository extends TrekRepository { name: write.name, description: write.description, lat: write.lat, - lng: write.lng, + lng: wrapOptionalLongitude(write.lng), address: write.address, category: write.category_id, price: write.price, @@ -963,7 +964,7 @@ export class PlacesRepository extends TrekRepository { name: input.name, description: input.description, lat: input.lat, - lng: input.lng, + lng: wrapOptionalLongitude(input.lng), address: input.address, category: input.category_id, price: input.price, @@ -1338,7 +1339,7 @@ export class PlacesRepository extends TrekRepository { trip: input.trip_id, name: input.name, lat: input.lat, - lng: input.lng, + lng: wrapOptionalLongitude(input.lng), transport_mode: 'walking', route_geometry: input.route_geometry, description: input.description ?? null, @@ -1360,7 +1361,7 @@ export class PlacesRepository extends TrekRepository { { name: input.name, lat: input.lat, - lng: input.lng, + lng: wrapOptionalLongitude(input.lng), transport_mode: 'walking', route_geometry: input.route_geometry, ...tourPlaceTextPatch(input), diff --git a/server/src/db/repositories/ReservationEndpoints.repository.ts b/server/src/db/repositories/ReservationEndpoints.repository.ts index 693c1f027..b75e2cb2b 100644 --- a/server/src/db/repositories/ReservationEndpoints.repository.ts +++ b/server/src/db/repositories/ReservationEndpoints.repository.ts @@ -4,6 +4,7 @@ import type { DB } from '../kysely/db'; import { travelerOwnsExpr, type ReservationTravelersOwnsKyselyDB } from './_shared/reservation-travelers-owns'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; +import { wrapLongitude } from '@trek/shared'; /** A `reservation_endpoints` row exactly as `r.*`/`SELECT *` read it (every scalar column). */ export interface ReservationEndpointRow { @@ -82,7 +83,7 @@ export class ReservationEndpointsRepository extends TrekRepository { diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts index 8930944b5..1987fe11f 100644 --- a/server/src/nest/maps/maps.service.ts +++ b/server/src/nest/maps/maps.service.ts @@ -39,7 +39,7 @@ import { } from './trek-places.client'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; -import { isOutsideChina } from '@trek/shared'; +import { isOutsideChina, wrapLongitude } from '@trek/shared'; import type { MapsSearchResult, MapsAutocompleteResult, MapsPlaceDetailsResult } from '@trek/shared'; import type { MapsPlacePhotoResult, MapsReverseResult, MapsResolveUrlResult } from '@trek/shared'; @@ -57,6 +57,17 @@ const NEARBY_CACHE = new Map= -180 && value <= 180)) return lng; + return String(wrapLongitude(value)); +} + type LocationBias = { low: { lat: number; lng: number }; high: { lat: number; lng: number } }; /** @@ -649,6 +660,7 @@ export class MapsService { lang?: string, opts?: { lane?: GeoLane; timeoutMs?: number; locality?: boolean }, ): Promise<{ name: string | null; address: string | null }> { + lng = onTheRealWorld(lng); // Amap answers first when it holds the keyed slot, and only for a point it // can possibly know: outside its box the call would cost a round trip to // come back empty before Nominatim is asked anyway. Resolved at userId 0, diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index 8463f5d9f..f8956a5ae 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -102,6 +102,8 @@ const UNNUMBERED = [ 'Migration20200101046320_a_place_knows_where_its_details_came_from', 'Migration20200101046330_an_object_no_row_names_is_marked_before_it_goes', 'Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes', + 'Migration20200101046350_a_place_lies_on_the_real_world', + 'Migration20200101046360_a_new_install_starts_with_more_addons_on', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/new-install-addons-migration.test.ts b/server/tests/unit/db/new-install-addons-migration.test.ts new file mode 100644 index 000000000..ae8150033 --- /dev/null +++ b/server/tests/unit/db/new-install-addons-migration.test.ts @@ -0,0 +1,74 @@ +/** + * `Migration20200101046360_a_new_install_starts_with_more_addons_on`: a new + * install (no account yet) starts with Journey and Collections on; an existing + * install keeps every addon exactly as it was. + */ +import { DEFAULT_ADDONS } from '../../../src/db/seeders/AddonSeeder'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; +import type { MikroORM } from '@mikro-orm/sqlite'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046360_a_new_install_starts_with_more_addons_on'; + +interface AddonRow { + id: string; + enabled: number; +} + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; +} + +const addons = (orm: MikroORM) => rawQuery(orm, 'SELECT id, enabled FROM addons ORDER BY id'); + +describe('a new install starts with more addons on', () => { + it('ADDON-NEW-001: a new install has Journey and Collections switched on and nothing else touched', async () => { + const orm = await ormBeforeTarget(); + try { + const before = await addons(orm); + expect(before).toContainEqual({ id: 'journey', enabled: 0 }); + expect(before).toContainEqual({ id: 'collections', enabled: 0 }); + + await migrateTo(orm, TARGET); + + expect(await addons(orm)).toEqual( + before.map((row) => (row.id === 'journey' || row.id === 'collections' ? { ...row, enabled: 1 } : row)), + ); + } finally { + await orm.close(true); + } + }, 30000); + + it('ADDON-NEW-002: an existing install keeps every addon as it was', async () => { + const orm = await ormBeforeTarget(); + try { + await rawExec( + orm, + `INSERT INTO users (id, username, email, password_hash) VALUES (1, 'admin', 'admin@test', 'x')`, + ); + const before = await addons(orm); + + await migrateTo(orm, TARGET); + + expect(await addons(orm)).toEqual(before); + expect(before).toContainEqual({ id: 'journey', enabled: 0 }); + expect(before).toContainEqual({ id: 'collections', enabled: 0 }); + } finally { + await orm.close(true); + } + }, 30000); + + it('ADDON-NEW-004: the seeder writes every trip addon but Road trip, Journey, Collections, Atlas, Vacay and Naver on', () => { + const enabled = (id: string) => DEFAULT_ADDONS.find((addon) => addon.id === id)?.enabled; + for (const addon of DEFAULT_ADDONS.filter((a) => a.type === 'trip')) { + expect([addon.id, addon.enabled]).toEqual([addon.id, addon.id === 'roadtrip' ? 0 : 1]); + } + for (const id of ['journey', 'collections', 'atlas', 'vacay', 'naver_list_import']) expect(enabled(id)).toBe(1); + }); +}); diff --git a/server/tests/unit/db/place-real-world-migration.test.ts b/server/tests/unit/db/place-real-world-migration.test.ts new file mode 100644 index 000000000..8237986bf --- /dev/null +++ b/server/tests/unit/db/place-real-world-migration.test.ts @@ -0,0 +1,116 @@ +/** + * `Migration20200101046350_a_place_lies_on_the_real_world`: a longitude saved + * from a repeated world copy (274.9 for -85.1, #2976) is moved back onto the + * real world in places, reservation endpoints, collection places and the + * places-index contribution outbox. Rows + * already in range, and places without coordinates, keep exactly what they had, + * and a second run changes nothing. + */ +import { Migration20200101046350_a_place_lies_on_the_real_world } from '../../../src/db/migrations/Migration20200101046350_a_place_lies_on_the_real_world'; +import { + createMigrationOrm, + migrateTo, + pendingNames, + rawExec, + rawQuery, + runMigrationDirect, +} from '../../helpers/migration-step'; +import type { MikroORM } from '@mikro-orm/sqlite'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046350_a_place_lies_on_the_real_world'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; +} + +async function seed(orm: MikroORM): Promise { + await rawExec(orm, `INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')`); + await rawExec(orm, `INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'Pacific')`); + await rawExec( + orm, + `INSERT INTO places (id, trip_id, name, lat, lng) VALUES + (1, 1, 'right-hand copy', 10.14, 274.921875), + (2, 1, 'left-hand copy', 35.68, -220.3), + (3, 1, 'two copies away', 35.68, 859.7), + (4, 1, 'real world', 34.01, -118.5), + (5, 1, 'date line', -17.7, 180), + (6, 1, 'no coordinates', NULL, NULL)`, + ); + await rawExec(orm, `INSERT INTO reservations (id, trip_id, title) VALUES (1, 1, 'LAX to AKL')`); + await rawExec( + orm, + `INSERT INTO reservation_endpoints (id, reservation_id, role, sequence, name, lat, lng) VALUES + (1, 1, 'from', 0, 'LAX', 33.94, -118.41), + (2, 1, 'to', 1, 'AKL', -37.01, -185.215)`, + ); + await rawExec(orm, `INSERT INTO collections (id, owner_id, name) VALUES (1, 1, 'Saved')`); + await rawExec( + orm, + `INSERT INTO collection_places (id, collection_id, owner_id, name, lat, lng) VALUES + (1, 1, 1, 'saved on a copy', 48.85, 362.35), + (2, 1, 1, 'saved at home', 48.85, 2.35)`, + ); + await rawExec( + orm, + `INSERT INTO place_contrib_outbox (id, contrib_key, field, value, place_id, place_name, lat, lng, cid, eligible_at, next_attempt_at) + VALUES (1, 'k1', 'name', 'x', 1, 'right-hand copy', 10.14, 274.921875, 'c1', '2026-01-01', '2026-01-01')`, + ); +} + +const lngs = async (orm: MikroORM, table: string) => + (await rawQuery<{ id: number; lng: number | null }>(orm, `SELECT id, lng FROM ${table} ORDER BY id`)).map((r) => [ + r.id, + r.lng === null ? null : Math.round(r.lng * 1e6) / 1e6, + ]); + +async function expectWrapped(orm: MikroORM): Promise { + expect(await lngs(orm, 'places')).toEqual([ + [1, -85.078125], + [2, 139.7], + [3, 139.7], + [4, -118.5], + [5, 180], + [6, null], + ]); + expect(await lngs(orm, 'reservation_endpoints')).toEqual([ + [1, -118.41], + [2, 174.785], + ]); + expect(await lngs(orm, 'collection_places')).toEqual([ + [1, 2.35], + [2, 2.35], + ]); + expect(await lngs(orm, 'place_contrib_outbox')).toEqual([[1, -85.078125]]); +} + +describe('a place lies on the real world migration', () => { + it('REALWORLD-MIG-001: moves longitudes from a world copy back, leaves the rest alone', async () => { + const orm = await ormBeforeTarget(); + try { + await seed(orm); + await migrateTo(orm, TARGET); + await expectWrapped(orm); + } finally { + await orm.close(true); + } + }, 30000); + + it('REALWORLD-MIG-002: running it again changes nothing', async () => { + const orm = await ormBeforeTarget(); + try { + await seed(orm); + await migrateTo(orm, TARGET); + await runMigrationDirect(orm, Migration20200101046350_a_place_lies_on_the_real_world); + await expectWrapped(orm); + } finally { + await orm.close(true); + } + }, 30000); +}); diff --git a/server/tests/unit/db/repositories/longitude-on-write.test.ts b/server/tests/unit/db/repositories/longitude-on-write.test.ts new file mode 100644 index 000000000..52c883d70 --- /dev/null +++ b/server/tests/unit/db/repositories/longitude-on-write.test.ts @@ -0,0 +1,186 @@ +/** + * Every write of a place, a booking endpoint or a saved collection place stores + * its longitude on the real world (#2976): a point from a repeated world copy + * (-220.3, 274.9) is kept as the same point in [-180, 180], whichever transport + * wrote it, since REST, MCP, plugin RPC and the importers all end here. A value + * already in range and a missing one are written as they came. + */ +import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity'; +import { Places } from '../../../../src/db/entities/Places.entity'; +import { ReservationEndpoints } from '../../../../src/db/entities/ReservationEndpoints.entity'; +import type { CollectionPlacesRepository } from '../../../../src/db/repositories/CollectionPlaces.repository'; +import type { PlacesRepository } from '../../../../src/db/repositories/Places.repository'; +import type { ReservationEndpointsRepository } from '../../../../src/db/repositories/ReservationEndpoints.repository'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createPlace, createReservation, createTrip, createUser } from '../../../helpers/factories'; +import { makeCollection } from '../../../helpers/factories/collections'; +import { findRow } from '../../../helpers/factories/rows'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let places: PlacesRepository; +let endpoints: ReservationEndpointsRepository; +let collectionPlaces: CollectionPlacesRepository; + +beforeAll(async () => { + t = await createTestOrm(testDb); + places = t.repo(Places); + endpoints = t.repo(ReservationEndpoints); + collectionPlaces = t.repo(CollectionPlaces); +}); +beforeEach(() => { + resetTestDb(testDb); + t.clear(); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +const placeWrite = { + description: null, + address: null, + category_id: null, + price: null, + currency: null, + place_time: null, + end_time: null, + notes: null, + image_url: null, + google_place_id: null, + google_ftid: null, + osm_id: null, + amap_poi_id: null, + website: null, + phone: null, + route_color: null, + stop_type: null, + fill_percent: null, + email: null, + opening_hours: null, +}; + +async function storedLng(id: number): Promise { + return (await findRow(t.orm, Places, { id }))?.lng; +} + +describe('longitude on write', () => { + it('LNGWRITE-001: insertPlace and updatePlace keep a point from a world copy on the real world', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const id = await places.insertPlace({ + ...placeWrite, + trip_id: trip.id, + name: 'Copy', + lat: 35.68, + lng: -220.3, + duration_minutes: 60, + transport_mode: 'walking', + route_geometry: null, + }); + expect(await storedLng(id)).toBeCloseTo(139.7, 9); + + await places.updatePlace(id, { + ...placeWrite, + name: 'Copy', + lat: 10.14, + lng: 274.921875, + duration_minutes: 60, + transport_mode: null, + }); + expect(await storedLng(id)).toBeCloseTo(-85.078125, 9); + + await places.updatePlace(id, { + ...placeWrite, + name: 'Copy', + lat: null, + lng: null, + duration_minutes: 60, + transport_mode: null, + }); + expect(await storedLng(id)).toBeNull(); + }); + + it('LNGWRITE-002: a place on the real world, the edges included, is written as it came', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + for (const lng of [-118.4, 180, -180]) { + const id = await places.insertTourPlace({ + trip_id: trip.id, + name: `At ${lng}`, + lat: 0, + lng, + route_geometry: null, + }); + expect(await storedLng(id)).toBe(lng); + } + }); + + it('LNGWRITE-003: tour places and their route rewrites wrap too', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const tourId = await places.insertTourPlace({ + trip_id: trip.id, + name: 'Ridge', + lat: 47, + lng: 371, + route_geometry: null, + }); + expect(await storedLng(tourId)).toBeCloseTo(11, 9); + + const place = createPlace(testDb, trip.id, { name: 'Old', lat: 1, lng: 1 }); + expect( + await places.updateTourRoute(place.id, trip.id, { name: 'New', lat: 1, lng: -349, route_geometry: null }), + ).toBe(true); + expect(await storedLng(place.id)).toBeCloseTo(11, 9); + }); + + it('LNGWRITE-004: a booking endpoint from a world copy is stored on the real world', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const reservation = createReservation(testDb, trip.id, { type: 'flight' }); + const id = await endpoints.insertEndpoint({ + reservation_id: reservation.id, + role: 'to', + sequence: 1, + name: 'AKL', + code: 'AKL', + lat: -37.01, + lng: -185.215, + timezone: null, + local_time: null, + local_date: null, + }); + expect((await findRow(t.orm, ReservationEndpoints, { id }))?.lng).toBeCloseTo(174.785, 9); + }); + + it('LNGWRITE-005: a saved collection place wraps on save and on update, and an update without lng leaves it alone', async () => { + const { user } = createUser(testDb); + const collection = await makeCollection(t, user.id, { name: 'Saved' }); + const id = await collectionPlaces.insertSavedPlace({ + ...placeWrite, + collection_id: collection.id, + owner_id: user.id, + saved_by: user.id, + name: 'Paris', + lat: 48.85, + lng: 362.35, + status: 'saved', + source_trip_id: null, + source_place_id: null, + links: null, + }); + const lngOf = async () => (await findRow(t.orm, CollectionPlaces, { id }))?.lng; + expect(await lngOf()).toBeCloseTo(2.35, 9); + + await collectionPlaces.updateFields(id, { name: 'Paris again' }); + expect(await lngOf()).toBeCloseTo(2.35, 9); + + await collectionPlaces.updateFields(id, { lng: -357.65 }); + expect(await lngOf()).toBeCloseTo(2.35, 9); + }); +}); diff --git a/server/tests/unit/nest/maps.nearby.test.ts b/server/tests/unit/nest/maps.nearby.test.ts index eb255c93b..3a907e563 100644 --- a/server/tests/unit/nest/maps.nearby.test.ts +++ b/server/tests/unit/nest/maps.nearby.test.ts @@ -301,3 +301,17 @@ describe('nearby helpers', () => { expect(nearbyCacheKey(52.5163, 13.3777, 500, 20, 'de')).not.toBe(nearbyCacheKey(52.5163, 13.3777, 500, 20, 'en')); }); }); + +describe('MapsService.reverseGeocode on a repeated world copy (#2976)', () => { + it('MAPS-NEARBY-COPY-002: a right-click on a world copy is reverse geocoded on the real world, a real point as it came', async () => { + const svc = make(); + const osm = (svc as unknown as { osm: { reverse: (...args: unknown[]) => Promise } }).osm; + const reverse = vi.spyOn(osm, 'reverse').mockResolvedValue({ name: 'Manzanillo', address: null }); + + expect(await svc.reverseGeocode('10.14', '274.921875')).toEqual({ name: 'Manzanillo', address: null }); + expect(reverse).toHaveBeenLastCalledWith('10.14', '-85.078125', undefined, undefined); + + await svc.reverseGeocode('48.85', '2.3500'); + expect(reverse).toHaveBeenLastCalledWith('48.85', '2.3500', undefined, undefined); + }); +}); diff --git a/shared/src/geo/longitude.spec.ts b/shared/src/geo/longitude.spec.ts new file mode 100644 index 000000000..860356a67 --- /dev/null +++ b/shared/src/geo/longitude.spec.ts @@ -0,0 +1,29 @@ +// LONGITUDE-001 to LONGITUDE-004: longitudes from a repeated world copy back onto the real one (#2976). +import { wrapLongitude, wrapOptionalLongitude } from './longitude'; + +import { describe, expect, it } from 'vitest'; + +describe('wrapLongitude', () => { + it('LONGITUDE-001: leaves a real longitude alone, the edges included', () => { + for (const lng of [0, 13.4, -118.4, 174.8, 180, -180]) expect(wrapLongitude(lng)).toBe(lng); + }); + + it('LONGITUDE-002: brings a point on a neighbouring copy back to where it is', () => { + expect(wrapLongitude(274.921875)).toBeCloseTo(-85.078125, 9); + expect(wrapLongitude(-220)).toBeCloseTo(140, 9); + expect(wrapLongitude(139.7 - 720)).toBeCloseTo(139.7, 9); + expect(wrapLongitude(360)).toBe(0); + expect(Object.is(wrapLongitude(-360), 0)).toBe(true); + }); + + it('LONGITUDE-003: hands a non-finite value back for the caller to reject', () => { + expect(wrapLongitude(Number.NaN)).toBeNaN(); + expect(wrapLongitude(Number.POSITIVE_INFINITY)).toBe(Number.POSITIVE_INFINITY); + }); + + it('LONGITUDE-004: passes null and undefined through for optional columns', () => { + expect(wrapOptionalLongitude(null)).toBeNull(); + expect(wrapOptionalLongitude(undefined)).toBeUndefined(); + expect(wrapOptionalLongitude(-220)).toBeCloseTo(140, 9); + }); +}); diff --git a/shared/src/geo/longitude.ts b/shared/src/geo/longitude.ts new file mode 100644 index 000000000..b7bb9171e --- /dev/null +++ b/shared/src/geo/longitude.ts @@ -0,0 +1,23 @@ +/** + * A longitude brought back onto the one real world, in [-180, 180]. + * + * A map that repeats the world sideways (Leaflet and MapLibre both do) reports a + * point on a neighbouring copy as, say, -220 or 274.9 instead of 140 or -85.1. + * Stored like that, a place sat on its copy for good: the geocoder found nothing + * there, and a route to a place on the real world ran across the whole map (#2976). + * + * The edges are kept as given, so a stored -180 or 180 does not flip sides. A + * value that is not a finite number is returned untouched, for the caller's own + * validation to deal with. + */ +export function wrapLongitude(lng: number): number { + if (!Number.isFinite(lng) || (lng >= -180 && lng <= 180)) return lng; + const wrapped = ((((lng + 180) % 360) + 360) % 360) - 180; + // -0 reads as 0 everywhere else; keep it out of storage and snapshots. + return wrapped === 0 ? 0 : wrapped; +} + +/** wrapLongitude for an optional column: null and undefined pass through. */ +export function wrapOptionalLongitude(lng: T): T { + return (typeof lng === 'number' ? wrapLongitude(lng) : lng) as T; +} diff --git a/shared/src/index.ts b/shared/src/index.ts index b6964ddcb..41eaee9c1 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -111,6 +111,7 @@ export * from './wanderer/wanderer.schema'; export * from './wanderer/wanderer-watch.schema'; export * from './wanderer/wanderer-mcp.schema'; export * from './geo/haversine'; +export * from './geo/longitude'; export * from './collection/collection.schema'; export * from './collection/collection-file.schema'; export * from './trip/trip.schema';