Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 100 additions & 2 deletions src/components/map/map-view.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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(),
Expand Down Expand Up @@ -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(<MapView {...VIEW} places={[place("one", 40.1, 33.0)]} />);

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(
<MapView {...VIEW} places={[place("a", 51.5, -0.1), place("b", 51.6, -0.2)]} />,
);

expect(fitBounds).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ maxZoom: 15 }),
);
});

it("keeps the basemap covering the viewport with a minimum zoom (#350)", () => {
setup();
render(<MapView {...VIEW} places={[]} />);

expect(setMinZoom).toHaveBeenCalledWith(2);
});

it("opens on the saved home instead of the whole world when nothing chose a view (#350)", () => {
setup();
render(
<MapView
{...VIEW}
places={[place("a", 51.5, -0.1)]}
home={{ lat: 6.52, lng: 3.37 }}
openOnHome
/>,
);

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(
<MapView
{...VIEW}
places={[place("a", 51.5, -0.1)]}
home={{ lat: 6.52, lng: 3.37 }}
initialViewport={{ lat: 1, lng: 2, zoom: 5 }}
/>,
);

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"));
Expand Down
93 changes: 88 additions & 5 deletions src/components/map/map-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<PlaceType, number>;
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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);
Expand All @@ -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;

Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -604,14 +676,25 @@ export default function MapView({
<MapResizeHandler />
<ClosePopupOnTrigger trigger={closePopupTrigger} />
{interactive && <ScrollZoomGuard />}
{interactive && <CoverViewportMinZoom />}
{interactive && onViewportChange && (
<ViewportReporter onViewportChange={onViewportChange} />
)}
{interactive &&
!userLocation &&
!focusPlace &&
!focusBounds &&
!initialViewport && <FitAllOnMount places={places} />}
!initialViewport &&
!(openOnHome && home) && <FitAllOnMount places={places} />}
{interactive &&
openOnHome &&
home &&
!userLocation &&
!focusPlace &&
!focusBounds &&
!homeStarted && (
<StartAtHome lat={home.lat} lng={home.lng} onStarted={markHomeStarted} />
)}

{userLocation && <FlyToUser lat={userLocation.lat} lng={userLocation.lng} />}
{focusPlace && (
Expand Down
28 changes: 22 additions & 6 deletions src/components/map/places-map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<MapViewport | null>(() => {
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<LatLng | null>(null);
const [closePopupTrigger, setClosePopupTrigger] = React.useState(0);
Expand Down Expand Up @@ -502,6 +517,7 @@ export function PlacesMap({
center={viewport ? [viewport.lat, viewport.lng] : defaultCenter}
zoom={viewport?.zoom ?? defaultZoom}
initialViewport={viewport}
openOnHome={openOnHome}
onViewportChange={handleViewportChange}
/>
</MapErrorBoundary>
Expand Down
Loading
Loading