import { create } from "@bufbuild/protobuf"; import type L from "leaflet"; import { CrosshairIcon, MinusIcon, PlusIcon } from "lucide-react"; import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "react-hot-toast"; import { useLocation, useNavigate } from "react-router-dom"; import { getLocationCoordinatesText } from "@/components/MemoMetadata/Location/locationHelpers"; import { MEMO_PANEL_INSET, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList, type MemoPanelSize } from "@/components/MemoPanel"; import { createMemoNavigationState } from "@/components/MemoView/navigation"; import { Button, buttonVariants } from "@/components/ui/button"; import { useMemoFilterContext } from "@/contexts/MemoFilterContext"; import { useSpaceContext } from "@/contexts/SpaceContext"; import useCurrentUser from "@/hooks/useCurrentUser"; import useMediaQuery from "@/hooks/useMediaQuery"; import { cn } from "@/lib/utils"; import { LocationSchema } from "@/types/proto/api/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; import { fitMemos, MapCanvas } from "./MapCanvas"; import { locationKey, type MapViewport, pointLabel, readViewport, splitLabel } from "./model"; import { useMapMemos } from "./useMapMemos"; import { useMapPins } from "./useMapPins"; /** Enough map beside the card to keep a selection visible. */ const RESERVED_BESIDE_PANEL = 160; export function MapView() { const t = useTranslate(); const location = useLocation(); const navigate = useNavigate(); const routeRef = useRef(location); routeRef.current = location; const desktop = useMediaQuery("md"); const { selectedSpaceName, creatorUsername } = useSpaceContext(); const user = useCurrentUser(); const { filters, removeFilter } = useMemoFilterContext(); const query = useMapMemos(); const pins = useMapPins(query.memos, !creatorUsername); const mapRef = useRef(null); const [panelSize, setPanelSize] = useState({ width: 0, height: 0 }); // Only a real change may re-render the map tree. const onPanelSize = useCallback( (next: MemoPanelSize) => setPanelSize((prev) => { const width = Math.round(next.width); const height = Math.round(next.height); return prev.width === width && prev.height === height ? prev : { width, height }; }), [], ); const [tileError, setTileError] = useState(false); const [saving, setSaving] = useState(false); const [composing, setComposing] = useState(false); const viewport = readViewport(location.search); // Selection is keyed by its joined names so panning, which rewrites the search, leaves it identity-stable. const selectedKey = new URLSearchParams(location.search).getAll("memo").join("|"); const selected = useMemo(() => (selectedKey ? selectedKey.split("|") : []), [selectedKey]); const selectedMemos = useMemo(() => { const names = new Set(selected); return query.memos.filter((memo) => names.has(memo.name)); }, [query.memos, selected]); const singlePoint = selectedMemos.length > 0 && selectedMemos.every((memo) => locationKey(memo.location!) === locationKey(selectedMemos[0].location!)) ? selectedMemos[0].location : undefined; const open = selected.length > 0; const updateQuery = useCallback( (change: (params: URLSearchParams) => void, replace = false) => { const current = routeRef.current; const next = new URLSearchParams(current.search); change(next); const search = next.toString(); if (search !== current.search.replace(/^\?/, "")) { const nextLocation = { ...current, search: search ? `?${search}` : "" }; routeRef.current = nextLocation; navigate({ pathname: current.pathname, search, hash: current.hash }, { replace, state: current.state }); } }, [navigate], ); const onMove = useCallback( (next: MapViewport) => updateQuery((search) => { search.set("lat", next.lat.toFixed(6)); search.set("lng", next.lng.toFixed(6)); search.set("zoom", String(next.zoom)); }, true), [updateQuery], ); const onReady = useCallback((map: L.Map | null) => { mapRef.current = map; }, []); const onSelect = (names: string[]) => { if (saving) return; updateQuery((search) => { search.delete("memo"); names.forEach((name) => search.append("memo", name)); }); }; const clearSelection = () => { if (saving) return; updateQuery((search) => search.delete("memo")); }; // Do not remove a deep-linked selection until all pages have arrived. useEffect(() => { if (!query.complete || !selected.length) return; const available = new Set(query.memos.map((memo) => memo.name)); if (selected.some((name) => !available.has(name))) { updateQuery((search) => { const keep = search.getAll("memo").filter((name) => available.has(name)); search.delete("memo"); keep.forEach((name) => search.append("memo", name)); }, true); } }, [query.complete, query.memos, selected, updateQuery]); // A place label is its author's words: the title uses one only when it speaks for every memo // there, and a new memo only inherits the writer's own label, never someone else's. const sharedLabel = singlePoint ? pointLabel(selectedMemos) : ""; const ownLabel = singlePoint && user ? pointLabel(selectedMemos.filter((memo) => memo.creator === user.name)) : ""; const composeLocation = useMemo( () => singlePoint ? create(LocationSchema, { latitude: singlePoint.latitude, longitude: singlePoint.longitude, placeholder: ownLabel || getLocationCoordinatesText(singlePoint), }) : undefined, [singlePoint, ownLabel], ); const afterSave = async (name: string) => { setSaving(false); const result = await query.refetch(); if (result.data?.pages.some((page) => page.memos.some((memo) => memo.name === name && memo.location))) { updateQuery((search) => search.set("memo", name)); } else toast( (toastState) => ( {t(result.isError ? "map.load-error" : "map.saved-outside-filter")}{" "} ), { duration: 8000 }, ); }; const heading = !singlePoint ? { title: t("map.selection") } : sharedLabel ? splitLabel(sharedLabel) : { title: getLocationCoordinatesText(singlePoint) }; // Floating surfaces let the basemap show through, the way Notion's and Linear's overlays do. const surfaceClass = "rounded-lg border border-border/60 bg-background/85 shadow-xs backdrop-blur-md"; // The calendar's 28px quiet square, a touch more on phones. const toolClass = cn(buttonVariants({ variant: "quiet", size: "icon-compact" }), "size-8 md:size-7"); return (
!composing && clearSelection()} onMove={onMove} onReady={onReady} onTileError={() => setTileError(true)} />

{t("common.map")}

{!query.complete && !query.isError && (

{t("map.loaded", { count: query.memos.length })}

)} {/* Phones pinch and double-tap to zoom, so they get only the fit control, and none while reading a place. */} {(desktop || !open) && (
{desktop && ( <>
)}
{query.isError && (

{t("map.load-error")}{" "}

)} {tileError && (

{t("map.tile-error")}{" "}

)}
{query.complete && query.memos.length === 0 && !open && (

{t(filters.length ? "map.no-results" : "map.empty")}

{/* Guests cannot add a location, so only filters get a hint for them. */} {(filters.length > 0 || user) && (

{t(filters.length ? "map.no-results-hint" : "map.empty-hint")}

)} {filters.length > 0 && ( )}
)} void afterSave(name), } : undefined } />
); }