From 4b7c96f4c5adbab3c7ed8af50d1afd0615973ecf Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 3 Dec 2026 11:10:14 +0100 Subject: [PATCH] fix(map): reveal selected places at street level Use street-level zoom in both renderers while keeping the selected pin between the map panels. Lift the selected Leaflet marker out of a dense group when needed, and keep a late route fit from overriding the selection. Closes #3306 --- client/scripts/size-baseline.json | 2 +- .../components/Map/MapView.leaflet.test.tsx | 46 ++++++++++++++ client/src/components/Map/MapView.test.tsx | 11 ++-- client/src/components/Map/MapView.tsx | 60 +++++++------------ client/src/components/Map/MapViewGL.tsx | 8 +-- .../components/Map/SelectionController.tsx | 48 +++++++++++---- client/src/components/Map/markerCluster.ts | 18 ++++-- .../src/components/Map/selectedPlaceTarget.ts | 3 + .../Map/useLeafletClusterSelection.ts | 54 +++++++++++++++++ .../Map/useSelectionCameraGL.test.ts | 4 +- .../components/Map/useSelectionCameraGL.ts | 4 +- 11 files changed, 188 insertions(+), 70 deletions(-) create mode 100644 client/src/components/Map/useLeafletClusterSelection.ts diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index 8f908e437..583a86bc2 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -5,7 +5,7 @@ "src/components/Admin/AdminPluginsPanel.tsx": 1265, "src/components/Budget/CostsPanel.test.tsx": 2725, "src/components/Budget/CostsPanel.tsx": 1607, - "src/components/Map/MapView.tsx": 1191, + "src/components/Map/MapView.tsx": 1170, "src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.tsx": 2083, "src/components/Planner/DayDetailPanel.test.tsx": 2331, diff --git a/client/src/components/Map/MapView.leaflet.test.tsx b/client/src/components/Map/MapView.leaflet.test.tsx index 25fc20410..61aade73d 100644 --- a/client/src/components/Map/MapView.leaflet.test.tsx +++ b/client/src/components/Map/MapView.leaflet.test.tsx @@ -145,6 +145,52 @@ async function renderMap() { } describe('MapView on a real Leaflet map', () => { + it('reveals the selected stop inside an island-wide cluster (#3306)', async () => { + const island = Array.from({ length: 29 }, (_, index) => ({ + // The later stops form a second cluster still too large to fan open at street level. + ...buildPlace({ id: 33060 + index, name: `Mahé stop ${index}`, lat: -4.62, + lng: index < 15 ? 55.44 + index * 0.001 : 55.447 + (index - 14) * 0.00001 }), + category_name: null, category_color: null, category_icon: null, + })) + const selected = island[7] + const view = render() + const map = maps[maps.length - 1] + view.rerender() + act(() => { map.setView([-4.62, 55.44], 8, { animate: false }) }) + await waitFor(() => expect(view.container.querySelector('.marker-cluster-wrapper')).not.toBeNull()) + expect(view.container.querySelector(`[data-place-name="${selected.name}"]`)).toBeNull() + function expectSelectedPin(place: typeof selected) { + let selectedPin: HTMLElement | null | undefined + map.eachLayer(layer => { + if (layer instanceof L.Marker && layer.options.zIndexOffset === 1000 && + layer.getLatLng().equals([place.lat, place.lng])) selectedPin = layer.getElement() + }) + expect(selectedPin).toBeInstanceOf(HTMLElement) + } + + view.rerender() + + await waitFor(() => { + expect(map.getZoom()).toBe(16) + expectSelectedPin(selected) + expect(view.container.querySelector('.marker-cluster-wrapper')?.textContent).toBe('14') + expect(map.latLngToContainerPoint([selected.lat, selected.lng]).y).toBeLessThan(280) + }) + + // The day's route can finish loading after the user chose a stop from the itinerary. + view.rerender() + expect(map.getZoom()).toBe(16) + + // At street zoom a switch to an offscreen place pans, with no zoom event to reveal it. + act(() => map.setView([-4.7, 55.4], 16, { animate: false })) + const next = island[15] + view.rerender() + await waitFor(() => expectSelectedPin(next)) + }) + it('RC-08: previews waypoint drags locally and commits only at pointer up without panning', async () => { const waypoint = { id: 'via-1', lat: 34.689, lng: 135.8398, role: 'via' as const } const waypoints = [waypoint] diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx index aa4200bb9..3c1f8e166 100644 --- a/client/src/components/Map/MapView.test.tsx +++ b/client/src/components/Map/MapView.test.tsx @@ -1282,6 +1282,9 @@ describe('MapView track casing pane (#776)', () => { }) describe('MapView selection panning (#921)', () => { + beforeEach(() => { mapMock.getZoom.mockReturnValue(17) }) + afterEach(() => { mapMock.getZoom.mockReturnValue(10) }) + it('FE-COMP-MAPVIEW-051: pans to the padding-corrected point when the map can project', () => { const projectable = mapMock as unknown as Record const add = vi.fn(() => ({ x: 5, y: 6 })) @@ -1292,7 +1295,7 @@ describe('MapView selection panning (#921)', () => { const { rerender } = render() rerender() - expect(projectable.project).toHaveBeenCalledWith([48, 2]) + expect(projectable.project).toHaveBeenCalledWith([48, 2], 17) // The offset is half the difference between the two padding corners. expect(add).toHaveBeenCalledWith([0, 0]) expect(mapMock.panTo).toHaveBeenCalledWith([49, 4], { animate: true }) @@ -1816,14 +1819,12 @@ describe('MapView — picking a stop that shares its coordinates', () => { 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', () => { + it('FE-COMP-MAPVIEW-078: focuses a stop with a pin of its own without opening a cluster', () => { clusterMock.stacked = false const { rerender } = render() rerender() 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() + expect(mapMock.setView).toHaveBeenCalledWith([hotel.lat, hotel.lng], 16, { animate: false }) }) }) diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index c9798c379..4cc056807 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -6,7 +6,8 @@ import ContainerResizeWatcher, { MapCameraSnapshot, OpeningFrameFit } from './Co import { openingView } from './openingView' import MarkerClusterGroup from 'react-leaflet-cluster' import { makeMarkerDraggable } from './markerDrag' -import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster' +import { CLUSTER_OPTIONS, createClusterIcon } from './markerCluster' +import { useLeafletClusterSelection } from './useLeafletClusterSelection' import RoadtripViaMarkers from './RoadtripViaMarkers' import PlannerWaypointMarker from './PlannerWaypointMarker' import HazardLayers from './HazardLayers' @@ -268,6 +269,7 @@ interface BoundsControllerProps extends Pick { + if (follow && selectedPlaceId != null) awaitingRoute.current = false + }, [selectedPlaceId, follow]) + // Once the just-selected day's route is ready, expand the fit to include it. // One-shot per day-fit, so later route-profile toggles don't re-zoom the map. useEffect(() => { @@ -513,7 +521,7 @@ interface MemoMarkerProps { /** 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 + onRegister: (id: number, marker: L.Marker | null) => void } const MemoMarker = memo(function MemoMarker({ @@ -528,7 +536,7 @@ const MemoMarker = memo(function MemoMarker({ // every render the marker took part in. 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]) + const register = useCallback((marker: L.Marker | null) => { onRegister(place.id, marker) }, [onRegister, place.id]) return ( (null) - const placeMarkersRef = useRef(new Map()) - 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) - }, []) - const assistantMarkerEl = useCallback((id: number) => (placeMarkersRef.current.get(id) as L.Marker | undefined)?.getElement() ?? null, []) - - 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 { registerClusterGroup, registerMarker, markerElement: assistantMarkerEl, standalonePlaceId, revealSelectedPlace } = + useLeafletClusterSelection(selectedPlaceId, places, mapZoom, followSelection) + const standaloneIndex = standalonePlaceId == null ? -1 : places.findIndex(place => place.id === standalonePlaceId) const markers = useMemo(() => places.map((place) => { const isSelected = place.id === selectedPlaceId @@ -930,8 +908,9 @@ export const MapView = memo(function MapView({ {initialView.refit && } {hasViewBaseLayer && } - 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} /> - + 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} selectedPlaceId={selectedPlaceId} /> + @@ -941,8 +920,9 @@ export const MapView = memo(function MapView({ - {markers} + {standaloneIndex < 0 ? markers : markers.filter((_, index) => index !== standaloneIndex)} + {markers[standaloneIndex]} {/* 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. */} diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index eacc2ee92..0202c8a3a 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -1818,7 +1818,6 @@ export function MapViewGL({ // The trip's flights in the air, as on the Leaflet map. useFlightAircraftGL(mapRef, mapReady, gl?.Marker, id => onReservationClickRef.current?.(id), reservations) - // Fit bounds on fitKey change — matches the Leaflet BoundsController const paddingOpts = useMemo(() => { if (isMobile) return { top: 40, right: 20, bottom: 40, left: 20 } const top = 60 @@ -1843,9 +1842,7 @@ export function MapViewGL({ const map = mapRef.current if (!map) return - // The map was built framed on these very places, so fitting now would only re-do that — - // and its maxZoom would overrule the gentler zoom a single place opens at. Adopt the - // current fitKey and stand down; every later fit (picking a day) still runs. + // Keep the opening frame, including its gentler single-place zoom. Later day fits still run. if (!fitRanRef.current && framedOnMountRef.current) { fitRanRef.current = true prevFitKey.current = fitKey @@ -1916,6 +1913,9 @@ export function MapViewGL({ } catch { /* noop */ } }, [focusPoints, focusKey, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (followSelection && selectedPlaceId != null) pendingRouteFitRef.current = null + }, [selectedPlaceId, followSelection]) useSelectionCameraGL({ mapRef, selectedPlaceId, places, dayPlaces, selectedPlace, follow: followSelection, padding: paddingOpts, enableMapbox3d, diff --git a/client/src/components/Map/SelectionController.tsx b/client/src/components/Map/SelectionController.tsx index c3f3411a7..14a0db075 100644 --- a/client/src/components/Map/SelectionController.tsx +++ b/client/src/components/Map/SelectionController.tsx @@ -6,7 +6,7 @@ import { frameLng } from '../../utils/lngFrame'; import type { ViewportPadding } from '../../utils/mapViewport'; import { useLngFrame } from './lngFrameContext'; import { isUnderChrome } from './mapChromePadding'; -import { selectedPlaceTarget } from './selectedPlaceTarget'; +import { PLACE_FOCUS_ZOOM, selectedPlaceTarget } from './selectedPlaceTarget'; interface SelectionControllerProps { /** False while the traveller locked the map (#2010): a pick changes nothing on it. */ @@ -16,6 +16,7 @@ interface SelectionControllerProps { dayPlaces: Place[]; selectedPlace: Place | null; paddingBox: ViewportPadding; + revealSelectedPlace: () => void; } /** @@ -29,6 +30,7 @@ export function SelectionController({ dayPlaces, selectedPlace, paddingBox, + revealSelectedPlace, }: SelectionControllerProps) { const map = useMap(); const frame = useLngFrame(); @@ -39,12 +41,33 @@ export function SelectionController({ const lat = target?.lat ?? null; const lng = target?.lng == null ? null : frameLng(frame, target.lng); + useEffect(() => { + if (!follow || selectedPlaceId == null) return; + let frame: number | null = null; + const revealAfterMove = () => { + if (frame !== null) cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => revealSelectedPlace()); + }; + map.on('moveend', revealAfterMove); + return () => { + map.off('moveend', revealAfterMove); + if (frame !== null) cancelAnimationFrame(frame); + }; + }, [map, follow, selectedPlaceId, revealSelectedPlace]); + useEffect(() => { const isNew = selectedPlaceId !== prev.current; prev.current = selectedPlaceId; if (!isNew || !follow || !selectedPlaceId || lat == null || lng == null) return; pannedWith.current = paddingBox; - panToPlace(map, [lat, lng], paddingBox); + const zoom = map.getZoom(); + const focusZoom = Math.max(zoom, PLACE_FOCUS_ZOOM); + const center = paddedCenter(map, [lat, lng], paddingBox, focusZoom); + if (zoom < focusZoom) { + map.setView(center, focusZoom, { animate: false }); + } else { + map.panTo(center, { animate: true }); + } }, [selectedPlaceId, follow, lat, lng, map, paddingBox]); // The place card only learns its height after it laid out, and grows again when its @@ -56,7 +79,7 @@ export function SelectionController({ if (!follow || !selectedPlaceId || lat == null || lng == null) return; if (typeof map.latLngToContainerPoint !== 'function') return; if (isUnderChrome(map.latLngToContainerPoint([lat, lng]), map.getSize(), paddingBox)) { - panToPlace(map, [lat, lng], paddingBox); + map.panTo(paddedCenter(map, [lat, lng], paddingBox, map.getZoom()), { animate: true }); } }, [paddingBox, follow, selectedPlaceId, lat, lng, map]); @@ -64,16 +87,19 @@ export function SelectionController({ } /** - * Pan to a place without changing zoom. The centre is offset by the side panels and the - * bottom card, so the pin lands in the middle of the *visible* map area rather than the - * geometric centre, where the card would cover it. + * Offset the centre at the destination zoom so the pin lands in the middle of the + * visible map area, above the bottom card and between the side panels. */ -function panToPlace(map: L.Map, latlng: [number, number], padding: ViewportPadding): void { +function paddedCenter( + map: L.Map, + latlng: [number, number], + padding: ViewportPadding, + zoom: number +): L.LatLngExpression { if (typeof map.project !== 'function' || typeof map.unproject !== 'function') { - map.panTo(latlng, { animate: true }); - return; + return latlng; } const { top, right, bottom, left } = padding; - const point = map.project(latlng).add([(right - left) / 2, (bottom - top) / 2]); - map.panTo(map.unproject(point), { animate: true }); + const point = map.project(latlng, zoom).add([(right - left) / 2, (bottom - top) / 2]); + return map.unproject(point, zoom); } diff --git a/client/src/components/Map/markerCluster.ts b/client/src/components/Map/markerCluster.ts index 6faa459f6..03ea6af40 100644 --- a/client/src/components/Map/markerCluster.ts +++ b/client/src/components/Map/markerCluster.ts @@ -62,7 +62,7 @@ export const REVEAL_FAN_MAX_CHILDREN = 12 * A small bubble always opens. A bigger one only when every stop in it sits on the same * coordinate, the stack no zoom can take apart, which is the case the fan is there for. * Anything else is a pile of ordinary neighbours that zooming in separates, so it stays - * closed and the selection is shown by the pan alone. + * closed until the camera reaches the place's neighbourhood. */ function fansOpenOnSelect(cluster: RevealableCluster): boolean { if (cluster.getChildCount() <= REVEAL_FAN_MAX_CHILDREN) return true @@ -81,13 +81,21 @@ function isRevealableCluster(layer: unknown): layer is RevealableCluster { * 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. See `fansOpenOnSelect` for which bubbles are opened. + * The selection camera handles the zoom, so a cluster's bounds do not override the + * place's padded view. See `fansOpenOnSelect` for which bubbles are opened. */ -export function revealInCluster(group: ClusterGroupLike | null | undefined, marker: unknown): boolean { +export function revealInCluster( + group: ClusterGroupLike | null | undefined, + marker: unknown, + onDenseCluster?: () => void, +): boolean { if (!group || !marker || typeof group.getVisibleParent !== 'function') return false const parent = group.getVisibleParent(marker) - if (parent === marker || !isRevealableCluster(parent) || !fansOpenOnSelect(parent)) return false + if (parent === marker || !isRevealableCluster(parent)) return false + if (!fansOpenOnSelect(parent)) { + onDenseCluster?.() + return false + } parent.spiderfy() return true } diff --git a/client/src/components/Map/selectedPlaceTarget.ts b/client/src/components/Map/selectedPlaceTarget.ts index 9f85a13d1..a08005e2f 100644 --- a/client/src/components/Map/selectedPlaceTarget.ts +++ b/client/src/components/Map/selectedPlaceTarget.ts @@ -5,6 +5,9 @@ export interface MapTarget { lng?: number | null } +/** Street-level zoom separates ordinary neighbours when a place is selected. */ +export const PLACE_FOCUS_ZOOM = 16 + /** * Where the map goes when a place is selected, the same in both renderers. * diff --git a/client/src/components/Map/useLeafletClusterSelection.ts b/client/src/components/Map/useLeafletClusterSelection.ts new file mode 100644 index 000000000..94f242712 --- /dev/null +++ b/client/src/components/Map/useLeafletClusterSelection.ts @@ -0,0 +1,54 @@ +import type L from 'leaflet'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { Place } from '../../types'; +import { revealInCluster, type ClusterGroupLike } from './markerCluster'; +import { PLACE_FOCUS_ZOOM } from './selectedPlaceTarget'; + +/** Reveals the selected pin while keeping its neighbours clustered. */ +export function useLeafletClusterSelection( + selectedPlaceId: number | null, + places: Place[], + zoom: number, + follow: boolean +) { + const clusterGroupRef = useRef(null); + const markersRef = useRef(new Map()); + // Picking the same stop again must check the cluster it sits in now. + const selection = useMemo(() => ({ id: selectedPlaceId }), [selectedPlaceId]); + const [standaloneSelection, setStandaloneSelection] = useState(null); + const canRevealStandalone = follow && zoom >= PLACE_FOCUS_ZOOM; + const standalonePlaceId = canRevealStandalone && selection === standaloneSelection ? selectedPlaceId : null; + + const registerClusterGroup = useCallback((group: unknown) => { + clusterGroupRef.current = (group as ClusterGroupLike | null) ?? null; + }, []); + const registerMarker = useCallback((id: number, marker: L.Marker | null) => { + if (marker) markersRef.current.set(id, marker); + else markersRef.current.delete(id); + }, []); + const markerElement = useCallback((id: number) => markersRef.current.get(id)?.getElement() ?? null, []); + + const revealSelectedPlace = useCallback( + (afterClustering = true) => { + const id = selection.id; + if (id == null || standalonePlaceId === id) return; + revealInCluster( + clusterGroupRef.current, + markersRef.current.get(id), + afterClustering && canRevealStandalone ? () => setStandaloneSelection(selection) : undefined + ); + }, + [selection, canRevealStandalone, standalonePlaceId] + ); + + useEffect(() => { + if (selectedPlaceId == null) return; + revealSelectedPlace(false); + // Let Leaflet finish re-clustering and the marker group's batched updates before + // drawing the selected pin by itself. The rest of a dense group keeps its bubble. + const frame = requestAnimationFrame(() => revealSelectedPlace()); + return () => cancelAnimationFrame(frame); + }, [selectedPlaceId, places, revealSelectedPlace]); + + return { registerClusterGroup, registerMarker, markerElement, standalonePlaceId, revealSelectedPlace }; +} diff --git a/client/src/components/Map/useSelectionCameraGL.test.ts b/client/src/components/Map/useSelectionCameraGL.test.ts index 02d5d33ae..28de7b382 100644 --- a/client/src/components/Map/useSelectionCameraGL.test.ts +++ b/client/src/components/Map/useSelectionCameraGL.test.ts @@ -43,10 +43,10 @@ function setup(selectedPlaceId: number, follow = true) { } describe('useSelectionCameraGL', () => { - it('SELCAM-GL-001: flies to a new selection, padded by the panels, at least to zoom 14', () => { + it('SELCAM-GL-001: focuses a new selection at street level with room for the panels (#3306)', () => { const { map } = setup(1); expect(map.flyTo).toHaveBeenCalledWith( - expect.objectContaining({ center: [50, 70], zoom: 14, padding: padding(0) }) + expect.objectContaining({ center: [50, 70], zoom: 16, padding: padding(0) }) ); }); diff --git a/client/src/components/Map/useSelectionCameraGL.ts b/client/src/components/Map/useSelectionCameraGL.ts index 87f77f3a8..c26718dfc 100644 --- a/client/src/components/Map/useSelectionCameraGL.ts +++ b/client/src/components/Map/useSelectionCameraGL.ts @@ -1,7 +1,7 @@ import { useEffect, useRef } from 'react'; import type { ViewportPadding } from '../../utils/mapViewport'; import { isUnderChrome } from './mapChromePadding'; -import { selectedPlaceTarget, type MapTarget } from './selectedPlaceTarget'; +import { PLACE_FOCUS_ZOOM, selectedPlaceTarget, type MapTarget } from './selectedPlaceTarget'; /** The part of a MapLibre/Mapbox map the selection camera drives. */ interface SelectionCameraMap { @@ -61,7 +61,7 @@ export function useSelectionCameraGL

({ try { map.flyTo({ center: [lng, lat], - zoom: Math.max(map.getZoom(), 14), + zoom: Math.max(map.getZoom(), PLACE_FOCUS_ZOOM), pitch: enableMapbox3d ? 45 : 0, duration: 400, padding,