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
81 changes: 81 additions & 0 deletions src/components/map/filters.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
47 changes: 47 additions & 0 deletions src/components/map/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends { lat: number; lng: number }>(
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
);
}
15 changes: 14 additions & 1 deletion src/components/map/map-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -52,6 +53,10 @@ interface MapPanelProps {
cityOptions?: City[];
typeCounts: Record<PlaceType, number>;
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;
Expand Down Expand Up @@ -88,6 +93,8 @@ export function MapPanel({
cityOptions,
typeCounts,
resultCount,
resultScope,
viewFilter,
rows,
resultsHeader,
activeFilters,
Expand Down Expand Up @@ -218,7 +225,12 @@ export function MapPanel({
<Separator />

<p className="text-xs font-semibold text-foreground">
{resultCount} {resultCount === 1 ? "place" : "places"} shown
{resultCount} {resultCount === 1 ? "place" : "places"}{" "}
{resultScope === "view"
? "in this view"
: resultScope === "total"
? "total"
: "shown"}
</p>

<ResultsList
Expand All @@ -234,6 +246,7 @@ export function MapPanel({
compare={compare}
focusId={focusId}
toggle={resultsToggle}
viewFilter={viewFilter}
/>

<SuggestPlaceDialog
Expand Down
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
Loading
Loading