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 { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext"; import MemoEditor from "@/components/MemoEditor"; import { getLocationDisplayText } from "@/components/MemoMetadata/Location/locationHelpers"; import MemoView from "@/components/MemoView"; import { createMemoNavigationState } from "@/components/MemoView/navigation"; import { Button, buttonVariants } from "@/components/ui/button"; import { useAuth } from "@/contexts/AuthContext"; import { useMemoFilterContext } from "@/contexts/MemoFilterContext"; import { NewMemoProvider } from "@/contexts/NewMemoContext"; import { useSpaceContext } from "@/contexts/SpaceContext"; import { useView } from "@/contexts/ViewContext"; import useCurrentUser from "@/hooks/useCurrentUser"; import useMediaQuery from "@/hooks/useMediaQuery"; import { cn } from "@/lib/utils"; import { LocationSchema } from "@/types/proto/api/v1/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; import { fitMemos, MapCanvas } from "./MapCanvas"; import { MapPanel } from "./MapPanel"; import { locationKey, type MapViewport, readViewport, splitLabel } from "./model"; import { useMapMemos } from "./useMapMemos"; 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 } = useSpaceContext(); const user = useCurrentUser(); const { isUserSettingsInitialized } = useAuth(); const { compactMode } = useView(); const { filters, removeFilter } = useMemoFilterContext(); const query = useMapMemos(); const mapRef = useRef(null); const frameRef = useRef(null); const [panelSize, setPanelSize] = useState({ width: 0, height: 0 }); // The panel reports on every resize-drag frame; only a real change may re-render the map tree. const onPanelSize = useCallback( (next: { width: number; height: number }) => 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); // Which selection is being written into; a changed selection closes the editor rather than moving a memo. const [composingFor, setComposingFor] = useState(); 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 composing = !!singlePoint && composingFor === selectedKey; 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]); const composeLocation = useMemo( () => singlePoint ? create(LocationSchema, { latitude: singlePoint.latitude, longitude: singlePoint.longitude, placeholder: getLocationDisplayText(singlePoint), }) : undefined, [singlePoint], ); const afterSave = async (name: string) => { setSaving(false); setComposingFor(undefined); 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 ? splitLabel(getLocationDisplayText(singlePoint)) : { title: t("map.selection") }; const contents = useMemo(() => selectedMemos.map((memo) => memo.content), [selectedMemos]); // 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"); const chipClass = buttonVariants({ variant: "quiet", size: "sm" }); const panelChildren = ( {selectedMemos.map((memo) => ( ))} {!selectedMemos.length &&

{t(query.complete ? "map.no-results" : "map.loading")}

} {/* Like a day in the calendar, a place ends with a quiet row that becomes the editor in place. */} {composeLocation && isUserSettingsInitialized && (composing ? ( void afterSave(name)} onCancel={() => setComposingFor(undefined)} /> ) : ( ))}
); // The panel slides out over 200ms; keep what it was showing so it never flashes an empty state on the way. const lastShown = useRef({ heading, children: panelChildren }); if (open) lastShown.current = { heading, children: panelChildren }; const shown = lastShown.current; return ( ); }