From 7e790c3fb7b4b9092af7a1469f1ad95a8d588518 Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 28 Oct 2026 09:16:38 +0100 Subject: [PATCH] fix(maps): draw the GL cluster bubbles like the Leaflet ones The MapLibre and Mapbox maps painted their place clusters as a canvas circle plus a symbol layer, so the count used whatever glyphs the map style ships and the bubble had no hover. They are now DOM pins built by the same markup and CSS as the Leaflet bubbles, with the same sizes, font and hover scale. The canvas layers stay, invisible, as the hit area the track and route layers check a click against. --- client/src/components/Map/MapViewGL.test.tsx | 29 +++++++ client/src/components/Map/MapViewGL.tsx | 80 +++++++++++++------ client/src/components/Map/markerCluster.ts | 3 +- .../components/Map/placeClusterLayers.test.ts | 18 +++++ .../src/components/Map/placeClusterLayers.ts | 28 +++++++ 5 files changed, 132 insertions(+), 26 deletions(-) create mode 100644 client/src/components/Map/placeClusterLayers.test.ts diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx index a5550a010..381f9906d 100644 --- a/client/src/components/Map/MapViewGL.test.tsx +++ b/client/src/components/Map/MapViewGL.test.tsx @@ -1768,6 +1768,35 @@ describe('MapViewGL', () => { expect(drawn).not.toContainEqual([2.3, 48.3]) }) + // The bubbles are DOM so they share the Leaflet map's font and hover; the canvas + // layers under them stay only as the hit area. + it('FE-COMP-MAPVIEWGL-106: every cluster draws one HTML count bubble that zooms in on a click', async () => { + loadOnAttach() + projectAtDayZoom() + const clusterSource = { ...geoSource(), getClusterExpansionZoom: vi.fn(() => 11) } + glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null)) + const cluster = { properties: { cluster_id: 5, point_count: 12 }, geometry: { coordinates: [139.7, 35.6] } } + glMap.querySourceFeatures.mockImplementation((_id: string, query?: { filter?: unknown[] }) => + query?.filter?.[0] === 'has' + // The same cluster crossing a tile edge, and a feature without a count. + ? [cluster, cluster, { properties: { cluster_id: 6 }, geometry: { coordinates: [1, 1] } }] + : []) + + render() + await flushFrames() + + const bubbles = glMarkers.created.filter(m => m.element.querySelector('.marker-cluster-custom')) + expect(bubbles).toHaveLength(1) + expect(bubbles[0].lngLat).toEqual([139.7, 35.6]) + expect(bubbles[0].element.textContent).toBe('12') + + act(() => { bubbles[0].element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + expect(clusterSource.getClusterExpansionZoom).toHaveBeenCalledWith(5, expect.any(Function)) + expect(glMap.easeTo).toHaveBeenCalledWith({ center: [139.7, 35.6], zoom: 11, duration: 350 }) + glMap.querySourceFeatures.mockReset() + glMap.querySourceFeatures.mockReturnValue([]) + }) + // 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). diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index fa809c80d..88f942a8c 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -50,7 +50,7 @@ import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport' import { selectedPlaceTarget } from './selectedPlaceTarget' -import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers' +import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID, createClusterBubble } from './placeClusterLayers' // Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich // HTML photo markers *and* cluster them natively, so we feed the place points @@ -140,12 +140,12 @@ function addPlaceClusterLayers(map: any): void { type: 'circle', source: PLACE_CLUSTER_SOURCE_ID, filter: ['has', 'point_count'], + // Invisible: the bubble the user sees is DOM (createClusterBubble), these two + // layers stay as the hit area the track and route layers check a click against. paint: { - 'circle-color': '#111827', - 'circle-opacity': 0.97, + 'circle-opacity': 0, + 'circle-stroke-opacity': 0, 'circle-radius': ['step', ['get', 'point_count'], 18, 10, 21, 50, 24], - 'circle-stroke-width': 2.5, - 'circle-stroke-color': 'rgba(255,255,255,0.9)', }, }) map.addLayer({ @@ -158,11 +158,7 @@ function addPlaceClusterLayers(map: any): void { 'text-size': 12, 'text-allow-overlap': true, }, - paint: { - 'text-color': '#ffffff', - 'text-halo-color': 'rgba(17,24,39,0.35)', - 'text-halo-width': 1, - }, + paint: { 'text-opacity': 0 }, }) map.addLayer({ id: PLACE_UNCLUSTERED_LAYER_ID, @@ -177,6 +173,31 @@ function addPlaceClusterLayers(map: any): void { }) } +/** Eases the map in to the zoom a cluster falls apart at. Both SDKs answer that + * question, one through a callback and one through a promise. */ +function expandCluster(map: ClusterMap, clusterId: unknown, coordinates: unknown): void { + if (clusterId == null || !Array.isArray(coordinates)) return + const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as ClusterSource | undefined + const easeToZoom = (nextZoom: number) => { + try { map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 }) } catch { /* noop */ } + } + try { + const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err, nextZoom) => { + if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom) + }) + if (typeof maybeZoom === 'number') easeToZoom(maybeZoom) + else if (maybeZoom instanceof Promise) maybeZoom.then(easeToZoom).catch(() => {}) + } catch { /* noop */ } +} + +/** The two map calls `expandCluster` makes, the same on both SDKs. */ +interface ClusterMap { + getSource: (id: string) => unknown + easeTo: (options: { center: unknown[]; zoom: number; duration: number }) => void +} +interface ClusterSource { + getClusterExpansionZoom?: (id: unknown, done: (err: Error | null, zoom: number) => void) => unknown +} function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement { // A stop that interrupts the drive gets its own small disc, decided before the photo @@ -612,6 +633,8 @@ export function MapViewGL({ useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates) // eslint-disable-next-line @typescript-eslint/no-explicit-any const markersRef = useRef>(new Map()) + /** The count bubbles, one per cluster the source currently reports. */ + const clusterPinsRef = useRef([]) // Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin). const pinLayerRef = useRef(null) const locationMarkerRef = useRef(null) @@ -642,6 +665,7 @@ export function MapViewGL({ // in the same frame the canvas draws, or the ones left out swim against the ones in. const repositionPins = useCallback(() => { markersRef.current.forEach(pin => pin.reposition()) + clusterPinsRef.current.forEach(pin => pin.reposition()) poiMarkersRef.current.forEach(pin => pin.reposition()) pluginMarkersRef.current.forEach(pin => pin.reposition()) routeViaMarkersRef.current.forEach(pin => pin.reposition()) @@ -1304,21 +1328,7 @@ export function MapViewGL({ ? map.queryRenderedFeatures(e.point, { layers: [PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID] }) : [] const feature = features?.[0] - const clusterId = feature?.properties?.cluster_id - const coordinates = feature?.geometry?.coordinates - if (clusterId == null || !Array.isArray(coordinates)) return - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as any - const easeToZoom = (nextZoom: number) => { - try { map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 }) } catch { /* noop */ } - } - try { - const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err: Error | null, nextZoom: number) => { - if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom) - }) - if (typeof maybeZoom === 'number') easeToZoom(maybeZoom) - else if (maybeZoom && typeof maybeZoom.then === 'function') maybeZoom.then(easeToZoom).catch(() => {}) - } catch { /* noop */ } + expandCluster(map, feature?.properties?.cluster_id, feature?.geometry?.coordinates) } const setClusterCursor = () => { const canvas = typeof map.getCanvas === 'function' ? map.getCanvas() : null @@ -1704,8 +1714,27 @@ export function MapViewGL({ source.setData(buildPlaceClusterData(places) as any) const placesById = new Map(validPlaces.map(place => [place.id, place])) let raf: number | null = null + const dropClusterPins = () => { + clusterPinsRef.current.forEach(pin => pin.remove()) + clusterPinsRef.current = [] + } + // One bubble per cluster id: a cluster crossing a tile edge comes back once per tile. + const reconcileClusterPins = () => { + dropClusterPins() + const seenClusters = new Set() + for (const feature of map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['has', 'point_count'] }) || []) { + const { cluster_id: clusterId, point_count: count } = feature?.properties ?? {} + const coordinates = feature?.geometry?.coordinates + if (typeof count !== 'number' || !Array.isArray(coordinates) || seenClusters.has(clusterId)) continue + seenClusters.add(clusterId) + const el = createClusterBubble(count) + el.addEventListener('click', (ev) => { ev.stopPropagation(); expandCluster(map, clusterId, coordinates) }) + clusterPinsRef.current.push(attachPin(map, gl, pinLayerRef.current, el, coordinates[0], coordinates[1])) + } + } const runReconcile = () => { raf = null + reconcileClusterPins() const features = map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['!', ['has', 'point_count']] }) || [] const seen = new Set() const visiblePlaces: PlaceWithCoords[] = [] @@ -1752,6 +1781,7 @@ export function MapViewGL({ return () => { if (raf !== null) cancelAnimationFrame(raf) + dropClusterPins() map.off('moveend', scheduleReconcile) map.off('zoomend', scheduleReconcile) map.off('idle', scheduleReconcile) diff --git a/client/src/components/Map/markerCluster.ts b/client/src/components/Map/markerCluster.ts index 6ecf64f2f..b9234c9dc 100644 --- a/client/src/components/Map/markerCluster.ts +++ b/client/src/components/Map/markerCluster.ts @@ -1,5 +1,6 @@ import L from 'leaflet' import { STACK_RADIUS_PX } from './coincidentPlaces' +import { clusterBubbleSize } from './placeClusterLayers' /** Up to here the map is an overview, where stops merge to keep the world readable. */ export const CLUSTER_UNTIL_ZOOM = 9 @@ -66,7 +67,7 @@ export interface ClusterLike { /** A count bubble sized by its count, styled by `.marker-cluster-custom` in index.css. */ export function createClusterIcon(cluster: ClusterLike) { const count = cluster.getChildCount() - const size = count < 10 ? 36 : count < 50 ? 42 : 48 + const size = clusterBubbleSize(count) return L.divIcon({ html: `
${count}
`, className: 'marker-cluster-wrapper', diff --git a/client/src/components/Map/placeClusterLayers.test.ts b/client/src/components/Map/placeClusterLayers.test.ts new file mode 100644 index 000000000..887c53406 --- /dev/null +++ b/client/src/components/Map/placeClusterLayers.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; +import { clusterBubbleSize, createClusterBubble } from './placeClusterLayers'; + +describe('cluster bubbles', () => { + it('FE-COMP-PLACECLUSTER-001: a bubble grows in three steps with its count', () => { + expect([1, 9, 10, 49, 50, 500].map(clusterBubbleSize)).toEqual([36, 36, 42, 42, 48, 48]); + }); + + it('FE-COMP-PLACECLUSTER-002: the GL bubble is the Leaflet markup inside a bare wrapper the pin can move', () => { + const wrapper = createClusterBubble(38); + expect(wrapper.className).toBe(''); + const bubble = wrapper.firstElementChild as HTMLElement; + expect(bubble.className).toBe('marker-cluster-custom'); + expect(bubble.style.width).toBe('42px'); + expect(bubble.style.height).toBe('42px'); + expect(bubble.textContent).toBe('38'); + }); +}); diff --git a/client/src/components/Map/placeClusterLayers.ts b/client/src/components/Map/placeClusterLayers.ts index 7cce947eb..cf659c8c0 100644 --- a/client/src/components/Map/placeClusterLayers.ts +++ b/client/src/components/Map/placeClusterLayers.ts @@ -5,3 +5,31 @@ */ export const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle'; export const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count'; + +/** A count bubble's diameter in pixels: both renderers size their bubbles by it. */ +export function clusterBubbleSize(count: number): number { + return count < 10 ? 36 : count < 50 ? 42 : 48; +} + +/** + * A count bubble as DOM, styled by `.marker-cluster-custom` in index.css. + * + * The GL map draws its bubbles with this element rather than as canvas text, so they + * read in the app's own font and get the same hover the Leaflet map has. A canvas + * symbol layer can only use the glyphs the map style ships and knows no `:hover`. + * The bubble sits in a bare wrapper because the pin positions its element through + * `transform`, which would otherwise override the hover's scale. + */ +export function createClusterBubble(count: number): HTMLDivElement { + const size = clusterBubbleSize(count); + const bubble = document.createElement('div'); + bubble.className = 'marker-cluster-custom'; + bubble.style.width = `${size}px`; + bubble.style.height = `${size}px`; + const label = document.createElement('span'); + label.textContent = String(count); + bubble.appendChild(label); + const wrapper = document.createElement('div'); + wrapper.appendChild(bubble); + return wrapper; +}