From 9cd8871e8b857fa145051511505cdd8756734626 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Tue, 1 Dec 2026 17:19:19 +0000 Subject: [PATCH 1/8] feat: allow reference data sources on public maps, add secondary colours Data (reference data) sources can now be added to a public map from the publish editor. Each public map colour scheme gains a secondary colour, used for a second area layer; trans-pride's was missing its #. Co-Authored-By: Claude Opus 5.5 --- .../map/[id]/publish/components/DataSourcesSelect.tsx | 6 +----- src/app/(private)/map/[id]/styles.ts | 11 +++++++++-- 2 files changed, 10 insertions(+), 7 deletions(-) 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", }, }; From ba5a67d315c43f0dd0cf4334b1912c029fa7e409 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Tue, 1 Dec 2026 17:20:30 +0000 Subject: [PATCH 2/8] feat: include area codes on public map markers for reference data Reference data sources geocoded by area code or name will be drawn as shaded areas on public maps, so the markers endpoint now sends the code of each record's area when called in a public map context. Co-Authored-By: Claude Opus 5.5 --- .../api/data-sources/[id]/markers/route.ts | 10 +++ src/types.ts | 6 ++ src/utils/dataSource.ts | 26 +++++++ tests/unit/utils/dataSource.test.ts | 71 +++++++++++++++++++ 4 files changed, 113 insertions(+) create mode 100644 src/utils/dataSource.ts create mode 100644 tests/unit/utils/dataSource.test.ts 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(); + }); +}); From 6998b25928ad0004b0fba2bdfcc11c2e4924551a Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Tue, 1 Dec 2026 17:24:22 +0000 Subject: [PATCH 3/8] chore: add sample council-level reference data CSV Co-Authored-By: Claude Opus 5.5 --- resources/dataSets/sampleCouncilCampaigns.csv | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 resources/dataSets/sampleCouncilCampaigns.csv 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 From 2f1807d9018b813a5db1f63d8c2a4ed65b5809b3 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Wed, 2 Dec 2026 12:08:32 +0000 Subject: [PATCH 4/8] feat: draw reference data sources as shaded areas on public maps Reference data sources geocoded by area are drawn on public maps by filtering the choropleth boundary tileset for their area set to the records' area codes, instead of as markers. Area sources alternate between the colour scheme's primary and secondary colours. The marker filtering (timeline, past events, public filters) moves into useVisibleMarkers so markers and areas hide the same records. Co-Authored-By: Claude Opus 5.5 --- .../map/[id]/components/DataSourceAreas.tsx | 111 +++++++++++++++ .../components/Markers/DataSourceMarkers.tsx | 105 +------------- .../map/[id]/components/Markers/Markers.tsx | 17 +++ .../map/[id]/hooks/useDataSourceAreaLayers.ts | 66 +++++++++ .../map/[id]/hooks/useVisibleMarkers.ts | 131 ++++++++++++++++++ 5 files changed, 330 insertions(+), 100 deletions(-) create mode 100644 src/app/(private)/map/[id]/components/DataSourceAreas.tsx create mode 100644 src/app/(private)/map/[id]/hooks/useDataSourceAreaLayers.ts create mode 100644 src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts 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..3daf4f31 --- /dev/null +++ b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx @@ -0,0 +1,111 @@ +import { useMemo } from "react"; +import { Layer, Source } from "react-map-gl/mapbox"; +import { useVisibleMarkers } from "../hooks/useVisibleMarkers"; +import { MARKER_CLIENT_EXCLUDED_KEY } from "./Markers/utils"; +import type { ChoroplethLayerConfig } from "./Choropleth/configs"; +import type { MarkerFeature } from "@/types"; + +export const DATA_SOURCE_AREAS_TOP_LAYER_ID = "data-source-areas-top"; + +const FILL_OPACITY = 0.5; + +/** + * 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 function DataSourceAreasPosition() { + return ( + + + + ); +} + +/** + * 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({ + dataSourceMarkers, + layerConfig, + color, + hideFilteredMarkers, + filterTimeRange, +}: { + dataSourceMarkers: { dataSourceId: string; markers: MarkerFeature[] }; + layerConfig: ChoroplethLayerConfig; + color: string; + hideFilteredMarkers: boolean; + filterTimeRange: { start: number; end: number } | null; +}) { + const visibleMarkers = useVisibleMarkers({ + dataSourceMarkers, + hideFilteredMarkers, + filterTimeRange, + }); + + const areaCodes = useMemo(() => { + const codes = new Set(); + for (const feature of visibleMarkers.features) { + const { areaCode, matched } = feature.properties; + const excluded = feature.properties[MARKER_CLIENT_EXCLUDED_KEY] === true; + if (areaCode && matched !== false && !excluded) { + codes.add(areaCode); + } + } + return [...codes]; + }, [visibleMarkers]); + + const { dataSourceId } = dataSourceMarkers; + const { sourceId, layerId, featureCodeProperty } = layerConfig.mapbox; + const areasSourceId = `${dataSourceId}-areas`; + const filter = ["in", ["get", featureCodeProperty], ["literal", areaCodes]]; + + return ( + + + + + ); +} 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..9bc0fa63 100644 --- a/src/app/(private)/map/[id]/components/Markers/Markers.tsx +++ b/src/app/(private)/map/[id]/components/Markers/Markers.tsx @@ -5,10 +5,12 @@ 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 { useLayers } from "../../hooks/useLayers"; import { useMapRef, useMapRoute } from "../../hooks/useMapCore"; import { useTimelineFilter } from "../../hooks/useTimelineFilter"; import { isPublicMapLayout } from "../../utils/mapRoute"; +import DataSourceAreas, { DataSourceAreasPosition } from "../DataSourceAreas"; import { DataSourceMarkers } from "./DataSourceMarkers"; import { isMarkerIconImageId, registerMarkerIcons } from "./markerIcons"; @@ -22,6 +24,7 @@ export default function Markers() { const { activeRange } = useTimelineFilter(); const areaStats = useAreaStats().data; const route = useMapRoute(); + const areaLayers = useDataSourceAreaLayers(); // 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 @@ -84,6 +87,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/useVisibleMarkers.ts b/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts new file mode 100644 index 00000000..a8701113 --- /dev/null +++ b/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts @@ -0,0 +1,131 @@ +import { 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 { FeatureCollection, Point } from "geojson"; + +export type VisibleMarkerProperties = MarkerFeature["properties"] & { + [MARKER_CLIENT_EXCLUDED_KEY]?: boolean; +}; + +/** + * A data source's marker features after the timeline, past-events and + * public map filters. Features hidden by the public map filters are kept but + * flagged with MARKER_CLIENT_EXCLUDED_KEY, so cluster counts stay correct. + */ +export function useVisibleMarkers({ + dataSourceMarkers, + hideFilteredMarkers, + filterTimeRange, +}: { + dataSourceMarkers: { dataSourceId: string; markers: MarkerFeature[] }; + hideFilteredMarkers: boolean; + filterTimeRange: { start: number; end: number } | null; +}) { + const filteredRecords = useFilteredRecords(); + const publicFilters = usePublicFilters(); + const publicDateFilter = usePublicDateFilter(); + const publicMap = usePublicMapValue(); + + 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; + + return 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), + }, + })); + + return { + type: "FeatureCollection", + features: mappedFeatures, + }; + }, [ + dataSourceMarkers.markers, + filteredRecords, + publicFilters, + publicDateFilter, + hideFilteredMarkers, + filterTimeRange, + hidePastEvents, + showingPastEvents, + eventDateFormat, + ]); +} From 06f0b5da6095cf27c29dcc26d11c6327afe37c68 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Wed, 2 Dec 2026 12:18:43 +0000 Subject: [PATCH 5/8] feat: make public map area layers clickable and hoverable Hovering a shaded area darkens it, clicking it selects every record geocoded to that area, and clicking a listing for an area source zooms out far enough to see the area. Co-Authored-By: Claude Opus 5.5 --- .../map/[id]/components/DataSourceAreas.tsx | 28 ++++++-- .../(private)/map/[id]/hooks/useMapClick.ts | 52 ++++++++++++++ .../(private)/map/[id]/hooks/useMapHover.ts | 69 +++++++++++++++++++ .../publish/components/DataRecordsList.tsx | 9 ++- src/app/(private)/map/[id]/publish/const.ts | 5 ++ .../map/[id]/utils/dataSourceAreas.ts | 54 +++++++++++++++ 6 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 src/app/(private)/map/[id]/utils/dataSourceAreas.ts diff --git a/src/app/(private)/map/[id]/components/DataSourceAreas.tsx b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx index 3daf4f31..5da991bd 100644 --- a/src/app/(private)/map/[id]/components/DataSourceAreas.tsx +++ b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx @@ -8,6 +8,17 @@ import type { MarkerFeature } from "@/types"; export const DATA_SOURCE_AREAS_TOP_LAYER_ID = "data-source-areas-top"; const FILL_OPACITY = 0.5; +const HOVER_FILL_OPACITY = 0.7; + +/** 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`, + }; +}; /** * Empty layer that fixes where area fills sit in the layer stack: area @@ -67,7 +78,11 @@ export default function DataSourceAreas({ const { dataSourceId } = dataSourceMarkers; const { sourceId, layerId, featureCodeProperty } = layerConfig.mapbox; - const areasSourceId = `${dataSourceId}-areas`; + const { + sourceId: areasSourceId, + fillLayerId, + lineLayerId, + } = getDataSourceAreasIds(dataSourceId); const filter = ["in", ["get", featureCodeProperty], ["literal", areaCodes]]; return ( @@ -79,7 +94,7 @@ export default function DataSourceAreas({ url={`mapbox://${sourceId}`} > { + const hit = queryDataSourceArea({ + map, + point: e.point, + areaLayers: dataSourceAreaLayers, + }); + if (!hit) { + return false; + } + + const markers = + markerQueries?.data.find((dsm) => dsm.dataSourceId === hit.dataSourceId) + ?.markers ?? []; + const records = []; + for (const marker of markers) { + const inArea = marker.properties.areaCode === hit.areaCode; + if (!inArea || marker.properties.matched === false) { + continue; + } + 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); + return true; + }; + const handleTurfClick = (e: mapboxgl.MapMouseEvent): boolean => { if (draw) { // Don't handle turf clicks when in direct_select (edit) mode @@ -412,6 +458,10 @@ export function useMapClickEffect({ return; } + if (handleDataSourceAreaClick(e)) { + return; + } + if (handleAreaClick(e)) { return; } @@ -448,6 +498,8 @@ export function useMapClickEffect({ interactionSourceId, secondaryAreaSetConfig, setSelectedSecondaryArea, + dataSourceAreaLayers, + markerQueries, ]); // 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..4ab06710 100644 --- a/src/app/(private)/map/[id]/hooks/useMapHover.ts +++ b/src/app/(private)/map/[id]/hooks/useMapHover.ts @@ -6,10 +6,13 @@ import { hoverMarkerAtom, hoverSecondaryAreaAtom, } from "../atoms/hoverAtoms"; +import { queryDataSourceArea } from "../utils/dataSourceAreas"; +import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; import { getClickedPolygonFeature } from "./useMapClick"; import { useEditAreaMode, usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; +import type { DataSourceAreaHit } from "../utils/dataSourceAreas"; import type MapboxDraw from "@mapbox/mapbox-gl-draw"; export function useMapHoverEffect({ @@ -24,6 +27,7 @@ export function useMapHoverEffect({ const mapRef = useMapRef(); const { choroplethLayerConfig } = useChoropleth(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); + const dataSourceAreaLayers = useDataSourceAreaLayers(); const { areaSetCode, mapbox: { sourceId, layerId, featureNameProperty }, @@ -57,6 +61,7 @@ export function useMapHoverEffect({ const prevPointer = { cursor: "" }; let hoveredFeatureId: string | number | undefined; let hoveredSecondaryFeatureId: string | number | undefined; + let hoveredDataSourceArea: DataSourceAreaHit | null = null; const clearAreaHover = () => { if (hoveredFeatureId !== undefined) { @@ -73,11 +78,61 @@ export function useMapHoverEffect({ } }; + const clearDataSourceAreaHover = () => { + if (!hoveredDataSourceArea) { + return; + } + const { sourceId, sourceLayer, areaCode } = hoveredDataSourceArea; + hoveredDataSourceArea = null; + 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; + } + + 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 +143,12 @@ export function useMapHoverEffect({ handleHoverSecondaryArea(e); if (handleHoverMarker(e)) { + clearAreaHover(); + clearDataSourceAreaHover(); + return; + } + + if (handleHoverDataSourceArea(e)) { clearAreaHover(); return; } @@ -107,6 +168,7 @@ export function useMapHoverEffect({ const onMouseLeave = () => { clearAreaHover(); + clearDataSourceAreaHover(); setHoverMarker(null); clearSecondaryAreaHover(); if (pinDropModeRef.current || editAreaModeRef.current) { @@ -307,6 +369,12 @@ export function useMapHoverEffect({ } } + try { + clearDataSourceAreaHover(); + } catch { + // Ignore error clearing feature state + } + map.off("mousemove", onMouseMove); map.off("mouseout", onMouseLeave); }; @@ -324,6 +392,7 @@ export function useMapHoverEffect({ interactionSourceId, secondaryAreaSetConfig, setHoverSecondaryArea, + dataSourceAreaLayers, ]); } diff --git a/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx b/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx index 3a9a0fe4..41ebc8b8 100644 --- a/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx +++ b/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx @@ -6,6 +6,8 @@ import { useInspectorState } from "@/app/(private)/map/[id]/hooks/useInspectorSt import { useMapRef } from "@/app/(private)/map/[id]/hooks/useMapCore"; import { cn } from "@/shadcn/utils"; import { formatRecordDate, getListingSort } from "@/utils/dataRecord"; +import { getPublicMapAreaSetCode } from "@/utils/dataSource"; +import { LISTING_AREA_ZOOM, LISTING_POINT_ZOOM } from "../const"; import { PAST_EVENTS_FILTER_KEY } from "../dateFilters"; import { useFilteredRecords, @@ -181,13 +183,16 @@ const RecordGroupItem = memo(function RecordGroupItem({ } if (recordGroup.geocodePoint) { + const isArea = dataSource + ? Boolean(getPublicMapAreaSetCode(dataSource)) + : false; mapRef?.current?.flyTo({ center: recordGroup.geocodePoint, - zoom: 14, + zoom: isArea ? LISTING_AREA_ZOOM : LISTING_POINT_ZOOM, }); } }, - [dataSourceConfig, isSelected, mapRef, setSelectedRecords], + [dataSource, dataSourceConfig, isSelected, mapRef, setSelectedRecords], ); return ( diff --git a/src/app/(private)/map/[id]/publish/const.ts b/src/app/(private)/map/[id]/publish/const.ts index f6d3991c..98e34929 100644 --- a/src/app/(private)/map/[id]/publish/const.ts +++ b/src/app/(private)/map/[id]/publish/const.ts @@ -1,5 +1,10 @@ export const TRANS_FRIENDLY_HOST = "trans-friendly-gp.mapped.tools"; +// Zoom when a listing is clicked: close in on a point, or far enough out to +// see the whole area for reference data drawn as areas +export const LISTING_POINT_ZOOM = 14; +export const LISTING_AREA_ZOOM = 9; + export const ALLOWED_FILTERS = [ { name: "Referral to a GIC", 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..1bd71de4 --- /dev/null +++ b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts @@ -0,0 +1,54 @@ +import { getDataSourceAreasIds } from "../components/DataSourceAreas"; +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; +} + +/** 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, + }; +}; From 7f10f851c173a592b612a12e01dc0dc56c66afa9 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Wed, 2 Dec 2026 12:21:08 +0000 Subject: [PATCH 6/8] feat: fly to a public map area when it is clicked Matches clicking a marker: centre on the area, zooming in no further than needed to see all of it. Co-Authored-By: Claude Opus 5.5 --- src/app/(private)/map/[id]/hooks/useMapClick.ts | 9 +++++++++ src/app/(private)/map/[id]/publish/const.ts | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/app/(private)/map/[id]/hooks/useMapClick.ts b/src/app/(private)/map/[id]/hooks/useMapClick.ts index 7ed0ed9f..7f3bd3be 100644 --- a/src/app/(private)/map/[id]/hooks/useMapClick.ts +++ b/src/app/(private)/map/[id]/hooks/useMapClick.ts @@ -4,6 +4,7 @@ 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 { usePinDropMode } from "./useMapControls"; @@ -318,6 +319,14 @@ export function useMapClickEffect({ 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; }; diff --git a/src/app/(private)/map/[id]/publish/const.ts b/src/app/(private)/map/[id]/publish/const.ts index 98e34929..2b37777e 100644 --- a/src/app/(private)/map/[id]/publish/const.ts +++ b/src/app/(private)/map/[id]/publish/const.ts @@ -1,7 +1,8 @@ export const TRANS_FRIENDLY_HOST = "trans-friendly-gp.mapped.tools"; // Zoom when a listing is clicked: close in on a point, or far enough out to -// see the whole area for reference data drawn as areas +// see the whole area for reference data drawn as areas. Clicking an area on +// the map also zooms in to at least LISTING_AREA_ZOOM. export const LISTING_POINT_ZOOM = 14; export const LISTING_AREA_ZOOM = 9; From f079a472bfcd8aa072ddbcde7d49b97ce558d88a Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Wed, 2 Dec 2026 12:25:46 +0000 Subject: [PATCH 7/8] feat: show a hover popover for public map areas Hovering a shaded area shows the same popover as a marker, listing the names (and dates, where shown) of the records in that area, up to five. Co-Authored-By: Claude Opus 5.5 --- .../(private)/map/[id]/atoms/hoverAtoms.ts | 9 +++++- .../map/[id]/components/MarkerPopup.tsx | 32 +++++++++++++------ src/app/(private)/map/[id]/constants.ts | 4 +++ .../(private)/map/[id]/hooks/useMapClick.ts | 11 +++---- .../(private)/map/[id]/hooks/useMapHover.ts | 29 +++++++++++++++-- .../map/[id]/utils/dataSourceAreas.ts | 16 ++++++++++ 6 files changed, 83 insertions(+), 18 deletions(-) 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/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]/constants.ts b/src/app/(private)/map/[id]/constants.ts index a6aff25c..7d4ac4c2 100644 --- a/src/app/(private)/map/[id]/constants.ts +++ b/src/app/(private)/map/[id]/constants.ts @@ -1,3 +1,7 @@ export { PARTY_COLORS } from "@/constants/colors"; export const DEFAULT_FILL_COLOR = "rgba(0, 0, 0, 0)"; + +// Most records listed in a hover popover (e.g. a public map area with several +// records); the rest are summarised as "and N more" +export const HOVER_POPUP_MAX_ITEMS = 5; diff --git a/src/app/(private)/map/[id]/hooks/useMapClick.ts b/src/app/(private)/map/[id]/hooks/useMapClick.ts index 7f3bd3be..d41fb1c8 100644 --- a/src/app/(private)/map/[id]/hooks/useMapClick.ts +++ b/src/app/(private)/map/[id]/hooks/useMapClick.ts @@ -5,7 +5,7 @@ import { type SelectedArea } from "@/app/(private)/map/[id]/atoms/selectedAreasA 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 { getAreaMarkers, queryDataSourceArea } from "../utils/dataSourceAreas"; import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; import { usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; @@ -297,11 +297,10 @@ export function useMapClickEffect({ markerQueries?.data.find((dsm) => dsm.dataSourceId === hit.dataSourceId) ?.markers ?? []; const records = []; - for (const marker of markers) { - const inArea = marker.properties.areaCode === hit.areaCode; - if (!inArea || marker.properties.matched === false) { - continue; - } + for (const marker of getAreaMarkers({ + markers, + areaCode: hit.areaCode, + })) { records.push({ id: marker.properties.id, dataSourceId: hit.dataSourceId, diff --git a/src/app/(private)/map/[id]/hooks/useMapHover.ts b/src/app/(private)/map/[id]/hooks/useMapHover.ts index 4ab06710..76da9263 100644 --- a/src/app/(private)/map/[id]/hooks/useMapHover.ts +++ b/src/app/(private)/map/[id]/hooks/useMapHover.ts @@ -6,11 +6,12 @@ import { hoverMarkerAtom, hoverSecondaryAreaAtom, } from "../atoms/hoverAtoms"; -import { queryDataSourceArea } from "../utils/dataSourceAreas"; +import { getAreaMarkers, queryDataSourceArea } from "../utils/dataSourceAreas"; import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; import { getClickedPolygonFeature } from "./useMapClick"; import { useEditAreaMode, usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; +import { useMarkerQueries } from "./useMarkerQueries"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; import type { DataSourceAreaHit } from "../utils/dataSourceAreas"; import type MapboxDraw from "@mapbox/mapbox-gl-draw"; @@ -28,6 +29,7 @@ export function useMapHoverEffect({ const { choroplethLayerConfig } = useChoropleth(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); const dataSourceAreaLayers = useDataSourceAreaLayers(); + const markerQueries = useMarkerQueries(); const { areaSetCode, mapbox: { sourceId, layerId, featureNameProperty }, @@ -120,6 +122,22 @@ export function useMapHoverEffect({ hoveredDataSourceArea = hit; } + // Popover listing the area's records, as for a marker + const markers = + markerQueries?.data.find((dsm) => dsm.dataSourceId === hit.dataSourceId) + ?.markers ?? []; + const items = getAreaMarkers({ markers, areaCode: hit.areaCode }).map( + (marker) => ({ + name: marker.properties.name, + date: marker.properties.date, + }), + ); + setHoverMarker( + items.length + ? { coordinates: [e.lngLat.lng, e.lngLat.lat], items } + : null, + ); + if (map.getCanvas().style.cursor !== "pointer") { prevPointer.cursor = map.getCanvas().style.cursor || ""; } @@ -198,9 +216,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 || ""; @@ -393,6 +417,7 @@ export function useMapHoverEffect({ secondaryAreaSetConfig, setHoverSecondaryArea, dataSourceAreaLayers, + markerQueries, ]); } diff --git a/src/app/(private)/map/[id]/utils/dataSourceAreas.ts b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts index 1bd71de4..48a79e61 100644 --- a/src/app/(private)/map/[id]/utils/dataSourceAreas.ts +++ b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts @@ -1,5 +1,6 @@ import { getDataSourceAreasIds } from "../components/DataSourceAreas"; import type { DataSourceAreaLayer } from "../hooks/useDataSourceAreaLayers"; +import type { MarkerFeature } from "@/types"; import type { MapRef } from "react-map-gl/mapbox"; export interface DataSourceAreaHit { @@ -10,6 +11,21 @@ export interface DataSourceAreaHit { sourceLayer: string; } +/** A data source's records geocoded to an area, excluding unmatched ones */ +export const getAreaMarkers = ({ + markers, + areaCode, +}: { + markers: MarkerFeature[]; + areaCode: string; +}) => { + return markers.filter( + (marker) => + marker.properties.areaCode === areaCode && + marker.properties.matched !== false, + ); +}; + /** The top-most data source area under a point, if any */ export const queryDataSourceArea = ({ map, From 6951a98e4db62085bd590f0b715141b101934aa6 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Wed, 2 Dec 2026 12:52:54 +0000 Subject: [PATCH 8/8] fix: limit public map area hover and click to visible records Area shading, hover and click now share one index of each area-drawn source's visible records, so filtered-out records no longer appear in the popover or selection. Also zoom listings by how a source is actually drawn, avoid rescanning markers on every mouse move, and move area constants and helpers to their own files. Co-Authored-By: Claude Opus 5.5 --- .../map/[id]/components/DataSourceAreas.tsx | 83 ++----- .../components/DataSourceAreasPosition.tsx | 23 ++ .../map/[id]/components/Markers/Markers.tsx | 21 +- src/app/(private)/map/[id]/constants.ts | 8 + .../[id]/hooks/useDataSourceAreaMarkers.ts | 62 +++++ .../(private)/map/[id]/hooks/useMapClick.ts | 20 +- .../(private)/map/[id]/hooks/useMapHover.ts | 37 +-- .../map/[id]/hooks/useTimelineFilter.ts | 19 ++ .../map/[id]/hooks/useVisibleMarkers.ts | 225 ++++++++++-------- .../publish/components/DataRecordsList.tsx | 16 +- .../map/[id]/utils/dataSourceAreas.ts | 23 +- 11 files changed, 317 insertions(+), 220 deletions(-) create mode 100644 src/app/(private)/map/[id]/components/DataSourceAreasPosition.tsx create mode 100644 src/app/(private)/map/[id]/hooks/useDataSourceAreaMarkers.ts diff --git a/src/app/(private)/map/[id]/components/DataSourceAreas.tsx b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx index 5da991bd..8b769735 100644 --- a/src/app/(private)/map/[id]/components/DataSourceAreas.tsx +++ b/src/app/(private)/map/[id]/components/DataSourceAreas.tsx @@ -1,82 +1,35 @@ import { useMemo } from "react"; import { Layer, Source } from "react-map-gl/mapbox"; -import { useVisibleMarkers } from "../hooks/useVisibleMarkers"; -import { MARKER_CLIENT_EXCLUDED_KEY } from "./Markers/utils"; +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 { MarkerFeature } from "@/types"; - -export const DATA_SOURCE_AREAS_TOP_LAYER_ID = "data-source-areas-top"; - -const FILL_OPACITY = 0.5; -const HOVER_FILL_OPACITY = 0.7; - -/** 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`, - }; -}; - -/** - * 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 function DataSourceAreasPosition() { - return ( - - - - ); -} +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({ - dataSourceMarkers, + dataSourceId, + areaMarkers, layerConfig, color, - hideFilteredMarkers, - filterTimeRange, }: { - dataSourceMarkers: { dataSourceId: string; markers: MarkerFeature[] }; + dataSourceId: string; + /** The source's visible records by area code (useDataSourceAreaMarkers) */ + areaMarkers: Map | undefined; layerConfig: ChoroplethLayerConfig; color: string; - hideFilteredMarkers: boolean; - filterTimeRange: { start: number; end: number } | null; }) { - const visibleMarkers = useVisibleMarkers({ - dataSourceMarkers, - hideFilteredMarkers, - filterTimeRange, - }); - - const areaCodes = useMemo(() => { - const codes = new Set(); - for (const feature of visibleMarkers.features) { - const { areaCode, matched } = feature.properties; - const excluded = feature.properties[MARKER_CLIENT_EXCLUDED_KEY] === true; - if (areaCode && matched !== false && !excluded) { - codes.add(areaCode); - } - } - return [...codes]; - }, [visibleMarkers]); + const areaCodes = useMemo( + () => [...(areaMarkers?.keys() ?? [])], + [areaMarkers], + ); - const { dataSourceId } = dataSourceMarkers; const { sourceId, layerId, featureCodeProperty } = layerConfig.mapbox; const { sourceId: areasSourceId, @@ -105,8 +58,8 @@ export default function DataSourceAreas({ "fill-opacity": [ "case", ["boolean", ["feature-state", "hover"], false], - HOVER_FILL_OPACITY, - FILL_OPACITY, + DATA_SOURCE_AREAS_HOVER_FILL_OPACITY, + DATA_SOURCE_AREAS_FILL_OPACITY, ], }} /> 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/Markers/Markers.tsx b/src/app/(private)/map/[id]/components/Markers/Markers.tsx index 9bc0fa63..1e85ca98 100644 --- a/src/app/(private)/map/[id]/components/Markers/Markers.tsx +++ b/src/app/(private)/map/[id]/components/Markers/Markers.tsx @@ -6,11 +6,13 @@ 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, { DataSourceAreasPosition } from "../DataSourceAreas"; +import DataSourceAreas from "../DataSourceAreas"; +import DataSourceAreasPosition from "../DataSourceAreasPosition"; import { DataSourceMarkers } from "./DataSourceMarkers"; import { isMarkerIconImageId, registerMarkerIcons } from "./markerIcons"; @@ -21,10 +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 @@ -40,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(() => { @@ -119,11 +115,10 @@ export default function Markers() { return ( ); } diff --git a/src/app/(private)/map/[id]/constants.ts b/src/app/(private)/map/[id]/constants.ts index 7d4ac4c2..c5e4e666 100644 --- a/src/app/(private)/map/[id]/constants.ts +++ b/src/app/(private)/map/[id]/constants.ts @@ -5,3 +5,11 @@ export const DEFAULT_FILL_COLOR = "rgba(0, 0, 0, 0)"; // Most records listed in a hover popover (e.g. a public map area with several // records); the rest are summarised as "and N more" export const HOVER_POPUP_MAX_ITEMS = 5; + +// Empty layer that public map data source areas are inserted before, so they +// stay below markers (DataSourceAreasPosition) +export const DATA_SOURCE_AREAS_TOP_LAYER_ID = "data-source-areas-top"; + +// Fill opacity of public map data source areas, and of the hovered one +export const DATA_SOURCE_AREAS_FILL_OPACITY = 0.5; +export const DATA_SOURCE_AREAS_HOVER_FILL_OPACITY = 0.7; 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 d41fb1c8..33b1add9 100644 --- a/src/app/(private)/map/[id]/hooks/useMapClick.ts +++ b/src/app/(private)/map/[id]/hooks/useMapClick.ts @@ -5,11 +5,11 @@ import { type SelectedArea } from "@/app/(private)/map/[id]/atoms/selectedAreasA 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 { getAreaMarkers, queryDataSourceArea } from "../utils/dataSourceAreas"; +import { queryDataSourceArea } from "../utils/dataSourceAreas"; import { useDataSourceAreaLayers } from "./useDataSourceAreaLayers"; +import { useDataSourceAreaMarkers } from "./useDataSourceAreaMarkers"; import { usePinDropMode } from "./useMapControls"; import { useMapRef } from "./useMapCore"; -import { useMarkerQueries } from "./useMarkerQueries"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; import { useSelectedAreas } from "./useSelectedAreas"; import { useSelectedSecondaryArea } from "./useSelectedSecondaryArea"; @@ -49,7 +49,7 @@ export function useMapClickEffect({ const [, setSelectedSecondaryArea] = useSelectedSecondaryArea(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); const dataSourceAreaLayers = useDataSourceAreaLayers(); - const markerQueries = useMarkerQueries(); + const dataSourceAreaMarkers = useDataSourceAreaMarkers(); const { mapbox: { sourceId, layerId, featureCodeProperty, featureNameProperty }, @@ -282,7 +282,7 @@ export function useMapClickEffect({ }; // Public map reference data drawn as areas (DataSourceAreas): select - // every record geocoded to the clicked area + // every visible record geocoded to the clicked area const handleDataSourceAreaClick = (e: mapboxgl.MapMouseEvent): boolean => { const hit = queryDataSourceArea({ map, @@ -293,14 +293,10 @@ export function useMapClickEffect({ return false; } - const markers = - markerQueries?.data.find((dsm) => dsm.dataSourceId === hit.dataSourceId) - ?.markers ?? []; + const areaMarkers = + dataSourceAreaMarkers.get(hit.dataSourceId)?.get(hit.areaCode) ?? []; const records = []; - for (const marker of getAreaMarkers({ - markers, - areaCode: hit.areaCode, - })) { + for (const marker of areaMarkers) { records.push({ id: marker.properties.id, dataSourceId: hit.dataSourceId, @@ -507,7 +503,7 @@ export function useMapClickEffect({ secondaryAreaSetConfig, setSelectedSecondaryArea, dataSourceAreaLayers, - markerQueries, + 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 76da9263..03185c2d 100644 --- a/src/app/(private)/map/[id]/hooks/useMapHover.ts +++ b/src/app/(private)/map/[id]/hooks/useMapHover.ts @@ -6,13 +6,14 @@ import { hoverMarkerAtom, hoverSecondaryAreaAtom, } from "../atoms/hoverAtoms"; -import { getAreaMarkers, queryDataSourceArea } from "../utils/dataSourceAreas"; +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 { useMarkerQueries } from "./useMarkerQueries"; import { useSecondaryAreaSetConfig } from "./useSecondaryAreaSet"; +import type { HoverMarkerItem } from "../atoms/hoverAtoms"; import type { DataSourceAreaHit } from "../utils/dataSourceAreas"; import type MapboxDraw from "@mapbox/mapbox-gl-draw"; @@ -29,7 +30,7 @@ export function useMapHoverEffect({ const { choroplethLayerConfig } = useChoropleth(); const secondaryAreaSetConfig = useSecondaryAreaSetConfig(); const dataSourceAreaLayers = useDataSourceAreaLayers(); - const markerQueries = useMarkerQueries(); + const dataSourceAreaMarkers = useDataSourceAreaMarkers(); const { areaSetCode, mapbox: { sourceId, layerId, featureNameProperty }, @@ -64,6 +65,7 @@ export function useMapHoverEffect({ let hoveredFeatureId: string | number | undefined; let hoveredSecondaryFeatureId: string | number | undefined; let hoveredDataSourceArea: DataSourceAreaHit | null = null; + let hoveredDataSourceAreaItems: HoverMarkerItem[] = []; const clearAreaHover = () => { if (hoveredFeatureId !== undefined) { @@ -86,6 +88,7 @@ export function useMapHoverEffect({ } const { sourceId, sourceLayer, areaCode } = hoveredDataSourceArea; hoveredDataSourceArea = null; + hoveredDataSourceAreaItems = []; if (!map.getSource(sourceId)) { return; } @@ -120,21 +123,23 @@ export function useMapHoverEffect({ { hover: true }, ); hoveredDataSourceArea = hit; - } - - // Popover listing the area's records, as for a marker - const markers = - markerQueries?.data.find((dsm) => dsm.dataSourceId === hit.dataSourceId) - ?.markers ?? []; - const items = getAreaMarkers({ markers, areaCode: hit.areaCode }).map( - (marker) => ({ + // 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( - items.length - ? { coordinates: [e.lngLat.lng, e.lngLat.lat], items } + hoveredDataSourceAreaItems.length + ? { + coordinates: [e.lngLat.lng, e.lngLat.lat], + items: hoveredDataSourceAreaItems, + } : null, ); @@ -417,7 +422,7 @@ export function useMapHoverEffect({ secondaryAreaSetConfig, setHoverSecondaryArea, dataSourceAreaLayers, - markerQueries, + 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 index a8701113..546001d9 100644 --- a/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts +++ b/src/app/(private)/map/[id]/hooks/useVisibleMarkers.ts @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useCallback, useMemo } from "react"; import { useDataSources } from "@/hooks/useDataSources"; import { getEventDateFormat, @@ -16,116 +16,155 @@ import { } from "../publish/hooks/usePublicFilters"; import { usePublicMapValue } from "../publish/hooks/usePublicMap"; import type { MarkerFeature } from "@/types"; -import type { FeatureCollection, Point } from "geojson"; +import type { Feature, FeatureCollection, Point } from "geojson"; export type VisibleMarkerProperties = MarkerFeature["properties"] & { [MARKER_CLIENT_EXCLUDED_KEY]?: boolean; }; -/** - * A data source's marker features after the timeline, past-events and - * public map filters. Features hidden by the public map filters are kept but - * flagged with MARKER_CLIENT_EXCLUDED_KEY, so cluster counts stay correct. - */ -export function useVisibleMarkers({ - dataSourceMarkers, - hideFilteredMarkers, - filterTimeRange, -}: { +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(); - const dataSourceId = dataSourceMarkers.dataSourceId; + 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 { 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; - - return 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, + // 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, ); - } - - 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, - ), + 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), ); - } - if (!hasClientFilters) { + const mappedFeatures = features.map((f) => ({ + ...f, + properties: { + ...f.properties, + [MARKER_CLIENT_EXCLUDED_KEY]: !recordIds.has(f.properties.id), + }, + })); + return { type: "FeatureCollection", - features, + features: mappedFeatures, }; - } - - 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), - }, - })); - - return { - type: "FeatureCollection", - features: mappedFeatures, - }; - }, [ - dataSourceMarkers.markers, - filteredRecords, - publicFilters, - publicDateFilter, - hideFilteredMarkers, - filterTimeRange, - hidePastEvents, - showingPastEvents, - eventDateFormat, - ]); + }, + [ + 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 41ebc8b8..54018c15 100644 --- a/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx +++ b/src/app/(private)/map/[id]/publish/components/DataRecordsList.tsx @@ -2,11 +2,11 @@ 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 { getPublicMapAreaSetCode } from "@/utils/dataSource"; import { LISTING_AREA_ZOOM, LISTING_POINT_ZOOM } from "../const"; import { PAST_EVENTS_FILTER_KEY } from "../dateFilters"; import { @@ -45,6 +45,7 @@ export default function DataRecordsList({ const filteredRecords = useFilteredRecords(); const publicDateFilter = usePublicDateFilter(); const searchLocation = useSearchLocation(); + const areaLayers = useDataSourceAreaLayers(); const listRef = useRef(null); useEffect(() => { @@ -64,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, ); @@ -109,6 +113,7 @@ export default function DataRecordsList({ colorScheme={colorScheme} dataSource={dataRecordsQuery.data} dataSourceConfig={dataSourceConfig} + drawnAsAreas={drawnAsAreas} id={id} isSelected={isSelected} mapRef={mapRef} @@ -126,6 +131,7 @@ const RecordGroupItem = memo(function RecordGroupItem({ colorScheme, dataSource, dataSourceConfig, + drawnAsAreas, id, isSelected, mapRef, @@ -135,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,16 +190,13 @@ const RecordGroupItem = memo(function RecordGroupItem({ } if (recordGroup.geocodePoint) { - const isArea = dataSource - ? Boolean(getPublicMapAreaSetCode(dataSource)) - : false; mapRef?.current?.flyTo({ center: recordGroup.geocodePoint, - zoom: isArea ? LISTING_AREA_ZOOM : LISTING_POINT_ZOOM, + zoom: drawnAsAreas ? LISTING_AREA_ZOOM : LISTING_POINT_ZOOM, }); } }, - [dataSource, dataSourceConfig, isSelected, mapRef, setSelectedRecords], + [dataSourceConfig, drawnAsAreas, isSelected, mapRef, setSelectedRecords], ); return ( diff --git a/src/app/(private)/map/[id]/utils/dataSourceAreas.ts b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts index 48a79e61..c4daaeb3 100644 --- a/src/app/(private)/map/[id]/utils/dataSourceAreas.ts +++ b/src/app/(private)/map/[id]/utils/dataSourceAreas.ts @@ -1,6 +1,4 @@ -import { getDataSourceAreasIds } from "../components/DataSourceAreas"; import type { DataSourceAreaLayer } from "../hooks/useDataSourceAreaLayers"; -import type { MarkerFeature } from "@/types"; import type { MapRef } from "react-map-gl/mapbox"; export interface DataSourceAreaHit { @@ -11,19 +9,14 @@ export interface DataSourceAreaHit { sourceLayer: string; } -/** A data source's records geocoded to an area, excluding unmatched ones */ -export const getAreaMarkers = ({ - markers, - areaCode, -}: { - markers: MarkerFeature[]; - areaCode: string; -}) => { - return markers.filter( - (marker) => - marker.properties.areaCode === areaCode && - marker.properties.matched !== false, - ); +/** 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 */