diff --git a/resources/dataSets/sampleCouncilCampaigns.csv b/resources/dataSets/sampleCouncilCampaigns.csv new file mode 100644 index 00000000..6d0ba440 --- /dev/null +++ b/resources/dataSets/sampleCouncilCampaigns.csv @@ -0,0 +1,23 @@ +Campaign name,Council,Council code,Status,Lead group,Description,Website,Launch date +Clean Air Bristol,"Bristol, City of",E06000023,Active,Bristol Climate Network,Pushing the council to extend the clean air zone to the whole city.,https://example.org/clean-air-bristol,2026-02-14 +Brighton Divest Now,Brighton and Hove,E06000043,Won,Divest Sussex,Council pension fund committed to divest from fossil fuels.,https://example.org/brighton-divest,2025-09-03 +Cornwall Retrofit Drive,Cornwall,E06000052,Active,Kernow Homes Coalition,Calling for a retrofit programme for council housing.,https://example.org/cornwall-retrofit,2026-04-22 +Cambridge Bus Fares,Cambridge,E07000008,Planning,Cambridge Transport Action,Campaign for capped bus fares across the city.,https://example.org/cambridge-buses,2026-10-01 +Exeter Solar Schools,Exeter,E07000041,Active,Devon Energy Collective,Solar panels on every council-run school roof.,https://example.org/exeter-solar,2026-01-18 +Norwich Green Spaces,Norwich,E07000148,Won,Norwich Parks Alliance,Protected three parks from development.,https://example.org/norwich-green,2025-06-30 +Oxford Low Traffic,Oxford,E07000178,Active,Oxford Streets for People,Expanding low traffic neighbourhoods.,https://example.org/oxford-ltn,2026-03-09 +Manchester Make Polluters Pay,Manchester,E08000003,Active,Greater Manchester Climate Action,Levy on large polluters to fund local climate action.,https://example.org/manchester-mpp,2026-05-12 +Manchester Warm Homes,Manchester,E08000003,Planning,Manchester Tenants Union,Insulation for every council home by 2030.,https://example.org/manchester-warm,2026-11-20 +Liverpool Waterfront Watch,Liverpool,E08000012,Active,Merseyside Climate Group,Opposing new fossil fuel infrastructure at the docks.,https://example.org/liverpool-waterfront,2026-07-04 +Newcastle Heat Network,Newcastle upon Tyne,E08000021,Active,Tyneside Energy Democracy,Publicly owned district heating for the city centre.,https://example.org/newcastle-heat,2025-11-15 +Birmingham Bike Lanes,Birmingham,E08000025,Won,Brum Cycle Campaign,Segregated cycle lanes on five main roads.,https://example.org/brum-bikes,2025-04-08 +Leeds Airport Expansion,Leeds,E08000035,Active,Leeds Climate Coalition,Stopping the airport expansion.,https://example.org/leeds-airport,2026-02-27 +Sheffield Street Trees,Sheffield,E08000039,Won,Sheffield Tree Action,Ended the felling of healthy street trees.,https://example.org/sheffield-trees,2025-03-21 +Hackney Play Streets,Hackney,E09000012,Active,Hackney Families for Clean Air,School streets outside every primary school.,https://example.org/hackney-play,2026-06-16 +Lambeth Community Energy,Lambeth,E09000022,Planning,Brixton Energy Co-op,Community-owned solar on council estates.,https://example.org/lambeth-energy,2026-09-05 +Belfast Climate Commission,Belfast,N09000003,Active,Belfast Climate Alliance,Holding the council to its net zero plan.,https://example.org/belfast-climate,2026-01-30 +Highland Wind Share,Highland,S12000017,Active,Highland Community Power,Community stake in new onshore wind.,https://example.org/highland-wind,2025-10-12 +Glasgow Free Transport,Glasgow City,S12000049,Active,Get Glasgow Moving,Free public transport for under 25s.,https://example.org/glasgow-transport,2026-08-19 +Swansea Tidal Power,Swansea,W06000011,Planning,Swansea Bay Energy,Revive the tidal lagoon as a public project.,https://example.org/swansea-tidal,2026-12-01 +Cardiff Food Growing,Cardiff,W06000015,Active,Cardiff Food Council,Allotments and growing spaces in every ward.,https://example.org/cardiff-food,2026-04-03 +West Sussex Gas Drilling,West Sussex,E10000032,Active,Frack Free Sussex,Opposing new oil and gas drilling sites (county council: will not geocode against LAD25).,https://example.org/west-sussex-drilling,2026-05-28 diff --git a/src/app/(private)/map/[id]/atoms/hoverAtoms.ts b/src/app/(private)/map/[id]/atoms/hoverAtoms.ts index 66d6df8a..c62e32ca 100644 --- a/src/app/(private)/map/[id]/atoms/hoverAtoms.ts +++ b/src/app/(private)/map/[id]/atoms/hoverAtoms.ts @@ -15,7 +15,14 @@ export const hoverSecondaryAreaAtom = atom<{ coordinates: [number, number]; } | null>(null); +export interface HoverMarkerItem { + name: string; + /** Formatted record date, when the public map shows dates */ + date?: string; +} + +/** The marker, or public map area, under the cursor: one item per record */ export const hoverMarkerAtom = atom<{ coordinates: [number, number]; - properties: Record; + items: HoverMarkerItem[]; } | null>(null); diff --git a/src/app/(private)/map/[id]/components/DataSourceAreas.tsx b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx new file mode 100644 index 00000000..8b769735 --- /dev/null +++ b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx @@ -0,0 +1,84 @@ +import { useMemo } from "react"; +import { Layer, Source } from "react-map-gl/mapbox"; +import { + DATA_SOURCE_AREAS_FILL_OPACITY, + DATA_SOURCE_AREAS_HOVER_FILL_OPACITY, + DATA_SOURCE_AREAS_TOP_LAYER_ID, +} from "../constants"; +import { getDataSourceAreasIds } from "../utils/dataSourceAreas"; +import type { ChoroplethLayerConfig } from "./Choropleth/configs"; +import type { VisibleMarkerFeature } from "../hooks/useVisibleMarkers"; + +/** + * Shades the areas a public map's reference data source was geocoded to, + * using the same boundary tilesets as the choropleth. + */ +export default function DataSourceAreas({ + dataSourceId, + areaMarkers, + layerConfig, + color, +}: { + dataSourceId: string; + /** The source's visible records by area code (useDataSourceAreaMarkers) */ + areaMarkers: Map | undefined; + layerConfig: ChoroplethLayerConfig; + color: string; +}) { + const areaCodes = useMemo( + () => [...(areaMarkers?.keys() ?? [])], + [areaMarkers], + ); + + const { sourceId, layerId, featureCodeProperty } = layerConfig.mapbox; + const { + sourceId: areasSourceId, + fillLayerId, + lineLayerId, + } = getDataSourceAreasIds(dataSourceId); + const filter = ["in", ["get", featureCodeProperty], ["literal", areaCodes]]; + + return ( + + + + + ); +} diff --git a/src/app/(private)/map/[id]/components/DataSourceAreasPosition.tsx b/src/app/(private)/map/[id]/components/DataSourceAreasPosition.tsx new file mode 100644 index 00000000..39f93ab6 --- /dev/null +++ b/src/app/(private)/map/[id]/components/DataSourceAreasPosition.tsx @@ -0,0 +1,23 @@ +import { Layer, Source } from "react-map-gl/mapbox"; +import { DATA_SOURCE_AREAS_TOP_LAYER_ID } from "../constants"; + +/** + * Empty layer that fixes where area fills sit in the layer stack: area + * layers are inserted before it, so they stay below markers that are added + * later, whatever order the data loads in. + */ +export default function DataSourceAreasPosition() { + return ( + + + + ); +} diff --git a/src/app/(private)/map/[id]/components/MarkerPopup.tsx b/src/app/(private)/map/[id]/components/MarkerPopup.tsx index 28fc24d6..4264d67c 100644 --- a/src/app/(private)/map/[id]/components/MarkerPopup.tsx +++ b/src/app/(private)/map/[id]/components/MarkerPopup.tsx @@ -1,5 +1,7 @@ import { Popup } from "react-map-gl/mapbox"; +import { HOVER_POPUP_MAX_ITEMS } from "../constants"; import { useHoverMarker } from "../hooks/useMapHover"; +import type { HoverMarkerItem } from "../atoms/hoverAtoms"; export default function MarkerPopup() { const [hoverMarker] = useHoverMarker(); @@ -13,12 +15,13 @@ export default function MarkerPopup() { function WrappedMarkerPopup({ coordinates, - properties, + items, }: { coordinates: [number, number]; - properties: Record; + items: HoverMarkerItem[]; }) { - const date = properties.date ? String(properties.date) : ""; + const shownItems = items.slice(0, HOVER_POPUP_MAX_ITEMS); + const moreCount = items.length - shownItems.length; return ( -

- {String(properties.name)} -

- {date && ( -

{date}

- )} +
+ {shownItems.map((item, index) => ( +
+

{item.name}

+ {item.date && ( +

+ {item.date} +

+ )} +
+ ))} + {moreCount > 0 && ( +

+ and {moreCount} more +

+ )} +
); } diff --git a/src/app/(private)/map/[id]/components/Markers/DataSourceMarkers.tsx b/src/app/(private)/map/[id]/components/Markers/DataSourceMarkers.tsx index a8783ddb..dbcc12a4 100644 --- a/src/app/(private)/map/[id]/components/Markers/DataSourceMarkers.tsx +++ b/src/app/(private)/map/[id]/components/Markers/DataSourceMarkers.tsx @@ -11,21 +11,9 @@ import { MarkerIconMode, MarkerSizeMode, } from "@/models/MapView"; -import { - getEventDateFormat, - getHidePastEvents, - getPastEventsCutoff, - isPastEvent, - parseDateValue, -} from "@/utils/dataRecord"; import { useDataSourceColumn } from "../../hooks/useDataSourceColumn"; import { useMapRoute } from "../../hooks/useMapCore"; -import { PAST_EVENTS_FILTER_KEY } from "../../publish/dateFilters"; -import { - useFilteredRecords, - usePublicDateFilter, - usePublicFilters, -} from "../../publish/hooks/usePublicFilters"; +import { useVisibleMarkers } from "../../hooks/useVisibleMarkers"; import { useColorScheme, usePublicMapValue, @@ -47,7 +35,6 @@ import { MARKER_CLIENT_EXCLUDED_KEY } from "./utils"; import type { MarkerPinStyle } from "./PinsLayer"; import type { MarkerVisualisation } from "@/models/MapView"; import type { MarkerFeature } from "@/types"; -import type { FeatureCollection } from "geojson"; const NOT_MATCHED_CASE = [ "any", @@ -81,100 +68,18 @@ export function DataSourceMarkers({ * two-tone style (see ClustersLayer) */ onChoropleth?: boolean; }) { - const filteredRecords = useFilteredRecords(); - const publicFilters = usePublicFilters(); - const publicDateFilter = usePublicDateFilter(); const publicMap = usePublicMapValue(); const colorScheme = useColorScheme(); const publicMapLayout = isPublicMapLayout(useMapRoute()); - - const dataSourceId = dataSourceMarkers.dataSourceId; - - // Public maps that hide past events drop them at the source level (so - // cluster counts stay correct), unless the "Past events" filter is active, - // in which case the client-filter exclusion below handles it. const { getDataSourceById } = useDataSources(); - const dataSource = getDataSourceById(dataSourceId); - const dataSourceConfig = publicMap?.dataSourceConfigs.find( - (c) => c.dataSourceId === dataSourceId, - ); - const hidePastEvents = - Boolean(publicMap) && getHidePastEvents({ dataSource, dataSourceConfig }); - const eventDateFormat = getEventDateFormat({ dataSource, dataSourceConfig }); - const showingPastEvents = - publicDateFilter[dataSourceId] === PAST_EVENTS_FILTER_KEY; - - const safeMarkers = useMemo(() => { - const hasClientFilters = - Object.keys(publicFilters).length > 0 || - Object.values(publicDateFilter).some(Boolean); - - let features = dataSourceMarkers.markers; - - // When hideFilteredMarkers is true, remove server-side unmatched markers - if (hideFilteredMarkers) { - features = features.filter((f) => f.properties.matched !== false); - } - - // Timeline filter: features must be dropped at the source level (not via - // layer filters) so cluster counts stay correct. Records without a - // parseable month are hidden while the filter is active. - if (filterTimeRange !== null) { - features = features.filter( - (f) => - typeof f.properties.month === "number" && - f.properties.month >= filterTimeRange.start && - f.properties.month <= filterTimeRange.end, - ); - } - if (hidePastEvents && !showingPastEvents) { - // Parsed here (not on the server) so the cutoff and the date share the - // visitor's timezone, matching the listing in useFilteredRecords. - const cutoff = getPastEventsCutoff(); - features = features.filter( - (f) => - !isPastEvent( - parseDateValue(f.properties.dateValue, eventDateFormat), - cutoff, - ), - ); - } - - if (!hasClientFilters) { - return { - type: "FeatureCollection", - features, - }; - } - - const recordIds = (filteredRecords || []) - .map((r: { id: string | number }) => r.id) - .filter(Boolean); - - const mappedFeatures = features.map((f) => ({ - ...f, - properties: { - ...f.properties, - [MARKER_CLIENT_EXCLUDED_KEY]: !recordIds.includes(f.properties.id), - }, - })); + const dataSourceId = dataSourceMarkers.dataSourceId; - return { - type: "FeatureCollection", - features: mappedFeatures, - }; - }, [ - dataSourceMarkers.markers, - filteredRecords, - publicFilters, - publicDateFilter, + const safeMarkers = useVisibleMarkers({ + dataSourceMarkers, hideFilteredMarkers, filterTimeRange, - hidePastEvents, - showingPastEvents, - eventDateFormat, - ]); + }); const sourceId = `${dataSourceId}-markers`; const publicMapColor = diff --git a/src/app/(private)/map/[id]/components/Markers/Markers.tsx b/src/app/(private)/map/[id]/components/Markers/Markers.tsx index 5c9498f8..1e85ca98 100644 --- a/src/app/(private)/map/[id]/components/Markers/Markers.tsx +++ b/src/app/(private)/map/[id]/components/Markers/Markers.tsx @@ -5,10 +5,14 @@ import { useMapConfig } from "@/app/(private)/map/[id]/hooks/useMapConfig"; import { useMapViews } from "@/app/(private)/map/[id]/hooks/useMapViews"; import { useMarkerQueries } from "@/app/(private)/map/[id]/hooks/useMarkerQueries"; import { useDataSources } from "@/hooks/useDataSources"; +import { useDataSourceAreaLayers } from "../../hooks/useDataSourceAreaLayers"; +import { useDataSourceAreaMarkers } from "../../hooks/useDataSourceAreaMarkers"; import { useLayers } from "../../hooks/useLayers"; import { useMapRef, useMapRoute } from "../../hooks/useMapCore"; -import { useTimelineFilter } from "../../hooks/useTimelineFilter"; +import { useTimelineFilterRange } from "../../hooks/useTimelineFilter"; import { isPublicMapLayout } from "../../utils/mapRoute"; +import DataSourceAreas from "../DataSourceAreas"; +import DataSourceAreasPosition from "../DataSourceAreasPosition"; import { DataSourceMarkers } from "./DataSourceMarkers"; import { isMarkerIconImageId, registerMarkerIcons } from "./markerIcons"; @@ -19,9 +23,11 @@ export default function Markers() { const { getDataSourceVisibility } = useLayers(); const { getDataSourceById } = useDataSources(); const mapRef = useMapRef(); - const { activeRange } = useTimelineFilter(); + const getFilterRange = useTimelineFilterRange(); const areaStats = useAreaStats().data; const route = useMapRoute(); + const areaLayers = useDataSourceAreaLayers(); + const areaMarkers = useDataSourceAreaMarkers(); // A choropleth fill is painted only when all of these hold (Choropleth.tsx) // Map.tsx only renders Choropleth outside the public map layout (not on @@ -37,13 +43,6 @@ export default function Markers() { hasAreaStats, ].every(Boolean); - // The timeline filter only applies to sources with a date column, - // matching the markers API - const getFilterRange = (dataSourceId: string) => { - const columnRoles = getDataSourceById(dataSourceId)?.columnRoles; - return columnRoles?.dateColumn ? activeRange : null; - }; - // Register the SDF icon sprites; map styles discard added images, so // re-register on style changes and on demand via styleimagemissing. useEffect(() => { @@ -84,6 +83,7 @@ export default function Markers() { return ( <> + {isPublicMapLayout(route) && } {memberMarkers && getDataSourceVisibility(memberMarkers.dataSourceId) && ( + ); + } return ( { + const publicMapLayout = isPublicMapLayout(useMapRoute()); + const publicDataSourceIds = usePublicDataSourceIds(); + const { getDataSourceById } = useDataSources(); + const { viewConfig } = useMapViews(); + const colorScheme = useColorScheme(); + + return useMemo(() => { + const layers = new Map(); + if (!publicMapLayout) { + return layers; + } + const colors = + publicMapColorSchemes[colorScheme] || publicMapColorSchemes.red; + for (const dataSourceId of publicDataSourceIds) { + const dataSource = getDataSourceById(dataSourceId); + if (!dataSource) { + continue; + } + const layerConfig = getSecondaryAreaSetConfig({ + areaSetCode: getPublicMapAreaSetCode(dataSource), + mapType: viewConfig.mapType, + }); + if (!layerConfig) { + continue; + } + const color = layers.size % 2 === 0 ? colors.primary : colors.secondary; + layers.set(dataSourceId, { layerConfig, color }); + } + return layers; + }, [ + publicMapLayout, + publicDataSourceIds, + getDataSourceById, + viewConfig.mapType, + colorScheme, + ]); +} diff --git a/src/app/(private)/map/[id]/hooks/useDataSourceAreaMarkers.ts b/src/app/(private)/map/[id]/hooks/useDataSourceAreaMarkers.ts new file mode 100644 index 00000000..889e4350 --- /dev/null +++ b/src/app/(private)/map/[id]/hooks/useDataSourceAreaMarkers.ts @@ -0,0 +1,62 @@ +import { useMemo } from "react"; +import { MARKER_CLIENT_EXCLUDED_KEY } from "../components/Markers/utils"; +import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; +import { useMarkerQueries } from "./useMarkerQueries"; +import { useTimelineFilterRange } from "./useTimelineFilter"; +import { useFilterVisibleMarkers } from "./useVisibleMarkers"; +import type { VisibleMarkerFeature } from "./useVisibleMarkers"; + +/** + * The visible records of each public map data source drawn as areas, keyed by + * data source ID and then by area code. Unmatched records and records hidden + * by the timeline, past-events or public map filters are left out. + * + * The area shading, hover popover and click selection all read this, so they + * always agree on which records an area holds. + */ +export function useDataSourceAreaMarkers(): Map< + string, + Map +> { + const areaLayers = useDataSourceAreaLayers(); + const markerQueries = useMarkerQueries(); + const filterVisibleMarkers = useFilterVisibleMarkers(); + const getFilterRange = useTimelineFilterRange(); + + return useMemo(() => { + const markersByDataSource = new Map< + string, + Map + >(); + for (const dataSourceMarkers of markerQueries?.data ?? []) { + const { dataSourceId } = dataSourceMarkers; + if (!areaLayers.has(dataSourceId)) { + continue; + } + + const visibleMarkers = filterVisibleMarkers({ + dataSourceMarkers, + hideFilteredMarkers: true, + filterTimeRange: getFilterRange(dataSourceId), + }); + + const markersByArea = new Map(); + for (const feature of visibleMarkers.features) { + const { areaCode } = feature.properties; + const excluded = + feature.properties[MARKER_CLIENT_EXCLUDED_KEY] === true; + if (!areaCode || excluded) { + continue; + } + const areaMarkers = markersByArea.get(areaCode); + if (areaMarkers) { + areaMarkers.push(feature); + } else { + markersByArea.set(areaCode, [feature]); + } + } + markersByDataSource.set(dataSourceId, markersByArea); + } + return markersByDataSource; + }, [markerQueries, areaLayers, filterVisibleMarkers, getFilterRange]); +} diff --git a/src/app/(private)/map/[id]/hooks/useMapClick.ts b/src/app/(private)/map/[id]/hooks/useMapClick.ts index 34d4185f..33b1add9 100644 --- a/src/app/(private)/map/[id]/hooks/useMapClick.ts +++ b/src/app/(private)/map/[id]/hooks/useMapClick.ts @@ -4,6 +4,10 @@ import { useEffect, useRef } from "react"; import { type SelectedArea } from "@/app/(private)/map/[id]/atoms/selectedAreasAtom"; import { useChoropleth } from "@/app/(private)/map/[id]/hooks/useChoropleth"; import { useInspectorState } from "@/app/(private)/map/[id]/hooks/useInspectorState"; +import { LISTING_AREA_ZOOM } from "../publish/const"; +import { queryDataSourceArea } from "../utils/dataSourceAreas"; +import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; +import { useDataSourceAreaMarkers } from "./useDataSourceAreaMarkers"; import { usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; @@ -44,6 +48,8 @@ export function useMapClickEffect({ const [selectedAreas, setSelectedAreas] = useSelectedAreas(); const [, setSelectedSecondaryArea] = useSelectedSecondaryArea(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); + const dataSourceAreaLayers = useDataSourceAreaLayers(); + const dataSourceAreaMarkers = useDataSourceAreaMarkers(); const { mapbox: { sourceId, layerId, featureCodeProperty, featureNameProperty }, @@ -275,6 +281,50 @@ export function useMapClickEffect({ return true; }; + // Public map reference data drawn as areas (DataSourceAreas): select + // every visible record geocoded to the clicked area + const handleDataSourceAreaClick = (e: mapboxgl.MapMouseEvent): boolean => { + const hit = queryDataSourceArea({ + map, + point: e.point, + areaLayers: dataSourceAreaLayers, + }); + if (!hit) { + return false; + } + + const areaMarkers = + dataSourceAreaMarkers.get(hit.dataSourceId)?.get(hit.areaCode) ?? []; + const records = []; + for (const marker of areaMarkers) { + records.push({ + id: marker.properties.id, + dataSourceId: hit.dataSourceId, + name: marker.properties.name, + geocodePoint: { + lng: marker.geometry.coordinates[0], + lat: marker.geometry.coordinates[1], + }, + }); + } + + if (records.length === 0) { + return false; + } + + resetInspector(); + setSelectedRecords(records); + + // Records in one area share its centre point, so fly there, as with + // markers, but no closer than needed to see the whole area + map.flyTo({ + center: records[0].geocodePoint, + zoom: Math.max(LISTING_AREA_ZOOM, map.getZoom()), + }); + + return true; + }; + const handleTurfClick = (e: mapboxgl.MapMouseEvent): boolean => { if (draw) { // Don't handle turf clicks when in direct_select (edit) mode @@ -412,6 +462,10 @@ export function useMapClickEffect({ return; } + if (handleDataSourceAreaClick(e)) { + return; + } + if (handleAreaClick(e)) { return; } @@ -448,6 +502,8 @@ export function useMapClickEffect({ interactionSourceId, secondaryAreaSetConfig, setSelectedSecondaryArea, + dataSourceAreaLayers, + dataSourceAreaMarkers, ]); // Clear active feature state when selectedBoundary is cleared (resetInspector called from outside) diff --git a/src/app/(private)/map/[id]/hooks/useMapHover.ts b/src/app/(private)/map/[id]/hooks/useMapHover.ts index ca16339e..03185c2d 100644 --- a/src/app/(private)/map/[id]/hooks/useMapHover.ts +++ b/src/app/(private)/map/[id]/hooks/useMapHover.ts @@ -6,10 +6,15 @@ import { hoverMarkerAtom, hoverSecondaryAreaAtom, } from "../atoms/hoverAtoms"; +import { queryDataSourceArea } from "../utils/dataSourceAreas"; +import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; +import { useDataSourceAreaMarkers } from "./useDataSourceAreaMarkers"; import { getClickedPolygonFeature } from "./useMapClick"; import { useEditAreaMode, usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; +import type { HoverMarkerItem } from "../atoms/hoverAtoms"; +import type { DataSourceAreaHit } from "../utils/dataSourceAreas"; import type MapboxDraw from "@mapbox/mapbox-gl-draw"; export function useMapHoverEffect({ @@ -24,6 +29,8 @@ export function useMapHoverEffect({ const mapRef = useMapRef(); const { choroplethLayerConfig } = useChoropleth(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); + const dataSourceAreaLayers = useDataSourceAreaLayers(); + const dataSourceAreaMarkers = useDataSourceAreaMarkers(); const { areaSetCode, mapbox: { sourceId, layerId, featureNameProperty }, @@ -57,6 +64,8 @@ export function useMapHoverEffect({ const prevPointer = { cursor: "" }; let hoveredFeatureId: string | number | undefined; let hoveredSecondaryFeatureId: string | number | undefined; + let hoveredDataSourceArea: DataSourceAreaHit | null = null; + let hoveredDataSourceAreaItems: HoverMarkerItem[] = []; const clearAreaHover = () => { if (hoveredFeatureId !== undefined) { @@ -73,11 +82,80 @@ export function useMapHoverEffect({ } }; + const clearDataSourceAreaHover = () => { + if (!hoveredDataSourceArea) { + return; + } + const { sourceId, sourceLayer, areaCode } = hoveredDataSourceArea; + hoveredDataSourceArea = null; + hoveredDataSourceAreaItems = []; + if (!map.getSource(sourceId)) { + return; + } + map.setFeatureState( + { source: sourceId, sourceLayer, id: areaCode }, + { hover: false }, + ); + }; + + // Public map reference data drawn as areas (DataSourceAreas) + const handleHoverDataSourceArea = (e: mapboxgl.MapMouseEvent): boolean => { + const hit = queryDataSourceArea({ + map, + point: e.point, + areaLayers: dataSourceAreaLayers, + }); + if (!hit) { + clearDataSourceAreaHover(); + return false; + } + + const sameSource = hoveredDataSourceArea?.sourceId === hit.sourceId; + const sameArea = hoveredDataSourceArea?.areaCode === hit.areaCode; + if (!sameSource || !sameArea) { + clearDataSourceAreaHover(); + map.setFeatureState( + { + source: hit.sourceId, + sourceLayer: hit.sourceLayer, + id: hit.areaCode, + }, + { hover: true }, + ); + hoveredDataSourceArea = hit; + // Popover listing the area's visible records, as for a marker. Only + // rebuilt when the hovered area changes, not on every mouse move. + const areaMarkers = + dataSourceAreaMarkers.get(hit.dataSourceId)?.get(hit.areaCode) ?? []; + hoveredDataSourceAreaItems = areaMarkers.map((marker) => ({ + name: marker.properties.name, + date: marker.properties.date, + })); + } + + // The popover follows the cursor, so update its position + setHoverMarker( + hoveredDataSourceAreaItems.length + ? { + coordinates: [e.lngLat.lng, e.lngLat.lat], + items: hoveredDataSourceAreaItems, + } + : null, + ); + + if (map.getCanvas().style.cursor !== "pointer") { + prevPointer.cursor = map.getCanvas().style.cursor || ""; + } + map.getCanvas().style.cursor = "pointer"; + return true; + }; + const onMouseMove = (e: mapboxgl.MapMouseEvent) => { if (pinDropModeRef.current || editAreaModeRef.current) { // In draw/pin modes, ignore hover effects and keep crosshair map.getCanvas().style.cursor = "crosshair"; clearAreaHover(); + clearDataSourceAreaHover(); setHoverMarker(null); clearSecondaryAreaHover(); return; @@ -88,6 +166,12 @@ export function useMapHoverEffect({ handleHoverSecondaryArea(e); if (handleHoverMarker(e)) { + clearAreaHover(); + clearDataSourceAreaHover(); + return; + } + + if (handleHoverDataSourceArea(e)) { clearAreaHover(); return; } @@ -107,6 +191,7 @@ export function useMapHoverEffect({ const onMouseLeave = () => { clearAreaHover(); + clearDataSourceAreaHover(); setHoverMarker(null); clearSecondaryAreaHover(); if (pinDropModeRef.current || editAreaModeRef.current) { @@ -136,9 +221,15 @@ export function useMapHoverEffect({ if (features?.length) { const feature = features[0]; if (!feature?.properties?.cluster) { + const properties = feature.properties || {}; setHoverMarker({ coordinates: [e.lngLat.lng, e.lngLat.lat], - properties: feature.properties || {}, + items: [ + { + name: String(properties.name), + date: properties.date ? String(properties.date) : undefined, + }, + ], }); if (map.getCanvas().style.cursor !== "pointer") { prevPointer.cursor = map.getCanvas().style.cursor || ""; @@ -307,6 +398,12 @@ export function useMapHoverEffect({ } } + try { + clearDataSourceAreaHover(); + } catch { + // Ignore error clearing feature state + } + map.off("mousemove", onMouseMove); map.off("mouseout", onMouseLeave); }; @@ -324,6 +421,8 @@ export function useMapHoverEffect({ interactionSourceId, secondaryAreaSetConfig, setHoverSecondaryArea, + dataSourceAreaLayers, + dataSourceAreaMarkers, ]); } diff --git a/src/app/(private)/map/[id]/hooks/useTimelineFilter.ts b/src/app/(private)/map/[id]/hooks/useTimelineFilter.ts index 036b2399..8d9f90f7 100644 --- a/src/app/(private)/map/[id]/hooks/useTimelineFilter.ts +++ b/src/app/(private)/map/[id]/hooks/useTimelineFilter.ts @@ -1,6 +1,8 @@ "use client"; import { useAtom } from "jotai"; +import { useCallback } from "react"; +import { useDataSources } from "@/hooks/useDataSources"; import { timelinePlaybackRangeAtom } from "../atoms/markerAtoms"; import { useMapViews } from "./useMapViews"; @@ -34,3 +36,20 @@ export function useTimelineFilter(): { setPlaybackRange, }; } + +/** + * The timeline range to filter a data source's markers to. The timeline + * filter only applies to sources with a date column, matching the markers + * API. + */ +export function useTimelineFilterRange() { + const { activeRange } = useTimelineFilter(); + const { getDataSourceById } = useDataSources(); + return useCallback( + (dataSourceId: string) => { + const columnRoles = getDataSourceById(dataSourceId)?.columnRoles; + return columnRoles?.dateColumn ? activeRange : null; + }, + [activeRange, getDataSourceById], + ); +} diff --git a/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts b/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts new file mode 100644 index 00000000..546001d9 --- /dev/null +++ b/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts @@ -0,0 +1,170 @@ +import { useCallback, useMemo } from "react"; +import { useDataSources } from "@/hooks/useDataSources"; +import { + getEventDateFormat, + getHidePastEvents, + getPastEventsCutoff, + isPastEvent, + parseDateValue, +} from "@/utils/dataRecord"; +import { MARKER_CLIENT_EXCLUDED_KEY } from "../components/Markers/utils"; +import { PAST_EVENTS_FILTER_KEY } from "../publish/dateFilters"; +import { + useFilteredRecords, + usePublicDateFilter, + usePublicFilters, +} from "../publish/hooks/usePublicFilters"; +import { usePublicMapValue } from "../publish/hooks/usePublicMap"; +import type { MarkerFeature } from "@/types"; +import type { Feature, FeatureCollection, Point } from "geojson"; + +export type VisibleMarkerProperties = MarkerFeature["properties"] & { + [MARKER_CLIENT_EXCLUDED_KEY]?: boolean; +}; + +export type VisibleMarkerFeature = Feature; + +interface VisibleMarkersOptions { + dataSourceMarkers: { dataSourceId: string; markers: MarkerFeature[] }; + hideFilteredMarkers: boolean; + filterTimeRange: { start: number; end: number } | null; +} + +/** + * A function that applies the timeline, past-events and public map filters to + * a data source's marker features. Features hidden by the public map filters + * are kept but flagged with MARKER_CLIENT_EXCLUDED_KEY, so cluster counts stay + * correct. + */ +export function useFilterVisibleMarkers() { + const filteredRecords = useFilteredRecords(); + const publicFilters = usePublicFilters(); + const publicDateFilter = usePublicDateFilter(); + const publicMap = usePublicMapValue(); + const { getDataSourceById } = useDataSources(); + + return useCallback( + ({ + dataSourceMarkers, + hideFilteredMarkers, + filterTimeRange, + }: VisibleMarkersOptions): FeatureCollection< + Point, + VisibleMarkerProperties + > => { + const { dataSourceId } = dataSourceMarkers; + + // Public maps that hide past events drop them at the source level (so + // cluster counts stay correct), unless the "Past events" filter is + // active, in which case the client-filter exclusion below handles it. + const dataSource = getDataSourceById(dataSourceId); + const dataSourceConfig = publicMap?.dataSourceConfigs.find( + (c) => c.dataSourceId === dataSourceId, + ); + const hidePastEvents = + Boolean(publicMap) && + getHidePastEvents({ dataSource, dataSourceConfig }); + const eventDateFormat = getEventDateFormat({ + dataSource, + dataSourceConfig, + }); + const showingPastEvents = + publicDateFilter[dataSourceId] === PAST_EVENTS_FILTER_KEY; + + const hasClientFilters = + Object.keys(publicFilters).length > 0 || + Object.values(publicDateFilter).some(Boolean); + + let features = dataSourceMarkers.markers; + + // When hideFilteredMarkers is true, remove server-side unmatched markers + if (hideFilteredMarkers) { + features = features.filter((f) => f.properties.matched !== false); + } + + // Timeline filter: features must be dropped at the source level (not via + // layer filters) so cluster counts stay correct. Records without a + // parseable month are hidden while the filter is active. + if (filterTimeRange !== null) { + features = features.filter( + (f) => + typeof f.properties.month === "number" && + f.properties.month >= filterTimeRange.start && + f.properties.month <= filterTimeRange.end, + ); + } + + if (hidePastEvents && !showingPastEvents) { + // Parsed here (not on the server) so the cutoff and the date share the + // visitor's timezone, matching the listing in useFilteredRecords. + const cutoff = getPastEventsCutoff(); + features = features.filter( + (f) => + !isPastEvent( + parseDateValue(f.properties.dateValue, eventDateFormat), + cutoff, + ), + ); + } + + if (!hasClientFilters) { + return { + type: "FeatureCollection", + features, + }; + } + + const recordIds = new Set( + (filteredRecords || []) + .map((r: { id: string | number }) => r.id) + .filter(Boolean), + ); + + const mappedFeatures = features.map((f) => ({ + ...f, + properties: { + ...f.properties, + [MARKER_CLIENT_EXCLUDED_KEY]: !recordIds.has(f.properties.id), + }, + })); + + return { + type: "FeatureCollection", + features: mappedFeatures, + }; + }, + [ + filteredRecords, + publicFilters, + publicDateFilter, + publicMap, + getDataSourceById, + ], + ); +} + +/** A data source's marker features after useFilterVisibleMarkers' filters */ +export function useVisibleMarkers({ + dataSourceMarkers, + hideFilteredMarkers, + filterTimeRange, +}: VisibleMarkersOptions) { + const filterVisibleMarkers = useFilterVisibleMarkers(); + const { dataSourceId, markers } = dataSourceMarkers; + + return useMemo( + () => + filterVisibleMarkers({ + dataSourceMarkers: { dataSourceId, markers }, + hideFilteredMarkers, + filterTimeRange, + }), + [ + filterVisibleMarkers, + dataSourceId, + markers, + hideFilteredMarkers, + filterTimeRange, + ], + ); +} diff --git a/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx b/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx index 3a9a0fe4..54018c15 100644 --- a/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx +++ b/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx @@ -2,10 +2,12 @@ import { memo, useCallback, useEffect, useMemo, useRef } from "react"; +import { useDataSourceAreaLayers } from "@/app/(private)/map/[id]/hooks/useDataSourceAreaLayers"; import { useInspectorState } from "@/app/(private)/map/[id]/hooks/useInspectorState"; import { useMapRef } from "@/app/(private)/map/[id]/hooks/useMapCore"; import { cn } from "@/shadcn/utils"; import { formatRecordDate, getListingSort } from "@/utils/dataRecord"; +import { LISTING_AREA_ZOOM, LISTING_POINT_ZOOM } from "../const"; import { PAST_EVENTS_FILTER_KEY } from "../dateFilters"; import { useFilteredRecords, @@ -43,6 +45,7 @@ export default function DataRecordsList({ const filteredRecords = useFilteredRecords(); const publicDateFilter = usePublicDateFilter(); const searchLocation = useSearchLocation(); + const areaLayers = useDataSourceAreaLayers(); const listRef = useRef(null); useEffect(() => { @@ -62,6 +65,9 @@ export default function DataRecordsList({ ); const dataSourceId = dataRecordsQuery.data?.id; + // Zoom to suit how the source is actually drawn: areas fall back to + // markers on the hex map or without a boundary tileset + const drawnAsAreas = Boolean(dataSourceId && areaLayers.has(dataSourceId)); const showingPastEvents = Boolean( dataSourceId && publicDateFilter[dataSourceId] === PAST_EVENTS_FILTER_KEY, ); @@ -107,6 +113,7 @@ export default function DataRecordsList({ colorScheme={colorScheme} dataSource={dataRecordsQuery.data} dataSourceConfig={dataSourceConfig} + drawnAsAreas={drawnAsAreas} id={id} isSelected={isSelected} mapRef={mapRef} @@ -124,6 +131,7 @@ const RecordGroupItem = memo(function RecordGroupItem({ colorScheme, dataSource, dataSourceConfig, + drawnAsAreas, id, isSelected, mapRef, @@ -133,6 +141,7 @@ const RecordGroupItem = memo(function RecordGroupItem({ colorScheme: PublicMapColorScheme; dataSource: RouterOutputs["dataSource"]["byIdWithRecords"] | undefined; dataSourceConfig: PublicMapDataSourceConfig | undefined; + drawnAsAreas: boolean; id: string; isSelected: boolean; mapRef: RefObject | null; @@ -183,11 +192,11 @@ const RecordGroupItem = memo(function RecordGroupItem({ if (recordGroup.geocodePoint) { mapRef?.current?.flyTo({ center: recordGroup.geocodePoint, - zoom: 14, + zoom: drawnAsAreas ? LISTING_AREA_ZOOM : LISTING_POINT_ZOOM, }); } }, - [dataSourceConfig, isSelected, mapRef, setSelectedRecords], + [dataSourceConfig, drawnAsAreas, isSelected, mapRef, setSelectedRecords], ); return ( diff --git a/src/app/(private)/map/[id]/publish/components/DataSourcesSelect.tsx b/src/app/(private)/map/[id]/publish/components/DataSourcesSelect.tsx index ca8a2632..44d98fb9 100644 --- a/src/app/(private)/map/[id]/publish/components/DataSourcesSelect.tsx +++ b/src/app/(private)/map/[id]/publish/components/DataSourcesSelect.tsx @@ -29,10 +29,6 @@ export default function DataSourcesSelect() { const publicDataSourceIds = usePublicDataSourceIds(); const setActiveDataSourceId = useSetActiveDataSourceId(); - const validDataSources = - dataSources?.filter((ds) => ds.recordType !== DataSourceRecordType.Data) || - []; - return ( @@ -42,7 +38,7 @@ export default function DataSourcesSelect() { Data Sources - {validDataSources.map((ds) => ( + {dataSources?.map((ds) => ( = { red: { primary: "#FF6B6B", primaryMuted: "#FFF6F6", + secondary: "#4C8FD6", }, blue: { primary: "#678DE3", primaryMuted: "#F5F8FD", + secondary: "#F08A4B", }, green: { primary: "#4DAB37", primaryMuted: "#F4FAF2", + secondary: "#8E5CC2", }, purple: { primary: "#A074B3", primaryMuted: "#F9F7FA", + secondary: "#E0A030", }, lime: { primary: "#C6D800", primaryMuted: "#FCFDF2", + secondary: "#2F8FA8", }, ["trans-pride"]: { primary: "#92C7DC", primaryMuted: "#F6FDFF", - secondary: "FDF3F9", + secondary: "#F5A9B8", secondaryMuted: "#FDF3F9", }, }; diff --git a/src/app/(private)/map/[id]/utils/dataSourceAreas.ts b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts new file mode 100644 index 00000000..c4daaeb3 --- /dev/null +++ b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts @@ -0,0 +1,63 @@ +import type { DataSourceAreaLayer } from "../hooks/useDataSourceAreaLayers"; +import type { MapRef } from "react-map-gl/mapbox"; + +export interface DataSourceAreaHit { + dataSourceId: string; + areaCode: string; + /** For feature state: the area source and its tileset layer */ + sourceId: string; + sourceLayer: string; +} + +/** Mapbox source and layer IDs for a data source drawn as areas */ +export const getDataSourceAreasIds = (dataSourceId: string) => { + const sourceId = `${dataSourceId}-areas`; + return { + sourceId, + fillLayerId: `${sourceId}-fill`, + lineLayerId: `${sourceId}-line`, + }; +}; + +/** The top-most data source area under a point, if any */ +export const queryDataSourceArea = ({ + map, + point, + areaLayers, +}: { + map: MapRef; + point: mapboxgl.PointLike; + areaLayers: Map; +}): DataSourceAreaHit | null => { + const dataSourceIdByLayerId = new Map(); + for (const dataSourceId of areaLayers.keys()) { + const { fillLayerId } = getDataSourceAreasIds(dataSourceId); + if (map.getLayer(fillLayerId)) { + dataSourceIdByLayerId.set(fillLayerId, dataSourceId); + } + } + if (dataSourceIdByLayerId.size === 0) { + return null; + } + + // Features come back top-most first + const [feature] = map.queryRenderedFeatures(point, { + layers: [...dataSourceIdByLayerId.keys()], + }); + const dataSourceId = feature?.layer + ? dataSourceIdByLayerId.get(feature.layer.id) + : undefined; + const layerConfig = dataSourceId + ? areaLayers.get(dataSourceId)?.layerConfig + : undefined; + if (!dataSourceId || !layerConfig || feature.id === undefined) { + return null; + } + + return { + dataSourceId, + areaCode: String(feature.id), + sourceId: getDataSourceAreasIds(dataSourceId).sourceId, + sourceLayer: layerConfig.mapbox.layerId, + }; +}; diff --git a/src/app/api/data-sources/[id]/markers/route.ts b/src/app/api/data-sources/[id]/markers/route.ts index 87690f0c..92b9a466 100644 --- a/src/app/api/data-sources/[id]/markers/route.ts +++ b/src/app/api/data-sources/[id]/markers/route.ts @@ -21,6 +21,7 @@ import { getListingSort, toMonthKey, } from "@/utils/dataRecord"; +import { getPublicMapAreaSetCode } from "@/utils/dataSource"; import type { DataRecord } from "@/models/DataRecord"; import type { RecordFilterInput } from "@/models/MapView"; import type { PublicMapDataSourceConfig } from "@/models/PublicMap"; @@ -111,6 +112,12 @@ export async function GET( // the record's month key, derived from the date parsed at import time const dateColumn = dataSource.columnRoles.dateColumn; + // Reference data sources are drawn as shaded areas on public maps, so each + // feature carries the code of the area its record was geocoded to + const areaSetCode = publicMapDataSourceConfig + ? getPublicMapAreaSetCode(dataSource) + : null; + const encoder = new TextEncoder(); // Created outside the ReadableStream so cancel() can close it too. Building @@ -168,6 +175,9 @@ export async function GET( : null, } : {}), + ...(areaSetCode + ? { areaCode: dr.geocodeResult.areas[areaSetCode] ?? null } + : {}), ...getIncludedProperties(dr, includeProperties), }, geometry: { diff --git a/src/types.ts b/src/types.ts index cfa30ee5..5eefc67f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -49,6 +49,9 @@ export interface MarkerFeature { // Record month key (year * 12 + zero-based month), only set when the // data source has a dateColumn role. month?: number | null; + // Code of the area the record was geocoded to, only set on public maps + // for reference data sources drawn as areas (getPublicMapAreaSetCode). + areaCode?: string | null; }; geometry: { coordinates: [number, number]; type: "Point" }; } @@ -72,6 +75,9 @@ export interface MarkerFeatureWithoutDataSourceId { // Record month key (year * 12 + zero-based month), only set when the // data source has a dateColumn role. month?: number | null; + // Code of the area the record was geocoded to, only set on public maps + // for reference data sources drawn as areas (getPublicMapAreaSetCode). + areaCode?: string | null; }; geometry: { coordinates: [number, number]; type: "Point" }; } diff --git a/src/utils/dataSource.ts b/src/utils/dataSource.ts new file mode 100644 index 00000000..d84a5f3b --- /dev/null +++ b/src/utils/dataSource.ts @@ -0,0 +1,26 @@ +import { AreaSetCode } from "@/models/AreaSet"; +import { DataSourceRecordType, GeocodingType } from "@/models/DataSource"; +import type { DataSource } from "@/models/DataSource"; + +/** + * The area set whose boundaries a reference data source is drawn with on a + * public map, or null when it is drawn as markers. + * + * Only reference data ("Data") sources geocoded by an area code or name are + * drawn as areas. Postcodes are excluded: their polygons aren't available. + */ +export const getPublicMapAreaSetCode = ( + dataSource: Pick, +): AreaSetCode | null => { + if (dataSource.recordType !== DataSourceRecordType.Data) { + return null; + } + const { geocodingConfig } = dataSource; + const isAreaGeocoded = + geocodingConfig.type === GeocodingType.Code || + geocodingConfig.type === GeocodingType.Name; + if (!isAreaGeocoded || geocodingConfig.areaSetCode === AreaSetCode.PC) { + return null; + } + return geocodingConfig.areaSetCode; +}; diff --git a/tests/unit/utils/dataSource.test.ts b/tests/unit/utils/dataSource.test.ts new file mode 100644 index 00000000..56496829 --- /dev/null +++ b/tests/unit/utils/dataSource.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from "vitest"; +import { AreaSetCode } from "@/models/AreaSet"; +import { DataSourceRecordType, GeocodingType } from "@/models/DataSource"; +import { getPublicMapAreaSetCode } from "@/utils/dataSource"; + +describe("getPublicMapAreaSetCode", () => { + test("returns the area set for a reference data source geocoded by code", () => { + expect( + getPublicMapAreaSetCode({ + recordType: DataSourceRecordType.Data, + geocodingConfig: { + type: GeocodingType.Code, + column: "Council", + areaSetCode: AreaSetCode.LAD25, + }, + }), + ).toBe(AreaSetCode.LAD25); + }); + + test("returns the area set for a reference data source geocoded by name", () => { + expect( + getPublicMapAreaSetCode({ + recordType: DataSourceRecordType.Data, + geocodingConfig: { + type: GeocodingType.Name, + column: "Constituency", + areaSetCode: AreaSetCode.WMC24, + }, + }), + ).toBe(AreaSetCode.WMC24); + }); + + test("returns null for postcodes", () => { + expect( + getPublicMapAreaSetCode({ + recordType: DataSourceRecordType.Data, + geocodingConfig: { + type: GeocodingType.Code, + column: "Postcode", + areaSetCode: AreaSetCode.PC, + }, + }), + ).toBeNull(); + }); + + test("returns null for other record types", () => { + expect( + getPublicMapAreaSetCode({ + recordType: DataSourceRecordType.Locations, + geocodingConfig: { + type: GeocodingType.Code, + column: "Council", + areaSetCode: AreaSetCode.LAD25, + }, + }), + ).toBeNull(); + }); + + test("returns null for point geocoding", () => { + expect( + getPublicMapAreaSetCode({ + recordType: DataSourceRecordType.Data, + geocodingConfig: { + type: GeocodingType.Coordinates, + latitudeColumn: "lat", + longitudeColumn: "lng", + }, + }), + ).toBeNull(); + }); +});