mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
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
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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(<MapView places={island} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER} />)
|
||||
const map = maps[maps.length - 1]
|
||||
view.rerender(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER} />)
|
||||
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(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
selectedPlaceId={selected.id} hasInspector inspectorHeight={360} />)
|
||||
|
||||
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(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
route={[[[-4.8, 55.5]], [[-4.9, 55.3]]]} selectedPlaceId={selected.id} hasInspector inspectorHeight={360} />)
|
||||
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(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
selectedPlaceId={next.id} hasInspector inspectorHeight={360} />)
|
||||
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]
|
||||
|
||||
@@ -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<string, unknown>
|
||||
const add = vi.fn(() => ({ x: 5, y: 6 }))
|
||||
@@ -1292,7 +1295,7 @@ describe('MapView selection panning (#921)', () => {
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={8} />)
|
||||
|
||||
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(<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()
|
||||
expect(mapMock.setView).toHaveBeenCalledWith([hotel.lat, hotel.lng], 16, { animate: false })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<MapViewProps, 'focusPoints' | 'focu
|
||||
framedOnMount?: boolean
|
||||
/** False while the map is locked (#2010): an arriving route no longer re-fits it. */
|
||||
follow?: boolean
|
||||
selectedPlaceId: number | null
|
||||
}
|
||||
|
||||
/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */
|
||||
@@ -278,7 +280,8 @@ function leafletPadding(box: ViewportPadding): L.FitBoundsOptions {
|
||||
}
|
||||
}
|
||||
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, focusKey, fitPadding, follow = true }: BoundsControllerProps) {
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false,
|
||||
focusPoints, focusKey, fitPadding, follow = true, selectedPlaceId }: BoundsControllerProps) {
|
||||
const map = useMap()
|
||||
const prevFitKey = useRef(-1)
|
||||
const awaitingRoute = useRef(false)
|
||||
@@ -332,6 +335,11 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
|
||||
awaitingRoute.current = true
|
||||
}, [fitKey]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// An explicit stop selection supersedes the pending automatic route fit.
|
||||
useEffect(() => {
|
||||
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 (
|
||||
<Marker
|
||||
ref={register}
|
||||
@@ -753,39 +761,9 @@ export const MapView = memo(function MapView({
|
||||
// HTML5 drag does not exist — and the day plan is not on screen there anyway.
|
||||
const markersDraggable = !isTouchDevice && !assistant.markersLocked
|
||||
|
||||
/**
|
||||
* 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)
|
||||
}, [])
|
||||
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({
|
||||
<ContainerResizeWatcher />
|
||||
{initialView.refit && <OpeningFrameFit frame={initialView.refit} />}
|
||||
{hasViewBaseLayer && <MapCameraSnapshot onChange={saveCameraSnapshot} />}
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} />
|
||||
<SelectionController follow={followSelection} places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} selectedPlace={selectedPlace} paddingBox={paddingBox} />
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} selectedPlaceId={selectedPlaceId} />
|
||||
<SelectionController follow={followSelection} places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces}
|
||||
selectedPlace={selectedPlace} paddingBox={paddingBox} revealSelectedPlace={revealSelectedPlace} />
|
||||
<MapClickHandler onClick={onMapClick} />
|
||||
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
|
||||
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
|
||||
@@ -941,8 +920,9 @@ export const MapView = memo(function MapView({
|
||||
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
|
||||
|
||||
<MarkerClusterGroup ref={registerClusterGroup} {...CLUSTER_OPTIONS} iconCreateFunction={createClusterIcon}>
|
||||
{markers}
|
||||
{standaloneIndex < 0 ? markers : markers.filter((_, index) => index !== standaloneIndex)}
|
||||
</MarkerClusterGroup>
|
||||
{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. */}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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<ClusterGroupLike | null>(null);
|
||||
const markersRef = useRef(new Map<number, L.Marker>());
|
||||
// Picking the same stop again must check the cluster it sits in now.
|
||||
const selection = useMemo(() => ({ id: selectedPlaceId }), [selectedPlaceId]);
|
||||
const [standaloneSelection, setStandaloneSelection] = useState<typeof selection | null>(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 };
|
||||
}
|
||||
@@ -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) })
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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<P extends MapTarget>({
|
||||
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,
|
||||
|
||||
Reference in New Issue
Block a user