diff --git a/src/app/(private)/map/[id]/components/FilterMarkers.tsx b/src/app/(private)/map/[id]/components/FilterMarkers.tsx index a905112b..24a40970 100644 --- a/src/app/(private)/map/[id]/components/FilterMarkers.tsx +++ b/src/app/(private)/map/[id]/components/FilterMarkers.tsx @@ -1,6 +1,10 @@ import { bbox, circle } from "@turf/turf"; -import { useEffect, useMemo } from "react"; +import { useEffect, useMemo, useRef } from "react"; import { Layer, Source } from "react-map-gl/mapbox"; +import { + useFitPadding, + useFitToAllMarkers, +} from "@/app/(private)/map/[id]/hooks/useFitToAllMarkers"; 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"; @@ -132,34 +136,112 @@ export default function FilterMarkers() { return filterTurfs; }, [turfs, view?.dataSourceViews]); - // Pan to markers when the table view is opened / filters changed + // A stable summary of the location filters (markers and turfs) across all + // data sources. The map is only moved when this (or the open table's + // filters) changes, not when the marker or turf queries refetch. + const { locationFilterKey, locationFilterCount } = useMemo(() => { + const summary = []; + let count = 0; + for (const dataSourceView of view?.dataSourceViews || []) { + const markers = getFilterMarkers(dataSourceView.filter); + const turfIds = getFilterTurfs(dataSourceView.filter); + count += markers.length + turfIds.length; + summary.push([dataSourceView.dataSourceId, markers, turfIds]); + } + return { + locationFilterKey: JSON.stringify(summary), + locationFilterCount: count, + }; + }, [view?.dataSourceViews]); + + const selectedDataSourceView = view?.dataSourceViews.find( + (dsv) => dsv.dataSourceId === selectedDataSourceId, + ); + const selectedFiltersEmpty = + !selectedDataSourceView?.filter.children?.length && + !selectedDataSourceView?.search; + + const fitToAllMarkers = useFitToAllMarkers(); + const fitPadding = useFitPadding(); + + // What the open table's filters looked like the last time the effect ran + const previousRef = useRef<{ + dataSourceId: string; + filtersEmpty: boolean; + locationFilterKey: string; + } | null>(null); + // A fit that is waiting for marker / turf data to load + const pendingFitRef = useRef<"locationFilters" | "allMarkers" | null>(null); + + // Move the map when the filters change, to show the user what they now cover: + // - location filters changed: fit to the remaining location filters + // - the open table's filters were cleared: fit to any location filters left + // on other data sources, otherwise reset to the initial (all markers) view + // Opening or switching table does not move the map. useEffect(() => { + const previous = previousRef.current; + previousRef.current = { + dataSourceId: selectedDataSourceId, + filtersEmpty: selectedFiltersEmpty, + locationFilterKey, + }; + if (!selectedDataSourceId) { + pendingFitRef.current = null; return; } - if ( - memberFilterMarkers.length || - otherFilterMarkers.length || - filterTurfs.length - ) { + if (previous?.dataSourceId !== selectedDataSourceId) { + pendingFitRef.current = null; + return; + } + + const filtersCleared = !previous.filtersEmpty && selectedFiltersEmpty; + const locationFiltersChanged = + previous.locationFilterKey !== locationFilterKey; + if (filtersCleared) { + pendingFitRef.current = locationFilterCount + ? "locationFilters" + : "allMarkers"; + } else if (locationFiltersChanged) { + pendingFitRef.current = locationFilterCount ? "locationFilters" : null; + } + + if (pendingFitRef.current === "allMarkers") { + if (fitToAllMarkers()) { + pendingFitRef.current = null; + } + return; + } + + if (pendingFitRef.current === "locationFilters") { const allPolygons = memberFilterMarkers .concat(otherFilterMarkers) .map((m) => m.geometry as Polygon | MultiPolygon) .concat(filterTurfs); + // Wait until every location filter has been resolved to a polygon + if (allPolygons.length < locationFilterCount) { + return; + } const bounds = calculateBounds(allPolygons); if (bounds) { mapRef?.current?.fitBounds(bounds, { - padding: 50, + padding: fitPadding, duration: 1000, }); } + pendingFitRef.current = null; } }, [ + filterTurfs, + fitPadding, + fitToAllMarkers, + locationFilterCount, + locationFilterKey, mapRef, memberFilterMarkers, otherFilterMarkers, - filterTurfs, selectedDataSourceId, + selectedFiltersEmpty, ]); return ( diff --git a/src/app/(private)/map/[id]/components/Map.tsx b/src/app/(private)/map/[id]/components/Map.tsx index ac949d05..eba288d6 100644 --- a/src/app/(private)/map/[id]/components/Map.tsx +++ b/src/app/(private)/map/[id]/components/Map.tsx @@ -11,17 +11,14 @@ import { v4 as uuidv4 } from "uuid"; import { useMapBounds } from "@/app/(private)/map/[id]/hooks/useMapBounds"; 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 { - useDropPinCleanupEffect, - usePlacedMarkersQuery, -} from "@/app/(private)/map/[id]/hooks/usePlacedMarkers"; +import { useDropPinCleanupEffect } from "@/app/(private)/map/[id]/hooks/usePlacedMarkers"; import { DEFAULT_ZOOM } from "@/constants"; import { useIsMobileEffect } from "@/hooks/useIsMobile"; import { MapType } from "@/models/MapView"; import { parseTurfPolygon } from "@/models/Turf"; import { getMarkerDataSourceIds } from "@/utils/map"; import { useDraw } from "../hooks/useDraw"; +import { useFitToAllMarkers } from "../hooks/useFitToAllMarkers"; import { useInspectorState } from "../hooks/useInspectorState"; import { useSetZoom } from "../hooks/useMapCamera"; import { @@ -70,9 +67,7 @@ export default function Map({ const [ready, setReady] = useState(false); const { viewConfig } = useMapViews(); const { mapConfig } = useMapConfig(); - const { data: placedMarkers = [] } = usePlacedMarkersQuery(); const { visibleTurfs } = useTurfState(); - const markerQueries = useMarkerQueries(); const [styleLoaded, setStyleLoaded] = useState(false); const { resetInspector, setSelectedTurf, selectedTurf } = useInspectorState(); const route = useMapRoute(); @@ -82,6 +77,7 @@ export default function Map({ const setDrawMode = useSetDrawMode(); const [currentMode, setCurrentMode] = useState(""); const [didInitialFit, setDidInitialFit] = useState(false); + const fitToAllMarkers = useFitToAllMarkers(); const { insertTurf, updateTurf, deleteTurf } = useTurfMutations(); @@ -289,70 +285,13 @@ export default function Map({ }, [mapRef, showControls, isMobile, ready]); useEffect(() => { - const map = mapRef?.current; - if ( - !map || - !ready || - didInitialFit || - markerQueries?.isFetching || - viewConfig.mapType === MapType.Hex - ) { + if (!ready || didInitialFit) { return; } - - const placedMarkerFeatures = placedMarkers?.length - ? placedMarkers.map((m) => ({ - type: "Feature" as const, - geometry: { - type: "Point" as const, - coordinates: [m.point.lng, m.point.lat], // [lng, lat] - }, - properties: {}, - })) - : []; - - const dataSourceMarkerFeatures = - markerQueries?.data.flatMap((d) => d.markers) || []; - - const features = [...placedMarkerFeatures, ...dataSourceMarkerFeatures]; - - if (features?.length) { - const [minLng, minLat, maxLng, maxLat] = turf?.bbox({ - type: "FeatureCollection", - features, - }); - - map.fitBounds( - [ - [minLng, minLat], - [maxLng, maxLat], - ], - { - padding: { - left: isMobile ? 0 : CONTROL_PANEL_WIDTH + 100, - right: isMobile ? 0 : 100, - top: isMobile ? 0 : 100, - bottom: isMobile ? 0 : 100, - }, - maxZoom: 12, - duration: 1000, - }, - ); + if (fitToAllMarkers()) { + setDidInitialFit(true); } - - setDidInitialFit(true); - }, [ - didInitialFit, - mapConfig.markerDataSourceIds, - mapConfig.membersDataSourceId, - mapRef, - markerQueries?.data, - markerQueries?.isFetching, - placedMarkers, - isMobile, - viewConfig.mapType, - ready, - ]); + }, [didInitialFit, fitToAllMarkers, ready]); return (
diff --git a/src/app/(private)/map/[id]/hooks/useFitToAllMarkers.ts b/src/app/(private)/map/[id]/hooks/useFitToAllMarkers.ts new file mode 100644 index 00000000..9d0d62c9 --- /dev/null +++ b/src/app/(private)/map/[id]/hooks/useFitToAllMarkers.ts @@ -0,0 +1,79 @@ +"use client"; + +import { bbox } from "@turf/turf"; +import { useCallback, useMemo } from "react"; +import { useIsMobileEffect } from "@/hooks/useIsMobile"; +import { MapType } from "@/models/MapView"; +import { CONTROL_PANEL_WIDTH } from "../styles"; +import { useMapRef } from "./useMapCore"; +import { useMapViews } from "./useMapViews"; +import { useMarkerQueries } from "./useMarkerQueries"; +import { usePlacedMarkersQuery } from "./usePlacedMarkers"; +import type { LngLatBoundsLike } from "mapbox-gl"; + +export function useFitPadding() { + const isMobile = useIsMobileEffect(); + return useMemo( + () => ({ + left: isMobile ? 0 : CONTROL_PANEL_WIDTH + 100, + right: isMobile ? 0 : 100, + top: isMobile ? 0 : 100, + bottom: isMobile ? 0 : 100, + }), + [isMobile], + ); +} + +/** + * Returns a function that fits the map to every marker (data source markers, + * matched or not, plus placed markers). Used for the initial map view, and to + * reset the view when filters are cleared. + * + * The function returns false if it couldn't run yet (map or markers still + * loading), so callers can retry once the data arrives. + */ +export function useFitToAllMarkers() { + const mapRef = useMapRef(); + const { viewConfig } = useMapViews(); + const markerQueries = useMarkerQueries(); + const { data: placedMarkers = [] } = usePlacedMarkersQuery(); + const padding = useFitPadding(); + + return useCallback((): boolean => { + const map = mapRef?.current; + if (!map || markerQueries.isFetching) { + return false; + } + // The hex map has a fixed view + if (viewConfig.mapType === MapType.Hex) { + return true; + } + + const placedMarkerFeatures = placedMarkers.map((m) => ({ + type: "Feature" as const, + geometry: { + type: "Point" as const, + coordinates: [m.point.lng, m.point.lat], // [lng, lat] + }, + properties: {}, + })); + const dataSourceMarkerFeatures = markerQueries.data.flatMap( + (d) => d.markers, + ); + const features = [...placedMarkerFeatures, ...dataSourceMarkerFeatures]; + if (!features.length) { + return true; + } + + const [minLng, minLat, maxLng, maxLat] = bbox({ + type: "FeatureCollection", + features, + }); + const bounds: LngLatBoundsLike = [ + [minLng, minLat], + [maxLng, maxLat], + ]; + map.fitBounds(bounds, { padding, maxZoom: 12, duration: 1000 }); + return true; + }, [mapRef, markerQueries, placedMarkers, padding, viewConfig.mapType]); +}