From 93b9f3f28dff03cf971bf8a5e8e5a86695fa213d Mon Sep 17 00:00:00 2001 From: Mikhail Chandran Date: Tue, 24 Nov 2026 14:43:52 +0530 Subject: [PATCH 1/7] fix(map): cap the search zoom and open on the visitor's last or home view A search that leaves one place fitted a zero-size box and zoomed to level 19, where the basemap is blank. The fit is now capped (16 for one place, 15 for several) and the go-to-place zoom shares one constant. The map used to open on the whole world with grey bands above and below the tiles. It now keeps the basemap covering the viewport with a minimum zoom, reopens where the visitor last left it (localStorage, guarded), and opens on a signed-in visitor's saved home when nothing else chose a view. An explicit lat/lng/zoom, place, search or filter in the URL still wins, and nothing asks for geolocation on load. Closes #350 Closes #353 --- src/components/map/map-view.test.tsx | 102 ++++++++++++++++++++++++- src/components/map/map-view.tsx | 93 ++++++++++++++++++++-- src/components/map/places-map.tsx | 28 +++++-- src/components/map/viewport.test.ts | 110 +++++++++++++++++++++++++++ src/components/map/viewport.ts | 86 +++++++++++++++++++++ 5 files changed, 406 insertions(+), 13 deletions(-) create mode 100644 src/components/map/viewport.test.ts create mode 100644 src/components/map/viewport.ts diff --git a/src/components/map/map-view.test.tsx b/src/components/map/map-view.test.tsx index 2347f6f..4f69b84 100644 --- a/src/components/map/map-view.test.tsx +++ b/src/components/map/map-view.test.tsx @@ -3,7 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import MapView, { pinIcon } from "@/components/map/map-view"; -const { flyTo } = vi.hoisted(() => ({ 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..dd98c2a 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,7 @@ 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"; type ClusterPointProps = { placeId: string; type: PlaceType }; type ClusterAggProps = Record; @@ -252,6 +253,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 +316,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 +342,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; @@ -533,11 +601,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 +676,7 @@ export default function MapView({ {interactive && } + {interactive && } {interactive && onViewportChange && ( )} @@ -611,7 +684,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.tsx b/src/components/map/places-map.tsx index 2247ab7..fdeb78e 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 { @@ -97,18 +98,32 @@ 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(); + }); + // 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; }); const handleViewportChange = React.useCallback((next: MapViewport) => { setViewport(next); + saveViewport(next); }, []); const [userLocation, setUserLocation] = React.useState(null); const [closePopupTrigger, setClosePopupTrigger] = React.useState(0); @@ -502,6 +517,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/viewport.test.ts b/src/components/map/viewport.test.ts new file mode 100644 index 0000000..0991f63 --- /dev/null +++ b/src/components/map/viewport.test.ts @@ -0,0 +1,110 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + FIT_MAX_ZOOM, + GO_TO_PLACE_ZOOM, + fitMaxZoom, + hasExplicitIntent, + loadViewport, + parseStoredViewport, + saveViewport, +} from "@/components/map/viewport"; + +afterEach(() => { + vi.restoreAllMocks(); + window.localStorage.clear(); +}); + +describe("fitMaxZoom", () => { + it("lets a single place go to street level but never past the cap", () => { + expect(fitMaxZoom(1)).toBe(FIT_MAX_ZOOM); + expect(FIT_MAX_ZOOM).toBeLessThanOrEqual(16); + }); + + it("keeps a group of places at the go-to-place zoom or wider", () => { + expect(fitMaxZoom(2)).toBe(GO_TO_PLACE_ZOOM); + expect(fitMaxZoom(500)).toBe(GO_TO_PLACE_ZOOM); + }); + + it("treats an empty result like a single place", () => { + expect(fitMaxZoom(0)).toBe(FIT_MAX_ZOOM); + }); +}); + +describe("parseStoredViewport", () => { + it("accepts a valid viewport", () => { + expect(parseStoredViewport('{"lat":19.07,"lng":72.87,"zoom":11}')).toEqual({ + lat: 19.07, + lng: 72.87, + zoom: 11, + }); + }); + + it.each([ + [null], + [""], + ["not json"], + ["null"], + ["[]"], + ['{"lat":"1","lng":2,"zoom":3}'], + ['{"lat":91,"lng":0,"zoom":3}'], + ['{"lat":0,"lng":181,"zoom":3}'], + ['{"lat":0,"lng":0,"zoom":-1}'], + ['{"lat":0,"lng":0,"zoom":40}'], + ['{"lat":0,"lng":0}'], + ])("rejects %s", (raw) => { + expect(parseStoredViewport(raw)).toBeNull(); + }); +}); + +describe("loadViewport and saveViewport", () => { + it("round-trips a viewport", () => { + saveViewport({ lat: 6.52, lng: 3.37, zoom: 12 }); + expect(loadViewport()).toEqual({ lat: 6.52, lng: 3.37, zoom: 12 }); + }); + + it("returns null when nothing was saved", () => { + expect(loadViewport()).toBeNull(); + }); + + it("returns null instead of throwing when storage is blocked", () => { + vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { + throw new Error("blocked"); + }); + expect(loadViewport()).toBeNull(); + }); + + it("does not throw when saving to blocked storage", () => { + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new Error("quota"); + }); + expect(() => saveViewport({ lat: 1, lng: 2, zoom: 3 })).not.toThrow(); + }); +}); + +describe("hasExplicitIntent", () => { + it("is false for a bare /map", () => { + expect( + hasExplicitIntent({ + placeId: null, + query: "", + city: null, + country: null, + types: [], + }), + ).toBe(false); + }); + + it.each([ + [{ placeId: "x" }], + [{ query: "esenboga" }], + [{ city: "mumbai" }], + [{ country: "IN" }], + [{ types: ["library"] }], + ])("is true for %o", (intent) => { + expect(hasExplicitIntent(intent)).toBe(true); + }); + + it("ignores a whitespace-only query", () => { + expect(hasExplicitIntent({ query: " " })).toBe(false); + }); +}); diff --git a/src/components/map/viewport.ts b/src/components/map/viewport.ts new file mode 100644 index 0000000..4baf49a --- /dev/null +++ b/src/components/map/viewport.ts @@ -0,0 +1,86 @@ +/** + * Shared rules for where the map starts and how far it zooms to reach a place. + * Kept free of Leaflet and React so the rules can be unit-tested on their own. + */ + +/** Highest zoom a fit or search may reach. Streets and landmarks are still drawn here; above it the basemap thins out (#353). */ +export const FIT_MAX_ZOOM = 16; + +/** Zoom used when flying to one chosen place, and the cap when fitting several (#353). */ +export const GO_TO_PLACE_ZOOM = 15; + +/** Zoom used when the map opens on the signed-in user's saved home (#350). */ +export const HOME_ZOOM = 11; + +const STORAGE_KEY = "studymap:last-viewport"; + +export interface StoredViewport { + lat: number; + lng: number; + zoom: number; +} + +/** Highest zoom to allow when fitting `count` places: a lone place may go closer than a group. */ +export function fitMaxZoom(count: number): number { + return count <= 1 ? FIT_MAX_ZOOM : GO_TO_PLACE_ZOOM; +} + +/** Reads a stored viewport, returning null for anything missing, malformed or out of range. */ +export function parseStoredViewport( + raw: string | null | undefined, +): StoredViewport | null { + if (!raw) return null; + try { + const value: unknown = JSON.parse(raw); + if (typeof value !== "object" || value === null) return null; + const { lat, lng, zoom } = value as Record; + if (typeof lat !== "number" || typeof lng !== "number" || typeof zoom !== "number") { + return null; + } + if (!Number.isFinite(lat) || !Number.isFinite(lng) || !Number.isFinite(zoom)) + return null; + if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null; + if (zoom < 0 || zoom > 22) return null; + return { lat, lng, zoom }; + } catch { + return null; + } +} + +/** The viewport the visitor last used, or null when storage is empty, blocked or corrupt. */ +export function loadViewport(): StoredViewport | null { + try { + return parseStoredViewport(window.localStorage.getItem(STORAGE_KEY)); + } catch { + return null; + } +} + +/** Remembers the viewport for the next visit. Silent when storage is unavailable (private mode, blocked cookies). */ +export function saveViewport(viewport: StoredViewport): void { + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(viewport)); + } catch { + // Storage can be full or blocked; the map still works without it. + } +} + +/** URL state that expresses an explicit intent, which must win over a remembered viewport. */ +export interface StartIntent { + placeId?: string | null; + query?: string; + city?: string | null; + country?: string | null; + types?: readonly string[]; +} + +/** True when the URL asks for something specific, so the last-used viewport should not override it. */ +export function hasExplicitIntent(intent: StartIntent): boolean { + return Boolean( + intent.placeId || + (intent.query && intent.query.trim()) || + intent.city || + intent.country || + (intent.types && intent.types.length > 0), + ); +} From 9e2e7a88db7369682cf7e36dbab17792d0702b50 Mon Sep 17 00:00:00 2001 From: Mikhail Chandran Date: Tue, 24 Nov 2026 14:48:11 +0530 Subject: [PATCH 2/7] feat(map): show city and country on result rows and let names wrap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rows showed only the type, so two places sharing a name prefix could not be told apart. The second line is now 'type · city, country' (distance last when known), the name may take two lines before truncating, and the three row actions are 44px touch targets below the lg sidebar breakpoint. Their aria-labels are unchanged. Closes #354 --- src/components/map/filter-presets.test.tsx | 42 -------- src/components/map/filter-presets.tsx | 68 ------------- src/components/map/results-list.test.tsx | 110 +++++++++++++++++++++ src/components/map/results-list.tsx | 23 +++-- 4 files changed, 127 insertions(+), 116 deletions(-) delete mode 100644 src/components/map/filter-presets.test.tsx delete mode 100644 src/components/map/filter-presets.tsx diff --git a/src/components/map/filter-presets.test.tsx b/src/components/map/filter-presets.test.tsx deleted file mode 100644 index 1d52bd1..0000000 --- a/src/components/map/filter-presets.test.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { FilterPresets } from "@/components/map/filter-presets"; - -afterEach(cleanup); - -describe("FilterPresets", () => { - it("lists the preset buttons in a labelled group", () => { - render(); - - const group = screen.getByRole("group", { name: "Filter presets" }); - expect(group).toBeTruthy(); - for (const label of [ - "Libraries", - "SAT centres", - "Exam centres", - "Govt offices", - "Airports", - ]) { - expect(screen.getByRole("button", { name: label })).toBeTruthy(); - } - }); - - it("applies one type for a single-type preset", () => { - const onApply = vi.fn(); - render(); - - fireEvent.click(screen.getByRole("button", { name: "Airports" })); - - expect(onApply).toHaveBeenCalledWith(["airport"]); - }); - - it("applies both exam types for the Exam centres preset", () => { - const onApply = vi.fn(); - render(); - - fireEvent.click(screen.getByRole("button", { name: "Exam centres" })); - - expect(onApply).toHaveBeenCalledWith(["sat_centre", "foreign_lang_exam_centre"]); - }); -}); diff --git a/src/components/map/filter-presets.tsx b/src/components/map/filter-presets.tsx deleted file mode 100644 index 22d6c92..0000000 --- a/src/components/map/filter-presets.tsx +++ /dev/null @@ -1,68 +0,0 @@ -"use client"; - -import { ClipboardCheck, GraduationCap, Landmark, Library, Plane } from "lucide-react"; -import type { LucideIcon } from "lucide-react"; - -import type { PlaceType } from "@/lib/types"; -import { Button } from "@/components/ui/button"; -import { cn } from "@/lib/utils"; - -interface FilterPreset { - label: string; - types: PlaceType[]; - icon: LucideIcon; -} - -/** - * Common filter combos, built from the real `PlaceType`s only (no invented - * categories). "Exam centres" is the one combo that spans two types - - * SAT and foreign-language exam centres are both "somewhere a student sits - * a timed exam", which is a distinct use case from a single-type filter. - */ -const FILTER_PRESETS: FilterPreset[] = [ - { label: "Libraries", types: ["library"], icon: Library }, - { label: "SAT centres", types: ["sat_centre"], icon: GraduationCap }, - { - label: "Exam centres", - types: ["sat_centre", "foreign_lang_exam_centre"], - icon: ClipboardCheck, - }, - { label: "Govt offices", types: ["gov_offices"], icon: Landmark }, - { label: "Airports", types: ["airport"], icon: Plane }, -]; - -interface FilterPresetsProps { - onApply: (types: PlaceType[]) => void; - className?: string; -} - -/** - * One-tap buttons for common filter combos, so a student doesn't have to - * rebuild "SAT + foreign-lang exam centres" from the category chips every - * time. Each preset replaces the active type filter with its own list. - */ -export function FilterPresets({ onApply, className }: FilterPresetsProps) { - return ( -
- {FILTER_PRESETS.map((preset) => { - const Icon = preset.icon; - return ( - - ); - })} -
- ); -} diff --git a/src/components/map/results-list.test.tsx b/src/components/map/results-list.test.tsx index ecbbb83..9801b5f 100644 --- a/src/components/map/results-list.test.tsx +++ b/src/components/map/results-list.test.tsx @@ -289,3 +289,113 @@ describe("ResultsList details and compare", () => { expect(onToggle).toHaveBeenCalledWith(expect.objectContaining({ id: "p1" })); }); }); + +describe("ResultsList row location (#354)", () => { + const base = { + type: "airport" as const, + lat: 19, + lng: 72, + gmaps_link: "https://maps.google.com/?q=19,72", + added_by: "test", + }; + const emptyState = { activeFilters: [], onReset: vi.fn(), onSuggest: vi.fn() }; + + it("tells two places with the same name apart by city and country", () => { + render( + , + ); + + expect(screen.getByText(/Airport · Mumbai, India/)).toBeTruthy(); + expect(screen.getByText(/Airport · Nagpur, India/)).toBeTruthy(); + }); + + it("puts the distance after the location when it is known", () => { + render( + , + ); + + expect(screen.getByText(/Airport · London, United Kingdom · /)).toBeTruthy(); + }); + + it("omits the country, with no stray comma, for a private place that has none", () => { + render( + , + ); + + expect(screen.getByText("Airport · Thane")).toBeTruthy(); + }); + + it("lets the name wrap to two lines instead of truncating to one", () => { + render( + , + ); + + const name = screen.getByText("A very long place name"); + expect(name.className).toContain("line-clamp-2"); + expect(name.className).not.toContain("truncate"); + }); + + it("keeps the accessible names of the row actions", () => { + render( + , + ); + + expect(screen.getByRole("button", { name: "Details for Heathrow" })).toBeTruthy(); + expect( + screen.getByRole("link", { name: "Open Heathrow in Google Maps" }), + ).toBeTruthy(); + expect(screen.getByRole("link", { name: "Directions to Heathrow" })).toBeTruthy(); + }); +}); diff --git a/src/components/map/results-list.tsx b/src/components/map/results-list.tsx index 97bc6bb..5165888 100644 --- a/src/components/map/results-list.tsx +++ b/src/components/map/results-list.tsx @@ -11,7 +11,8 @@ import { } from "lucide-react"; import type { Place } from "@/lib/types"; -import { PLACE_TYPE_LABELS } from "@/lib/types"; +import { PLACE_TYPE_LABELS, humanizeCity } from "@/lib/types"; +import { countryName } from "@/lib/places-utils"; import { directionsUrl } from "@/lib/map"; import { formatDistance } from "@/lib/geo"; import { Button } from "@/components/ui/button"; @@ -53,6 +54,16 @@ interface ResultsListProps { pageSize?: number; } +/** "Mumbai, India": the city and, when the place has one, its country, so same-named places are told apart (#354). */ +export function placeLocationLabel(place: Place): string { + const city = humanizeCity(place.city); + return place.country ? `${city}, ${countryName(place.country)}` : city; +} + +/** Touch-sized (44px) below the `lg` sidebar breakpoint, where the list sits in the mobile sheet. */ +const ROW_ACTION_CLASS = + "flex min-h-11 min-w-11 shrink-0 items-center justify-center rounded-md p-2 text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:bg-background focus-visible:text-foreground lg:min-h-0 lg:min-w-0"; + /** Rows rendered before "Show more", so the unfiltered map does not build ~2,000 rows. */ export const RESULTS_PAGE_SIZE = 100; @@ -187,13 +198,13 @@ export function ResultsList({ title={`${place.name} (${PLACE_TYPE_LABELS[place.type]})`} > - + {place.name} - {PLACE_TYPE_LABELS[place.type]} + {PLACE_TYPE_LABELS[place.type]} · {placeLocationLabel(place)} {distanceKm !== undefined && ` · ${formatDistance(distanceKm)}`} @@ -202,7 +213,7 @@ export function ResultsList({ type="button" onClick={() => onDetails(place)} aria-label={"Details for " + place.name} - className="shrink-0 rounded-md p-2 text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:bg-background focus-visible:text-foreground" + className={ROW_ACTION_CLASS} > @@ -214,7 +225,7 @@ export function ResultsList({ rel="noreferrer" onClick={(e) => e.stopPropagation()} aria-label={`Open ${place.name} in Google Maps`} - className="shrink-0 rounded-md p-2 text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:bg-background focus-visible:text-foreground" + className={ROW_ACTION_CLASS} > @@ -225,7 +236,7 @@ export function ResultsList({ rel="noreferrer" onClick={(e) => e.stopPropagation()} aria-label={`Directions to ${place.name}`} - className="shrink-0 rounded-md p-2 text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:bg-background focus-visible:text-foreground" + className={ROW_ACTION_CLASS} > From bd980cfa1206f32de24fc9b7722e77d7750dc661 Mon Sep 17 00:00:00 2001 From: Mikhail Chandran Date: Tue, 24 Nov 2026 14:48:11 +0530 Subject: [PATCH 3/7] refactor(map): merge the category chips and filter presets into one filter row Chips and presets both set the same types filter under different labels. The chip row stays (it carries counts and the pin colours), the one combo chips cannot express, SAT plus foreign-language exam centres, becomes a leading 'All exam centres' chip, and the single-type presets go. The row gains an 'N categories selected' line with Clear, and the scrolling row fades its right edge instead of clipping a chip. Labels come from PLACE_TYPE_LABELS only. Closes #352 --- src/components/map/category-chips.test.tsx | 153 +++++++++++++++++++ src/components/map/category-chips.tsx | 166 +++++++++++++++------ src/components/map/map-panel.tsx | 5 +- src/components/map/places-map.test.tsx | 30 +++- 4 files changed, 305 insertions(+), 49 deletions(-) create mode 100644 src/components/map/category-chips.test.tsx diff --git a/src/components/map/category-chips.test.tsx b/src/components/map/category-chips.test.tsx new file mode 100644 index 0000000..e4d225a --- /dev/null +++ b/src/components/map/category-chips.test.tsx @@ -0,0 +1,153 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { CategoryChips, EXAM_COMBO, matchesCombo } from "@/components/map/category-chips"; +import { PLACE_TYPES, PLACE_TYPE_LABELS } from "@/lib/types"; +import type { PlaceType } from "@/lib/types"; + +afterEach(cleanup); + +const counts = Object.fromEntries(PLACE_TYPES.map((type, i) => [type, i + 1])) as Record< + PlaceType, + number +>; + +describe("CategoryChips (#352)", () => { + it("renders one chip per type, labelled exactly as PLACE_TYPE_LABELS", () => { + render(); + + const group = screen.getByRole("group", { name: "Filter by place type" }); + for (const type of PLACE_TYPES) { + expect(group.textContent).toContain(PLACE_TYPE_LABELS[type]); + } + }); + + it("is the only filter row: no second preset group", () => { + render( + , + ); + + expect(screen.queryByRole("group", { name: "Filter presets" })).toBeNull(); + expect(screen.getAllByRole("group")).toHaveLength(1); + }); + + it("toggles a single type", () => { + const onToggle = vi.fn(); + render(); + + fireEvent.click( + screen.getByRole("button", { name: new RegExp(PLACE_TYPE_LABELS.airport) }), + ); + + expect(onToggle).toHaveBeenCalledWith("airport"); + }); + + it("offers the exam-centres combo only when onSetTypes is given", () => { + const { rerender } = render( + , + ); + expect(screen.queryByRole("button", { name: /All exam centres/ })).toBeNull(); + + rerender( + , + ); + expect(screen.getByRole("button", { name: /All exam centres/ })).toBeTruthy(); + }); + + it("selects both exam types from the combo chip, and clears them on a second tap", () => { + const onSetTypes = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getByRole("button", { name: /All exam centres/ })); + expect(onSetTypes).toHaveBeenLastCalledWith([...EXAM_COMBO]); + + rerender( + , + ); + const chip = screen.getByRole("button", { name: /All exam centres/ }); + expect(chip.getAttribute("aria-pressed")).toBe("true"); + fireEvent.click(chip); + expect(onSetTypes).toHaveBeenLastCalledWith([]); + }); + + it("shows a selected count and a Clear action only while something is selected", () => { + const onClear = vi.fn(); + const { rerender } = render( + , + ); + expect(screen.queryByRole("button", { name: "Clear" })).toBeNull(); + + rerender( + , + ); + expect(screen.getByText(/2 categories selected/)).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Clear" })); + expect(onClear).toHaveBeenCalledOnce(); + }); + + it("uses the singular for one selected category", () => { + render( + , + ); + expect(screen.getByText(/1 category selected/)).toBeTruthy(); + }); + + it("fades the right edge of the scrolling row instead of clipping a chip", () => { + render(); + + const group = screen.getByRole("group", { name: "Filter by place type" }); + expect(group.className).toContain("overflow-x-auto"); + expect(group.className).toContain("mask-image"); + }); +}); + +describe("matchesCombo", () => { + it("matches the same types in any order", () => { + expect(matchesCombo(["foreign_lang_exam_centre", "sat_centre"], EXAM_COMBO)).toBe( + true, + ); + }); + + it("does not match a subset, a superset or an empty selection", () => { + expect(matchesCombo(["sat_centre"], EXAM_COMBO)).toBe(false); + expect(matchesCombo([...EXAM_COMBO, "library"], EXAM_COMBO)).toBe(false); + expect(matchesCombo([], EXAM_COMBO)).toBe(false); + }); +}); diff --git a/src/components/map/category-chips.tsx b/src/components/map/category-chips.tsx index cce94e3..44ecb09 100644 --- a/src/components/map/category-chips.tsx +++ b/src/components/map/category-chips.tsx @@ -5,10 +5,35 @@ import type { PlaceType } from "@/lib/types"; import { PLACE_TYPE_COLORS } from "@/lib/map"; import { cn } from "@/lib/utils"; +/** + * A multi-type shortcut that single-type chips cannot express: SAT and + * foreign-language exam centres are both "somewhere a student sits a timed + * exam". It is the only combo, so it sits in front of the chips instead of in a + * second filter bar (#352). + */ +export const EXAM_COMBO: readonly PlaceType[] = [ + "sat_centre", + "foreign_lang_exam_centre", +]; + +/** True when `selected` is exactly `combo`, in any order. */ +export function matchesCombo( + selected: readonly PlaceType[], + combo: readonly PlaceType[], +) { + return ( + selected.length === combo.length && combo.every((type) => selected.includes(type)) + ); +} + interface CategoryChipsProps { selected: PlaceType[]; counts: Record; onToggle: (type: PlaceType) => void; + /** Replaces the whole type selection; enables the leading exam-centres chip. */ + onSetTypes?: (types: PlaceType[]) => void; + /** Clears the type selection; enables the "N selected, Clear" line. */ + onClear?: () => void; /** When true, lay out as a single horizontally scrolling row (mobile). */ scroll?: boolean; } @@ -16,61 +41,116 @@ interface CategoryChipsProps { /** * Category filters as colour-coded toggle chips. Each chip doubles as the map * legend (colour dot matches the pin) and shows how many of that type are - * currently visible. Selecting none means everything shows. + * currently visible. Selecting none means everything shows. The label of every + * chip is the one used everywhere else for that type (`PLACE_TYPE_LABELS`). */ export function CategoryChips({ selected, counts, onToggle, + onSetTypes, + onClear, scroll = false, }: CategoryChipsProps) { + const examCount = EXAM_COMBO.reduce((sum, type) => sum + counts[type], 0); + const examActive = matchesCombo(selected, EXAM_COMBO); + return ( -
- {PLACE_TYPES.map((type) => { - const active = selected.includes(type); - const color = PLACE_TYPE_COLORS[type]; - return ( +
+ {onClear && selected.length > 0 && ( +
+ + {selected.length} {selected.length === 1 ? "category" : "categories"} selected + - ); - })} +
+ )} +
+ {onSetTypes && ( + PLACE_TYPE_LABELS[type]).join(" + ")} + count={examCount} + onClick={() => onSetTypes(examActive ? [] : [...EXAM_COMBO])} + /> + )} + {PLACE_TYPES.map((type) => ( + onToggle(type)} + /> + ))} +
); } + +function Chip({ + active, + color, + label, + title, + count, + onClick, +}: { + active: boolean; + color: string; + label: string; + title?: string; + count: number; + onClick: () => void; +}) { + return ( + + ); +} diff --git a/src/components/map/map-panel.tsx b/src/components/map/map-panel.tsx index 1b535b7..0ab89d4 100644 --- a/src/components/map/map-panel.tsx +++ b/src/components/map/map-panel.tsx @@ -8,7 +8,6 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Separator } from "@/components/ui/separator"; import { CategoryChips } from "@/components/map/category-chips"; -import { FilterPresets } from "@/components/map/filter-presets"; import { CityFilter } from "@/components/map/city-filter"; import { CountryFilter } from "@/components/map/country-filter"; import { NearMeButton } from "@/components/map/near-me-button"; @@ -139,11 +138,11 @@ export function MapPanel({ selected={filters.types} counts={typeCounts} onToggle={toggleType} + onSetTypes={(types) => onFiltersChange({ ...filters, types })} + onClear={() => onFiltersChange({ ...filters, types: [] })} scroll={scrollChips} /> - onFiltersChange({ ...filters, types })} /> -
{ }); }); -describe("PlacesMap filter presets", () => { - it("narrows the results to the preset's type and sets it in the URL", () => { +describe("PlacesMap category filter", () => { + function renderMap() { render( { defaultZoom={11} />, ); + } + + it("narrows the results to the chosen type and sets it in the URL", () => { + renderMap(); expect(screen.getByText("City Library")).toBeTruthy(); - fireEvent.click(screen.getByRole("button", { name: "Airports" })); + fireEvent.click(screen.getByRole("button", { name: /^Airport/ })); expect(screen.getByText("City Airport")).toBeTruthy(); expect(screen.queryByText("City Library")).toBeNull(); @@ -320,6 +324,26 @@ describe("PlacesMap filter presets", () => { advance(500); expect(params().get("types")).toBe("airport"); }); + + it("has one filter row, not a second row of presets (#352)", () => { + renderMap(); + + expect(screen.queryByRole("group", { name: "Filter presets" })).toBeNull(); + expect(screen.getAllByRole("group", { name: "Filter by place type" })).toHaveLength( + 1, + ); + }); + + it("shows how many categories are selected and clears them", () => { + renderMap(); + fireEvent.click(screen.getByRole("button", { name: /^Airport/ })); + expect(screen.getByText(/1 category selected/)).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "Clear" })); + + expect(screen.queryByText(/category selected/)).toBeNull(); + expect(screen.getByText("City Library")).toBeTruthy(); + }); }); describe("PlacesMap country filter", () => { From faef1070ba4540262afcc956b8dbbdc815a561d1 Mon Sep 17 00:00:00 2001 From: Mikhail Chandran Date: Tue, 24 Nov 2026 14:52:09 +0530 Subject: [PATCH 4/7] feat(map): list only the places in the visible map area, with a Search this area prompt The results list was driven by filters only, so panning to Lagos still listed Heathrow first. An 'Only places in this view' switch (on by default from zoom 8) limits the list to the area the map showed, and the header now reads 'N places in this view' or 'N places total'. The list is pinned to one area: moving the map shows a 'Search this area' button instead of re-sorting rows under the visitor's cursor mid-scroll. Nearest-first still applies when a location is set. The map now reports its visible bounds; they are kept out of the URL and storage. Works in the desktop panel and the mobile sheet, which share one MapPanel. Closes #351 --- src/components/map/filters.test.ts | 81 +++++++++++++++++ src/components/map/filters.ts | 47 ++++++++++ src/components/map/map-panel.tsx | 15 +++- src/components/map/map-view.tsx | 16 +++- src/components/map/places-map.test.tsx | 120 +++++++++++++++++++++++++ src/components/map/places-map.tsx | 69 +++++++++++--- src/components/map/results-list.tsx | 44 +++++++++ 7 files changed, 379 insertions(+), 13 deletions(-) create mode 100644 src/components/map/filters.test.ts 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"}

; @@ -235,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 { @@ -546,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); 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 fdeb78e..91a62f4 100644 --- a/src/components/map/places-map.tsx +++ b/src/components/map/places-map.tsx @@ -42,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, @@ -121,10 +127,25 @@ export function PlacesMap({ if (state.lat !== null && state.lng !== null) return false; return !hasExplicitIntent(state) && loadViewport() === null; }); - const handleViewportChange = React.useCallback((next: MapViewport) => { - setViewport(next); - saveViewport(next); - }, []); + // "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); @@ -278,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(() => { @@ -302,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({ @@ -451,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, 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 && (