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),
+ );
+}