Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

feat(map): add a map page for located memos

johnnyjoyghbc89ec000606
diff --git a/web/package.json b/web/package.json
index 68c98046e..07d418026 100644
--- a/web/package.json
+++ b/web/package.json
@@ -29,6 +29,7 @@
"@github/relative-time-element": "^5.0.0",
"@lezer/highlight": "^1.2.3",
"@lezer/markdown": "^1.7.2",
+ "@maplibre/maplibre-gl-leaflet": "^0.1.4",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/react-query": "^5.100.9",
"@tanstack/react-query-devtools": "^5.100.9",
@@ -45,6 +46,7 @@
"leaflet.markercluster": "^1.5.3",
"lodash-es": "^4.18.1",
"lucide-react": "^1.34.0",
+ "maplibre-gl": "^6.8.0",
"mdast-util-from-markdown": "^2.0.3",
"mdast-util-gfm": "^3.1.0",
"mermaid": "^11.14.0",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
index f78b1a52a..1588af96c 100644
--- a/web/pnpm-lock.yaml
+++ b/web/pnpm-lock.yaml
@@ -47,6 +47,9 @@ importers:
'@lezer/markdown':
specifier: ^1.7.2
version: 1.7.2
+ '@maplibre/maplibre-gl-leaflet':
+ specifier: ^0.1.4
'@tailwindcss/vite':
specifier: ^4.2.4
@@ -95,6 +98,9 @@ importers:
lucide-react:
specifier: ^1.34.0
version: 1.34.0([email protected])
+ maplibre-gl:
+ specifier: ^6.8.0
+ version: 6.8.0
mdast-util-from-markdown:
specifier: ^2.0.3
version: 2.0.3
@@ -615,6 +621,42 @@ packages:
resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==}
+ '@mapbox/[email protected]':
+ resolution: {integrity: sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==}
+ engines: {node: '>= 22'}
+
+ '@mapbox/[email protected]':
+ resolution: {integrity: sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==}
+
+ '@mapbox/[email protected]':
+ resolution: {integrity: sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==}
+
+ '@mapbox/[email protected]':
+ resolution: {integrity: sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==}
+
+ '@mapbox/[email protected]':
+ resolution: {integrity: sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==}
+
+ '@maplibre/[email protected]':
+ resolution: {integrity: sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ==}
+
+ '@maplibre/[email protected]':
+ resolution: {integrity: sha512-k57wcndZIvq3m08g2je4pjUPGr43ffNW3j+gXbymt8Vi2l1lUERUi1UmdTZcTPN8LuDDYOMWRNBaSLwpAu02ew==}
+ peerDependencies:
+ '@types/leaflet': ^1.9.0
+ leaflet: ^1.9.3
+ maplibre-gl: ^2.4.0 || ^3.3.1 || ^4.3.2 || ^5.0.0 || ^6.0.0
+
+ '@maplibre/[email protected]':
+ resolution: {integrity: sha512-I/qcIKVFHFSg1Meu/eqHrkSTjIez0gCsSaK56TNPutM3TkE61aSq6F1cZ4Kg4KiNs3cpViLtubDjfyRcQCdEJQ==}
+ hasBin: true
+
+ '@maplibre/[email protected]':
+ resolution: {integrity: sha512-5n5dgolE2EYxwCKgx8vlwURCB8A+kyfJJyThlYimjlGgOcOe2Bhw9VxxnnHC91OC9PgHg+nVdgVPTYPkIo62vg==}
+
+ '@maplibre/[email protected]':
+ resolution: {integrity: sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==}
+
'@marijn/[email protected]':
resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
@@ -1556,6 +1598,9 @@ packages:
resolution: {integrity: sha512-JahakDAIg1gyOm7dlgWSDjV4n7Ip2PKR55NIT6jrMfIgLFgWo81vdr1/QGqWtFNRqXP9UV71oVePtjqS2ebnPw==}
+ resolution: {integrity: sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q==}
+
resolution: {integrity: sha512-9wHk8x6dyuimoe18EdiDPWKExNdxYqo4fn4FwOVVper6RxT3cmpBwBkWWfSOCYJjQdIco/nPhJhNLmn4Ufg1Yg==}
@@ -1616,6 +1661,9 @@ packages:
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
+ resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==}
+
resolution: {integrity: sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==}
peerDependencies:
@@ -1752,6 +1800,9 @@ packages:
engines: {node: '>=6'}
hasBin: true
+ resolution: {integrity: sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==}
+
resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
engines: {node: '>=6'}
@@ -1761,6 +1812,9 @@ packages:
resolution: {integrity: sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==}
hasBin: true
+ resolution: {integrity: sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==}
+
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
@@ -1881,6 +1935,10 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-+ZkjKTodsVLY0ewQThvXRxXQsclcsSgOm5LlnrBM3G8AloMJKt6Haw8mY4xrOl8T0WMqH6DTYjktZ9zGQXZd4w==}
+ engines: {node: '>=16.14.0', npm: '>=8.1.0'}
+
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
@@ -2037,12 +2095,18 @@ packages:
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}
+
resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+ resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==}
+
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -2072,6 +2136,10 @@ packages:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+ resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
+ hasBin: true
+
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -2092,6 +2160,9 @@ packages:
resolution: {integrity: sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==}
engines: {node: ^10 || ^12 || >=14}
+ resolution: {integrity: sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==}
+
resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
@@ -2099,10 +2170,16 @@ packages:
resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
+ resolution: {integrity: sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==}
+
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==}
+
resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==}
peerDependencies:
@@ -2215,6 +2292,9 @@ packages:
resolution: {integrity: sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==}
+ resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==}
+
resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==}
@@ -2305,6 +2385,9 @@ packages:
resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==}
+
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
@@ -2979,6 +3062,49 @@ snapshots:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
+ '@mapbox/[email protected]': {}
+
+ '@mapbox/[email protected]': {}
+
+ '@mapbox/[email protected]': {}
+
+ '@mapbox/[email protected]': {}
+
+ '@mapbox/[email protected]':
+ dependencies:
+ '@mapbox/point-geometry': 1.1.0
+ '@types/geojson': 7946.0.16
+ pbf: 5.1.2
+
+ '@maplibre/[email protected]':
+ dependencies:
+ kdbush: 4.1.0
+
+ dependencies:
+ '@types/leaflet': 1.9.21
+ leaflet: 1.9.4
+ maplibre-gl: 6.8.0
+
+ '@maplibre/[email protected]':
+ dependencies:
+ '@mapbox/jsonlint-lines-primitives': 2.0.3
+ '@mapbox/unitbezier': 1.0.0
+ json-stringify-pretty-compact: 4.0.0
+ minimist: 1.2.8
+ quickselect: 3.0.0
+ tinyqueue: 3.0.0
+
+ '@maplibre/[email protected]':
+ dependencies:
+ '@mapbox/point-geometry': 1.1.0
+
+ '@maplibre/[email protected]':
+ dependencies:
+ '@mapbox/point-geometry': 1.1.0
+ '@types/geojson': 7946.0.16
+ pbf: 5.1.2
+
'@marijn/[email protected]': {}
'@mermaid-js/[email protected]':
@@ -3821,6 +3947,8 @@ snapshots:
optionalDependencies:
'@types/trusted-types': 2.0.7
+
@@ -3859,6 +3987,8 @@ snapshots:
+
dependencies:
csstype: 3.2.3
@@ -4058,12 +4188,16 @@ snapshots:
+
dependencies:
commander: 8.3.0
+
@@ -4154,6 +4288,26 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ '@mapbox/point-geometry': 1.1.0
+ '@mapbox/tiny-sdf': 2.2.0
+ '@mapbox/unitbezier': 1.0.0
+ '@mapbox/vector-tile': 3.0.0
+ '@maplibre/geojson-vt': 6.1.1
+ '@maplibre/maplibre-gl-style-spec': 26.4.1
+ '@maplibre/mlt': 1.2.1
+ '@maplibre/vt-pbf': 4.3.2
+ '@types/geojson': 7946.0.16
+ earcut: 3.2.3
+ gl-matrix: 3.4.4
+ kdbush: 4.1.0
+ murmurhash-js: 1.0.0
+ pbf: 5.1.2
+ potpack: 2.1.0
+ quickselect: 3.0.0
+ tinyqueue: 3.0.0
+
@@ -4557,6 +4711,8 @@ snapshots:
+
dependencies:
acorn: 8.16.0
@@ -4566,6 +4722,8 @@ snapshots:
+
@@ -4596,6 +4754,10 @@ snapshots:
+ dependencies:
+ resolve-protobuf-schema: 2.1.0
+
@@ -4619,6 +4781,8 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
+
dependencies:
ansi-regex: 5.0.1
@@ -4627,8 +4791,12 @@ snapshots:
+
+
dependencies:
react: 19.2.6
@@ -4783,6 +4951,10 @@ snapshots:
+ dependencies:
+ protocol-buffers-schema: 3.6.1
+
@@ -4875,6 +5047,8 @@ snapshots:
fdir: 6.5.0([email protected])
picomatch: 4.0.4
+
diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsx
index 06496cd59..5c63b0296 100644
--- a/web/src/components/AppSidebar/AppSidebar.tsx
+++ b/web/src/components/AppSidebar/AppSidebar.tsx
@@ -23,7 +23,8 @@ import {
UserRoundIcon,
} from "lucide-react";
import { type ReactNode, useEffect } from "react";
-import { Link, matchPath, useLocation, useNavigate, useSearchParams } from "react-router-dom";
+import { Link, matchPath, useLocation, useNavigate } from "react-router-dom";
+import { MAP_MEMO_FILTER } from "@/components/MapView/useMapMemos";
import { MemoDetailSidebar } from "@/components/MemoDetailSidebar";
import { DEFAULT_SETTING_SECTION, SETTINGS_SECTIONS } from "@/components/Settings/settingSections";
import StatisticsView from "@/components/StatisticsView";
@@ -43,6 +44,7 @@ import useCurrentUser from "@/hooks/useCurrentUser";
import { type MemoStatsContext, useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
import useMediaQuery from "@/hooks/useMediaQuery";
import { useNotifications, useUser } from "@/hooks/useUserQueries";
+import { combineCELFilters } from "@/lib/cel-filter";
import { getMemoScopePath, getProfileUsername, type PrimaryMemoScope, resolveMemoScope } from "@/lib/memo-views";
import { userNamePrefix } from "@/lib/resource-names";
import { cn } from "@/lib/utils";
@@ -79,34 +81,28 @@ const NewMemoAction = ({ onClick }: { onClick: () => void }) => {
);
};
-const ProfileMode = () => {
+const ProfileNavigation = () => {
const t = useTranslate();
- const [searchParams, setSearchParams] = useSearchParams();
const { setMobileOpen } = useAppSidebar();
- const active = searchParams.get("view") === "map" ? "map" : "memos";
- const setMode = (mode: "memos" | "map") => {
- setSearchParams((params) => {
- mode === "map" ? params.set("view", "map") : params.delete("view");
- return params;
- });
- setMobileOpen(false);
- };
return (
<SidebarSection label={t("common.profile")}>
- <SidebarRow
- state={active === "memos" ? "current" : "idle"}
- icon={LayoutListIcon}
- label={t("common.memos")}
- onClick={() => setMode("memos")}
- />
- <SidebarRow state={active === "map" ? "current" : "idle"} icon={MapIcon} label={t("common.map")} onClick={() => setMode("map")} />
+ <SidebarRow state="current" icon={LayoutListIcon} label={t("common.memos")} onClick={() => setMobileOpen(false)} />
</SidebarSection>
);
};
/** The calendar is its own month view, so its sidebar narrows by view and tag but skips the heatmap. */
-const CollectionSidebarContent = ({ context, showStatistics = true }: { context: MemoStatsContext; showStatistics?: boolean }) => {
+const CollectionSidebarContent = ({
+ context,
+ showStatistics = true,
+ scopeFilter,
+}: {
+ context: MemoStatsContext;
+ showStatistics?: boolean;
+ /** A page that can only show part of the collection counts that part, so a tag never promises memos the page cannot show. */
+ scopeFilter?: string;
+}) => {
const t = useTranslate();
const location = useLocation();
const currentUser = useCurrentUser();
@@ -122,7 +118,8 @@ const CollectionSidebarContent = ({ context, showStatistics = true }: { context:
const statsUserName = context === "home" ? currentUser?.name : context === "profile" ? profileUser?.name : undefined;
// User-level collections stay aligned with their unscoped feeds even when a Space is remembered.
const isUserLevelCollection = context === "profile" || context === "archived";
- const statsFilter = isUserLevelCollection ? undefined : memoFilter;
+ const collectionFilter = isUserLevelCollection ? undefined : memoFilter;
+ const statsFilter = scopeFilter ? combineCELFilters(collectionFilter, scopeFilter) : collectionFilter;
const { statistics, tags } = useFilteredMemoStats({
context,
userName: statsUserName,
@@ -136,7 +133,7 @@ const CollectionSidebarContent = ({ context, showStatistics = true }: { context:
return (
<div className={SIDEBAR_SECTION_STACK_CLASSES}>
- {context === "profile" && <ProfileMode />}
+ {context === "profile" && <ProfileNavigation />}
{showStatistics && (
<SidebarSection ariaLabel={t("common.statistics")}>
<StatisticsView statisticsData={statistics} onDateSelect={() => setMobileOpen(false)} />
@@ -292,6 +289,7 @@ const RouteSidebarContent = () => {
}
if (kind === "views") return <ViewsSection manageActive />;
if (kind === "calendar") return <CollectionSidebarContent context="home" showStatistics={false} />;
+ if (kind === "map") return <CollectionSidebarContent context="home" showStatistics={false} scopeFilter={MAP_MEMO_FILTER} />;
if (kind === "attachments") return <AttachmentsSidebarContent />;
if (kind === "inbox") return <InboxSidebarContent />;
if (kind === "settings") return <SettingsSidebarContent />;
@@ -382,6 +380,13 @@ const GlobalNavigation = () => {
icon: CalendarDaysIcon,
active: routeKind === "calendar",
},
+ {
+ id: "map",
+ label: t("common.map"),
+ path: collectionPathForLocation(ROUTES.MAP, location.pathname),
+ icon: MapIcon,
+ active: routeKind === "map",
+ },
{
id: "attachments",
label: t("common.attachments"),
@@ -613,7 +618,7 @@ const AppSidebar = ({ className }: { className?: string }) => {
export const MobileAppHeader = () => {
const { setMobileOpen } = useAppSidebar();
return (
- <header className="sticky top-0 z-20 flex h-12 w-full items-center justify-start gap-1 border-b border-border/70 bg-background/90 px-2 backdrop-blur-md md:hidden">
+ <header className="sticky top-0 z-20 flex h-12 w-full shrink-0 items-center justify-start gap-1 border-b border-border/70 bg-background/90 px-2 backdrop-blur-md md:hidden">
<Button variant="ghost" size="icon" onClick={() => setMobileOpen(true)} aria-label="Open navigation" data-mobile-navigation-trigger>
<MenuIcon className="size-[18px]" />
</Button>
diff --git a/web/src/components/AppSidebar/routes.ts b/web/src/components/AppSidebar/routes.ts
index d602f0de3..aab64be4a 100644
--- a/web/src/components/AppSidebar/routes.ts
+++ b/web/src/components/AppSidebar/routes.ts
@@ -2,7 +2,17 @@ import { matchPath } from "react-router-dom";
import { getProfileUsername, isCalendarRoute, isMemoScopeRoute, type MemoScope, resolveMemoScope } from "@/lib/memo-views";
import { collectionPathForLocation, ROUTES, resolveCollectionRoute } from "@/router/routes";
-export type SidebarRouteKind = MemoScope | "profile" | "views" | "calendar" | "attachments" | "inbox" | "settings" | "memo" | "common";
+export type SidebarRouteKind =
+ | MemoScope
+ | "profile"
+ | "views"
+ | "calendar"
+ | "map"
+ | "attachments"
+ | "inbox"
+ | "settings"
+ | "memo"
+ | "common";
export type RouteSearchScope = "route-collection" | "user-collection" | "profile" | "all";
@@ -18,6 +28,7 @@ export const getSidebarRouteKind = (path: string): SidebarRouteKind => {
if (getProfileUsername(normalizedPath) !== undefined) return "profile";
if (matchPath(ROUTES.VIEWS, normalizedPath)) return "views";
if (isCalendarRoute(normalizedPath)) return "calendar";
+ if (matchPath(ROUTES.MAP, normalizedPath)) return "map";
if (matchPath(ROUTES.ATTACHMENTS, normalizedPath)) return "attachments";
if (matchPath(ROUTES.INBOX, normalizedPath)) return "inbox";
if (matchPath(ROUTES.SETTING, normalizedPath)) return "settings";
@@ -37,12 +48,12 @@ export const getRouteActionPolicy = (path: string): RouteActionPolicy => {
// Calendar and attachments browse the route collection but are not memo lists
// themselves, so a search leaves for the same collection's Home.
- if (kind === "calendar" || kind === "attachments") {
+ if (kind === "calendar" || kind === "map" || kind === "attachments") {
return { searchScope: "route-collection", searchDestination: collectionPathForLocation(ROUTES.HOME, path) };
}
if (kind === "profile") {
- // Re-enter the memo list tab on the same profile (dropping ?view=map).
+ // Keep search within the same profile.
return { searchScope: "profile", searchDestination: path.length > 1 ? path.replace(/\/+$/, "") : path };
}
diff --git a/web/src/components/MapView/MapCanvas.tsx b/web/src/components/MapView/MapCanvas.tsx
new file mode 100644
index 000000000..6ecea3d61
--- /dev/null
+++ b/web/src/components/MapView/MapCanvas.tsx
@@ -0,0 +1,174 @@
+import L from "leaflet";
+import "leaflet/dist/leaflet.css";
+import "leaflet.markercluster/dist/MarkerCluster.css";
+import { useEffect, useMemo, useRef } from "react";
+import { MapContainer, Marker, useMapEvents } from "react-leaflet";
+import MarkerClusterGroup from "react-leaflet-cluster";
+import { getLocationDisplayText } from "@/components/MemoMetadata/Location/locationHelpers";
+import { BasemapLayer } from "@/components/map/BasemapLayer";
+import { createMarkerIcon, MinimalAttributionControl } from "@/components/map/map-utils";
+import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
+import { type MapViewport, revealOffset } from "./model";
+
+interface Props {
+ memos: Memo[];
+ selected: string[];
+ viewport?: MapViewport;
+ complete: boolean;
+ desktop: boolean;
+ panelSize: { width: number; height: number };
+ onSelect: (names: string[]) => void;
+ /** A click on bare map, which reads as "put that away" the way it does on a place card. */
+ onDismiss: () => void;
+ onMove: (viewport: MapViewport) => void;
+ onReady: (map: L.Map | null) => void;
+ onTileError: () => void;
+}
+
+// Positron's own city dots are 4px black; ours are bigger, colored and white-edged so they never blend in.
+const markerIcon = createMarkerIcon({ size: 22, dot: 16 });
+const selectedIcon = createMarkerIcon({ size: 36, dot: 20, halo: true });
+
+export function fitMemos(map: L.Map, memos: Memo[]) {
+ if (memos.length)
+ map.fitBounds(L.latLngBounds(memos.map((memo) => [memo.location!.latitude, memo.location!.longitude])), {
+ padding: [64, 96],
+ maxZoom: 15,
+ });
+}
+
+function MapBehavior(props: Props) {
+ const latest = useRef(props);
+ latest.current = props;
+ const initialFit = useRef(Boolean(props.viewport));
+ const map = useMapEvents({
+ moveend: () => {
+ const center = map.getCenter().wrap();
+ latest.current.onMove({ lat: center.lat, lng: center.lng, zoom: map.getZoom() });
+ },
+ click: () => latest.current.onDismiss(),
+ });
+ useEffect(() => {
+ props.onReady(map);
+ const resize = new ResizeObserver(() => map.invalidateSize({ pan: false }));
+ resize.observe(map.getContainer());
+ return () => {
+ resize.disconnect();
+ props.onReady(null);
+ };
+ }, [map, props.onReady]);
+ useEffect(() => {
+ const viewport = props.viewport;
+ if (!viewport) return;
+ const center = map.getCenter().wrap();
+ if (Math.abs(center.lat - viewport.lat) > 0.00002 || Math.abs(center.lng - viewport.lng) > 0.00002 || map.getZoom() !== viewport.zoom) {
+ map.setView([viewport.lat, viewport.lng], viewport.zoom, { animate: false });
+ }
+ }, [map, props.viewport?.lat, props.viewport?.lng, props.viewport?.zoom]);
+ useEffect(() => {
+ if (!props.complete || initialFit.current) return;
+ initialFit.current = true;
+ fitMemos(map, props.memos);
+ }, [map, props.complete, props.memos]);
+ const selectedName = props.selected[0];
+ const selectedLocation = props.memos.find((item) => item.name === selectedName)?.location;
+ useEffect(() => {
+ if (!selectedLocation || !props.panelSize.width) return;
+ const point = map.latLngToContainerPoint([selectedLocation.latitude, selectedLocation.longitude]);
+ const offset = revealOffset(point, map.getSize(), props.panelSize, props.desktop);
+ if (offset[0] || offset[1]) map.panBy(offset, { animate: false });
+ }, [
+ map,
+ selectedName,
+ props.panelSize.width,
+ props.panelSize.height,
+ props.desktop,
+ selectedLocation?.latitude,
+ selectedLocation?.longitude,
+ ]);
+ return null;
+}
+
+function Markers({ memos, selected, onSelect }: Pick<Props, "memos" | "selected" | "onSelect">) {
+ const names = useRef(new WeakMap<L.Marker, string>());
+ const selection = useMemo(() => new Set(selected), [selected]);
+ // Identity-stable positions: a fresh tuple per render would make every marker re-enter the cluster tree.
+ const points = useMemo(
+ () =>
+ memos.map((memo) => ({
+ memo,
+ position: [memo.location!.latitude, memo.location!.longitude] as [number, number],
+ label: getLocationDisplayText(memo.location!),
+ })),
+ [memos],
+ );
+ const clusterGroup = useRef<{ refreshClusters(): void } | null>(null);
+ useEffect(() => {
+ clusterGroup.current?.refreshClusters();
+ }, [selection]);
+ return (
+ <MarkerClusterGroup
+ ref={clusterGroup}
+ chunkedLoading
+ maxClusterRadius={40}
+ zoomToBoundsOnClick={false}
+ spiderfyOnMaxZoom={false}
+ showCoverageOnHover={false}
+ iconCreateFunction={(cluster: { getChildCount(): number; getAllChildMarkers(): L.Marker[] }) => {
+ const active = cluster.getAllChildMarkers().some((marker) => selection.has(names.current.get(marker) ?? ""));
+ return L.divIcon({
+ html: `<span class="grid size-7 place-items-center rounded-full border-[1.5px] border-background bg-primary text-primary-foreground text-xs font-medium tabular-nums shadow-[0_1px_3px_rgba(15,23,42,0.35)]${active ? " outline-[4px] outline-primary/20" : ""}">${cluster.getChildCount()}</span>`,
+ className: "",
+ iconSize: [28, 28],
+ });
+ }}
+ // A cluster is "the notes around here": clicking it opens them for reading instead of zooming
+ // to spread the pins apart. Zoom stays with the wheel and the +/− stack.
+ onClick={(event: L.LeafletMouseEvent & { layer?: { getAllChildMarkers(): L.Marker[] } }) => {
+ if (!event.layer?.getAllChildMarkers) return;
+ const children: L.Marker[] = event.layer.getAllChildMarkers();
+ onSelect(
+ children.flatMap((marker) => {
+ const name = names.current.get(marker);
+ return name ? [name] : [];
+ }),
+ );
+ }}
+ >
+ {points.map(({ memo, position, label }) => (
+ <Marker
+ key={memo.name}
+ ref={(marker) => {
+ if (marker) names.current.set(marker, memo.name);
+ }}
+ position={position}
+ icon={selection.has(memo.name) ? selectedIcon : markerIcon}
+ zIndexOffset={selection.has(memo.name) ? 1000 : 0}
+ title={label}
+ alt={label}
+ eventHandlers={{ click: () => onSelect([memo.name]) }}
+ />
+ ))}
+ </MarkerClusterGroup>
+ );
+}
+
+export function MapCanvas(props: Props) {
+ const initial = useRef(props.viewport);
+ return (
+ <MapContainer
+ center={[initial.current?.lat ?? 20, initial.current?.lng ?? 0]}
+ zoom={initial.current?.zoom ?? 2}
+ maxZoom={19}
+ minZoom={0}
+ zoomControl={false}
+ attributionControl={false}
+ className="map-attribution-minimal absolute! inset-0 z-0 !bg-muted"
+ >
+ <BasemapLayer onTileError={props.onTileError} />
+ <MinimalAttributionControl />
+ <MapBehavior {...props} />
+ <Markers memos={props.memos} selected={props.selected} onSelect={props.onSelect} />
+ </MapContainer>
+ );
+}
diff --git a/web/src/components/MapView/MapPanel.tsx b/web/src/components/MapView/MapPanel.tsx
new file mode 100644
index 000000000..5971492bc
--- /dev/null
+++ b/web/src/components/MapView/MapPanel.tsx
@@ -0,0 +1,120 @@
+import { Dialog } from "@base-ui/react/dialog";
+import { XIcon } from "lucide-react";
+import { type CSSProperties, type ReactNode, type RefObject, useCallback, useEffect, useRef, useState } from "react";
+import { type PersistedWidthConfig, SidebarResizeHandle, usePersistedWidth } from "@/components/AppSidebar";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { useTranslate } from "@/utils/i18n";
+
+/** App sidebar plus enough map beside the rail to keep a selection visible. */
+const RESERVED_BESIDE_PANEL = 256 + 160;
+const PANEL_WIDTH_CONFIG: PersistedWidthConfig = {
+ storageKey: "memos-map-panel-width",
+ defaultWidth: 400,
+ minWidth: 320,
+ maxWidthFor: (viewportWidth) => Math.min(640, viewportWidth - RESERVED_BESIDE_PANEL),
+};
+
+interface Props {
+ open: boolean;
+ title: string;
+ subtitle?: string;
+ desktop: boolean;
+ container: RefObject<HTMLElement | null>;
+ busy: boolean;
+ onClose: () => void;
+ onSize: (size: { width: number; height: number }) => void;
+ children: ReactNode;
+}
+
+export function MapPanel({ open, title, subtitle, desktop, container, busy, onClose, onSize, children }: Props) {
+ const t = useTranslate();
+ const ref = useRef<HTMLDivElement>(null);
+ const [element, setElement] = useState<HTMLDivElement | null>(null);
+ const attachPanel = useCallback((node: HTMLDivElement | null) => {
+ ref.current = node;
+ setElement(node);
+ }, []);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const [expanded, setExpanded] = useState(false);
+ const iconControlClassName = buttonVariants({ variant: "quiet", size: "icon-compact" });
+ const { width, minWidth, maxWidth, setWidth } = usePersistedWidth(PANEL_WIDTH_CONFIG);
+ useEffect(() => {
+ if (!open || !element) {
+ onSize({ width: 0, height: 0 });
+ return;
+ }
+ const observer = new ResizeObserver(() => {
+ const rect = element.getBoundingClientRect();
+ onSize({ width: rect.width, height: rect.height });
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [open, onSize, element]);
+
+ return (
+ <Dialog.Root
+ open={open}
+ modal={false}
+ disablePointerDismissal
+ onOpenChange={(next, details) => {
+ if (!next) {
+ if (busy) details.cancel();
+ else onClose();
+ }
+ }}
+ >
+ <Dialog.Portal container={container}>
+ <Dialog.Popup
+ ref={attachPanel}
+ initialFocus={scrollRef}
+ aria-describedby={undefined}
+ data-map-panel
+ style={{ "--map-panel-width": `${width}px`, ...(!desktop ? { height: expanded ? "90%" : "45%" } : {}) } as CSSProperties}
+ className={cn(
+ "absolute z-20 flex min-h-0 flex-col border border-border/70 bg-background shadow-md outline-none transition-transform duration-200",
+ desktop
+ ? "inset-y-3 end-3 w-[var(--map-panel-width)] rounded-xl data-starting-style:translate-x-full data-ending-style:translate-x-full"
+ : "inset-x-0 bottom-0 rounded-t-2xl pb-[env(safe-area-inset-bottom)] data-starting-style:translate-y-full data-ending-style:translate-y-full",
+ )}
+ >
+ {desktop && (
+ <SidebarResizeHandle
+ width={width}
+ minWidth={minWidth}
+ maxWidth={maxWidth}
+ onWidthChange={setWidth}
+ targetRef={ref}
+ cssVariable="--map-panel-width"
+ defaultWidth={PANEL_WIDTH_CONFIG.defaultWidth}
+ edge="start"
+ label={t("map.resize-panel")}
+ />
+ )}
+ {!desktop && (
+ <button
+ type="button"
+ className="flex h-7 shrink-0 items-center justify-center"
+ aria-label={t(expanded ? "map.collapse" : "map.expand")}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ <span className="h-1 w-10 rounded-full bg-muted-foreground/35" />
+ </button>
+ )}
+ <header className="flex shrink-0 items-center gap-0.5 border-b border-border/70 py-2.5 ps-3 pe-3">
+ <div className="min-w-0 flex-1">
+ <Dialog.Title className="truncate text-base font-semibold tracking-tight text-foreground">{title}</Dialog.Title>
+ {subtitle && <p className="truncate text-xs text-muted-foreground">{subtitle}</p>}
+ </div>
+ <Dialog.Close disabled={busy} render={<button type="button" className={iconControlClassName} aria-label={t("common.close")} />}>
+ <XIcon strokeWidth={1.8} />
+ </Dialog.Close>
+ </header>
+ <div ref={scrollRef} tabIndex={-1} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-4 outline-none">
+ {children}
+ </div>
+ </Dialog.Popup>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/web/src/components/MapView/MapView.tsx b/web/src/components/MapView/MapView.tsx
new file mode 100644
index 000000000..3d1a77672
--- /dev/null
+++ b/web/src/components/MapView/MapView.tsx
@@ -0,0 +1,349 @@
+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<L.Map | null>(null);
+ const frameRef = useRef<HTMLElement>(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<string>();
+ 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) => (
+ <span>
+ {t(result.isError ? "map.load-error" : "map.saved-outside-filter")}{" "}
+ <button
+ type="button"
+ className="underline"
+ onClick={() => {
+ toast.dismiss(toastState.id);
+ navigate(`/${name}`, { state: createMemoNavigationState(`${location.pathname}${location.search}`) });
+ }}
+ >
+ {t("map.open-memo")}
+ </button>
+ </span>
+ ),
+ { 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 = (
+ <NewMemoProvider>
+ <MentionResolutionProvider contents={contents}>
+ {selectedMemos.map((memo) => (
+ <MemoView
+ key={memo.name}
+ memo={memo}
+ compact={compactMode}
+ showVisibility
+ showPinned
+ showSpace={!selectedSpaceName}
+ parentPage={`${location.pathname}${location.search}`}
+ />
+ ))}
+ </MentionResolutionProvider>
+ {!selectedMemos.length && <p className="text-sm text-muted-foreground">{t(query.complete ? "map.no-results" : "map.loading")}</p>}
+ {/* Like a day in the calendar, a place ends with a quiet row that becomes the editor in place. */}
+ {composeLocation &&
+ isUserSettingsInitialized &&
+ (composing ? (
+ <MemoEditor
+ key={selectedKey}
+ cacheKey={`map-editor:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`}
+ defaultLocation={composeLocation}
+ defaultSpace={selectedSpaceName}
+ autoFocus
+ onSavingChange={setSaving}
+ onConfirm={(name) => void afterSave(name)}
+ onCancel={() => setComposingFor(undefined)}
+ />
+ ) : (
+ <button type="button" className={cn(chipClass, "self-start")} onClick={() => setComposingFor(selectedKey)}>
+ <PlusIcon strokeWidth={1.8} />
+ <span>{t("map.new-here")}</span>
+ </button>
+ ))}
+ </NewMemoProvider>
+ );
+ // 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 (
+ <section
+ ref={frameRef}
+ // `clip`, not `hidden`: the panel mounts translated outside this box and takes focus, and a hidden
+ // overflow would let the browser scroll the whole map to reveal it for the length of the slide.
+ className="relative isolate min-h-0 w-full flex-1 overflow-clip [&_.leaflet-bottom]:bottom-[var(--map-inset-bottom)]! [&_.leaflet-right]:right-[var(--map-inset-end)]! [&_.leaflet-bottom]:transition-[bottom] [&_.leaflet-right]:transition-[right] [&_.leaflet-bottom]:duration-200 [&_.leaflet-right]:duration-200"
+ style={
+ {
+ // Controls and attribution keep clear of the panel: above a bottom sheet, beside a side rail.
+ "--map-inset-bottom": !desktop && open ? `${panelSize.height}px` : "0px",
+ "--map-inset-end": desktop && open ? `${panelSize.width + 12}px` : "0px",
+ } as CSSProperties
+ }
+ data-map-page
+ >
+ <MapCanvas
+ memos={query.memos}
+ selected={selected}
+ viewport={viewport}
+ complete={query.complete}
+ desktop={desktop}
+ panelSize={panelSize}
+ onSelect={onSelect}
+ // A bare-map click puts the panel away, but never out from under the editor.
+ onDismiss={() => !composing && clearSelection()}
+ onMove={onMove}
+ onReady={onReady}
+ onTileError={() => setTileError(true)}
+ />
+ <h1 className="sr-only">{t("common.map")}</h1>
+ {!query.complete && !query.isError && (
+ <p
+ role="status"
+ className={cn(
+ "absolute start-3 top-3 z-10 flex h-7 items-center px-2.5 text-xs text-muted-foreground tabular-nums",
+ surfaceClass,
+ )}
+ >
+ {t("map.loaded", { count: query.memos.length })}
+ </p>
+ )}
+ {/* Phones pinch and double-tap to zoom, so they get only the fit control, and none while reading a place. */}
+ {(desktop || !open) && (
+ <div
+ role="group"
+ aria-label={t("common.map")}
+ className={cn("absolute start-3 bottom-3 z-10 flex flex-col items-center p-1", surfaceClass)}
+ >
+ {desktop && (
+ <>
+ <button
+ type="button"
+ className={toolClass}
+ aria-label={t("map.zoom-in")}
+ title={t("map.zoom-in")}
+ onClick={() => mapRef.current?.zoomIn()}
+ >
+ <PlusIcon strokeWidth={1.75} />
+ </button>
+ <button
+ type="button"
+ className={toolClass}
+ aria-label={t("map.zoom-out")}
+ title={t("map.zoom-out")}
+ onClick={() => mapRef.current?.zoomOut()}
+ >
+ <MinusIcon strokeWidth={1.75} />
+ </button>
+ <span aria-hidden="true" className="my-1 h-px w-4 bg-border/70" />
+ </>
+ )}
+ <button
+ type="button"
+ className={toolClass}
+ aria-label={t("map.fit-all")}
+ title={t("map.fit-all")}
+ disabled={query.memos.length === 0}
+ onClick={() => {
+ if (mapRef.current) fitMemos(mapRef.current, query.memos);
+ }}
+ >
+ <CrosshairIcon strokeWidth={1.75} />
+ </button>
+ </div>
+ )}
+ <div className="pointer-events-none absolute inset-x-3 bottom-8 z-10 flex flex-col items-center gap-2">
+ {query.isError && (
+ <p role="alert" className={cn("pointer-events-auto px-4 py-2 text-sm", surfaceClass)}>
+ {t("map.load-error")}{" "}
+ <button type="button" className="ms-2 underline" onClick={() => void query.retry()}>
+ {t("search.retry")}
+ </button>
+ </p>
+ )}
+ {tileError && (
+ <p role="alert" className={cn("pointer-events-auto px-4 py-2 text-sm", surfaceClass)}>
+ {t("map.tile-error")}{" "}
+ <button
+ type="button"
+ className="ms-2 underline"
+ onClick={() => {
+ setTileError(false);
+ mapRef.current?.eachLayer((layer) => {
+ if ("redraw" in layer && typeof layer.redraw === "function") layer.redraw();
+ });
+ }}
+ >
+ {t("search.retry")}
+ </button>
+ </p>
+ )}
+ </div>
+ {query.complete && query.memos.length === 0 && !open && (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center p-8">
+ <div className={cn("pointer-events-auto max-w-sm rounded-xl p-5 text-center", surfaceClass)}>
+ <h2 className="font-medium">{t(filters.length ? "map.no-results" : "map.empty")}</h2>
+ <p className="mt-2 text-sm text-muted-foreground">{t(filters.length ? "map.no-results-hint" : "map.empty-hint")}</p>
+ {filters.length > 0 && (
+ <Button className="mt-4" variant="outline" onClick={() => removeFilter(() => true)}>
+ {t("map.clear-filters")}
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ <MapPanel
+ open={open}
+ title={shown.heading.title}
+ subtitle={shown.heading.subtitle}
+ desktop={desktop}
+ container={frameRef}
+ busy={saving}
+ onClose={clearSelection}
+ onSize={onPanelSize}
+ >
+ {shown.children}
+ </MapPanel>
+ </section>
+ );
+}
diff --git a/web/src/components/MapView/model.ts b/web/src/components/MapView/model.ts
new file mode 100644
index 000000000..bace2fea3
--- /dev/null
+++ b/web/src/components/MapView/model.ts
@@ -0,0 +1,59 @@
+import type { MemoTimeBasis } from "@/contexts/ViewContext";
+import { getMemoSortTime } from "@/hooks/useMemoSorting";
+import type { Location, Memo } from "@/types/proto/api/v1/memo_service_pb";
+
+export interface MapViewport {
+ lat: number;
+ lng: number;
+ zoom: number;
+}
+
+export const validLocation = (location: Location | undefined): location is Location =>
+ !!location &&
+ Number.isFinite(location.latitude) &&
+ Number.isFinite(location.longitude) &&
+ Math.abs(location.latitude) <= 90 &&
+ Math.abs(location.longitude) <= 180;
+
+export const locationKey = (location: Location): string => `${location.latitude},${location.longitude}`;
+
+/** A geocoded label split into the place itself and the region after it, so a rail can lead with the place. */
+export function splitLabel(label: string): { title: string; subtitle?: string } {
+ const index = label.indexOf(",");
+ if (index <= 0) return { title: label };
+ const subtitle = label.slice(index + 1).trim();
+ return subtitle ? { title: label.slice(0, index).trim(), subtitle } : { title: label };
+}
+
+export function mapMemos(pages: { memos: Memo[] }[] | undefined, timeBasis: MemoTimeBasis): Memo[] {
+ const memos = new Map<string, Memo>();
+ for (const page of pages ?? []) for (const memo of page.memos) memos.set(memo.name, memo);
+ const time = (memo: Memo) => getMemoSortTime(memo, timeBasis)?.getTime() ?? 0;
+ return [...memos.values()]
+ .filter((memo) => validLocation(memo.location))
+ .sort((a, b) => time(b) - time(a) || a.name.localeCompare(b.name));
+}
+
+export function readViewport(search: string): MapViewport | undefined {
+ const params = new URLSearchParams(search);
+ const values = ["lat", "lng", "zoom"].map((key) => params.get(key));
+ if (values.some((value) => value === null || value.trim() === "")) return undefined;
+ const [lat, lng, zoom] = values.map(Number);
+ if (![lat, lng, zoom].every(Number.isFinite) || Math.abs(lat) > 90 || Math.abs(lng) > 180 || zoom < 0 || zoom > 19) return undefined;
+ return { lat, lng, zoom };
+}
+
+/** Smallest translation that leaves a selected point visible beside an overlay. */
+export function revealOffset(
+ point: { x: number; y: number },
+ size: { x: number; y: number },
+ panel: { width: number; height: number },
+ desktop: boolean,
+) {
+ const right = desktop ? Math.max(48, size.x - panel.width - 40) : size.x - 32;
+ const bottom = desktop ? size.y - 32 : Math.max(100, size.y - panel.height - 32);
+ return [
+ point.x > right ? point.x - right : point.x < 32 ? point.x - 32 : 0,
+ point.y > bottom ? point.y - bottom : point.y < 96 ? point.y - 96 : 0,
+ ] as [number, number];
+}
diff --git a/web/src/components/MapView/useMapMemos.ts b/web/src/components/MapView/useMapMemos.ts
new file mode 100644
index 000000000..4b3b2b977
--- /dev/null
+++ b/web/src/components/MapView/useMapMemos.ts
@@ -0,0 +1,37 @@
+import { useEffect, useMemo } from "react";
+import { useAuth } from "@/contexts/AuthContext";
+import { useSpaceContext } from "@/contexts/SpaceContext";
+import { useView } from "@/contexts/ViewContext";
+import useCurrentUser from "@/hooks/useCurrentUser";
+import { useMemoFilters } from "@/hooks/useMemoFilters";
+import { useInfiniteMemos } from "@/hooks/useMemoQueries";
+import { combineCELFilters } from "@/lib/cel-filter";
+import { buildMemoCreatorFilter } from "@/lib/resource-names";
+import { State } from "@/types/proto/api/v1/common_pb";
+import { mapMemos } from "./model";
+
+/** What the map can show; the sidebar counts against the same scope. */
+export const MAP_MEMO_FILTER = "has_location";
+
+export function useMapMemos() {
+ const user = useCurrentUser();
+ const { isUserSettingsInitialized } = useAuth();
+ const { memoFilter } = useSpaceContext();
+ const { timeBasis } = useView();
+ const viewFilter = useMemoFilters({ includeMemoViews: true, includePinned: false });
+ const filter = combineCELFilters(memoFilter, viewFilter, user && buildMemoCreatorFilter(user.name), MAP_MEMO_FILTER);
+ const query = useInfiniteMemos(
+ { filter, state: State.NORMAL, pageSize: 500, orderBy: `${timeBasis} desc, name desc` },
+ { enabled: Boolean(user) && isUserSettingsInitialized },
+ );
+ const { hasNextPage, isFetching, isError, fetchNextPage } = query;
+ useEffect(() => {
+ if (hasNextPage && !isFetching && !isError) void fetchNextPage().catch(() => {});
+ }, [hasNextPage, isFetching, isError, fetchNextPage, query.data?.pages.length]);
+ const memos = useMemo(
+ () => mapMemos(isUserSettingsInitialized && user ? query.data?.pages : undefined, timeBasis),
+ [query.data, timeBasis, isUserSettingsInitialized, user],
+ );
+ const complete = isUserSettingsInitialized && query.isSuccess && !query.hasNextPage && !query.isFetching;
+ return { ...query, memos, complete, retry: () => (query.isFetchNextPageError ? query.fetchNextPage() : query.refetch()) };
+}
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
index d8f8e518e..8e4cf89ce 100644
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
@@ -142,6 +142,8 @@ const MemoDetailSidebar = ({
const originLabel = useMemo(() => {
const originPath = parentPage?.split(/[?#]/, 1)[0] || "/";
switch (getSidebarRouteKind(originPath)) {
+ case "map":
+ return t("common.map");
case "explore":
return t("common.explore");
case "archived":
diff --git a/web/src/components/MemoEditor/hooks/useAutoSave.ts b/web/src/components/MemoEditor/hooks/useAutoSave.ts
index 109459a1d..873296228 100644
--- a/web/src/components/MemoEditor/hooks/useAutoSave.ts
+++ b/web/src/components/MemoEditor/hooks/useAutoSave.ts
@@ -1,11 +1,13 @@
import { equals } from "@bufbuild/protobuf";
import { useCallback, useEffect, useRef } from "react";
import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { LocationSchema } from "@/types/proto/api/v1/memo_service_pb";
import { cacheService, type EditorDraft } from "../services";
import { useEditorStore } from "../state";
const sameDraft = (left: EditorDraft, right: EditorDraft): boolean =>
left.content === right.content &&
+ (left.location === right.location || (!!left.location && !!right.location && equals(LocationSchema, left.location, right.location))) &&
left.attachments.length === right.attachments.length &&
left.attachments.every((attachment, index) => {
const other = right.attachments[index];
@@ -21,7 +23,11 @@ const sameDraft = (left: EditorDraft, right: EditorDraft): boolean =>
export const useAutoSave = (username: string, cacheKey: string | undefined, enabled = true) => {
const store = useEditorStore();
const initialState = store.getState();
- const latestDraftRef = useRef<EditorDraft>({ content: initialState.content, attachments: initialState.metadata.attachments });
+ const latestDraftRef = useRef<EditorDraft>({
+ content: initialState.content,
+ attachments: initialState.metadata.attachments,
+ location: initialState.metadata.location ?? null,
+ });
const discardedDraftRef = useRef<EditorDraft | undefined>(undefined);
useEffect(() => {
@@ -33,15 +39,19 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
if (discardedDraftRef.current !== undefined && !sameDraft(discardedDraftRef.current, draft)) {
discardedDraftRef.current = undefined;
}
- cacheService.save(key, draft.content, draft.attachments);
+ cacheService.save(key, draft.content, draft.attachments, draft.location);
};
// Persist the current draft on mount/enable, then on every relevant change.
const state = store.getState();
- persist({ content: state.content, attachments: state.metadata.attachments });
+ persist({ content: state.content, attachments: state.metadata.attachments, location: state.metadata.location ?? null });
return store.subscribe(() => {
const nextState = store.getState();
- const draft = { content: nextState.content, attachments: nextState.metadata.attachments };
+ const draft = {
+ content: nextState.content,
+ attachments: nextState.metadata.attachments,
+ location: nextState.metadata.location ?? null,
+ };
if (!sameDraft(draft, latestDraftRef.current)) {
persist(draft);
}
@@ -57,7 +67,7 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
return;
}
- cacheService.saveNow(key, latestDraftRef.current.content, latestDraftRef.current.attachments);
+ cacheService.saveNow(key, latestDraftRef.current.content, latestDraftRef.current.attachments, latestDraftRef.current.location);
};
const handleVisibilityChange = () => {
if (document.visibilityState === "hidden") {
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts
index ee92fe02b..83a1b501a 100644
--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
-import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
+import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { cacheService, memoService } from "../services";
import { useEditorContext } from "../state";
import type { EditorController } from "../types/editorController";
@@ -12,6 +12,7 @@ interface UseMemoInitOptions {
autoFocus?: boolean | (() => boolean);
defaultVisibility?: Visibility;
defaultCreateTime?: Date;
+ defaultLocation?: Location;
}
export const useMemoInit = ({
@@ -22,6 +23,7 @@ export const useMemoInit = ({
autoFocus,
defaultVisibility,
defaultCreateTime,
+ defaultLocation,
}: UseMemoInitOptions) => {
const { actions, dispatch } = useEditorContext();
const initializedRef = useRef(false);
@@ -44,6 +46,7 @@ export const useMemoInit = ({
if (cachedDraft.attachments.length > 0) {
dispatch(actions.setMetadata({ attachments: cachedDraft.attachments }));
}
+ dispatch(actions.setMetadata({ location: cachedDraft.location === null ? undefined : (cachedDraft.location ?? defaultLocation) }));
if (defaultVisibility !== undefined) {
dispatch(actions.setMetadata({ visibility: defaultVisibility }));
}
@@ -71,7 +74,7 @@ export const useMemoInit = ({
clearTimeout(restoreCursorTimer);
}
};
- }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, actions, dispatch, editorRef]);
+ }, [memo, cacheKey, username, autoFocus, defaultVisibility, defaultCreateTime, defaultLocation, actions, dispatch, editorRef]);
return { isInitialized };
};
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index afba0154f..a88269b55 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -42,6 +42,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
memo,
parentMemoName,
defaultSpace,
+ defaultLocation,
autoFocus,
onFocusModeExit,
placeholder,
@@ -94,6 +95,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
autoFocus,
defaultVisibility,
defaultCreateTime,
+ defaultLocation,
});
const isDraftCacheEnabled = !memo;
diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/services/cacheService.ts
index 92bd05856..f6f2c69b5 100644
--- a/web/src/components/MemoEditor/services/cacheService.ts
+++ b/web/src/components/MemoEditor/services/cacheService.ts
@@ -2,27 +2,31 @@ import { fromJson, type JsonValue, toJson } from "@bufbuild/protobuf";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { type Location, LocationSchema } from "@/types/proto/api/v1/memo_service_pb";
+
export const CACHE_DEBOUNCE_DELAY = 500;
const pendingSaves = new Map<string, number>();
const cursors = new Map<string, number>();
const STRUCTURED_CACHE_ENTRY_KIND = "memos.editor-cache";
-const STRUCTURED_CACHE_ENTRY_VERSION = 2;
+const STRUCTURED_CACHE_ENTRY_VERSION = 3;
export interface EditorDraft {
content: string;
attachments: Attachment[];
+ /** Undefined for legacy drafts; null explicitly remembers a removed location. */
+ location?: Location | null;
}
function deserializeDraft(raw: string): EditorDraft {
try {
- const parsed = JSON.parse(raw) as { kind?: unknown; version?: unknown; content?: unknown; attachments?: unknown };
+ const parsed = JSON.parse(raw) as { kind?: unknown; version?: unknown; content?: unknown; attachments?: unknown; location?: unknown };
if (parsed.kind === STRUCTURED_CACHE_ENTRY_KIND && parsed.version === 1 && typeof parsed.content === "string") {
return { content: parsed.content, attachments: [] };
}
if (
parsed.kind === STRUCTURED_CACHE_ENTRY_KIND &&
- parsed.version === STRUCTURED_CACHE_ENTRY_VERSION &&
+ (parsed.version === 2 || parsed.version === STRUCTURED_CACHE_ENTRY_VERSION) &&
typeof parsed.content === "string"
) {
const attachments = Array.isArray(parsed.attachments)
@@ -34,7 +38,18 @@ function deserializeDraft(raw: string): EditorDraft {
}
})
: [];
- return { content: parsed.content, attachments };
+ let location: Location | null | undefined;
+ if (parsed.version === STRUCTURED_CACHE_ENTRY_VERSION) {
+ location = null;
+ if (parsed.location) {
+ try {
+ location = fromJson(LocationSchema, parsed.location as JsonValue, { ignoreUnknownFields: true });
+ } catch {
+ /* Ignore malformed metadata. */
+ }
+ }
+ }
+ return { content: parsed.content, attachments, ...(location !== undefined ? { location } : {}) };
}
} catch {
// Drafts have historically been stored as raw markdown strings.
@@ -43,22 +58,19 @@ function deserializeDraft(raw: string): EditorDraft {
return { content: raw, attachments: [] };
}
-function serializeDraft(content: string, attachments: Attachment[]): string {
- if (attachments.length === 0) {
- return content;
- }
-
+function serializeDraft(content: string, attachments: Attachment[], location: Location | null): string {
return JSON.stringify({
kind: STRUCTURED_CACHE_ENTRY_KIND,
version: STRUCTURED_CACHE_ENTRY_VERSION,
+ location: location ? toJson(LocationSchema, location) : null,
content,
attachments: attachments.map((attachment) => toJson(AttachmentSchema, attachment)),
});
}
-function writeEntry(key: string, content: string, attachments: Attachment[]): void {
+function writeEntry(key: string, content: string, attachments: Attachment[], location: Location | null): void {
if (content.trim() || attachments.length > 0) {
- localStorage.setItem(key, serializeDraft(content, attachments));
+ localStorage.setItem(key, serializeDraft(content, attachments, location));
} else {
localStorage.removeItem(key);
}
@@ -69,7 +81,7 @@ export const cacheService = {
return `${username}-${cacheKey || ""}`;
},
- save: (key: string, content: string, attachments: Attachment[] = []) => {
+ save: (key: string, content: string, attachments: Attachment[] = [], location: Location | null = null) => {
const pendingSave = pendingSaves.get(key);
if (pendingSave) {
window.clearTimeout(pendingSave);
@@ -78,20 +90,20 @@ export const cacheService = {
const timeoutId = window.setTimeout(() => {
pendingSaves.delete(key);
- writeEntry(key, content, attachments);
+ writeEntry(key, content, attachments, location);
}, CACHE_DEBOUNCE_DELAY);
pendingSaves.set(key, timeoutId);
},
- saveNow: (key: string, content: string, attachments: Attachment[] = []) => {
+ saveNow: (key: string, content: string, attachments: Attachment[] = [], location: Location | null = null) => {
const pendingSave = pendingSaves.get(key);
if (pendingSave) {
window.clearTimeout(pendingSave);
pendingSaves.delete(key);
}
- writeEntry(key, content, attachments);
+ writeEntry(key, content, attachments, location);
},
load(key: string): string {
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts
index d3bcd879d..b9d1595a1 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/types/components.ts
@@ -12,6 +12,8 @@ export interface MemoEditorProps {
parentMemoName?: string;
/** Assigns a newly created top-level memo to this Space. Ignored for edits and comments. */
defaultSpace?: string;
+ /** Seeds a new memo once; restored draft metadata takes precedence. */
+ defaultLocation?: Location;
/** A callback can decide whether focus is still appropriate after draft restoration. */
autoFocus?: boolean | (() => boolean);
/**
diff --git a/web/src/components/MemoMetadata/Location/LocationDisplayView.tsx b/web/src/components/MemoMetadata/Location/LocationDisplayView.tsx
index bcb201042..0626f311c 100644
--- a/web/src/components/MemoMetadata/Location/LocationDisplayView.tsx
+++ b/web/src/components/MemoMetadata/Location/LocationDisplayView.tsx
@@ -1,7 +1,9 @@
import { MapPinIcon } from "lucide-react";
import { useState } from "react";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
+import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
import type { Location } from "@/types/proto/api/v1/memo_service_pb";
import { getLocationCoordinatesText, getLocationDisplayText } from "./locationHelpers";
@@ -25,17 +27,27 @@ const LocationDisplayView = ({ location }: LocationDisplayViewProps) => {
<button
type="button"
title={displayText}
- className="inline-flex max-w-full min-w-0 items-center gap-1 h-7 px-2 rounded-md border border-border bg-background text-sm font-medium shadow-xs transition-all hover:bg-accent hover:text-accent-foreground"
+ className={cn(
+ "inline-flex min-h-7 max-w-full min-w-0 items-center gap-1.5 rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground data-popup-open:text-foreground",
+ FOCUS_VISIBLE_OUTLINE_CLASSES,
+ )}
/>
}
>
- <MapPinIcon className="w-3.5 h-3.5 shrink-0 text-muted-foreground" />
- <span className="shrink-0 text-nowrap opacity-80">[{getLocationCoordinatesText(location, 2)}]</span>
+ <MapPinIcon className="size-3.5 shrink-0" aria-hidden="true" />
<span className="min-w-0 truncate">{displayText}</span>
</PopoverTrigger>
- <PopoverContent align="start">
- <div className="min-w-80 sm:w-lg flex flex-col justify-start items-start">
- {popoverOpen && <LazyLocationPicker latlng={{ lat: location.latitude, lng: location.longitude }} readonly={true} />}
+ <PopoverContent align="start" className="w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl p-0">
+ {popoverOpen && (
+ <LazyLocationPicker
+ latlng={{ lat: location.latitude, lng: location.longitude }}
+ readonly
+ className="h-52 rounded-none border-0 shadow-none"
+ />
+ )}
+ <div className="space-y-1 px-3 py-2.5">
+ {location.placeholder.trim() && <p className="wrap-anywhere text-sm font-medium">{displayText}</p>}
+ <p className="text-xs tabular-nums text-muted-foreground">{getLocationCoordinatesText(location, 6)}</p>
</div>
</PopoverContent>
</Popover>
diff --git a/web/src/components/MemoMetadata/Location/locationHelpers.ts b/web/src/components/MemoMetadata/Location/locationHelpers.ts
index 6dae17f0b..1a104f1ce 100644
--- a/web/src/components/MemoMetadata/Location/locationHelpers.ts
+++ b/web/src/components/MemoMetadata/Location/locationHelpers.ts
@@ -1,7 +1,7 @@
import type { Location } from "@/types/proto/api/v1/memo_service_pb";
export const getLocationDisplayText = (location: Location): string => {
- return location.placeholder || `${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}`;
+ return location.placeholder.trim() || getLocationCoordinatesText(location);
};
export const getLocationCoordinatesText = (location: Location, digits = 4): string => {
diff --git a/web/src/components/MemoView/navigation.ts b/web/src/components/MemoView/navigation.ts
index 9cf8ce455..39bcde7ab 100644
--- a/web/src/components/MemoView/navigation.ts
+++ b/web/src/components/MemoView/navigation.ts
@@ -1,4 +1,3 @@
-import { getProfileUsername } from "@/lib/memo-views";
import { ROUTES } from "@/router/routes";
export interface MemoNavigationState {
@@ -69,9 +68,6 @@ export const withMemoFilter = (page: string, filter: string): string => {
const pathname = questionMark === -1 ? pathAndSearch : pathAndSearch.slice(0, questionMark);
const search = questionMark === -1 ? "" : pathAndSearch.slice(questionMark + 1);
const searchParams = new URLSearchParams(search);
- if (getProfileUsername(pathname) !== undefined && searchParams.get("view") === "map") {
- searchParams.delete("view");
- }
searchParams.set("filter", filter);
return `${pathname || ROUTES.HOME}?${searchParams.toString()}`;
};
diff --git a/web/src/components/UserMemoMap/UserMemoMap.tsx b/web/src/components/UserMemoMap/UserMemoMap.tsx
deleted file mode 100644
index a14467d64..000000000
--- a/web/src/components/UserMemoMap/UserMemoMap.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-import { timestampDate } from "@bufbuild/protobuf/wkt";
-import L, { DivIcon } from "leaflet";
-import "leaflet/dist/leaflet.css";
-import "leaflet.markercluster/dist/MarkerCluster.css";
-import { ArrowUpRightIcon, MapPinIcon } from "lucide-react";
-import { useEffect, useMemo } from "react";
-import { MapContainer, Marker, Popup, useMap } from "react-leaflet";
-import MarkerClusterGroup from "react-leaflet-cluster";
-import { Link, useLocation } from "react-router-dom";
-import MemoSpaceBadge from "@/components/MemoView/components/MemoSpaceBadge";
-import { createMemoNavigationState } from "@/components/MemoView/navigation";
-import { defaultMarkerIcon, MinimalAttributionControl, OpenStreetMapTileLayer } from "@/components/map/map-utils";
-import { useInfiniteMemos } from "@/hooks/useMemoQueries";
-import { buildMemoCreatorFilter } from "@/lib/resource-names";
-import { cn } from "@/lib/utils";
-import { State } from "@/types/proto/api/v1/common_pb";
-import { Memo } from "@/types/proto/api/v1/memo_service_pb";
-
-interface Props {
- creator: string;
- className?: string;
-}
-
-interface ClusterGroup {
- getChildCount(): number;
-}
-
-const createClusterCustomIcon = (cluster: ClusterGroup) => {
- return new DivIcon({
- html: `<span class="flex h-8 w-8 items-center justify-center rounded-full border border-border bg-background/95 text-xs font-semibold text-foreground shadow-sm backdrop-blur-sm">${cluster.getChildCount()}</span>`,
- className: "border-none bg-transparent",
- iconSize: L.point(32, 32, true),
- });
-};
-
-const MapFitBounds = ({ memos }: { memos: Memo[] }) => {
- const map = useMap();
-
- useEffect(() => {
- if (memos.length === 0) return;
-
- const validMemos = memos.filter((m) => m.location);
- if (validMemos.length === 0) return;
-
- const bounds = L.latLngBounds(validMemos.map((memo) => [memo.location!.latitude, memo.location!.longitude]));
- map.fitBounds(bounds, { padding: [50, 50], maxZoom: 15 });
- }, [memos, map]);
-
- return null;
-};
-
-const UserMemoMap = ({ creator, className }: Props) => {
- const location = useLocation();
- const parentPage = `${location.pathname}${location.search}`;
- const creatorFilter = useMemo(() => buildMemoCreatorFilter(creator), [creator]);
-
- const { data, isLoading } = useInfiniteMemos(
- {
- state: State.NORMAL,
- orderBy: "create_time desc",
- pageSize: 1000,
- filter: creatorFilter,
- },
- { enabled: Boolean(creatorFilter) },
- );
-
- const memosWithLocation = useMemo(() => data?.pages.flatMap((page) => page.memos).filter((memo) => memo.location) || [], [data]);
-
- if (isLoading) return null;
-
- const defaultCenter = { lat: 48.8566, lng: 2.3522 };
-
- return (
- <div
- className={cn(
- "memo-user-map relative z-0 h-[380px] w-full overflow-hidden rounded-xl border border-border bg-background shadow-sm",
- className,
- )}
- >
- {memosWithLocation.length === 0 && (
- <div className="absolute inset-0 z-[1000] flex items-center justify-center pointer-events-none">
- <div className="flex flex-col items-center gap-1.5 rounded-xl border border-border bg-background/92 px-5 py-3 shadow-sm backdrop-blur-sm">
- <MapPinIcon className="h-5 w-5 text-muted-foreground opacity-70" />
- <p className="text-xs font-medium tracking-[0.02em] text-muted-foreground">No location data found</p>
- </div>
- </div>
- )}
-
- <div className="pointer-events-none absolute left-4 top-4 z-[950] flex items-start justify-between gap-3 rounded-xl border border-border bg-background/92 px-3 py-2.5 shadow-sm backdrop-blur-sm">
- <div className="flex items-center gap-2">
- <span className="grid size-7 place-items-center rounded-full bg-primary/10 text-primary">
- <MapPinIcon className="size-3.5" />
- </span>
- <div className="min-w-0">
- <p className="text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">Mapped memos</p>
- <p className="text-sm font-semibold text-foreground">{memosWithLocation.length} places pinned</p>
- </div>
- </div>
- </div>
-
- <MapContainer
- center={defaultCenter}
- zoom={2}
- className="map-attribution-minimal h-full w-full z-0 !bg-muted"
- scrollWheelZoom
- zoomControl={false}
- attributionControl={false}
- >
- <MinimalAttributionControl />
- <OpenStreetMapTileLayer />
- <MarkerClusterGroup
- chunkedLoading
- iconCreateFunction={createClusterCustomIcon}
- maxClusterRadius={40}
- spiderfyOnMaxZoom
- showCoverageOnHover={false}
- >
- {memosWithLocation.map((memo) => (
- <Marker
- key={memo.name}
- position={[memo.location!.latitude, memo.location!.longitude]}
- icon={defaultMarkerIcon}
- title={memo.snippet || "Memo location"}
- >
- <Popup
- closeButton={false}
- className={cn(
- "w-64!",
- "[&_.leaflet-popup-content-wrapper]:rounded-lg",
- "[&_.leaflet-popup-content-wrapper]:border",
- "[&_.leaflet-popup-content-wrapper]:border-border",
- "[&_.leaflet-popup-content-wrapper]:bg-background",
- "[&_.leaflet-popup-content-wrapper]:shadow-lg",
- "[&_.leaflet-popup-content]:m-1",
- "[&_.leaflet-popup-content]:[font-size:inherit]",
- "[&_.leaflet-popup-content]:[line-height:inherit]",
- "[&_.leaflet-popup-tip]:bg-background",
- )}
- >
- <div className="flex flex-col gap-2.5 p-3">
- <div className="flex items-start justify-between gap-3">
- <div className="space-y-1">
- <div className="flex flex-wrap items-center gap-1">
- <span className="inline-flex rounded-full border border-border/70 bg-muted/50 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
- Memo
- </span>
- <MemoSpaceBadge spaceName={memo.space} />
- </div>
- <span className="block text-[11px] font-medium text-muted-foreground">
- {memo.createTime &&
- timestampDate(memo.createTime).toLocaleDateString(undefined, {
- year: "numeric",
- month: "short",
- day: "numeric",
- })}
- </span>
- </div>
- <Link
- to={`/memos/${memo.name.split("/").pop()}`}
- state={createMemoNavigationState(parentPage)}
- className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2.5 py-1 text-[11px] font-medium text-foreground transition-all hover:border-primary/40 hover:text-primary"
- >
- Open
- <ArrowUpRightIcon className="h-3.5 w-3.5" />
- </Link>
- </div>
- <div className="space-y-1">
- <div className="line-clamp-3 text-sm leading-snug font-medium text-foreground">{memo.snippet || "No content"}</div>
- <div className="text-[11px] text-muted-foreground">
- {memo.location!.latitude.toFixed(2)}°, {memo.location!.longitude.toFixed(2)}°
- </div>
- </div>
- </div>
- </Popup>
- </Marker>
- ))}
- </MarkerClusterGroup>
- <MapFitBounds memos={memosWithLocation} />
- </MapContainer>
- </div>
- );
-};
-
-export default UserMemoMap;
diff --git a/web/src/components/UserMemoMap/index.ts b/web/src/components/UserMemoMap/index.ts
deleted file mode 100644
index f64b3914b..000000000
--- a/web/src/components/UserMemoMap/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "./UserMemoMap";
diff --git a/web/src/components/map/BasemapLayer.tsx b/web/src/components/map/BasemapLayer.tsx
new file mode 100644
index 000000000..83ab9e5ff
--- /dev/null
+++ b/web/src/components/map/BasemapLayer.tsx
@@ -0,0 +1,85 @@
+import type { MaplibreGL } from "leaflet";
+import { useEffect, useRef, useState } from "react";
+import { useMap } from "react-leaflet";
+import { useResolvedTheme } from "@/hooks/useResolvedTheme";
+import { isDarkTheme } from "@/utils/theme";
+import { OpenStreetMapTileLayer } from "./map-utils";
+
+let positronModule: Promise<typeof import("./positron")> | undefined;
+
+/** OpenFreeMap's quiet basemaps: Positron in light themes, its dark counterpart otherwise. */
+const basemapStyle = (dark: boolean) => `https://tiles.openfreemap.org/styles/${dark ? "dark" : "positron"}`;
+
+interface Props {
+ onTileError?: () => void;
+}
+
+export function BasemapLayer({ onTileError }: Props) {
+ const map = useMap();
+ const dark = isDarkTheme(useResolvedTheme());
+ const darkRef = useRef(dark);
+ darkRef.current = dark;
+ const layerRef = useRef<MaplibreGL>(undefined);
+ const [fallback, setFallback] = useState(false);
+
+ useEffect(() => {
+ if (fallback) return;
+ let cancelled = false;
+ let layer: MaplibreGL | undefined;
+ const fail = () => {
+ if (!cancelled) setFallback(true);
+ };
+ // Also cover a stalled style request, worker startup, or module download.
+ const timeout = window.setTimeout(fail, 15_000);
+ let ready = false;
+ const loaded = () => {
+ ready = true;
+ window.clearTimeout(timeout);
+ };
+ // Only a style that never loads, or a lost GL context, is fatal. MapLibre also reports every
+ // failed tile or sprite request here, and those are not a reason to abandon the vector map.
+ const failBeforeLoad = (event: unknown) => {
+ if (!ready && !(event as { tile?: unknown } | undefined)?.tile) fail();
+ };
+
+ positronModule ??= import("./positron");
+ void positronModule
+ .then(({ createPositronLayer }) => {
+ if (cancelled) return;
+ try {
+ layer = createPositronLayer(basemapStyle(darkRef.current));
+ layer.addTo(map);
+ } catch {
+ // The bridge cannot tear down a layer whose WebGL map never constructed, so drop its container here.
+ layer?.getContainer()?.remove();
+ layer = undefined;
+ fail();
+ return;
+ }
+ layerRef.current = layer;
+ const renderer = layer.getMaplibreMap();
+ renderer.on("load", loaded);
+ renderer.on("error", failBeforeLoad);
+ renderer.on("webglcontextlost", fail);
+ })
+ .catch(fail);
+
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timeout);
+ const renderer = layer?.getMaplibreMap();
+ renderer?.off("load", loaded);
+ renderer?.off("error", failBeforeLoad);
+ renderer?.off("webglcontextlost", fail);
+ layer?.remove();
+ layerRef.current = undefined;
+ };
+ }, [map, fallback]);
+
+ // A theme change restyles the live map; MapLibre diffs the styles and keeps its context and tiles.
+ useEffect(() => {
+ layerRef.current?.getMaplibreMap().setStyle(basemapStyle(dark));
+ }, [dark]);
+
+ return fallback ? <OpenStreetMapTileLayer eventHandlers={{ tileerror: () => onTileError?.() }} /> : null;
+}
diff --git a/web/src/components/map/LocationPicker.tsx b/web/src/components/map/LocationPicker.tsx
index 9c46dcbe1..c615b3994 100644
--- a/web/src/components/map/LocationPicker.tsx
+++ b/web/src/components/map/LocationPicker.tsx
@@ -5,6 +5,7 @@ import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { MapContainer, Marker, useMap, useMapEvents } from "react-leaflet";
import { cn } from "@/lib/utils";
+import { BasemapLayer } from "./BasemapLayer";
import { defaultMarkerIcon, MinimalAttributionControl, OpenStreetMapTileLayer } from "./map-utils";
import type { MapPoint } from "./types";
@@ -204,7 +205,7 @@ const noopOnLocationChange = () => {};
const LocationPicker = ({ readonly: readOnly = false, latlng, onChange = noopOnLocationChange, className }: LocationPickerProps) => {
const mapCenter = useMemo(() => toLatLng(latlng ?? DEFAULT_CENTER), [latlng?.lat, latlng?.lng]);
const markerPosition = latlng ? mapCenter : undefined;
- const statusLabel = readOnly ? "Pinned location" : latlng ? "Selected location" : "Choose a location";
+ const statusLabel = latlng ? "Selected location" : "Choose a location";
return (
<div
@@ -222,17 +223,20 @@ const LocationPicker = ({ readonly: readOnly = false, latlng, onChange = noopOnL
attributionControl={false}
>
<MinimalAttributionControl />
- <OpenStreetMapTileLayer />
+ {/* A read-only preview is a glance, not worth a WebGL renderer and a style download. */}
+ {readOnly ? <OpenStreetMapTileLayer /> : <BasemapLayer />}
<LocationMarker position={markerPosition} readonly={readOnly} onChange={onChange} />
<MapControls position={latlng} />
<MapCleanup />
</MapContainer>
- <div className="pointer-events-none absolute left-3 top-3 z-[450] flex items-center gap-2">
- <div className="rounded-full border border-border bg-background/92 px-2.5 py-1 text-[11px] font-medium tracking-[0.02em] text-foreground/80 shadow-sm backdrop-blur-sm">
- {statusLabel}
+ {!readOnly && (
+ <div className="pointer-events-none absolute left-3 top-3 z-[450] flex items-center gap-2">
+ <div className="rounded-full border border-border bg-background/92 px-2.5 py-1 text-[11px] font-medium tracking-[0.02em] text-foreground/80 shadow-sm backdrop-blur-sm">
+ {statusLabel}
+ </div>
</div>
- </div>
+ )}
</div>
);
};
diff --git a/web/src/components/map/map-utils.tsx b/web/src/components/map/map-utils.tsx
index 6cbdc8565..bb771c73e 100644
--- a/web/src/components/map/map-utils.tsx
+++ b/web/src/components/map/map-utils.tsx
@@ -1,30 +1,39 @@
import { DivIcon } from "leaflet";
import ReactDOMServer from "react-dom/server";
-import { AttributionControl, TileLayer } from "react-leaflet";
+import { AttributionControl, TileLayer, type TileLayerProps } from "react-leaflet";
const OPENSTREETMAP_TILE_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png";
const OPENSTREETMAP_ATTRIBUTION = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
-export const OpenStreetMapTileLayer = () => <TileLayer url={OPENSTREETMAP_TILE_URL} attribution={OPENSTREETMAP_ATTRIBUTION} maxZoom={19} />;
+export const OpenStreetMapTileLayer = ({ eventHandlers }: Pick<TileLayerProps, "eventHandlers"> = {}) => (
+ <TileLayer url={OPENSTREETMAP_TILE_URL} attribution={OPENSTREETMAP_ATTRIBUTION} maxZoom={19} eventHandlers={eventHandlers} />
+);
export const MinimalAttributionControl = () => <AttributionControl prefix={false} />;
interface MarkerIconOptions {
- fill?: string;
+ /** The box the dot is centered in; with a halo the tinted disc fills it. */
size?: number;
- className?: string;
+ /** Dot diameter. Defaults to the box minus 4px, the bare dot's breathing room. */
+ dot?: number;
+ /** A translucent disc behind the dot marks the selected point without a heavier dot. */
+ halo?: boolean;
}
export const createMarkerIcon = (options?: MarkerIconOptions): DivIcon => {
- const { fill = "var(--primary)", size = 24, className = "" } = options || {};
+ const { size = 24, dot = size - 4, halo = false } = options || {};
return new DivIcon({
className: "relative border-none bg-transparent",
html: ReactDOMServer.renderToString(
- <div aria-hidden="true" className={`grid place-items-center ${className}`.trim()} style={{ width: size, height: size }}>
+ <div
+ aria-hidden="true"
+ className={`grid place-items-center rounded-full ${halo ? "bg-primary/20" : ""}`.trim()}
+ style={{ width: size, height: size }}
+ >
<span
- className="rounded-full border-2 border-white shadow-[0_2px_7px_rgba(15,23,42,0.4)]"
- style={{ width: size - 4, height: size - 4, backgroundColor: fill }}
+ className="rounded-full border-2 border-white shadow-[0_1px_4px_rgba(15,23,42,0.4)]"
+ style={{ width: dot, height: dot, backgroundColor: "var(--primary)" }}
/>
</div>,
),
diff --git a/web/src/components/map/positron.ts b/web/src/components/map/positron.ts
new file mode 100644
index 000000000..f92dc40b2
--- /dev/null
+++ b/web/src/components/map/positron.ts
@@ -0,0 +1,17 @@
+import { maplibreGL } from "@maplibre/maplibre-gl-leaflet";
+import { setWorkerUrl } from "maplibre-gl";
+import workerUrl from "maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url";
+import "maplibre-gl/dist/maplibre-gl.css";
+
+setWorkerUrl(workerUrl);
+
+export function createPositronLayer(style: string) {
+ return maplibreGL({
+ style,
+ minZoom: -1,
+ attributionControl: {
+ customAttribution:
+ '<a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
+ },
+ });
+}
diff --git a/web/src/hooks/useMemoQueries.ts b/web/src/hooks/useMemoQueries.ts
index fecb5c2b3..8f4adbf0d 100644
--- a/web/src/hooks/useMemoQueries.ts
+++ b/web/src/hooks/useMemoQueries.ts
@@ -179,12 +179,13 @@ export function useMemos(request: Partial<ListMemosRequest> = {}) {
export function useInfiniteMemos(request: Partial<ListMemosRequest> = {}, options?: { enabled?: boolean }) {
return useInfiniteQuery({
queryKey: memoKeys.list(request),
- queryFn: async ({ pageParam }) => {
+ queryFn: async ({ pageParam, signal }) => {
const response = await memoServiceClient.listMemos(
create(ListMemosRequestSchema, {
...request,
pageToken: pageParam || "",
} as Record<string, unknown>),
+ { signal },
);
return response;
},
diff --git a/web/src/hooks/useResolvedTheme.ts b/web/src/hooks/useResolvedTheme.ts
new file mode 100644
index 000000000..e337b1cc7
--- /dev/null
+++ b/web/src/hooks/useResolvedTheme.ts
@@ -0,0 +1,15 @@
+import { useEffect, useState } from "react";
+import { useAuth } from "@/contexts/AuthContext";
+import { getSystemTheme, getThemeWithFallback, type ResolvedTheme, resolveTheme, setupSystemThemeListener } from "@/utils/theme";
+
+/** The theme actually in effect: the user's setting, or the OS scheme while that setting is "system". */
+export const useResolvedTheme = (): ResolvedTheme => {
+ const { userGeneralSetting } = useAuth();
+ const theme = getThemeWithFallback(userGeneralSetting?.theme);
+ const [systemTheme, setSystemTheme] = useState(getSystemTheme);
+ useEffect(() => {
+ if (theme !== "system") return;
+ return setupSystemThemeListener(() => setSystemTheme(getSystemTheme()));
+ }, [theme]);
+ return theme === "system" ? systemTheme : resolveTheme(theme);
+};
diff --git a/web/src/layouts/RootLayout.tsx b/web/src/layouts/RootLayout.tsx
index b809990f0..1cc00d8cb 100644
--- a/web/src/layouts/RootLayout.tsx
+++ b/web/src/layouts/RootLayout.tsx
@@ -16,6 +16,8 @@ import { MemoFilterProvider, useMemoFilterContext } from "@/contexts/MemoFilterC
import { SpaceProvider } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
+import { cn } from "@/lib/utils";
+import { ROUTES, resolveCollectionRoute } from "@/router/routes";
import { InstanceAccessMode } from "@/types/proto/api/v1/instance_service_pb";
import { buildAuthRoute, shouldGatePrivateInstance } from "@/utils/auth-redirect";
import { useTranslate } from "@/utils/i18n";
@@ -26,7 +28,7 @@ const DemoBanner = () => {
const t = useTranslate();
return (
- <div className="static w-full border-b border-border bg-muted/70 px-4 py-2 text-sm text-muted-foreground sm:px-6">
+ <div className="static w-full shrink-0 border-b border-border bg-muted/70 px-4 py-2 text-sm text-muted-foreground sm:px-6">
<div className="mx-auto flex max-w-5xl flex-col items-start gap-1 sm:flex-row sm:items-center sm:justify-center sm:gap-2">
<span className="font-medium text-foreground">{t("demo.banner-title")}</span>
<span>{t("demo.banner-description")}</span>
@@ -46,6 +48,8 @@ const RootLayoutContent = () => {
const { profile } = useInstance();
const { removeFilter } = useMemoFilterContext();
const { pathname } = location;
+ // The map fills the viewport and scrolls inside itself, so the document must not.
+ const fullBleed = resolveCollectionRoute(pathname).pathname.toLowerCase() === ROUTES.MAP;
const prevPathnameRef = useRef<string | undefined>(undefined);
const shellRef = useRef<HTMLDivElement>(null);
const { width: sidebarWidth, minWidth, maxWidth, setWidth: setSidebarWidth } = useSidebarWidth();
@@ -75,7 +79,11 @@ const RootLayoutContent = () => {
}
return (
- <div ref={shellRef} className="min-h-full w-full bg-background" style={{ [SIDEBAR_WIDTH_VAR]: `${sidebarWidth}px` } as CSSProperties}>
+ <div
+ ref={shellRef}
+ className={cn("w-full bg-background", fullBleed ? "h-dvh overflow-hidden" : "min-h-full")}
+ style={{ [SIDEBAR_WIDTH_VAR]: `${sidebarWidth}px` } as CSSProperties}
+ >
{md && (
<div className="fixed inset-y-0 start-0 z-30 w-(--app-sidebar-width) border-e border-border/70">
<AppSidebar />
@@ -89,7 +97,9 @@ const RootLayoutContent = () => {
</div>
)}
<MobileAppSidebar />
- <main className="flex min-h-full w-full min-w-0 flex-col items-center md:ps-(--app-sidebar-width)">
+ <main
+ className={cn("flex w-full min-w-0 flex-col items-center md:ps-(--app-sidebar-width)", fullBleed ? "h-full min-h-0" : "min-h-full")}
+ >
<MobileAppHeader />
{profile.demo && <DemoBanner />}
<Outlet />
diff --git a/web/src/lib/memo-views.ts b/web/src/lib/memo-views.ts
index 52c31ea60..251e9d71c 100644
--- a/web/src/lib/memo-views.ts
+++ b/web/src/lib/memo-views.ts
@@ -1,3 +1,4 @@
+import { matchPath } from "react-router-dom";
import { ROUTES, resolveCollectionRoute } from "@/router/routes";
export type MemoScope = "home" | "explore" | "archived";
@@ -43,7 +44,10 @@ export const isCalendarRoute = (pathname: string): boolean => {
* profile and the calendar. Views, calendar days and tags apply in place on all of them.
*/
export const isMemoCollectionRoute = (pathname: string): boolean =>
- isMemoScopeRoute(pathname) || getProfileUsername(pathname) !== undefined || isCalendarRoute(pathname);
+ isMemoScopeRoute(pathname) ||
+ getProfileUsername(pathname) !== undefined ||
+ isCalendarRoute(pathname) ||
+ matchPath(ROUTES.MAP, comparablePathname(pathname)) !== null;
export const getMemoScopePath = (scope: PrimaryMemoScope): string => (scope === "explore" ? ROUTES.EXPLORE : ROUTES.HOME);
diff --git a/web/src/locales/az.json b/web/src/locales/az.json
index 680f45be9..c9105703e 100644
--- a/web/src/locales/az.json
+++ b/web/src/locales/az.json
@@ -1,4 +1,25 @@
{
+ "map": {
+ "resize-panel": "Məkan panelinin enini dəyiş",
+ "collapse": "Paneli yığ",
+ "expand": "Paneli genişləndir",
+ "selection": "Seçilmiş qeydlər",
+ "loaded": "{{count}} qeyd yükləndi",
+ "fit-all": "Bütün nəticələri göstər",
+ "zoom-in": "Yaxınlaşdır",
+ "zoom-out": "Uzaqlaşdır",
+ "load-error": "Bütün qeydləri yükləmək mümkün olmadı.",
+ "tile-error": "Xəritə yüklənmədi. Qeydləriniz hələ də əlçatandır.",
+ "empty": "Hələ məkanı olan qeyd yoxdur",
+ "empty-hint": "Qeydi burada görmək üçün ona məkan əlavə edin.",
+ "no-results": "Uyğun qeyd yoxdur",
+ "no-results-hint": "Filtrləri təmizləməyi sınayın.",
+ "clear-filters": "Filtrləri təmizlə",
+ "loading": "Qeydlər yüklənir…",
+ "new-here": "Burada qeyd yaz",
+ "saved-outside-filter": "Saxlanıldı. Bu qeyd cari xəritə nəticələrinə daxil deyil.",
+ "open-memo": "Qeydi aç"
+ },
"about": {
"api-docs": "API sənədləri",
"api-docs-note": "REST və gRPC arayışı",
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index e2786193e..a4457d161 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -1,4 +1,25 @@
{
+ "map": {
+ "resize-panel": "Resize location panel",
+ "collapse": "Collapse panel",
+ "expand": "Expand panel",
+ "selection": "Selected memos",
+ "loaded": "{{count}} loaded",
+ "fit-all": "Show all results",
+ "zoom-in": "Zoom in",
+ "zoom-out": "Zoom out",
+ "load-error": "Could not load all memos.",
+ "tile-error": "The map could not load. Your memos are still available.",
+ "empty": "No memos with a location yet",
+ "empty-hint": "Add a location to a memo to see it here.",
+ "no-results": "No matching memos",
+ "no-results-hint": "Try clearing your filters.",
+ "clear-filters": "Clear filters",
+ "loading": "Loading memos…",
+ "new-here": "Write here",
+ "saved-outside-filter": "Saved. This memo is outside the current map results.",
+ "open-memo": "Open memo"
+ },
"about": {
"api-docs": "API Docs",
"api-docs-note": "REST and gRPC reference",
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 7c589c6fc..277d9b2c5 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -1,4 +1,25 @@
{
+ "map": {
+ "resize-panel": "调整地点面板宽度",
+ "collapse": "收起面板",
+ "expand": "展开面板",
+ "selection": "选中的 Memo",
+ "loaded": "已加载 {{count}} 条",
+ "fit-all": "查看全部结果",
+ "zoom-in": "放大",
+ "zoom-out": "缩小",
+ "load-error": "未能加载全部 Memo。",
+ "tile-error": "地图加载失败,你仍可以阅读 Memo。",
+ "empty": "还没有带位置的 Memo",
+ "empty-hint": "给 Memo 添加位置后,它就会显示在这里。",
+ "no-results": "没有符合条件的 Memo",
+ "no-results-hint": "试试清除筛选条件。",
+ "clear-filters": "清除筛选",
+ "loading": "正在加载 Memo…",
+ "new-here": "在这里记录",
+ "saved-outside-filter": "已保存,这条 Memo 不在当前地图结果中。",
+ "open-memo": "打开 Memo"
+ },
"about": {
"api-docs": "API 文档",
"api-docs-note": "REST 与 gRPC 参考",
diff --git a/web/src/pages/Map.tsx b/web/src/pages/Map.tsx
new file mode 100644
index 000000000..f36f2794a
--- /dev/null
+++ b/web/src/pages/Map.tsx
@@ -0,0 +1,3 @@
+import { MapView } from "@/components/MapView/MapView";
+
+export default MapView;
diff --git a/web/src/pages/UserProfile.tsx b/web/src/pages/UserProfile.tsx
index a7c3a875a..598bae22d 100644
--- a/web/src/pages/UserProfile.tsx
+++ b/web/src/pages/UserProfile.tsx
@@ -1,6 +1,6 @@
import { UserRoundIcon } from "lucide-react";
-import { type ReactNode, Suspense } from "react";
-import { Link, useParams, useSearchParams } from "react-router-dom";
+import { type ReactNode } from "react";
+import { Link, useParams } from "react-router-dom";
import MemoView from "@/components/MemoView";
import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import UserAvatar from "@/components/UserAvatar";
@@ -16,11 +16,6 @@ import { State } from "@/types/proto/api/v1/common_pb";
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
import type { User } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
-import { lazyWithReload } from "@/utils/lazy";
-
-type TabView = "memos" | "map";
-
-const UserMemoMap = lazyWithReload(() => import("@/components/UserMemoMap"));
const PROFILE_TITLE_CLASSES = "text-xl font-semibold leading-7 tracking-[-0.01em] text-foreground";
const PROFILE_AVATAR_SLOT_CLASSES = "mt-0.5 size-10 shrink-0 rounded-lg";
@@ -79,9 +74,7 @@ const ProfileNotFound = ({ username }: { username: string }) => {
const UserProfile = () => {
const t = useTranslate();
const username = useParams().username ?? "";
- const [searchParams] = useSearchParams();
const currentUser = useCurrentUser();
- const activeTab = (searchParams.get("view") === "map" ? "map" : "memos") as TabView;
const { data: user, isLoading } = useUser(`${userNamePrefix}${username}`, { enabled: !!username });
const showSkeleton = useDelayedFlag(isLoading, LOADING_INDICATOR_DELAY_MS);
@@ -97,7 +90,7 @@ const UserProfile = () => {
state: State.NORMAL,
});
- if (user && activeTab === "memos") {
+ if (user) {
// Visitors only see what the backend lets them see, so an empty list means nothing
// shared rather than nothing written. The owner sees everything and gets the default.
const isOwner = currentUser?.name === user.name;
@@ -118,18 +111,7 @@ const UserProfile = () => {
// Everything that is not the list shares the list's single-column reading rail.
return (
<section className="mx-auto flex w-full max-w-2xl flex-col gap-4">
- {isLoading ? (
- showSkeleton && <ProfileHeaderSkeleton />
- ) : !user ? (
- <ProfileNotFound username={username} />
- ) : (
- <>
- <ProfileHeader user={user} />
- <Suspense fallback={<div className="h-[60dvh] rounded-xl border border-border bg-muted/30 sm:h-[500px]" />}>
- <UserMemoMap creator={user.name} className="h-[60dvh] rounded-xl sm:h-[500px]" />
- </Suspense>
- </>
- )}
+ {isLoading ? showSkeleton && <ProfileHeaderSkeleton /> : <ProfileNotFound username={username} />}
</section>
);
};
diff --git a/web/src/router/index.tsx b/web/src/router/index.tsx
index 7c8308d76..81b61a1e5 100644
--- a/web/src/router/index.tsx
+++ b/web/src/router/index.tsx
@@ -18,6 +18,7 @@ const AdminSignIn = lazyWithReload(() => import("@/pages/AdminSignIn"));
const About = lazyWithReload(() => import("@/pages/About"));
const Archived = lazyWithReload(() => import("@/pages/Archived"));
const AuthCallback = lazyWithReload(() => import("@/pages/AuthCallback"));
+const MemoMap = lazyWithReload(() => import("@/pages/Map"));
const Calendar = lazyWithReload(() => import("@/pages/Calendar"));
const Explore = lazyWithReload(() => import("@/pages/Explore"));
const Home = lazyWithReload(() => import("@/pages/Home"));
@@ -123,12 +124,14 @@ export const routeConfig: RouteObject[] = [
],
},
{ path: "attachments", element: <Attachments /> },
+ { path: "map", element: <MemoMap /> },
],
},
{ path: "*", element: <NotFound /> },
],
},
{ path: Routes.ATTACHMENTS, element: <Attachments /> },
+ { path: Routes.MAP, element: <MemoMap /> },
{ path: Routes.INBOX, element: <Inboxes /> },
{ path: Routes.SETTING, element: <Setting /> },
],
diff --git a/web/src/router/routes.ts b/web/src/router/routes.ts
index 50afcc686..627f25ec9 100644
--- a/web/src/router/routes.ts
+++ b/web/src/router/routes.ts
@@ -8,6 +8,7 @@ export const ROUTES = {
INBOX: "/inbox",
ARCHIVED: "/archived",
CALENDAR: "/calendar",
+ MAP: "/map",
VIEWS: "/views",
SETTING: "/setting",
EXPLORE: "/explore",
@@ -28,7 +29,7 @@ export type RoutePath = (typeof ROUTES)[RouteKey];
export const SPACE_ROUTE_PATTERN = "/spaces/:spaceUid";
/** Collection pages that exist both globally and beneath a Space. */
-const COLLECTION_ROUTE_PATTERNS = [ROUTES.HOME, ROUTES.EXPLORE, ROUTES.ATTACHMENTS, CALENDAR_ROUTE_PATTERN];
+const COLLECTION_ROUTE_PATTERNS = [ROUTES.HOME, ROUTES.EXPLORE, ROUTES.ATTACHMENTS, CALENDAR_ROUTE_PATTERN, ROUTES.MAP];
const isCollectionPathname = (pathname: string): boolean =>
COLLECTION_ROUTE_PATTERNS.some((path) => matchPath({ path, caseSensitive: false }, pathname) !== null);
diff --git a/web/src/utils/theme.ts b/web/src/utils/theme.ts
index caed6dcf8..2232be921 100644
--- a/web/src/utils/theme.ts
+++ b/web/src/utils/theme.ts
@@ -182,7 +182,7 @@ const updateThemeColorMeta = (theme: ResolvedTheme): void => {
}
};
-const isDarkTheme = (theme: ResolvedTheme): boolean => {
+export const isDarkTheme = (theme: ResolvedTheme): boolean => {
return theme.endsWith("-dark") || theme.endsWith(".dark");
};
diff --git a/web/tests/basemap-layer.test.tsx b/web/tests/basemap-layer.test.tsx
new file mode 100644
index 000000000..ebc7a1ade
--- /dev/null
+++ b/web/tests/basemap-layer.test.tsx
@@ -0,0 +1,104 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { StrictMode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { BasemapLayer } from "@/components/map/BasemapLayer";
+import { createPositronLayer } from "@/components/map/positron";
+
+const mocks = vi.hoisted(() => ({
+ map: { setView: vi.fn(), fitBounds: vi.fn() },
+ create: vi.fn(),
+}));
+
+vi.mock("react-leaflet", () => ({ useMap: () => mocks.map }));
+vi.mock("@/hooks/useResolvedTheme", () => ({ useResolvedTheme: () => "default" }));
+vi.mock("@/components/map/positron", () => ({ createPositronLayer: mocks.create }));
+vi.mock("@/components/map/map-utils", () => ({
+ OpenStreetMapTileLayer: ({ eventHandlers }: { eventHandlers: { tileerror: () => void } }) => (
+ <button type="button" onClick={eventHandlers.tileerror}>
+ OSM fallback
+ </button>
+ ),
+}));
+
+describe("BasemapLayer", () => {
+ let listeners: Map<string, () => void>;
+ let layer: { addTo: ReturnType<typeof vi.fn>; remove: ReturnType<typeof vi.fn>; getMaplibreMap: ReturnType<typeof vi.fn> };
+
+ beforeEach(() => {
+ listeners = new Map();
+ layer = {
+ addTo: vi.fn(),
+ remove: vi.fn(),
+ getMaplibreMap: vi.fn(() => ({
+ on: (event: string, callback: () => void) => listeners.set(event, callback),
+ off: (event: string) => listeners.delete(event),
+ })),
+ };
+ vi.mocked(createPositronLayer).mockReturnValue(layer as unknown as ReturnType<typeof createPositronLayer>);
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it("loads the vector layer without moving the map and cleans up on unmount", async () => {
+ const view = render(<BasemapLayer />);
+ await waitFor(() => expect(layer.addTo).toHaveBeenCalledWith(mocks.map));
+ expect(screen.queryByText("OSM fallback")).not.toBeInTheDocument();
+ expect(mocks.map.setView).not.toHaveBeenCalled();
+ expect(mocks.map.fitBounds).not.toHaveBeenCalled();
+ view.unmount();
+ expect(layer.remove).toHaveBeenCalledOnce();
+ expect(listeners.size).toBe(0);
+ });
+
+ it.each(["error", "webglcontextlost"])("falls back on %s without reporting a failure until OSM also fails", async (event) => {
+ const onTileError = vi.fn();
+ render(<BasemapLayer onTileError={onTileError} />);
+ await waitFor(() => expect(listeners.has(event)).toBe(true));
+ act(() => listeners.get(event)!());
+ expect(layer.remove).toHaveBeenCalledOnce();
+ expect(onTileError).not.toHaveBeenCalled();
+ act(() => screen.getByRole("button", { name: "OSM fallback" }).click());
+ expect(onTileError).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back when WebGL initialization throws", async () => {
+ layer.addTo.mockImplementation(() => {
+ throw new Error("WebGL unavailable");
+ });
+ render(<BasemapLayer />);
+ expect(await screen.findByText("OSM fallback")).toBeInTheDocument();
+ expect(layer.remove).toHaveBeenCalledOnce();
+ });
+
+ it("falls back on a stalled load", async () => {
+ vi.useFakeTimers();
+ render(<BasemapLayer />);
+ await act(async () => vi.advanceTimersByTimeAsync(15_000));
+ expect(screen.getByText("OSM fallback")).toBeInTheDocument();
+ });
+
+ it("keeps a loaded vector layer past the initial timeout", async () => {
+ vi.useFakeTimers();
+ render(<BasemapLayer />);
+ await act(async () => vi.advanceTimersByTimeAsync(0));
+ act(() => listeners.get("load")!());
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(screen.queryByText("OSM fallback")).not.toBeInTheDocument();
+ });
+
+ it("does not attach a late import after unmount", async () => {
+ const view = render(<BasemapLayer />);
+ view.unmount();
+ await act(async () => {});
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+
+ it("attaches only the active effect's layer in Strict Mode", async () => {
+ render(
+ <StrictMode>
+ <BasemapLayer />
+ </StrictMode>,
+ );
+ await waitFor(() => expect(layer.addTo).toHaveBeenCalledOnce());
+ });
+});
diff --git a/web/tests/date-filter-navigation.test.tsx b/web/tests/date-filter-navigation.test.tsx
index a9b4e852b..82d014115 100644
--- a/web/tests/date-filter-navigation.test.tsx
+++ b/web/tests/date-filter-navigation.test.tsx
@@ -20,7 +20,7 @@ const Harness = () => {
describe("useDateFilterNavigation", () => {
it("preserves unrelated query parameters while replacing the date filter", async () => {
render(
- <MemoryRouter initialEntries={["/u/steven?view=map&filter=tagSearch%3Awork"]}>
+ <MemoryRouter initialEntries={["/u/steven?sort=displayTime&filter=tagSearch%3Awork"]}>
<MemoFilterProvider>
<Harness />
</MemoFilterProvider>
@@ -31,7 +31,7 @@ describe("useDateFilterNavigation", () => {
await waitFor(() => {
const params = new URLSearchParams(screen.getByTestId("search").textContent ?? "");
- expect(params.get("view")).toBe("map");
+ expect(params.get("sort")).toBe("displayTime");
expect(params.get("filter")).toContain("tagSearch:work");
expect(params.get("filter")).toContain("displayTime:2026-08-02");
});
diff --git a/web/tests/location-display-view.test.tsx b/web/tests/location-display-view.test.tsx
index 43c80e20f..d932f621f 100644
--- a/web/tests/location-display-view.test.tsx
+++ b/web/tests/location-display-view.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import LocationDisplayView from "@/components/MemoMetadata/Location/LocationDisplayView";
import type { Location } from "@/types/proto/api/v1/memo_service_pb";
@@ -8,6 +8,28 @@ vi.mock("@/components/map/LazyLocationPicker", () => ({
}));
describe("LocationDisplayView", () => {
+ it("shows the place name first and reveals coordinates only with the map", async () => {
+ render(<LocationDisplayView location={{ latitude: 35.005, longitude: 135.768, placeholder: "Kyoto coffee" } as Location} />);
+ const trigger = screen.getByRole("button", { name: "Kyoto coffee" });
+ expect(trigger).toHaveTextContent(/^Kyoto coffee$/);
+ expect(screen.queryByTestId("location-picker")).not.toBeInTheDocument();
+ expect(screen.queryByText(/35\.005/)).not.toBeInTheDocument();
+
+ fireEvent.click(trigger);
+ expect(await screen.findByTestId("location-picker")).toBeVisible();
+ expect(screen.getByText("35.005000°, 135.768000°")).toBeVisible();
+ });
+
+ it.each(["", " "])("uses one coordinate label for an unnamed location, including zero", (placeholder) => {
+ render(<LocationDisplayView location={{ latitude: 0, longitude: 0, placeholder } as Location} />);
+ expect(screen.getByRole("button", { name: "0.0000°, 0.0000°" })).toHaveTextContent(/^0.0000°, 0.0000°$/);
+ });
+
+ it("renders nothing without a location", () => {
+ const { container } = render(<LocationDisplayView />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
it("truncates the visible address while preserving the full value as a title", () => {
const placeholder = "A very long street address that should not force the memo metadata row wider than its container";
const location = { latitude: 1.3521, longitude: 103.8198, placeholder } as Location;
diff --git a/web/tests/location-picker.test.tsx b/web/tests/location-picker.test.tsx
index 12ba33394..89e54e958 100644
--- a/web/tests/location-picker.test.tsx
+++ b/web/tests/location-picker.test.tsx
@@ -61,9 +61,10 @@ vi.mock("react-leaflet", () => ({
vi.mock("@/components/map/map-utils", () => ({
defaultMarkerIcon: {},
MinimalAttributionControl: () => <div data-testid="attribution" />,
- OpenStreetMapTileLayer: () => <div data-testid="map-layer" />,
}));
+vi.mock("@/components/map/BasemapLayer", () => ({ BasemapLayer: () => <div data-testid="map-layer" /> }));
+
describe("LocationPicker", () => {
it("uses the explicit minimal attribution control", () => {
const { getByTestId } = render(<LocationPicker />);
diff --git a/web/tests/map-canvas.test.tsx b/web/tests/map-canvas.test.tsx
new file mode 100644
index 000000000..9ca66ce5c
--- /dev/null
+++ b/web/tests/map-canvas.test.tsx
@@ -0,0 +1,87 @@
+import { create } from "@bufbuild/protobuf";
+import { render } from "@testing-library/react";
+import type { ComponentProps, ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MapCanvas } from "@/components/MapView/MapCanvas";
+import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
+
+const map = vi.hoisted(() => ({
+ getContainer: vi.fn(),
+ invalidateSize: vi.fn(),
+ getCenter: () => ({ wrap: () => ({ lat: 35, lng: 135 }) }),
+ getZoom: () => 12,
+ getSize: () => ({ x: 1000, y: 800 }),
+ latLngToContainerPoint: () => ({ x: 800, y: 400 }),
+ setView: vi.fn(),
+ fitBounds: vi.fn(),
+ panBy: vi.fn(),
+}));
+vi.mock("react-leaflet", () => ({
+ MapContainer: ({ children }: { children: ReactNode }) => children,
+ Marker: () => null,
+ useMap: () => map,
+ useMapEvents: () => map,
+}));
+vi.mock("react-leaflet-cluster", () => ({ default: ({ children }: { children: ReactNode }) => children }));
+vi.mock("@/components/map/map-utils", () => ({
+ createMarkerIcon: () => ({}),
+ MinimalAttributionControl: () => null,
+}));
+
+vi.mock("@/components/map/BasemapLayer", () => ({ BasemapLayer: () => null }));
+
+beforeEach(() => {
+ map.getContainer.mockReturnValue(document.createElement("div"));
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+});
+afterEach(() => vi.unstubAllGlobals());
+
+const memo = create(MemoSchema, { name: "memos/selected", location: { latitude: 35, longitude: 135 } });
+function props(): ComponentProps<typeof MapCanvas> {
+ return {
+ memos: [],
+ selected: [],
+ complete: false,
+ desktop: true,
+ panelSize: { width: 0, height: 0 },
+ onSelect: vi.fn(),
+ onDismiss: vi.fn(),
+ onMove: vi.fn(),
+ onReady: vi.fn(),
+ onTileError: vi.fn(),
+ };
+}
+
+describe("map viewport", () => {
+ it("reveals a deep-linked marker when its page arrives without changing zoom", () => {
+ const initial = {
+ ...props(),
+ viewport: { lat: 35, lng: 135, zoom: 12 },
+ selected: [memo.name],
+ panelSize: { width: 400, height: 776 },
+ };
+ const { rerender } = render(<MapCanvas {...initial} />);
+ expect(map.panBy).not.toHaveBeenCalled();
+ rerender(<MapCanvas {...initial} memos={[memo]} complete />);
+ expect(map.panBy).toHaveBeenCalledWith([240, 0], { animate: false });
+ expect(map.fitBounds).not.toHaveBeenCalled();
+ expect(map.setView).not.toHaveBeenCalled();
+ });
+ it("fits once after complete loading and never refits on a later refresh or panel change", () => {
+ const initial = props();
+ const { rerender } = render(<MapCanvas {...initial} memos={[memo]} />);
+ expect(map.fitBounds).not.toHaveBeenCalled();
+ rerender(<MapCanvas {...initial} memos={[memo]} complete />);
+ expect(map.fitBounds).toHaveBeenCalledOnce();
+ rerender(
+ <MapCanvas {...initial} memos={[memo, { ...memo, name: "memos/another" }]} complete panelSize={{ width: 400, height: 776 }} />,
+ );
+ expect(map.fitBounds).toHaveBeenCalledOnce();
+ });
+});
diff --git a/web/tests/map-memos.test.tsx b/web/tests/map-memos.test.tsx
new file mode 100644
index 000000000..9919a4c3a
--- /dev/null
+++ b/web/tests/map-memos.test.tsx
@@ -0,0 +1,122 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useMapMemos } from "@/components/MapView/useMapMemos";
+import { memoDetailQueryOptions, useDeleteMemo, useUpdateMemo } from "@/hooks/useMemoQueries";
+import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
+
+const state = vi.hoisted(() => ({ list: vi.fn(), update: vi.fn(), delete: vi.fn(), get: vi.fn(), filter: "", settingsReady: true }));
+vi.mock("@/connect", () => ({
+ memoServiceClient: { listMemos: state.list, updateMemo: state.update, deleteMemo: state.delete, getMemo: state.get },
+}));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ isUserSettingsInitialized: state.settingsReady }) }));
+vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ memoFilter: 'space == "spaces/travel"' }) }));
+vi.mock("@/contexts/ViewContext", () => ({ useView: () => ({ timeBasis: "create_time" }) }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/qa" }) }));
+vi.mock("@/hooks/useMemoFilters", () => ({ useMemoFilters: () => state.filter }));
+
+function setup() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+ return { client, wrapper, ...renderHook(() => useMapMemos(), { wrapper }) };
+}
+const page = (offset: number, count: number, nextPageToken = "") => ({
+ memos: Array.from({ length: count }, (_, index) =>
+ create(MemoSchema, { name: `memos/${offset + index}`, location: { latitude: 35, longitude: 135 } }),
+ ),
+ nextPageToken,
+});
+
+describe("map pagination", () => {
+ beforeEach(() => {
+ state.filter = "";
+ state.settingsReady = true;
+ });
+ it("automatically drains every page and scopes the requests", async () => {
+ state.list
+ .mockResolvedValueOnce(page(0, 500, "second"))
+ .mockResolvedValueOnce(page(500, 500, "third"))
+ .mockResolvedValueOnce(page(1000, 12));
+ const { result } = setup();
+ await waitFor(() => expect(result.current.complete).toBe(true));
+ expect(result.current.memos).toHaveLength(1012);
+ expect(state.list.mock.calls.map(([request]) => request.pageToken)).toEqual(["", "second", "third"]);
+ const request = state.list.mock.calls[0][0];
+ expect(request.pageSize).toBe(500);
+ expect(request.filter).toContain('creator == "users/qa"');
+ expect(request.filter).toContain('space == "spaces/travel"');
+ expect(request.filter).toContain("has_location");
+ });
+ it("retains partial results without claiming completion and retries the failed page", async () => {
+ state.list
+ .mockResolvedValueOnce(page(0, 500, "second"))
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce(page(500, 2));
+ const { result } = setup();
+ await waitFor(() => expect(result.current.isFetchNextPageError).toBe(true));
+ expect(result.current.complete).toBe(false);
+ expect(result.current.memos).toHaveLength(500);
+ await act(async () => {
+ await result.current.retry();
+ });
+ await waitFor(() => expect(result.current.complete).toBe(true));
+ expect(result.current.memos).toHaveLength(502);
+ });
+ it("cancels the previous request when filters change", async () => {
+ let signal: AbortSignal | undefined;
+ state.list
+ .mockImplementationOnce((_request, options) => {
+ signal = options.signal;
+ return new Promise((_resolve, reject) =>
+ signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))),
+ );
+ })
+ .mockResolvedValueOnce(page(0, 1));
+ const { result, rerender } = setup();
+ await waitFor(() => expect(state.list).toHaveBeenCalledOnce());
+ state.filter = '"work" in tags';
+ rerender();
+ await waitFor(() => expect(result.current.complete).toBe(true));
+ expect(signal?.aborted).toBe(true);
+ expect(result.current.memos).toHaveLength(1);
+ });
+ it("waits for content hiding preferences before requesting memos", () => {
+ state.settingsReady = false;
+ const { result } = setup();
+ expect(state.list).not.toHaveBeenCalled();
+ expect(result.current.complete).toBe(false);
+ });
+ it("reflects location updates and deletion through the shared mutation cache", async () => {
+ const original = page(0, 1);
+ state.list.mockResolvedValueOnce(original);
+ const { result, wrapper } = setup();
+ await waitFor(() => expect(result.current.complete).toBe(true));
+ const updated = { ...original.memos[0], location: { ...original.memos[0].location!, latitude: 0, longitude: 0 } };
+ state.update.mockResolvedValueOnce(updated);
+ state.list.mockResolvedValueOnce({ memos: [updated], nextPageToken: "" });
+ const mutations = renderHook(() => ({ update: useUpdateMemo(), remove: useDeleteMemo() }), { wrapper });
+ await act(async () => {
+ await mutations.result.current.update.mutateAsync({ update: updated, updateMask: ["location"] });
+ });
+ await waitFor(() => expect(result.current.memos[0].location?.latitude).toBe(0));
+ state.delete.mockResolvedValueOnce({});
+ state.list.mockResolvedValueOnce(page(0, 0));
+ await act(async () => {
+ await mutations.result.current.remove.mutateAsync(updated.name);
+ });
+ await waitFor(() => expect(result.current.memos).toHaveLength(0));
+ });
+ it("removes a denied memo from map pages when detail access expires", async () => {
+ state.list.mockResolvedValueOnce(page(0, 1));
+ const { client, result } = setup();
+ await waitFor(() => expect(result.current.complete).toBe(true));
+ state.get.mockRejectedValueOnce(new ConnectError("no longer available", Code.PermissionDenied));
+ await act(async () => {
+ await client.fetchQuery(memoDetailQueryOptions("memos/0"));
+ });
+ await waitFor(() => expect(result.current.memos).toHaveLength(0));
+ });
+});
diff --git a/web/tests/map-model.test.ts b/web/tests/map-model.test.ts
new file mode 100644
index 000000000..6d5af0ce4
--- /dev/null
+++ b/web/tests/map-model.test.ts
@@ -0,0 +1,54 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, it } from "vitest";
+import { locationKey, mapMemos, readViewport, revealOffset, splitLabel, validLocation } from "@/components/MapView/model";
+import { LocationSchema, MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
+
+const memo = (name: string, latitude = 0, longitude = 0) => create(MemoSchema, { name, location: { latitude, longitude } });
+
+describe("map model", () => {
+ it("keeps all pages, deduplicates resources and takes their latest location", () => {
+ const pages = Array.from({ length: 3 }, (_, page) => ({
+ memos: Array.from({ length: 500 }, (_, index) => memo(`memos/${page * 500 + index}`)),
+ }));
+ pages.push({ memos: [memo("memos/1", 35, 135)] });
+ const result = mapMemos(pages, "create_time");
+ expect(result).toHaveLength(1500);
+ expect(result.find((item) => item.name === "memos/1")?.location?.latitude).toBe(35);
+ });
+ it("accepts zero coordinates and rejects invalid positions", () => {
+ expect(validLocation(create(LocationSchema))).toBe(true);
+ for (const [latitude, longitude] of [
+ [NaN, 0],
+ [0, Infinity],
+ [91, 0],
+ [0, -181],
+ ]) {
+ expect(validLocation(create(LocationSchema, { latitude, longitude }))).toBe(false);
+ }
+ expect(
+ mapMemos([{ memos: [memo("valid"), memo("invalid", 95), create(MemoSchema, { name: "missing" })] }], "create_time").map(
+ (item) => item.name,
+ ),
+ ).toEqual(["valid"]);
+ });
+ it("does not merge different coordinates based on their labels", () => {
+ const a = create(LocationSchema, { placeholder: "Cafe", latitude: 1, longitude: 2 });
+ const b = create(LocationSchema, { placeholder: "Cafe", latitude: 1, longitude: 3 });
+ expect(locationKey(a)).not.toBe(locationKey(b));
+ });
+ it("validates a restorable viewport", () => {
+ expect(readViewport("?lat=0&lng=0&zoom=0")).toEqual({ lat: 0, lng: 0, zoom: 0 });
+ for (const search of ["", "?lat=&lng=0&zoom=1", "?lat=91&lng=0&zoom=3", "?lat=0&lng=0&zoom=20"])
+ expect(readViewport(search)).toBeUndefined();
+ });
+ it("only pans a covered marker and never changes zoom", () => {
+ expect(revealOffset({ x: 800, y: 300 }, { x: 1000, y: 800 }, { width: 400, height: 780 }, true)).toEqual([240, 0]);
+ expect(revealOffset({ x: 100, y: 300 }, { x: 1000, y: 800 }, { width: 400, height: 780 }, true)).toEqual([0, 0]);
+ expect(revealOffset({ x: 100, y: 650 }, { x: 390, y: 800 }, { width: 390, height: 360 }, false)).toEqual([0, 242]);
+ });
+ it("leads a geocoded label with its place", () => {
+ expect(splitLabel("Qiucun, Guangde, Anhui")).toEqual({ title: "Qiucun", subtitle: "Guangde, Anhui" });
+ expect(splitLabel("Kyoto")).toEqual({ title: "Kyoto" });
+ expect(splitLabel("Kyoto, ")).toEqual({ title: "Kyoto, " });
+ });
+});
diff --git a/web/tests/map-routes.test.ts b/web/tests/map-routes.test.ts
new file mode 100644
index 000000000..91d481ce7
--- /dev/null
+++ b/web/tests/map-routes.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { getRouteActionPolicy, getSidebarRouteKind } from "@/components/AppSidebar/routes";
+import { createMemoNavigationState, resolveMemoDetailOrigin, withMemoFilter } from "@/components/MemoView/navigation";
+import { isMemoCollectionRoute } from "@/lib/memo-views";
+import { getSpaceSwitchPath, resolveCollectionRoute } from "@/router/routes";
+
+describe("map navigation", () => {
+ it.each(["/map", "/spaces/travel/map"])("recognizes %s as a filterable collection", (pathname) => {
+ expect(resolveCollectionRoute(pathname).isCollection).toBe(true);
+ expect(isMemoCollectionRoute(pathname)).toBe(true);
+ expect(getSidebarRouteKind(pathname)).toBe("map");
+ });
+ it("preserves viewport, selection and filters across Space switches and memo detail", () => {
+ const search = "?lat=35&lng=135&zoom=14&memo=memos%2Fone&filter=tagSearch%3Atravel";
+ expect(getSpaceSwitchPath({ pathname: "/map", search }, "spaces/travel")).toBe(`/spaces/travel/map${search}`);
+ expect(resolveMemoDetailOrigin(createMemoNavigationState(`/map${search}`))).toBe(`/map${search}`);
+ expect(withMemoFilter(`/map${search}`, "tagSearch:food")).toContain("lat=35&lng=135&zoom=14&memo=memos%2Fone&filter=tagSearch%3Afood");
+ });
+ it("sends Quick Find to Home within the active collection", () => {
+ expect(getRouteActionPolicy("/map")).toEqual({ searchScope: "route-collection", searchDestination: "/" });
+ expect(getRouteActionPolicy("/spaces/travel/map")).toEqual({ searchScope: "route-collection", searchDestination: "/spaces/travel" });
+ });
+});
diff --git a/web/tests/map-view.test.tsx b/web/tests/map-view.test.tsx
new file mode 100644
index 000000000..678e42e0c
--- /dev/null
+++ b/web/tests/map-view.test.tsx
@@ -0,0 +1,108 @@
+import { create } from "@bufbuild/protobuf";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MapView } from "@/components/MapView/MapView";
+import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
+
+const mocks = vi.hoisted(() => ({ editor: {} as MemoEditorProps, refetch: vi.fn(), toast: vi.fn() }));
+const item = create(MemoSchema, { name: "memos/one", location: { placeholder: "Kyoto", latitude: 35, longitude: 135 } });
+vi.mock("@/components/MapView/MapCanvas", () => ({ MapCanvas: () => <div data-testid="map" />, fitMemos: vi.fn() }));
+vi.mock("@/components/MapView/MapPanel", () => ({
+ MapPanel: ({ open, busy, children }: { open: boolean; busy: boolean; children: ReactNode }) =>
+ open ? (
+ <div data-testid="panel" data-busy={busy}>
+ {children}
+ </div>
+ ) : null,
+}));
+vi.mock("@/components/MapView/useMapMemos", () => ({
+ useMapMemos: () => ({ memos: [item], complete: true, refetch: mocks.refetch }),
+}));
+vi.mock("@/components/MemoEditor", () => ({
+ default: (props: MemoEditorProps) => {
+ mocks.editor = props;
+ return <div data-testid="editor" />;
+ },
+}));
+vi.mock("@/components/MemoView", () => ({ default: () => <p>Memo</p> }));
+vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+ MentionResolutionProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@/contexts/NewMemoContext", () => ({ NewMemoProvider: ({ children }: { children: ReactNode }) => children }));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ isUserSettingsInitialized: true }) }));
+vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ selectedSpaceName: "spaces/travel" }) }));
+vi.mock("@/contexts/MemoFilterContext", () => ({ useMemoFilterContext: () => ({ filters: [], removeFilter: vi.fn() }) }));
+vi.mock("@/contexts/ViewContext", () => ({ useView: () => ({ timeBasis: "create_time", compactMode: false }) }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/qa" }) }));
+vi.mock("@/hooks/useMediaQuery", () => ({ default: () => true }));
+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
+vi.mock("react-hot-toast", () => ({ toast: mocks.toast }));
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+function start() {
+ render(
+ <MemoryRouter initialEntries={["/spaces/travel/map?lat=35&lng=135&zoom=12&memo=memos%2Fone"]}>
+ <MapView />
+ </MemoryRouter>,
+ );
+ fireEvent.click(screen.getByText("map.new-here"));
+}
+
+describe("map composer", () => {
+ it("keeps map fitting available without a location-picking action", async () => {
+ render(
+ <MemoryRouter initialEntries={["/map"]}>
+ <MapView />
+ </MemoryRouter>,
+ );
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "map.pick-location" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "map.fit-all" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.more" })).not.toBeInTheDocument();
+ });
+ it("seeds the selected point and Space and releases controls after save", async () => {
+ mocks.refetch.mockResolvedValue({ data: { pages: [{ memos: [item] }] } });
+ start();
+ expect(mocks.editor.defaultSpace).toBe("spaces/travel");
+ expect(mocks.editor.defaultLocation).toEqual(item.location);
+ act(() => mocks.editor.onSavingChange?.(true));
+ expect(screen.getByTestId("panel")).toHaveAttribute("data-busy", "true");
+ act(() => mocks.editor.onConfirm?.("memos/one"));
+ await waitFor(() => expect(screen.getByTestId("panel")).toHaveAttribute("data-busy", "false"));
+ expect(screen.queryByTestId("editor")).not.toBeInTheDocument();
+ });
+ it("offers a working action when the saved memo falls outside the filter", async () => {
+ mocks.refetch.mockResolvedValue({ data: { pages: [{ memos: [] }] } });
+ start();
+ act(() => mocks.editor.onConfirm?.("memos/outside"));
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalled());
+ // Toasts render outside the router; the action must not require router context.
+ const toastContent = mocks.toast.mock.calls[0][0]({ id: "saved" });
+ render(toastContent);
+ expect(screen.getByRole("button", { name: "map.open-memo" })).toBeVisible();
+ });
+ it("reports refresh failure without claiming the saved memo is outside the filter", async () => {
+ mocks.refetch.mockResolvedValue({ isError: true });
+ start();
+ act(() => mocks.editor.onConfirm?.("memos/saved"));
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalled());
+ render(mocks.toast.mock.calls[0][0]({ id: "saved" }));
+ expect(screen.getByText("map.load-error")).toBeVisible();
+ expect(screen.queryByText("map.saved-outside-filter")).not.toBeInTheDocument();
+ });
+});
diff --git a/web/tests/memo-detail-sidebar.test.tsx b/web/tests/memo-detail-sidebar.test.tsx
index f9c2bdf02..c5aaf61c4 100644
--- a/web/tests/memo-detail-sidebar.test.tsx
+++ b/web/tests/memo-detail-sidebar.test.tsx
@@ -46,6 +46,13 @@ describe("MemoDetailSidebar", () => {
currentUserState.value = { name: "users/alice" };
});
+ it("returns to the scoped map with its filters, viewport, and selection", () => {
+ const parentPage = "/spaces/travel/map?filter=tagSearch%3Atravel&lat=35&lng=135&zoom=12&memo=memos%2Fdetail";
+ renderSidebar(<MemoDetailSidebar memo={create(MemoSchema, { name: "memos/detail" })} parentPage={parentPage} hasExplicitOrigin />);
+
+ expect(screen.getByRole("link", { name: "memo.back-to:common.map" })).toHaveAttribute("href", parentPage);
+ });
+
it("organizes source, in-page navigation, connections, and frequent actions without repeating metadata", async () => {
const memo = create(MemoSchema, {
name: "memos/detail",
diff --git a/web/tests/memo-editor-cache.test.ts b/web/tests/memo-editor-cache.test.ts
index 78f0ab998..da2994ad6 100644
--- a/web/tests/memo-editor-cache.test.ts
+++ b/web/tests/memo-editor-cache.test.ts
@@ -3,6 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cacheService } from "@/components/MemoEditor/services/cacheService";
import { AttachmentSchema, MotionMediaFamily, MotionMediaRole, MotionMediaSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { LocationSchema } from "@/types/proto/api/v1/memo_service_pb";
+
describe("memo editor cache", () => {
beforeEach(() => {
const storage = new Map<string, string>();
@@ -91,6 +93,16 @@ describe("memo editor cache", () => {
expect(cacheService.load(key)).toBe(jsonDraft);
});
+ it("round-trips an edited or removed location and isolates Space drafts", () => {
+ const point = create(LocationSchema, { latitude: 0, longitude: 135, placeholder: "Cafe" });
+ cacheService.saveNow("map:space-a:point", "draft", [], point);
+ cacheService.saveNow("map:space-b:point", "draft", [], null);
+ expect(cacheService.loadDraft("map:space-a:point").location).toEqual(point);
+ expect(cacheService.loadDraft("map:space-b:point").location).toBeNull();
+ localStorage.setItem("legacy", JSON.stringify({ kind: "memos.editor-cache", version: 2, content: "old", attachments: [] }));
+ expect(cacheService.loadDraft("legacy").location).toBeUndefined();
+ });
+
it("keeps the cursor for the next editor mount", () => {
const key = cacheService.key("users/steven", "global-memo-editor");
diff --git a/web/tests/memo-search-queries.test.tsx b/web/tests/memo-search-queries.test.tsx
index f74be7381..c226450d9 100644
--- a/web/tests/memo-search-queries.test.tsx
+++ b/web/tests/memo-search-queries.test.tsx
@@ -31,7 +31,7 @@ describe("memo search requests", () => {
const filter = buildMemoFilter({ filters: buildQuickFindFilters(expression, [], true, "cel"), includePinned: false });
const { result } = renderHook(() => useInfiniteMemos({ filter }), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(listMemos).toHaveBeenCalledWith(expect.objectContaining({ filter: `(${expression})` }));
+ expect(listMemos).toHaveBeenCalledWith(expect.objectContaining({ filter: `(${expression})` }), expect.anything());
expect(result.current.data?.pages[0].memos).toEqual([]);
});
diff --git a/web/tests/memo-tag-navigation.test.tsx b/web/tests/memo-tag-navigation.test.tsx
index ceea8a9aa..461baa6b2 100644
--- a/web/tests/memo-tag-navigation.test.tsx
+++ b/web/tests/memo-tag-navigation.test.tsx
@@ -48,7 +48,7 @@ describe("Memo tag navigation", () => {
});
it("returns a Profile-origin tag to that profile's memo list", () => {
- origin.parentPage = "/u/alice?view=map";
+ origin.parentPage = "/u/alice";
render(
<MemoryRouter initialEntries={["/memos/parent"]}>
diff --git a/web/tests/memo-view-navigation.test.ts b/web/tests/memo-view-navigation.test.ts
index a0f9e1629..b8ba2aa48 100644
--- a/web/tests/memo-view-navigation.test.ts
+++ b/web/tests/memo-view-navigation.test.ts
@@ -30,8 +30,10 @@ describe("memo view navigation", () => {
).toBe("/explore?filter=contentSearch%3Aroadmap");
});
- it("keeps a Profile map origin intact", () => {
- expect(resolveMemoParentPage({ pathname: "/u/alice", search: "?view=map", memoName: "memos/123" })).toBe("/u/alice?view=map");
+ it("keeps a filtered Profile origin intact", () => {
+ expect(resolveMemoParentPage({ pathname: "/u/alice", search: "?filter=tagSearch%3Awork", memoName: "memos/123" })).toBe(
+ "/u/alice?filter=tagSearch%3Awork",
+ );
});
it("uses Home for direct and shared resource entries", () => {
@@ -86,12 +88,12 @@ describe("memo view navigation", () => {
});
it("replaces the filter without dropping other origin query parameters", () => {
- expect(withMemoFilter("/u/alice?view=memos&filter=old#section", "tagSearch:design")).toBe(
- "/u/alice?view=memos&filter=tagSearch%3Adesign",
+ expect(withMemoFilter("/u/alice?sort=displayTime&filter=old#section", "tagSearch:design")).toBe(
+ "/u/alice?sort=displayTime&filter=tagSearch%3Adesign",
);
});
- it("returns a Profile map origin to its memo list when applying a filter", () => {
- expect(withMemoFilter("/u/alice?view=map", "tagSearch:design")).toBe("/u/alice?filter=tagSearch%3Adesign");
+ it("applies a filter within the originating Profile", () => {
+ expect(withMemoFilter("/u/alice", "tagSearch:design")).toBe("/u/alice?filter=tagSearch%3Adesign");
});
});
diff --git a/web/tests/memo-views.test.ts b/web/tests/memo-views.test.ts
index da889016b..a743766d7 100644
--- a/web/tests/memo-views.test.ts
+++ b/web/tests/memo-views.test.ts
@@ -37,7 +37,7 @@ describe("memo scopes", () => {
expect(isMemoCollectionRoute("/")).toBe(true);
expect(isMemoCollectionRoute("/archived")).toBe(true);
expect(isMemoCollectionRoute("/u/steven")).toBe(true);
- expect(isMemoCollectionRoute("/u/steven/?view=map")).toBe(true);
+ expect(isMemoCollectionRoute("/u/steven/?filter=tagSearch%3Awork")).toBe(true);
expect(isMemoCollectionRoute("/calendar")).toBe(true);
expect(isMemoCollectionRoute("/Calendar/2026/08/02/")).toBe(true);
expect(isMemoCollectionRoute("/calendars")).toBe(false);
diff --git a/web/tests/use-auto-save.test.tsx b/web/tests/use-auto-save.test.tsx
index 1bb41ac6f..49e3d2c49 100644
--- a/web/tests/use-auto-save.test.tsx
+++ b/web/tests/use-auto-save.test.tsx
@@ -47,7 +47,7 @@ describe("useAutoSave (store-subscribed)", () => {
act(() => {
api.dispatch(api.actions.updateContent("hello world"));
});
- expect(saveSpy).toHaveBeenCalledWith(key, "hello world", []);
+ expect(saveSpy).toHaveBeenCalledWith(key, "hello world", [], null);
});
it("persists uploaded attachments when editor metadata changes", () => {
@@ -68,7 +68,7 @@ describe("useAutoSave (store-subscribed)", () => {
api.dispatch(api.actions.setMetadata({ attachments: [image] }));
});
- expect(saveSpy).toHaveBeenCalledWith(key, "", [image]);
+ expect(saveSpy).toHaveBeenCalledWith(key, "", [image], null);
});
it("persists metadata changes for an attachment with the same name", () => {
@@ -98,7 +98,7 @@ describe("useAutoSave (store-subscribed)", () => {
api.dispatch(api.actions.setMetadata({ attachments: [updated] }));
});
- expect(saveSpy).toHaveBeenCalledWith(key, "", [updated]);
+ expect(saveSpy).toHaveBeenCalledWith(key, "", [updated], null);
});
it("does not persist when disabled", () => {
diff --git a/web/tests/use-memo-init.test.tsx b/web/tests/use-memo-init.test.tsx
index 2ca675c92..e1073beb6 100644
--- a/web/tests/use-memo-init.test.tsx
+++ b/web/tests/use-memo-init.test.tsx
@@ -8,16 +8,19 @@ import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state"
import type { EditorController } from "@/components/MemoEditor/types/editorController";
import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { type Location, LocationSchema } from "@/types/proto/api/v1/memo_service_pb";
+
const editorRef = { current: null } as RefObject<EditorController | null>;
let getEditorState: ReturnType<typeof useEditorContext>["getState"];
-function Probe({ autoFocus }: { autoFocus?: boolean | (() => boolean) }) {
+function Probe({ autoFocus, defaultLocation }: { autoFocus?: boolean | (() => boolean); defaultLocation?: Location }) {
getEditorState = useEditorContext().getState;
useMemoInit({
editorRef,
username: "users/steven",
cacheKey: "restored-draft",
autoFocus,
+ defaultLocation,
});
return null;
}
@@ -64,6 +67,30 @@ describe("useMemoInit", () => {
expect(focus).toHaveBeenCalledTimes(allowed ? 1 : 0);
});
+ it("seeds a new location once and honors a restored removal", () => {
+ const point = create(LocationSchema, { latitude: 35, longitude: 135, placeholder: "Cafe" });
+ const { unmount, rerender } = render(
+ <EditorProvider>
+ <Probe defaultLocation={point} />
+ </EditorProvider>,
+ );
+ expect(getEditorState().metadata.location).toEqual(point);
+ rerender(
+ <EditorProvider>
+ <Probe defaultLocation={create(LocationSchema, { latitude: 1 })} />
+ </EditorProvider>,
+ );
+ expect(getEditorState().metadata.location).toEqual(point);
+ unmount();
+ cacheService.saveNow(cacheService.key("users/steven", "restored-draft"), "Draft without a location", [], null);
+ render(
+ <EditorProvider>
+ <Probe defaultLocation={point} />
+ </EditorProvider>,
+ );
+ expect(getEditorState().metadata.location).toBeUndefined();
+ });
+
it("restores uploaded attachment bindings with a new memo draft", async () => {
const attachment = create(AttachmentSchema, {
name: "attachments/image-one",
diff --git a/web/tests/user-memo-map.test.tsx b/web/tests/user-memo-map.test.tsx
deleted file mode 100644
index 8cc7194f7..000000000
--- a/web/tests/user-memo-map.test.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import type { ReactNode } from "react";
-import { MemoryRouter } from "react-router-dom";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import UserMemoMap from "@/components/UserMemoMap/UserMemoMap";
-
-const mocks = vi.hoisted(() => ({
- bounds: {},
- fitBounds: vi.fn(),
- latLngBounds: vi.fn(),
- useInfiniteMemos: vi.fn(),
-}));
-
-vi.mock("leaflet", () => ({
- default: {
- latLngBounds: mocks.latLngBounds,
- point: vi.fn(),
- },
- DivIcon: class {
- constructor(_options: unknown) {}
- },
-}));
-
-vi.mock("react-leaflet", () => ({
- MapContainer: ({ children, attributionControl }: { children: ReactNode; attributionControl?: boolean }) => (
- <div data-testid="map" data-attribution-control={attributionControl}>
- {children}
- </div>
- ),
- Marker: ({ children, title }: { children: ReactNode; title?: string }) => (
- <div data-testid="memo-marker" data-title={title}>
- {children}
- </div>
- ),
- Popup: ({ children }: { children: ReactNode }) => children,
- useMap: () => ({ fitBounds: mocks.fitBounds }),
-}));
-
-vi.mock("react-leaflet-cluster", () => ({
- default: ({ children }: { children: ReactNode }) => children,
-}));
-
-vi.mock("@/components/map/map-utils", () => ({
- defaultMarkerIcon: {},
- MinimalAttributionControl: () => <div data-testid="attribution" />,
- OpenStreetMapTileLayer: () => <div data-testid="map-layer" />,
-}));
-
-vi.mock("@/components/MemoView/components/MemoSpaceBadge", () => ({
- default: () => null,
-}));
-
-vi.mock("@/hooks/useMemoQueries", () => ({
- useInfiniteMemos: mocks.useInfiniteMemos,
-}));
-
-describe("UserMemoMap", () => {
- beforeEach(() => {
- mocks.fitBounds.mockReset();
- mocks.latLngBounds.mockReset();
- mocks.latLngBounds.mockReturnValue(mocks.bounds);
- mocks.useInfiniteMemos.mockReturnValue({ data: { pages: [] }, isLoading: false });
- });
-
- it("uses the explicit minimal attribution control", () => {
- render(
- <MemoryRouter>
- <UserMemoMap creator="users/1" />
- </MemoryRouter>,
- );
-
- expect(screen.getByTestId("map")).toHaveAttribute("data-attribution-control", "false");
- expect(screen.getByTestId("attribution")).toBeInTheDocument();
- expect(screen.getByTestId("map-layer")).toBeInTheDocument();
- });
-
- it("caps automatic zoom and gives memo markers an accessible name", () => {
- mocks.useInfiniteMemos.mockReturnValue({
- data: {
- pages: [
- {
- memos: [
- {
- name: "memos/1",
- snippet: "Lunch spot",
- location: { latitude: 1, longitude: 2 },
- },
- ],
- },
- ],
- },
- isLoading: false,
- });
-
- render(
- <MemoryRouter>
- <UserMemoMap creator="users/1" />
- </MemoryRouter>,
- );
-
- expect(mocks.latLngBounds).toHaveBeenCalledWith([[1, 2]]);
- expect(mocks.fitBounds).toHaveBeenCalledWith(mocks.bounds, { padding: [50, 50], maxZoom: 15 });
- expect(screen.getByTestId("memo-marker")).toHaveAttribute("data-title", "Lunch spot");
- });
-});