Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(map): make stops that share a spot reachable again

Mauricea782e0e47184
diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx
index 3a35c46d3..e81ec544f 100644
--- a/client/src/components/Map/MapView.test.tsx
+++ b/client/src/components/Map/MapView.test.tsx
@@ -56,6 +56,37 @@ vi.mock('../../hooks/useGeolocation', () => ({
// after the map already rendered.
const thumbCallbacks = vi.hoisted(() => new Map<string, (thumb: string) => void>())
+// The cluster group and the Leaflet markers MapView reaches for when a selection lands
+// on a stop that shares its coordinates and so has no pin of its own. `stacked` decides
+// whether the group answers with a bubble or with the marker itself.
+const clusterMock = vi.hoisted(() => {
+ const spiderfy = vi.fn()
+ return {
+ spiderfy,
+ stacked: false,
+ asked: [] as unknown[],
+ markers: new Map<Element, object>(),
+ /**
+ * One marker double per pin, not per coordinate. Stops that share a coordinate are
+ * the whole point here, and a registry keyed by place id only proves anything when
+ * the two markers on that coordinate can be told apart.
+ */
+ stub(node: Element) {
+ const existing = clusterMock.markers.get(node)
+ if (existing) return existing
+ const fresh = { pin: node }
+ clusterMock.markers.set(node, fresh)
+ return fresh
+ },
+ group: {
+ getVisibleParent(marker: unknown) {
+ clusterMock.asked.push(marker)
+ return clusterMock.stacked ? { spiderfy } : marker
+ },
+ },
+ }
+})
+
vi.mock('react-leaflet', () => ({
// center/zoom are surfaced so tests can assert the camera the map is built
// with; maxZoom because a cluster refuses to attach to a map without one.
@@ -63,9 +94,16 @@ vi.mock('react-leaflet', () => ({
<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom} data-maxzoom={maxZoom}>{children}</div>
),
TileLayer: () => <div data-testid="tile-layer" />,
- Marker: ({ children, eventHandlers, position, icon, zIndexOffset }: any) => (
+ Marker: ({ children, eventHandlers, position, icon, zIndexOffset, ref }: any) => (
<div
- ref={node => { if (node && zIndexOffset === 500) eventHandlers?.add?.({ target: { getElement: () => node } }) }}
+ ref={node => {
+ if (node && zIndexOffset === 500) eventHandlers?.add?.({ target: { getElement: () => node } })
+ // Stands in for the L.Marker react-leaflet hands back, so MapView's registry has
+ // something to look a selected stop up by. Only the markers the cluster group
+ // holds get one: a place pin is all this double stands in for, and the route-via
+ // markers outside the group expect a Leaflet marker of their own.
+ ref?.(node?.closest('[data-testid="cluster-group"]') ? clusterMock.stub(node) : null)
+ }}
data-testid="marker"
data-lat={position[0]}
data-lng={position[1]}
@@ -118,8 +156,8 @@ vi.mock('react-leaflet', () => ({
vi.mock('react-leaflet-cluster', () => ({
// The real cluster group calls iconCreateFunction itself; the probe button
// lets a test invoke it with a chosen child count.
- default: ({ children, iconCreateFunction }: any) => (
- <div data-testid="cluster-group">
+ default: ({ children, iconCreateFunction, ref }: any) => (
+ <div data-testid="cluster-group" ref={node => { ref?.(node ? clusterMock.group : null) }}>
<button
data-testid="cluster-icon-probe"
onClick={(e: any) => {
@@ -174,6 +212,9 @@ const ORIGINAL_WIDTH = window.innerWidth
afterEach(() => {
vi.clearAllMocks()
resetAllStores()
+ clusterMock.markers.clear()
+ clusterMock.asked.length = 0
+ clusterMock.stacked = false
mapMock.panes.clear()
thumbCallbacks.clear()
geoMock.position = null
@@ -1242,3 +1283,54 @@ describe('MapView — untrusted values in the marker HTML', () => {
expect(iconHtml()).toContain('#00ff00')
})
})
+
+// Stops modelling one building — drop the bags, check in, the museum inside it — all
+// carry the same coordinates, so only the top pin of the pile is ever on screen. The
+// places rail used to raise the chosen one with a z-index; inside a bubble there is no
+// pin to raise, so the bubble has to open instead (#2344).
+describe('MapView — picking a stop that shares its coordinates', () => {
+ const hotel = { lat: 48.8584, lng: 2.2945 }
+ const stacked = [
+ buildMapPlace({ id: 1, name: 'Drop the bags', ...hotel }),
+ buildMapPlace({ id: 2, name: 'Check in', ...hotel }),
+ buildMapPlace({ id: 3, name: 'Louvre', lat: 48.8606, lng: 2.3376 }),
+ ]
+ /** The place pins, in the order the places were handed over. */
+ const pins = () => screen.getAllByTestId('marker').filter(node => node.closest('[data-testid="cluster-group"]'))
+ const markerOf = (index: number) => clusterMock.markers.get(pins()[index])
+
+ it('FE-COMP-MAPVIEW-077: the bubble it is hiding in is fanned open', () => {
+ clusterMock.stacked = true
+ const { rerender } = render(<MapView places={stacked} />)
+ expect(clusterMock.spiderfy).not.toHaveBeenCalled()
+
+ rerender(<MapView places={stacked} selectedPlaceId={2} />)
+ expect(clusterMock.spiderfy).toHaveBeenCalled()
+ // And it asked about the stop that was picked — not about the one stacked under it,
+ // which carries the same coordinates, and not about whichever registered first.
+ expect(clusterMock.asked).toContain(markerOf(1))
+ expect(clusterMock.asked).not.toContain(markerOf(0))
+ expect(clusterMock.asked).not.toContain(markerOf(2))
+ })
+
+ it('FE-COMP-MAPVIEW-079: a stop in another pile is looked up by its own id', () => {
+ clusterMock.stacked = true
+ const { rerender } = render(<MapView places={stacked} />)
+ rerender(<MapView places={stacked} selectedPlaceId={3} />)
+
+ expect(clusterMock.asked).toContain(markerOf(2))
+ expect(clusterMock.asked).not.toContain(markerOf(0))
+ expect(clusterMock.asked).not.toContain(markerOf(1))
+ })
+
+ it('FE-COMP-MAPVIEW-078: a stop with a pin of its own is left alone, camera included', () => {
+ clusterMock.stacked = false
+ const { rerender } = render(<MapView places={stacked} />)
+ rerender(<MapView places={stacked} selectedPlaceId={1} />)
+
+ expect(clusterMock.spiderfy).not.toHaveBeenCalled()
+ // The selection still only pans: the zoom belongs to the day fit.
+ expect(mapMock.panTo).toHaveBeenCalled()
+ expect(mapMock.setView).not.toHaveBeenCalled()
+ })
+})
diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx
index 82332b5bf..a1aae0dab 100644
--- a/client/src/components/Map/MapView.tsx
+++ b/client/src/components/Map/MapView.tsx
@@ -4,7 +4,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup'
import { MapContainer, TileLayer, Marker, Polyline, CircleMarker, Circle, useMap, Tooltip } from 'react-leaflet'
import MarkerClusterGroup from 'react-leaflet-cluster'
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
-import { CLUSTER_OPTIONS, createClusterIcon } from './markerCluster'
+import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
import RoadtripViaMarkers from './RoadtripViaMarkers'
import HazardLayers from './HazardLayers'
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
@@ -629,16 +629,25 @@ interface MemoMarkerProps {
onHoverOut: () => void
/** Off in read-only trips and on the phone, where HTML5 drag does not exist. */
draggable: boolean
+ /** Hands the Leaflet marker up, so a selection can find the bubble it is hiding in. */
+ onRegister: (id: number, marker: unknown) => void
}
const MemoMarker = memo(function MemoMarker({
- place, isSelected, orderNumbers, photoUrl, onClickPlace, onHover, onHoverOut, draggable,
+ place, isSelected, orderNumbers, photoUrl, onClickPlace, onHover, onHoverOut, draggable, onRegister,
}: MemoMarkerProps) {
const icon = createPlaceIcon({ ...place, image_url: photoUrl }, orderNumbers, isSelected)
const cleanupRef = useRef<(() => void) | null>(null)
+ // react-leaflet compares `position` by reference and calls setLatLng whenever it
+ // 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 register = useCallback((marker: unknown) => { onRegister(place.id, marker) }, [onRegister, place.id])
return (
<Marker
- position={[place.lat, place.lng]}
+ ref={register}
+ position={position}
icon={icon}
eventHandlers={{
// The element only exists once Leaflet has put the marker on the map,
@@ -902,6 +911,39 @@ export const MapView = memo(function MapView({
// HTML5 drag does not exist — and the day plan is not on screen there anyway.
const markersDraggable = !isTouchDevice
+ /**
+ * Reaching a stop that shares its coordinates with others.
+ *
+ * Such a stop has no pin of its own while the stack is collapsed — it is inside a
+ * cluster bubble — so the z-index that used to lift the selected pin out of the pile
+ * has nothing to lift. Fan the bubble open instead, which leaves the camera alone
+ * (#2344). The registry is what lets a selection find its Leaflet marker at all.
+ */
+ const clusterGroupRef = useRef<ClusterGroupLike | null>(null)
+ const placeMarkersRef = useRef(new Map<number, unknown>())
+ const registerClusterGroup = useCallback((group: unknown) => {
+ clusterGroupRef.current = (group as ClusterGroupLike | null) ?? null
+ }, [])
+ const registerMarker = useCallback((id: number, marker: unknown) => {
+ if (marker) placeMarkersRef.current.set(id, marker)
+ else placeMarkersRef.current.delete(id)
+ }, [])
+
+ useEffect(() => {
+ if (selectedPlaceId == null) return
+ let frame: number | null = null
+ const reveal = () => {
+ frame = null
+ revealInCluster(clusterGroupRef.current, placeMarkersRef.current.get(selectedPlaceId))
+ }
+ reveal()
+ // The group takes its markers in on a microtask and adds them in chunks, so a
+ // selection that arrives with the map — a link straight into a day — finds nothing
+ // on the first pass. A second attempt one frame later does.
+ if (typeof requestAnimationFrame === 'function') frame = requestAnimationFrame(reveal)
+ return () => { if (frame !== null) cancelAnimationFrame(frame) }
+ }, [selectedPlaceId, places])
+
const markers = useMemo(() => places.map((place) => {
const isSelected = place.id === selectedPlaceId
const pck = photoCacheKey(place)
@@ -919,9 +961,10 @@ export const MapView = memo(function MapView({
onHover={handleMarkerHover}
onHoverOut={handleMarkerHoverOut}
draggable={markersDraggable}
+ onRegister={registerMarker}
/>
)
- }), [places, selectedPlaceId, dayOrderMap, photoUrls, handleMarkerClick, handleMarkerHover, handleMarkerHoverOut, markersDraggable])
+ }), [places, selectedPlaceId, dayOrderMap, photoUrls, handleMarkerClick, handleMarkerHover, handleMarkerHoverOut, markersDraggable, registerMarker])
// Parsing track geometry is the expensive part (tracks run to tens of thousands
// of points), so it hangs off `places` alone — a selection change must not
@@ -1088,7 +1131,7 @@ export const MapView = memo(function MapView({
<PoiDropTarget onPoiDropOnRoute={onPoiDropOnRoute} />
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
- <MarkerClusterGroup {...CLUSTER_OPTIONS} iconCreateFunction={createClusterIcon}>
+ <MarkerClusterGroup ref={registerClusterGroup} {...CLUSTER_OPTIONS} iconCreateFunction={createClusterIcon}>
{markers}
</MarkerClusterGroup>
diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx
index 43e0d9104..aa7e9dc1b 100644
--- a/client/src/components/Map/MapViewGL.test.tsx
+++ b/client/src/components/Map/MapViewGL.test.tsx
@@ -870,6 +870,17 @@ describe('MapViewGL', () => {
properties: Record<string, unknown>
geometry: { type: string; coordinates: number[] | number[][] | number[][][] }
}
+ // A projection for the tests that care how far apart two pins land on screen. The map
+ // double projects 10 px per degree, an overview so coarse that a whole city sits under
+ // one pin; a real map is around 1500 px per degree at the zoom a day is fitted to.
+ // Setting an implementation at all is also what puts project() back: an earlier test
+ // pins it to a single point, and clearAllMocks keeps an implementation once set.
+ const PX_PER_DEGREE = 1500
+ const projectAtDayZoom = () =>
+ glMap.project.mockImplementation((lngLat: [number, number]) => (
+ { x: lngLat[0] * PX_PER_DEGREE, y: lngLat[1] * PX_PER_DEGREE }
+ ))
+
const geoSource = () => ({ setData: vi.fn((_data: unknown) => {}) })
function lastData(src: ReturnType<typeof geoSource>): { features: GeoFeature[] } {
const calls = vi.mocked(src.setData).mock.calls
@@ -1534,6 +1545,7 @@ describe('MapViewGL', () => {
it('FE-COMP-MAPVIEWGL-047: only the unclustered leaves of the cluster source get a rich marker (#1385)', async () => {
loadOnAttach()
+ projectAtDayZoom()
const clusterSource = geoSource()
glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))
glMap.querySourceFeatures.mockReturnValue([
@@ -1565,6 +1577,102 @@ describe('MapViewGL', () => {
expect(drawn).not.toContainEqual([2.3, 48.3])
})
+ // One building modelled as several stops — drop the bags, check in, the museum inside
+ // it — puts every pin on the same spot, and all but the top one are unreachable. There
+ // is no spiderfy on a GL map, so the stack draws as the one pin worth seeing (#2344).
+ it('FE-COMP-MAPVIEWGL-077: stops on one coordinate draw one pin, and picking a buried one makes it that pin', async () => {
+ loadOnAttach()
+ projectAtDayZoom()
+ const clusterSource = geoSource()
+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))
+ glMap.querySourceFeatures.mockReturnValue([
+ { properties: { placeId: 71 } },
+ { properties: { placeId: 72 } },
+ { properties: { placeId: 73 } },
+ ])
+ const hotel = { lat: 48.8584, lng: 2.2945 }
+ const places = [
+ buildMapPlace({ id: 71, name: 'Drop the bags', ...hotel }),
+ buildMapPlace({ id: 72, name: 'Check in', ...hotel }),
+ buildMapPlace({ id: 73, name: 'Louvre', lat: 60.1, lng: 9.3 }),
+ ]
+ // The order badge is what tells the two stops on the hotel apart on screen.
+ const dayOrderMap = { 71: [1], 72: [2], 73: [3] }
+ const pinsOnTheHotel = () => glMarkers.created.filter(marker => marker.lngLat?.[0] === hotel.lng)
+
+ const { rerender } = render(<MapViewGL places={places} fitKey={1} dayOrderMap={dayOrderMap} />)
+ await flushFrames()
+
+ expect(pinsOnTheHotel()).toHaveLength(1)
+ expect(pinsOnTheHotel()[0].element.innerHTML).toContain('>1</span>')
+ // The stop elsewhere is untouched by the folding.
+ expect(glMarkers.created.map(m => m.lngLat)).toContainEqual([9.3, 60.1])
+
+ glMarkers.clear()
+ rerender(<MapViewGL places={places} fitKey={1} dayOrderMap={dayOrderMap} selectedPlaceId={72} />)
+ await flushFrames()
+
+ expect(pinsOnTheHotel()).toHaveLength(1)
+ expect(pinsOnTheHotel()[0].element.innerHTML).toContain('>2</span>')
+ })
+
+ // Two ordinary neighbours — a hotel and the restaurant across the street — are not a
+ // pile. Nothing here can fan a bubble open again, so anything the fold reaches beyond
+ // the pins that cover each other is a stop the map simply loses (#2344).
+ it('FE-COMP-MAPVIEWGL-078: stops a few hundred metres apart keep a pin each', async () => {
+ loadOnAttach()
+ projectAtDayZoom()
+ const clusterSource = geoSource()
+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))
+ glMap.querySourceFeatures.mockReturnValue([
+ { properties: { placeId: 81 } },
+ { properties: { placeId: 82 } },
+ ])
+ // ~300 m apart at this latitude, which the projection above puts 6 px apart: well
+ // inside the width of a pin, and still two stops a user has to be able to reach.
+ const places = [
+ buildMapPlace({ id: 81, name: 'Hotel Le Marais', lat: 48.8584, lng: 2.2945 }),
+ buildMapPlace({ id: 82, name: 'Chez Julien', lat: 48.8584, lng: 2.2986 }),
+ ]
+
+ render(<MapViewGL places={places} fitKey={1} />)
+ await flushFrames()
+
+ const drawn = glMarkers.created.map(m => m.lngLat)
+ expect(drawn).toContainEqual([2.2945, 48.8584])
+ expect(drawn).toContainEqual([2.2986, 48.8584])
+ })
+
+ // Without a projection there is no telling which pins land on each other, and a guess
+ // costs a stop its marker for good. Draw them all instead, as the map always did.
+ it('FE-COMP-MAPVIEWGL-079: a map that cannot place its pins still draws every one of them', async () => {
+ loadOnAttach()
+ const clusterSource = geoSource()
+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))
+ glMap.querySourceFeatures.mockReturnValue([
+ { properties: { placeId: 91 } },
+ { properties: { placeId: 92 } },
+ ])
+ const places = [
+ buildMapPlace({ id: 91, lat: 48.1, lng: 2.1 }),
+ buildMapPlace({ id: 92, lat: 48.2, lng: 2.2 }),
+ ]
+
+ const projection = glMap.project
+ const engine = glMap as unknown as { project?: unknown }
+ try {
+ engine.project = undefined
+ render(<MapViewGL places={places} fitKey={1} />)
+ await flushFrames()
+ } finally {
+ engine.project = projection
+ }
+
+ const drawn = glMarkers.created.map(m => m.lngLat)
+ expect(drawn).toContainEqual([2.1, 48.1])
+ expect(drawn).toContainEqual([2.2, 48.2])
+ })
+
it('FE-COMP-MAPVIEWGL-048: the day route becomes one LineString per drawn segment', async () => {
const routeSource = geoSource()
glMap.getSource.mockImplementation((id: string) => (id === 'trip-route' ? routeSource : null))
diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx
index 9f21dfb4f..24c5dcf97 100644
--- a/client/src/components/Map/MapViewGL.tsx
+++ b/client/src/components/Map/MapViewGL.tsx
@@ -27,6 +27,7 @@ import type { Day, Place, Reservation, RouteVia } from '../../types'
import type { MapHoverInfo } from './mapHover'
import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker'
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
+import { groupCoincidentPlaces } from './coincidentPlaces'
import type { RoadtripHazard } from '@trek/shared'
import { useHazardLayerGL } from './useHazardLayerGL'
import { useDawarichTrailGL } from './useDawarichTrailGL'
@@ -229,7 +230,15 @@ interface Props {
onMapReady?: (map: any | null) => void
}
-/** How eagerly place markers merge into a cluster. */
+/**
+ * How eagerly place markers merge into a cluster.
+ *
+ * The overview band the Leaflet map clusters in as well (`CLUSTER_UNTIL_ZOOM` there),
+ * kept as plain numbers rather than shared constants so the GL bundle does not have to
+ * carry Leaflet for them. Above the cutoff supercluster hands every point back on its
+ * own, and the stops that share a coordinate are folded together at the pin level
+ * instead — see the reconcile below.
+ */
const CLUSTER_RADIUS = 20
const CLUSTER_MAX_ZOOM = 8
@@ -1872,7 +1881,24 @@ export function MapViewGL({
seen.add(id)
visiblePlaces.push(place)
}
- reconcileMarkers(visiblePlaces)
+ // Without a projection there is no way to tell which pins land on each other, so
+ // nothing is folded and every stop keeps the pin it has always had.
+ if (typeof map.project !== 'function') {
+ reconcileMarkers(visiblePlaces)
+ return
+ }
+ // Above the cluster cutoff supercluster reports every point unclustered, so stops
+ // on one coordinate would each get a pin and all but one of them would be buried
+ // (#2344). There is no spiderfy on a GL map to fan them out, so the pile draws as
+ // the one pin that is wanted: the selected stop when it is in there, which is what
+ // makes picking it from the places rail visible at all. Only pins that sit on each
+ // other fold — this side cannot undo a fold, hence its own tight radius.
+ const stacks = groupCoincidentPlaces(
+ visiblePlaces,
+ place => map.project([place.lng, place.lat]),
+ selectedPlaceId,
+ )
+ reconcileMarkers(stacks.map(stack => stack.lead))
}
const scheduleReconcile = () => {
if (raf !== null) return
diff --git a/client/src/components/Map/coincidentPlaces.test.ts b/client/src/components/Map/coincidentPlaces.test.ts
new file mode 100644
index 000000000..fd9517c6e
--- /dev/null
+++ b/client/src/components/Map/coincidentPlaces.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import { COINCIDENT_RADIUS_PX, groupCoincidentPlaces, STACK_RADIUS_PX } from './coincidentPlaces'
+
+interface Stop { id: number; x: number; y: number }
+const stop = (id: number, x: number, y = 0): Stop => ({ id, x, y })
+const project = (item: Stop) => ({ x: item.x, y: item.y })
+
+describe('stops that share a spot on screen', () => {
+ it('COINCIDENT-001: stops on one coordinate become a single group', () => {
+ const groups = groupCoincidentPlaces([stop(1, 40), stop(2, 40), stop(3, 40)], project)
+ expect(groups).toHaveLength(1)
+ expect(groups[0].members.map(member => member.id)).toEqual([1, 2, 3])
+ expect(groups[0].lead.id).toBe(1)
+ })
+
+ it('COINCIDENT-002: the fold reaches no further than the pins that cover each other', () => {
+ const apart = groupCoincidentPlaces([stop(1, 0), stop(2, COINCIDENT_RADIUS_PX)], project)
+ expect(apart.map(group => group.members.length)).toEqual([1, 1])
+ // Inside the radius the lower pin has nothing showing to click at anyway.
+ const touching = groupCoincidentPlaces([stop(1, 0), stop(2, COINCIDENT_RADIUS_PX - 0.5)], project)
+ expect(touching.map(group => group.members.length)).toEqual([2])
+ // A pin's width apart is two ordinary neighbouring stops — a hotel and the
+ // restaurant across the street — and both of them keep a pin, since the renderer
+ // this grouping serves has no bubble to put the second one in (#2344).
+ const neighbours = groupCoincidentPlaces([stop(1, 0), stop(2, STACK_RADIUS_PX)], project)
+ expect(neighbours.map(group => group.members.length)).toEqual([1, 1])
+ })
+
+ it('COINCIDENT-003: the same stops group the same way whatever order they arrive in', () => {
+ const stops = [stop(3, 100), stop(1, 0), stop(2, 1), stop(1, 0)]
+ const groups = groupCoincidentPlaces(stops, project)
+ expect(groups.map(group => group.members.map(member => member.id))).toEqual([[1, 2], [3]])
+ expect(groupCoincidentPlaces([...stops].reverse(), project)).toEqual(groups)
+ })
+
+ it('COINCIDENT-004: a stop the map cannot place keeps a group of its own rather than vanishing', () => {
+ const missing = { id: 9, x: Number.NaN, y: 0 }
+ const groups = groupCoincidentPlaces([stop(1, 0), missing, stop(2, 400)], item => (
+ item.id === 9 ? null : project(item)
+ ))
+ expect(groups.map(group => group.members.map(member => member.id))).toEqual([[1], [2], [9]])
+ expect(groupCoincidentPlaces([missing], project).map(group => group.lead)).toEqual([missing])
+ // And two of them stay apart: an item nothing could place cannot swallow another.
+ const unplaceable = groupCoincidentPlaces([stop(1, 0), stop(2, 0)], () => null)
+ expect(unplaceable.map(group => group.members.map(member => member.id))).toEqual([[1], [2]])
+ })
+
+ it('COINCIDENT-005: the selected stop is the one drawn for its stack', () => {
+ const stops = [stop(1, 40), stop(2, 40), stop(3, 400)]
+ expect(groupCoincidentPlaces(stops, project, 2)[0].lead.id).toBe(2)
+ // A selection from another stack, or none at all, leaves the first member leading.
+ expect(groupCoincidentPlaces(stops, project, 3)[0].lead.id).toBe(1)
+ expect(groupCoincidentPlaces(stops, project, null)[0].lead.id).toBe(1)
+ })
+})
diff --git a/client/src/components/Map/coincidentPlaces.ts b/client/src/components/Map/coincidentPlaces.ts
new file mode 100644
index 000000000..4879d5a30
--- /dev/null
+++ b/client/src/components/Map/coincidentPlaces.ts
@@ -0,0 +1,79 @@
+/**
+ * Stops that land on the same spot on screen.
+ *
+ * A trip often models one building as several stops — drop the bags, check in, the
+ * museum inside the hotel, the tour — and every one of them carries the same
+ * coordinates. No zoom level can pull those apart, so each renderer draws the pile as a
+ * single thing instead. This is the grouping the GL side does that with, kept clear of
+ * Leaflet and of the GL SDKs so it can be reasoned about without a map.
+ *
+ * The two renderers fold at deliberately different distances, because a fold costs them
+ * different things. Leaflet folds into a cluster bubble that carries a count and fans
+ * open on click, so a stop inside one is still reachable and the generous
+ * `STACK_RADIUS_PX` is a straight improvement on two pins overlapping. MapLibre and
+ * Mapbox have no spiderfy: a folded-away stop there has no marker at all, and with it no
+ * hover card, no click target, no drag onto a day and no order badge. So the GL side
+ * folds at `COINCIDENT_RADIUS_PX`, which reaches no further than pins that are
+ * effectively the same point — where nothing was reachable before the fold either. The
+ * two numbers are not meant to be brought in line: a fold is only safe where the
+ * renderer can undo it.
+ */
+
+/**
+ * How close two pins have to be before Leaflet stacks them into a cluster.
+ *
+ * A place pin is 36 px across (44 while selected), so a third of a pin is already
+ * enough overlap to swallow whatever is underneath: two stops two metres apart sit
+ * about 7 px apart at the map's maximum zoom.
+ */
+export const STACK_RADIUS_PX = 12
+
+/**
+ * How close two pins have to be before the GL renderer draws the pile as one pin.
+ *
+ * Two pixels is the rounding of a projection rather than a distance on the ground. Pins
+ * that close overlap by more than nine tenths of their width, so the buried one had
+ * nothing left to hover or click before the fold either. Two stops a few hundred metres
+ * apart — the neighbours a city day is made of — sit further apart than that from the
+ * overview zooms upwards, and keep a marker each.
+ */
+export const COINCIDENT_RADIUS_PX = 2
+
+export interface CoincidentGroup<T> {
+ /** The one member drawn for the whole group. */
+ lead: T
+ /** Every member, in id order. */
+ members: T[]
+}
+
+/**
+ * Bundle the items whose projected pixels sit within `COINCIDENT_RADIUS_PX` of each other.
+ *
+ * `project` is the caller's map: a GL `map.project`, or a plain stub under test. An item
+ * it cannot place — no coordinates, a projection that came back NaN — is given a group
+ * of its own rather than grouped at the origin or dropped, so a projection that fails
+ * costs nobody their pin. Grouping runs in id order so the same input always produces
+ * the same groups, and `leadId` (the selected stop, normally) decides which member of a
+ * group is the one drawn.
+ */
+export function groupCoincidentPlaces<T extends { id: number }>(
+ items: T[],
+ project: (item: T) => { x: number; y: number } | null | undefined,
+ leadId: number | null = null,
+): CoincidentGroup<T>[] {
+ const groups: { members: T[]; at: { x: number; y: number } | null }[] = []
+ const unique = new Map(items.map(item => [item.id, item]))
+ for (const item of [...unique.values()].sort((a, b) => a.id - b.id)) {
+ const point = project(item)
+ const at = point && Number.isFinite(point.x) && Number.isFinite(point.y) ? point : null
+ // An unplaceable item anchors its group nowhere, so nothing joins it and nothing is
+ // folded into it: hiding a pin is only ever allowed where another pin covers it.
+ const stack = at && groups.find(group => group.at && Math.hypot(at.x - group.at.x, at.y - group.at.y) < COINCIDENT_RADIUS_PX)
+ if (stack) stack.members.push(item)
+ else groups.push({ members: [item], at })
+ }
+ return groups.map(({ members }) => ({
+ members,
+ lead: members.find(member => member.id === leadId) ?? members[0],
+ }))
+}
diff --git a/client/src/components/Map/markerCluster.test.ts b/client/src/components/Map/markerCluster.test.ts
new file mode 100644
index 000000000..bc5b25ad7
--- /dev/null
+++ b/client/src/components/Map/markerCluster.test.ts
@@ -0,0 +1,121 @@
+/**
+ * What the shared cluster options do to stops that share a coordinate (#2344).
+ *
+ * Nothing is mocked: the behaviour under test is leaflet.markercluster's own. The
+ * library's single answer to markers no zoom can separate is to fan them out on click,
+ * and whether that can fire at all is decided entirely by this option block — which is
+ * why the block is worth a test of its own rather than a snapshot in a component suite.
+ */
+import { describe, it, expect, afterEach } from 'vitest'
+import L from 'leaflet'
+import 'leaflet.markercluster'
+import { CLUSTER_OPTIONS, CLUSTER_RADIUS_PX, CLUSTER_UNTIL_ZOOM, revealInCluster } from './markerCluster'
+import { COINCIDENT_RADIUS_PX, STACK_RADIUS_PX } from './coincidentPlaces'
+import { MAP_MAX_ZOOM } from '../../constants/mapDefaults'
+
+/**
+ * `leaflet.markercluster` ships no types and we do not depend on
+ * `@types/leaflet.markercluster`, so the factory and the two internals these tests read
+ * back are named here rather than pulling a package in.
+ */
+type Group = L.Layer & {
+ _maxZoom: number
+ addLayers: (layers: L.Marker[]) => Group
+ getVisibleParent: (marker: L.Marker) => L.Layer | null
+}
+const markerClusterGroup = (L as unknown as { markerClusterGroup: (options: unknown) => Group }).markerClusterGroup
+
+const containers: HTMLElement[] = []
+
+function mapAt(zoom: number, maxZoom = MAP_MAX_ZOOM): L.Map {
+ const el = document.createElement('div')
+ Object.defineProperty(el, 'clientWidth', { value: 800 })
+ Object.defineProperty(el, 'clientHeight', { value: 600 })
+ document.body.appendChild(el)
+ containers.push(el)
+ return L.map(el, { center: [48.8584, 2.2945], zoom, maxZoom })
+}
+
+/** A group already on the map, holding a marker per coordinate. */
+function stopsOn(map: L.Map, coords: [number, number][]) {
+ const group = markerClusterGroup(CLUSTER_OPTIONS)
+ group.addTo(map)
+ const markers = coords.map(coord => L.marker(coord))
+ group.addLayers(markers)
+ return { group, markers }
+}
+
+const HOTEL: [number, number] = [48.8584, 2.2945]
+// ~300 m east: two ordinary neighbouring stops in a city day plan.
+const NEARBY: [number, number] = [48.8584, 2.2986]
+
+afterEach(() => { for (const el of containers.splice(0)) el.remove() })
+
+describe('the shared cluster options', () => {
+ it('MARKERCLUSTER-001: cluster by the overview radius in the overview, by a pin width above it', () => {
+ const radius = CLUSTER_OPTIONS.maxClusterRadius
+ expect(radius(0)).toBe(CLUSTER_RADIUS_PX)
+ expect(radius(CLUSTER_UNTIL_ZOOM - 1)).toBe(CLUSTER_RADIUS_PX)
+ expect(radius(CLUSTER_UNTIL_ZOOM)).toBe(STACK_RADIUS_PX)
+ expect(radius(MAP_MAX_ZOOM)).toBe(STACK_RADIUS_PX)
+ // Wider than what the GL renderer folds at, and meant to stay wider: a bubble here
+ // hands the stops in it back on a click, where a folded GL pin is simply gone.
+ expect(STACK_RADIUS_PX).toBeGreaterThan(COINCIDENT_RADIUS_PX)
+ })
+
+ it('MARKERCLUSTER-002: carry no clustering cutoff at all, not even an undefined one', () => {
+ // The library guards on `!== null`, so the key spelled with `undefined` gives the
+ // group a NaN maximum zoom, builds no grid at all and throws on the first marker.
+ expect('disableClusteringAtZoom' in CLUSTER_OPTIONS).toBe(false)
+ })
+
+ it('MARKERCLUSTER-003: take their maximum zoom from the map, which is what makes the fan reachable', () => {
+ expect(stopsOn(mapAt(14), []).group._maxZoom).toBe(MAP_MAX_ZOOM)
+ })
+
+ it('MARKERCLUSTER-004: follow a mount site that lowers its own ceiling, silently', () => {
+ // Nothing throws and nothing warns: a map mounted with a lower ceiling simply moves
+ // the zoom at which a stack can still be fanned open.
+ expect(stopsOn(mapAt(14, 15), []).group._maxZoom).toBe(15)
+ })
+
+ it('MARKERCLUSTER-005: keep stops on one coordinate in a bubble at a day zoom, and fan them open', () => {
+ const map = mapAt(16)
+ const { group, markers } = stopsOn(map, [HOTEL, HOTEL, HOTEL])
+ const bubble = group.getVisibleParent(markers[0])
+ expect(bubble).not.toBe(markers[0])
+ expect(group.getVisibleParent(markers[2])).toBe(bubble)
+
+ expect(revealInCluster(group, markers[0])).toBe(true)
+ const spread = markers.map(marker => `${marker.getLatLng().lat},${marker.getLatLng().lng}`)
+ expect(new Set(spread).size).toBe(3)
+ })
+
+ it('MARKERCLUSTER-006: leave neighbouring stops alone at a day zoom, as they are today', () => {
+ const map = mapAt(16)
+ const { group, markers } = stopsOn(map, [HOTEL, NEARBY])
+ expect(group.getVisibleParent(markers[0])).toBe(markers[0])
+ expect(group.getVisibleParent(markers[1])).toBe(markers[1])
+ })
+
+ it('MARKERCLUSTER-007: still merge those same stops in the overview the radius was tuned for', () => {
+ const map = mapAt(5)
+ const { group, markers } = stopsOn(map, [HOTEL, NEARBY])
+ expect(group.getVisibleParent(markers[0])).not.toBe(markers[0])
+ expect(group.getVisibleParent(markers[0])).toBe(group.getVisibleParent(markers[1]))
+ })
+})
+
+describe('reaching a stop inside a bubble', () => {
+ it('MARKERCLUSTER-008: does nothing when there is no group, no marker or no bubble to open', () => {
+ expect(revealInCluster(null, {})).toBe(false)
+ expect(revealInCluster({ getVisibleParent: () => null }, null)).toBe(false)
+ expect(revealInCluster({}, {})).toBe(false)
+ expect(revealInCluster({ getVisibleParent: () => null }, {})).toBe(false)
+ const marker = {}
+ // A stop with a pin of its own is its own visible parent: nothing to fan.
+ expect(revealInCluster({ getVisibleParent: () => marker }, marker)).toBe(false)
+ // And a parent from a group that cannot spiderfy is left alone rather than called.
+ expect(revealInCluster({ getVisibleParent: () => ({}) }, {})).toBe(false)
+ })
+})
diff --git a/client/src/components/Map/markerCluster.ts b/client/src/components/Map/markerCluster.ts
index a80a69fd2..6ecf64f2f 100644
--- a/client/src/components/Map/markerCluster.ts
+++ b/client/src/components/Map/markerCluster.ts
@@ -1,4 +1,10 @@
import L from 'leaflet'
+import { STACK_RADIUS_PX } from './coincidentPlaces'
+
+/** Up to here the map is an overview, where stops merge to keep the world readable. */
+export const CLUSTER_UNTIL_ZOOM = 9
+/** The overview radius, in pixels at the current zoom. */
+export const CLUSTER_RADIUS_PX = 20
/**
* The cluster group the planner and the public share page both draw places with,
@@ -8,15 +14,50 @@ export const CLUSTER_OPTIONS = {
chunkedLoading: true,
chunkInterval: 30,
chunkDelay: 0,
- // Pixels at the current zoom, so ordinary stops still come apart by zooming in.
- maxClusterRadius: 20,
- disableClusteringAtZoom: 9,
+ /**
+ * Pixels at the current zoom, so ordinary stops still come apart by zooming in.
+ * From the day zooms upwards only the width of a pin counts: stops sharing one
+ * coordinate cannot be separated by any zoom, and a cluster is the only thing
+ * that can fan them apart again. There is deliberately no `disableClusteringAtZoom`
+ * here — it redefines the group's own maximum zoom, which is what the spiderfy
+ * branch is measured against.
+ *
+ * A whole pin's third is affordable precisely because the fold is reversible here:
+ * what comes out of it is a counted bubble the user can click open. The GL renderer
+ * has no fan to offer and folds far tighter — see `COINCIDENT_RADIUS_PX`.
+ */
+ maxClusterRadius: (zoom: number) => (zoom < CLUSTER_UNTIL_ZOOM ? CLUSTER_RADIUS_PX : STACK_RADIUS_PX),
spiderfyOnMaxZoom: true,
+ // The default legs put four 36px pins barely a pin apart and six of them back on
+ // top of each other, which is the stack the fan is there to undo.
+ spiderfyDistanceMultiplier: 1.6,
showCoverageOnHover: false,
zoomToBoundsOnClick: true,
animate: false,
}
+/** The part of a cluster group that `revealInCluster` reads. */
+export interface ClusterGroupLike {
+ getVisibleParent?: (marker: unknown) => unknown
+}
+
+/**
+ * Fan open the bubble a stop is hidden inside, if it is in one.
+ *
+ * Picking a stop from the places rail used to raise its pin out of the stack with a
+ * z-index. A stop sharing its coordinates now sits in a cluster instead and has no pin
+ * of its own to raise, so the bubble has to open for the selection to be visible at all.
+ * Deliberately not `zoomToShowLayer`: the zoom belongs to the day fit, and the selection
+ * only ever pans.
+ */
+export function revealInCluster(group: ClusterGroupLike | null | undefined, marker: unknown): boolean {
+ if (!group || !marker || typeof group.getVisibleParent !== 'function') return false
+ const parent = group.getVisibleParent(marker) as { spiderfy?: () => void } | null
+ if (!parent || parent === marker || typeof parent.spiderfy !== 'function') return false
+ parent.spiderfy()
+ return true
+}
+
/** The part of a Leaflet cluster this factory reads. */
export interface ClusterLike {
getChildCount: () => number
diff --git a/client/tests/unit/pages/SharedTripPage.map.test.tsx b/client/tests/unit/pages/SharedTripPage.map.test.tsx
index 9b7f9f238..fa2cae0a8 100644
--- a/client/tests/unit/pages/SharedTripPage.map.test.tsx
+++ b/client/tests/unit/pages/SharedTripPage.map.test.tsx
@@ -6,7 +6,9 @@ import React from 'react';
import L from 'leaflet';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, within } from '../../helpers/render';
-import { CLUSTER_OPTIONS, createClusterIcon } from '../../../src/components/Map/markerCluster';
+import { CLUSTER_OPTIONS, CLUSTER_RADIUS_PX, CLUSTER_UNTIL_ZOOM, createClusterIcon } from '../../../src/components/Map/markerCluster';
+import { STACK_RADIUS_PX } from '../../../src/components/Map/coincidentPlaces';
+import { MAP_MAX_ZOOM } from '../../../src/constants/mapDefaults';
import SharedTripPage from '../../../src/pages/SharedTripPage';
const mocks = vi.hoisted(() => ({
@@ -119,6 +121,22 @@ describe('the map on a public share page', () => {
expect(small.options.html).toContain('width:36px;height:36px');
});
+ it('FE-PAGE-SHARED-MAP-005: two stops on one coordinate stay in a bubble a guest can open (#2344)', () => {
+ mocks.hook = hookState(
+ payload([place(11, 'Drop the bags', 31.24, 121.49), place(12, 'Check in', 31.24, 121.49)]),
+ );
+ render(<SharedTripPage />);
+
+ const props = mocks.clusterProps[0];
+ // A guest has no places rail to fall back on, so the bubble is the only way in and
+ // nothing may switch clustering off above the zoom the trip is read at.
+ expect(props).not.toHaveProperty('disableClusteringAtZoom');
+ expect(props.spiderfyOnMaxZoom).toBe(true);
+ const radius = props.maxClusterRadius as (zoom: number) => number;
+ expect(radius(MAP_MAX_ZOOM)).toBe(STACK_RADIUS_PX);
+ expect(radius(CLUSTER_UNTIL_ZOOM - 1)).toBe(CLUSTER_RADIUS_PX);
+ });
+
it('FE-PAGE-SHARED-MAP-004: a place without coordinates is left out of the map, as before', () => {
mocks.hook = hookState(
payload([place(11, 'The Bund', 31.24, 121.49), { id: 12, name: 'Geocoding failed' } as never]),