diff --git a/src/components/map/filters.test.ts b/src/components/map/filters.test.ts new file mode 100644 index 0000000..0300b92 --- /dev/null +++ b/src/components/map/filters.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; + +import { + IN_VIEW_AUTO_ZOOM, + filterByBounds, + inBounds, + sameBounds, + wantsInView, + type MapBounds, +} from "@/components/map/filters"; + +const LAGOS: MapBounds = { west: 3.0, south: 6.3, east: 3.7, north: 6.8 }; + +const place = (id: string, lat: number, lng: number) => ({ id, lat, lng }); + +describe("inBounds", () => { + it("includes a point inside and on the edge", () => { + expect(inBounds({ lat: 6.52, lng: 3.37 }, LAGOS)).toBe(true); + expect(inBounds({ lat: 6.3, lng: 3.0 }, LAGOS)).toBe(true); + expect(inBounds({ lat: 6.8, lng: 3.7 }, LAGOS)).toBe(true); + }); + + it("excludes points outside on either axis", () => { + expect(inBounds({ lat: 51.47, lng: -0.45 }, LAGOS)).toBe(false); + expect(inBounds({ lat: 6.52, lng: 4.0 }, LAGOS)).toBe(false); + expect(inBounds({ lat: 7.0, lng: 3.37 }, LAGOS)).toBe(false); + }); + + it("handles a view that crosses the antimeridian", () => { + const fiji: MapBounds = { west: 170, south: -25, east: 190, north: -10 }; + expect(inBounds({ lat: -18, lng: 178 }, fiji)).toBe(true); + expect(inBounds({ lat: -18, lng: -178 }, fiji)).toBe(true); + expect(inBounds({ lat: -18, lng: 160 }, fiji)).toBe(false); + expect(inBounds({ lat: -18, lng: -160 }, fiji)).toBe(false); + }); + + it("includes every longitude once the view is a full world wide", () => { + const world: MapBounds = { west: -200, south: -80, east: 200, north: 80 }; + expect(inBounds({ lat: 10, lng: 123 }, world)).toBe(true); + expect(inBounds({ lat: 85, lng: 123 }, world)).toBe(false); + }); +}); + +describe("filterByBounds", () => { + it("lists only the places in view, keeping their order", () => { + const places = [ + place("heathrow", 51.47, -0.45), + place("ikeja", 6.6, 3.34), + place("lekki", 6.45, 3.55), + place("jfk", 40.64, -73.78), + ]; + + expect(filterByBounds(places, LAGOS).map((p) => p.id)).toEqual(["ikeja", "lekki"]); + }); + + it("returns nothing when no place is in view", () => { + expect(filterByBounds([place("jfk", 40.64, -73.78)], LAGOS)).toEqual([]); + }); +}); + +describe("sameBounds", () => { + it("treats a tiny nudge as the same view", () => { + expect(sameBounds(LAGOS, { ...LAGOS, east: 3.7002 })).toBe(true); + }); + + it("treats a real pan as a different view", () => { + expect(sameBounds(LAGOS, { west: 8, south: 6.3, east: 8.7, north: 6.8 })).toBe(false); + }); +}); + +describe("wantsInView", () => { + it("follows the zoom when the visitor has not chosen", () => { + expect(wantsInView(null, IN_VIEW_AUTO_ZOOM - 1)).toBe(false); + expect(wantsInView(null, IN_VIEW_AUTO_ZOOM)).toBe(true); + }); + + it("obeys an explicit choice at any zoom", () => { + expect(wantsInView(true, 2)).toBe(true); + expect(wantsInView(false, 15)).toBe(false); + }); +}); diff --git a/src/components/map/filters.ts b/src/components/map/filters.ts index 8614cac..2c829c7 100644 --- a/src/components/map/filters.ts +++ b/src/components/map/filters.ts @@ -8,3 +8,50 @@ export interface PlaceFilters { country: string | null; query: string; } + +/** The visible map rectangle, in degrees. A view wider than the world reports `east - west` of 360 or more. */ +export interface MapBounds { + west: number; + south: number; + east: number; + north: number; +} + +/** Zoom at and above which the list follows the map by default (#351). Below it the map shows a whole region, so listing it all is the useful view. */ +export const IN_VIEW_AUTO_ZOOM = 8; + +/** Whether the "only places in this view" filter is on: the visitor's choice, else automatic from the zoom. */ +export function wantsInView(preference: boolean | null, zoom: number): boolean { + return preference ?? zoom >= IN_VIEW_AUTO_ZOOM; +} + +/** True when a point lies inside `bounds`, including a view that wraps past the antimeridian. */ +export function inBounds( + point: { lat: number; lng: number }, + bounds: MapBounds, +): boolean { + if (point.lat < bounds.south || point.lat > bounds.north) return false; + const span = bounds.east - bounds.west; + if (span >= 360) return true; + // Measure east of the west edge, wrapped into [0, 360), so lng 179 and -179 compare correctly. + const offset = (((point.lng - bounds.west) % 360) + 360) % 360; + return offset <= span; +} + +/** The places that fall inside `bounds`, in their original order. */ +export function filterByBounds( + places: readonly T[], + bounds: MapBounds, +): T[] { + return places.filter((place) => inBounds(place, bounds)); +} + +/** True when two views are the same to within `tolerance` degrees, so a nudge does not offer "Search this area". */ +export function sameBounds(a: MapBounds, b: MapBounds, tolerance = 0.0005): boolean { + return ( + Math.abs(a.west - b.west) <= tolerance && + Math.abs(a.south - b.south) <= tolerance && + Math.abs(a.east - b.east) <= tolerance && + Math.abs(a.north - b.north) <= tolerance + ); +} diff --git a/src/components/map/map-panel.tsx b/src/components/map/map-panel.tsx index 1b535b7..01ba478 100644 --- a/src/components/map/map-panel.tsx +++ b/src/components/map/map-panel.tsx @@ -19,6 +19,7 @@ import { ResultsList, type CompareControls, type ResultRow, + type ViewFilterControls, } from "@/components/map/results-list"; import type { PlaceFilters } from "@/components/map/filters"; import type { LatLng } from "@/lib/geo"; @@ -52,6 +53,10 @@ interface MapPanelProps { cityOptions?: City[]; typeCounts: Record; resultCount: number; + /** What `resultCount` counts: the places in the visible map area, or all places that match the filters. */ + resultScope?: "view" | "total"; + /** The "Only places in this view" switch and "Search this area" prompt; omitted to hide them. */ + viewFilter?: ViewFilterControls; rows: ResultRow[]; resultsHeader: string; @@ -88,6 +93,8 @@ export function MapPanel({ cityOptions, typeCounts, resultCount, + resultScope, + viewFilter, rows, resultsHeader, activeFilters, @@ -218,7 +225,12 @@ export function MapPanel({

- {resultCount} {resultCount === 1 ? "place" : "places"} shown + {resultCount} {resultCount === 1 ? "place" : "places"}{" "} + {resultScope === "view" + ? "in this view" + : resultScope === "total" + ? "total" + : "shown"}

({ flyTo: vi.fn() })); +const { flyTo, fitBounds, setView, setMinZoom } = vi.hoisted(() => ({ + flyTo: vi.fn(), + fitBounds: vi.fn(), + setView: vi.fn(), + setMinZoom: vi.fn(), +})); vi.mock("react-leaflet", async () => { const React = await import("react"); @@ -16,8 +21,11 @@ vi.mock("react-leaflet", async () => { }), getZoom: () => 18, getContainer: () => document.createElement("div"), - fitBounds: vi.fn(), + fitBounds, flyTo, + setView, + setMinZoom, + getBoundsZoom: () => 2, scrollWheelZoom: { disable: vi.fn(), enable: vi.fn(), enabled: () => false }, on: vi.fn(), off: vi.fn(), @@ -122,6 +130,96 @@ describe("MapView configuration", () => { }); }); +describe("MapView start view", () => { + const place = (id: string, lat: number, lng: number) => ({ + id, + name: id, + type: "library" as const, + city: "london", + lat, + lng, + gmaps_link: "", + added_by: "test", + }); + + function setup() { + vi.stubEnv("NEXT_PUBLIC_MAPTILER_KEY", "test-key"); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + fitBounds.mockClear(); + setView.mockClear(); + setMinZoom.mockClear(); + } + + it("caps the zoom when a search leaves a single place (#353)", () => { + setup(); + render(); + + expect(fitBounds).toHaveBeenCalledWith( + [ + [40.1, 33.0], + [40.1, 33.0], + ], + expect.objectContaining({ maxZoom: 16 }), + ); + }); + + it("caps the zoom lower when it fits several places (#353)", () => { + setup(); + render( + , + ); + + expect(fitBounds).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ maxZoom: 15 }), + ); + }); + + it("keeps the basemap covering the viewport with a minimum zoom (#350)", () => { + setup(); + render(); + + expect(setMinZoom).toHaveBeenCalledWith(2); + }); + + it("opens on the saved home instead of the whole world when nothing chose a view (#350)", () => { + setup(); + render( + , + ); + + expect(setView).toHaveBeenCalledTimes(1); + expect(setView).toHaveBeenCalledWith([6.52, 3.37], 11, { animate: false }); + expect(fitBounds).not.toHaveBeenCalled(); + }); + + it("ignores the saved home when a viewport was restored (#350)", () => { + setup(); + render( + , + ); + + expect(setView).not.toHaveBeenCalled(); + expect(fitBounds).not.toHaveBeenCalled(); + }); +}); + describe("pinIcon", () => { it("returns the same icon instance for the same place type", () => { expect(pinIcon("library")).toBe(pinIcon("library")); diff --git a/src/components/map/map-view.tsx b/src/components/map/map-view.tsx index 85a3685..13f5653 100644 --- a/src/components/map/map-view.tsx +++ b/src/components/map/map-view.tsx @@ -2,7 +2,7 @@ import "leaflet/dist/leaflet.css"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import L from "leaflet"; import Supercluster from "supercluster"; import { @@ -22,6 +22,8 @@ import type { Bounds } from "@/lib/places-utils"; import { densityCells, type HeatCell } from "@/lib/heatmap"; import { PLACE_TYPE_COLORS } from "@/lib/map"; import { PinPopup } from "@/components/pins/pin-popup"; +import { GO_TO_PLACE_ZOOM, HOME_ZOOM, fitMaxZoom } from "@/components/map/viewport"; +import type { MapBounds } from "@/components/map/filters"; type ClusterPointProps = { placeId: string; type: PlaceType }; type ClusterAggProps = Record; @@ -234,6 +236,8 @@ export interface MapViewport { lat: number; lng: number; zoom: number; + /** The visible rectangle. Reported by the map as it moves; absent on a viewport restored from the URL. */ + bounds?: MapBounds; } interface MapViewProps { @@ -252,6 +256,8 @@ interface MapViewProps { center: [number, number]; /** When set, the map starts at this viewport instead of fitting all places. */ initialViewport?: MapViewport | null; + /** True when nothing in the URL or storage chose a start view, so a signed-in visitor's home may (#350). */ + openOnHome?: boolean; /** Fired on pan/zoom end with the current center and zoom. */ onViewportChange?: (viewport: MapViewport) => void; /** Increment to imperatively close all open popups. */ @@ -313,13 +319,19 @@ function FlyToUser({ lat, lng }: { lat: number; lng: number }) { function FlyToPlace({ id, lat, lng }: { id: string; lat: number; lng: number }) { const map = useMap(); useEffect(() => { - map.flyTo([lat, lng], 15, { duration: 1, animate: !prefersReducedMotion() }); + map.flyTo([lat, lng], GO_TO_PLACE_ZOOM, { + duration: 1, + animate: !prefersReducedMotion(), + }); }, [map, id, lat, lng]); return null; } /** Fits the initial view to every place's extent, once, so the map opens - * showing the whole dataset instead of a fixed Mumbai-only crop. */ + * showing the whole dataset instead of a fixed Mumbai-only crop. A single + * place (for example a `?q=` search with one hit) has a zero-size extent, so + * the zoom is capped or Leaflet would fall back to its maximum, where the + * basemap is blank (#353). */ function FitAllOnMount({ places }: { places: Place[] }) { const map = useMap(); const fitted = useRef(false); @@ -333,12 +345,71 @@ function FitAllOnMount({ places }: { places: Place[] }) { [Math.min(...lats), Math.min(...lngs)], [Math.max(...lats), Math.max(...lngs)], ], - { padding: [32, 32] }, + { padding: [32, 32], maxZoom: fitMaxZoom(places.length) }, ); }, [map, places]); return null; } +/** + * Opens on the signed-in visitor's saved home instead of the whole world (#350). + * The home arrives after the map has mounted, so this jumps there once, without + * animation, and only if the visitor has not touched the map yet. + */ +function StartAtHome({ + lat, + lng, + onStarted, +}: { + lat: number; + lng: number; + /** Tells the parent the jump happened, so a later remount never repeats it. */ + onStarted: () => void; +}) { + const map = useMap(); + const touched = useRef(false); + const jumped = useRef(false); + useEffect(() => { + const container = map.getContainer(); + const mark = () => { + touched.current = true; + }; + container.addEventListener("pointerdown", mark, { once: true }); + container.addEventListener("keydown", mark, { once: true }); + return () => { + container.removeEventListener("pointerdown", mark); + container.removeEventListener("keydown", mark); + }; + }, [map]); + useEffect(() => { + if (jumped.current || touched.current) return; + jumped.current = true; + map.setView([lat, lng], HOME_ZOOM, { animate: false }); + onStarted(); + }, [map, lat, lng, onStarted]); + return null; +} + +/** + * Keeps the basemap covering the whole viewport. Without a minimum zoom the + * world can be zoomed out until grey strips show above and below the tiles + * (#350); the minimum is the smallest zoom at which the world still fills the + * container, and it follows the container size. + */ +function CoverViewportMinZoom() { + const map = useMap(); + useEffect(() => { + const world = L.latLngBounds([-85, -180], [85, 180]); + const apply = () => map.setMinZoom(map.getBoundsZoom(world, true)); + apply(); + map.on("resize", apply); + return () => { + map.off("resize", apply); + }; + }, [map]); + return null; +} + const HEAT_PANE = "studymap-heat"; const HEAT_CELL_PX = 48; @@ -478,12 +549,21 @@ function ViewportReporter({ useEffect(() => { function report() { const center = map.getCenter(); - const viewport = { + const view = map.getBounds(); + const round = (value: number) => Math.round(value * 1e4) / 1e4; + const viewport: MapViewport = { lat: Math.round(center.lat * 1e5) / 1e5, lng: Math.round(center.lng * 1e5) / 1e5, zoom: Math.round(map.getZoom() * 10) / 10, + bounds: { + west: round(view.getWest()), + south: round(view.getSouth()), + east: round(view.getEast()), + north: round(view.getNorth()), + }, }; - const key = `${viewport.lat},${viewport.lng},${viewport.zoom}`; + const b = viewport.bounds as MapBounds; + const key = `${viewport.lat},${viewport.lng},${viewport.zoom},${b.west},${b.south},${b.east},${b.north}`; if (key === last.current) return; last.current = key; onViewportChange(viewport); @@ -533,11 +613,15 @@ export default function MapView({ zoom, center, initialViewport = null, + openOnHome = false, onViewportChange, closePopupTrigger = 0, heatmap = false, }: MapViewProps) { const mapTilerKey = process.env.NEXT_PUBLIC_MAPTILER_KEY?.trim(); + // Set once the map has opened on the visitor's home, so a later filter change never jumps back. + const [homeStarted, setHomeStarted] = useState(false); + const markHomeStarted = useCallback(() => setHomeStarted(true), []); useEffect(() => { if ( @@ -604,6 +688,7 @@ export default function MapView({ {interactive && } + {interactive && } {interactive && onViewportChange && ( )} @@ -611,7 +696,17 @@ export default function MapView({ !userLocation && !focusPlace && !focusBounds && - !initialViewport && } + !initialViewport && + !(openOnHome && home) && } + {interactive && + openOnHome && + home && + !userLocation && + !focusPlace && + !focusBounds && + !homeStarted && ( + + )} {userLocation && } {focusPlace && ( diff --git a/src/components/map/places-map.test.tsx b/src/components/map/places-map.test.tsx index 1101b7f..9c420af 100644 --- a/src/components/map/places-map.test.tsx +++ b/src/components/map/places-map.test.tsx @@ -11,6 +11,7 @@ const { renderMap } = vi.hoisted(() => ({ places: Place[]; focusId: string | null; initialViewport: MapViewport | null; + onViewportChange?: (viewport: MapViewport) => void; }) => null >(() => null), })); @@ -415,3 +416,122 @@ describe("PlacesMap details and compare", () => { expect(screen.getByText("2 places side by side.")).toBeTruthy(); }); }); + +describe("PlacesMap list follows the map (#351)", () => { + const LAGOS = { west: 3.0, south: 6.3, east: 3.7, north: 6.8 }; + const LONDON = { west: -0.6, south: 51.3, east: 0.3, north: 51.7 }; + const WORLD: Place[] = [ + place({ id: "ikeja", name: "Ikeja Library", city: "lagos", lat: 6.6, lng: 3.34 }), + place({ id: "lekki", name: "Lekki Library", city: "lagos", lat: 6.45, lng: 3.55 }), + place({ + id: "heathrow", + name: "Heathrow Library", + city: "london", + lat: 51.47, + lng: -0.45, + }), + ]; + + function renderWorld() { + render( + , + ); + } + + function moveTo(bounds: typeof LAGOS, zoom: number) { + const onViewportChange = renderMap.mock.lastCall?.[0].onViewportChange; + act(() => { + onViewportChange?.({ + lat: (bounds.north + bounds.south) / 2, + lng: (bounds.east + bounds.west) / 2, + zoom, + bounds, + }); + }); + } + + afterEach(() => window.localStorage.clear()); + + it("lists every place, as a total, while the map is zoomed out", () => { + renderWorld(); + + moveTo({ west: -180, south: -80, east: 180, north: 80 }, 2); + + expect(screen.getByText("3 places total")).toBeTruthy(); + expect(screen.getByText("Heathrow Library")).toBeTruthy(); + expect(screen.getByText("Ikeja Library")).toBeTruthy(); + }); + + it("lists only the places in view once the map is zoomed in", () => { + renderWorld(); + + moveTo(LAGOS, 10); + + expect(screen.getByText("2 places in this view")).toBeTruthy(); + expect(screen.getByText("Ikeja Library")).toBeTruthy(); + expect(screen.queryByText("Heathrow Library")).toBeNull(); + }); + + it("does not reshuffle the list when the map moves, and offers Search this area instead", () => { + renderWorld(); + moveTo(LAGOS, 10); + expect(screen.queryByRole("button", { name: "Search this area" })).toBeNull(); + + moveTo(LONDON, 10); + + expect(screen.getByText("Ikeja Library")).toBeTruthy(); + expect(screen.queryByText("Heathrow Library")).toBeNull(); + expect(screen.getByRole("button", { name: "Search this area" })).toBeTruthy(); + }); + + it("lists the new area after Search this area is tapped", () => { + renderWorld(); + moveTo(LAGOS, 10); + moveTo(LONDON, 10); + + fireEvent.click(screen.getByRole("button", { name: "Search this area" })); + + expect(screen.getByText("1 place in this view")).toBeTruthy(); + expect(screen.getByText("Heathrow Library")).toBeTruthy(); + expect(screen.queryByText("Ikeja Library")).toBeNull(); + expect(screen.queryByRole("button", { name: "Search this area" })).toBeNull(); + }); + + it("goes back to every place when the switch is turned off", () => { + renderWorld(); + moveTo(LAGOS, 10); + + fireEvent.click(screen.getByRole("switch", { name: "Only places in this view" })); + + expect(screen.getByText("3 places total")).toBeTruthy(); + expect(screen.getByText("Heathrow Library")).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Search this area" })).toBeNull(); + }); + + it("keeps the filters applied inside the view", () => { + renderWorld(); + moveTo(LAGOS, 10); + + fireEvent.change(searchInputs()[0], { target: { value: "Lekki" } }); + advance(500); + + expect(screen.getByText("1 place in this view")).toBeTruthy(); + expect(screen.getByText("Lekki Library")).toBeTruthy(); + expect(screen.queryByText("Ikeja Library")).toBeNull(); + }); + + it("does not store the bounds in the URL", () => { + renderWorld(); + moveTo(LAGOS, 10); + advance(500); + + expect(params().get("lat")).toBe("6.55"); + expect(window.location.search).not.toContain("west"); + expect(window.location.search).not.toContain("bounds"); + }); +}); diff --git a/src/components/map/places-map.tsx b/src/components/map/places-map.tsx index 2247ab7..91a62f4 100644 --- a/src/components/map/places-map.tsx +++ b/src/components/map/places-map.tsx @@ -19,6 +19,7 @@ import { import { placesByDistance, type LatLng } from "@/lib/geo"; import { buildShareUrl, mapStateToSearch, parseMapState } from "@/lib/share"; import type { MapViewport } from "@/components/map/map-view"; +import { hasExplicitIntent, loadViewport, saveViewport } from "@/components/map/viewport"; import { createClient } from "@/lib/supabase/client"; import { isMissingTableError } from "@/lib/utils"; import { @@ -41,7 +42,13 @@ import { useMediaQuery } from "@/lib/use-media-query"; import { UserPlaceDialog } from "@/components/map/user-place-dialog"; import { UserHomeDialog } from "@/components/map/user-home-dialog"; import type { ResultRow } from "@/components/map/results-list"; -import type { PlaceFilters } from "@/components/map/filters"; +import { + filterByBounds, + sameBounds, + wantsInView, + type MapBounds, + type PlaceFilters, +} from "@/components/map/filters"; const MapView = dynamic(() => import("@/components/map/map-view"), { ssr: false, @@ -97,19 +104,48 @@ export function PlacesMap({ }); // A viewport in the URL restores that exact center/zoom on load instead of // fitting all places; it is then kept in sync as the user pans (see #118). + // Start view, first match wins (#350): an explicit URL viewport, then the + // place, search or filter the URL asked for (the map fits those itself), then + // wherever this visitor last left the map, then the saved home (below), then + // the whole dataset. const [viewport, setViewport] = React.useState(() => { if (typeof window === "undefined") return null; const state = parseMapState(window.location.search); - if (state.lat === null || state.lng === null) return null; - return { - lat: state.lat, - lng: state.lng, - zoom: state.zoom ?? defaultZoom, - }; + if (state.lat !== null && state.lng !== null) { + return { + lat: state.lat, + lng: state.lng, + zoom: state.zoom ?? defaultZoom, + }; + } + return hasExplicitIntent(state) ? null : loadViewport(); }); - const handleViewportChange = React.useCallback((next: MapViewport) => { - setViewport(next); - }, []); + // True only when nothing chose the start view, so a saved home is allowed to. + const [openOnHome] = React.useState(() => { + if (typeof window === "undefined") return false; + const state = parseMapState(window.location.search); + if (state.lat !== null && state.lng !== null) return false; + return !hasExplicitIntent(state) && loadViewport() === null; + }); + // "Only places in this view" (#351): null follows the zoom, true/false is the + // visitor's choice. The list is built for `appliedBounds`, which only moves + // when the visitor taps "Search this area" or flips the switch, so the list + // never reshuffles under their cursor while they scroll it. + const [inViewPref, setInViewPref] = React.useState(null); + const [appliedBounds, setAppliedBounds] = React.useState(null); + const handleViewportChange = React.useCallback( + (next: MapViewport) => { + setViewport(next); + saveViewport({ lat: next.lat, lng: next.lng, zoom: next.zoom }); + // The first time the list is meant to follow the map, pin it to this view. + setAppliedBounds( + (prev) => + prev ?? + (next.bounds && wantsInView(inViewPref, next.zoom) ? next.bounds : null), + ); + }, + [inViewPref], + ); const [userLocation, setUserLocation] = React.useState(null); const [closePopupTrigger, setClosePopupTrigger] = React.useState(0); const [heatmap, setHeatmap] = React.useState(false); @@ -263,10 +299,31 @@ export function PlacesMap({ [privatePlaces, cities], ); + const inViewOn = wantsInView(inViewPref, viewport?.zoom ?? defaultZoom); + const activeBounds = inViewOn ? appliedBounds : null; + // The places the list shows: those matching the filters, and, when the + // switch is on, only the ones inside the area the list was built for. + const listed = React.useMemo( + () => (activeBounds ? filterByBounds(visible, activeBounds) : visible), + [visible, activeBounds], + ); + const viewMoved = Boolean( + activeBounds && viewport?.bounds && !sameBounds(activeBounds, viewport.bounds), + ); + + function changeInView(on: boolean) { + setInViewPref(on); + if (on) setAppliedBounds(viewport?.bounds ?? null); + } + + function searchThisArea() { + setAppliedBounds(viewport?.bounds ?? null); + } + const byDistance = React.useMemo(() => { if (!userLocation) return []; - return placesByDistance(visible, userLocation); - }, [visible, userLocation]); + return placesByDistance(listed, userLocation); + }, [listed, userLocation]); // Build the results list: nearest-first when located, otherwise all visible. const { rows, resultsHeader, resultsToggle } = React.useMemo(() => { @@ -287,11 +344,11 @@ export function PlacesMap({ }; } return { - rows: visible.map((place) => ({ place })) as ResultRow[], + rows: listed.map((place) => ({ place })) as ResultRow[], resultsHeader: "All places", resultsToggle: null, }; - }, [userLocation, byDistance, sortByDistance, visible]); + }, [userLocation, byDistance, sortByDistance, listed]); function share() { const url = buildShareUrl({ @@ -436,7 +493,14 @@ export function PlacesMap({ cities, cityOptions: filterCities, typeCounts, - resultCount: visible.length, + resultCount: listed.length, + resultScope: (activeBounds ? "view" : "total") as "view" | "total", + viewFilter: { + checked: inViewOn, + onChange: changeInView, + moved: viewMoved, + onSearchArea: searchThisArea, + }, rows, resultsHeader, activeFilters, @@ -502,6 +566,7 @@ export function PlacesMap({ center={viewport ? [viewport.lat, viewport.lng] : defaultCenter} zoom={viewport?.zoom ?? defaultZoom} initialViewport={viewport} + openOnHome={openOnHome} onViewportChange={handleViewportChange} /> diff --git a/src/components/map/results-list.tsx b/src/components/map/results-list.tsx index 97bc6bb..58cde62 100644 --- a/src/components/map/results-list.tsx +++ b/src/components/map/results-list.tsx @@ -15,6 +15,7 @@ import { PLACE_TYPE_LABELS } from "@/lib/types"; import { directionsUrl } from "@/lib/map"; import { formatDistance } from "@/lib/geo"; import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; import { EmptyState } from "@/components/ui/empty-state"; import { CategoryIcon } from "@/components/map/category-icon"; import { VerifiedBadge } from "@/components/pins/verified-badge"; @@ -51,6 +52,17 @@ interface ResultsListProps { toggle?: { label: string; onClick: () => void } | null; /** Rows rendered at once; a "Show more" button reveals the next page. */ pageSize?: number; + /** Limits the list to the visible map area (#351). Omit to hide the control. */ + viewFilter?: ViewFilterControls; +} + +/** The "Only places in this view" switch and the "Search this area" prompt. */ +export interface ViewFilterControls { + checked: boolean; + onChange: (checked: boolean) => void; + /** True once the map has moved away from the area the list was built for. */ + moved: boolean; + onSearchArea: () => void; } /** Rows rendered before "Show more", so the unfiltered map does not build ~2,000 rows. */ @@ -67,8 +79,10 @@ export function ResultsList({ focusId, toggle, pageSize = RESULTS_PAGE_SIZE, + viewFilter, }: ResultsListProps) { const [limit, setLimit] = React.useState(pageSize); + const viewSwitchId = React.useId(); // A new result set (filter, search, nearest-first) starts again from the first page. const [seenRows, setSeenRows] = React.useState(rows); @@ -101,6 +115,36 @@ export function ResultsList({ )} + {viewFilter && ( +
+
+ + +
+ {viewFilter.checked && viewFilter.moved && ( + + )} +
+ )} + {compare && compare.selectedIds.length > 0 && (