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.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
refactor(web): share one floating memo panel between calendar and map
johnnyjoyghc218355b1b6e
diff --git a/web/src/components/CalendarView/CalendarView.tsx b/web/src/components/CalendarView/CalendarView.tsxindex 2743adc97..2069be903 100644--- a/web/src/components/CalendarView/CalendarView.tsx+++ b/web/src/components/CalendarView/CalendarView.tsx@@ -1,9 +1,9 @@-import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { useLocation, useNavigate } from "react-router-dom";-import { SidebarResizeHandle } from "@/components/AppSidebar";+import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/utils/deriveDefaultCreateTime";+import { MEMO_PANEL_INSET, MEMO_PANEL_TITLE_CLASS, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList } from "@/components/MemoPanel";import MemoListError from "@/components/PagedMemoList/MemoListError";-import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";import { useAuth } from "@/contexts/AuthContext";import { useInstance } from "@/contexts/InstanceContext";import { useSpaceContext } from "@/contexts/SpaceContext";@@ -11,7 +11,7 @@ import useCurrentUser from "@/hooks/useCurrentUser";import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";import useMediaQuery from "@/hooks/useMediaQuery";import { useMemoFilters } from "@/hooks/useMemoFilters";-import { formatMonthLabel, getToday } from "@/lib/calendar-utils";+import { formatMonthLabel, getToday, parseLocalDate } from "@/lib/calendar-utils";import { combineCELFilters } from "@/lib/cel-filter";import { buildMemoCreatorFilter } from "@/lib/resource-names";import { isMemoBlurred } from "@/lib/tag";@@ -20,12 +20,12 @@ import type { Memo } from "@/types/proto/api/v1/memo_service_pb";import { useTranslate } from "@/utils/i18n";import { CalendarGrid } from "./CalendarGrid";import { CalendarHeader } from "./CalendarHeader";-import { DayPanel } from "./DayPanel";import { buildCalendarPath, getDefaultDate } from "./paths";-import { DAY_PANEL_DEFAULT_WIDTH, DAY_PANEL_WIDTH_VAR, useDayPanelWidth } from "./useDayPanelWidth";import { useMonthMemos } from "./useMonthMemos";const NO_MEMOS: Memo[] = [];+/** Page padding plus seven legible 72px columns. */+const RESERVED_BESIDE_PANEL = 48 + 7 * 72;export interface CalendarViewProps {/** `YYYY-MM` */@@ -34,18 +34,15 @@ export interface CalendarViewProps {date?: string;}-const isEditableTarget = (target: EventTarget | null): boolean =>- target instanceof HTMLElement && (target.isContentEditable || target.closest("input, textarea, select, [contenteditable]") !== null);-/*** The signed-in user's memos as a month, scoped like Home to the remembered collection.* Month and day both live in the URL; this component only reads them and renders.*- * The open day has three homes. From xl it is a resizable panel beside the grid. Between md- * and xl the grid keeps its full width and the day slides in as a sheet from the end edge.- * Below md the grid is compact and the day's list sits under it, the way phone calendars- * work, so a day is always shown there: today in the current month, otherwise the first of- * the month, until the URL names one.+ * The open day has two homes. From md it is the floating memo panel at the end edge; at xl+ * the grid gives way to it so every column stays legible, below xl it floats over the+ * trailing columns. Below md the grid is compact and the day's list sits under it, the way+ * phone calendars work, so a day is always shown there: today in the current month,+ * otherwise the first of the month, until the URL names one.*/export const CalendarView = ({ month, date }: CalendarViewProps) => {const t = useTranslate();@@ -55,8 +52,6 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {const user = useCurrentUser();const md = useMediaQuery("md");const xl = useMediaQuery("xl");- const panelRef = useRef<HTMLElement>(null);- const panelWidth = useDayPanelWidth();const { userTagsSetting, isInitialized: authInitialized, isUserSettingsInitialized } = useAuth();const { isInitialized: instanceInitialized } = useInstance();const { memoFilter: contextFilter } = useSpaceContext();@@ -98,32 +93,44 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {const today = getToday();const activeDate = date ?? (md ? undefined : getDefaultDate(month, today));+ const activeMemos = (activeDate && model[activeDate]?.memos) || NO_MEMOS;+ const dateLabel = useMemo(+ () =>+ activeDate+ ? (parseLocalDate(activeDate)?.toLocaleDateString(i18n.language, { weekday: "long", month: "long", day: "numeric" }) ?? activeDate)+ : "",+ [activeDate, i18n.language],+ );+ const defaultCreateTime = useMemo(() => (activeDate ? deriveDefaultCreateTimeFromDate(activeDate) : undefined), [activeDate]);+ const [saving, setSaving] = useState(false);+ const panelOpen = Boolean(date) && md;- // The sheet stays mounted after its day closes so it can slide out; it keeps showing the- // last open day while it does.- // The sheet stays mounted across a close so its exit animation can play; it keeps showing the- // last open day. Set during render, so no frame ever commits the previous day's content.- const [sheetDate, setSheetDate] = useState(date);- if (date && date !== sheetDate) setSheetDate(date);- const dayMemos = (day: string | undefined) => (day && model[day]?.memos) || NO_MEMOS;-- useEffect(() => {- if (!date || !xl) return;- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key !== "Escape" || event.defaultPrevented || isEditableTarget(event.target)) return;- closeDay();- };- document.addEventListener("keydown", handleKeyDown);- return () => document.removeEventListener("keydown", handleKeyDown);- }, [date, xl, closeDay]);+ const list = activeDate && (+ <MemoPanelList+ memos={activeMemos}+ selectionKey={activeDate}+ timeDisplay="time"+ compose={{+ cacheKey: `calendar-day-editor:${activeDate}`,+ label: t("calendar.new-memo-on-day"),+ defaults: { defaultCreateTime },+ onSavingChange: setSaving,+ }}+ />+ );// A failed month must not pass for an empty one.const isEmptyMonth = !isLoading && !error && Object.keys(model).length === 0;return (- <div className="flex w-full items-start gap-6">- {/* From xl the section is sticky and viewport-tall so the grid can fill it beside the panel. */}- <section className="flex w-full min-w-0 flex-1 flex-col gap-1 xl:sticky xl:top-6 xl:h-[calc(100dvh-3.5rem)]">+ <>+ {/* From xl the section is viewport-tall so the grid can fill it, and pads its end edge by+ the open panel's width so the card floats beside the grid rather than over it. The+ padding reads the panel's own custom property, so it follows a resize drag live. */}+ <section+ className="flex w-full min-w-0 flex-col gap-1 xl:h-[calc(100dvh-3.5rem)]"+ style={{ paddingInlineEnd: xl && panelOpen ? `calc(${MEMO_PANEL_WIDTH_CSS} + ${MEMO_PANEL_INSET}px)` : undefined }}+ ><CalendarHeader month={month} monthLabel={monthLabel} today={today} activeDate={activeDate} closable={md} /><CalendarGridmonth={month}@@ -142,48 +149,20 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {</p>)}{activeDate && !md && (- <div className="mt-4">- <DayPanel date={activeDate} memos={dayMemos(activeDate)} />- </div>+ <section aria-label={dateLabel} className="mt-4 flex w-full flex-col">+ <header className="mb-3 border-b border-border/70 pb-3">+ <h2 className={MEMO_PANEL_TITLE_CLASS}>{dateLabel}</h2>+ </header>+ {list}+ </section>)}</section>- {sheetDate && md && !xl && (- <Sheet open={Boolean(date)} onOpenChange={(open) => !open && closeDay()}>- {/* The panel keeps its own close control in every tier, so the sheet's is hidden. */}- <SheetContent- side="right"- className="w-[28rem] max-w-[90vw] gap-0 overflow-y-auto px-6 pb-8 pt-5 sm:max-w-md [&_[data-slot=sheet-close]]:hidden"- >- <SheetTitle className="sr-only">{sheetDate}</SheetTitle>- <DayPanel date={sheetDate} memos={dayMemos(sheetDate)} onClose={closeDay} />- </SheetContent>- </Sheet>- )}-- {date && xl && (- // The panel's start edge is both its separator from the grid and the resize rail, the- // same grammar as the app sidebar's end edge; it stretches to the row so the edge runs- // the full height of the grid, and further when the day's list is longer.- <aside- ref={panelRef}- className="relative w-[var(--calendar-day-panel-width)] shrink-0 self-stretch border-s border-border/70 ps-6"- style={{ [DAY_PANEL_WIDTH_VAR]: `${panelWidth.width}px` } as CSSProperties}- >- <SidebarResizeHandle- width={panelWidth.width}- minWidth={panelWidth.minWidth}- maxWidth={panelWidth.maxWidth}- onWidthChange={panelWidth.setWidth}- targetRef={panelRef}- cssVariable={DAY_PANEL_WIDTH_VAR}- defaultWidth={DAY_PANEL_DEFAULT_WIDTH}- edge="start"- label={t("calendar.resize-panel")}- />- <DayPanel date={date} memos={dayMemos(date)} onClose={closeDay} />- </aside>+ {md && (+ <MemoPanel open={panelOpen} title={dateLabel} reservedWidth={RESERVED_BESIDE_PANEL} busy={saving} onClose={closeDay}>+ {list}+ </MemoPanel>)}- </div>+ </>);};diff --git a/web/src/components/CalendarView/DayPanel.tsx b/web/src/components/CalendarView/DayPanel.tsxdeleted file mode 100644index 517e798c0..000000000--- a/web/src/components/CalendarView/DayPanel.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { PlusIcon, XIcon } from "lucide-react";-import { useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";-import MemoEditor from "@/components/MemoEditor";-import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/utils/deriveDefaultCreateTime";-import MemoView from "@/components/MemoView";-import { buttonVariants } from "@/components/ui/button";-import { useAuth } from "@/contexts/AuthContext";-import { NewMemoProvider } from "@/contexts/NewMemoContext";-import { useSpaceContext } from "@/contexts/SpaceContext";-import { useView } from "@/contexts/ViewContext";-import { parseLocalDate } from "@/lib/calendar-utils";-import { cn } from "@/lib/utils";-import type { Memo } from "@/types/proto/api/v1/memo_service_pb";-import { useTranslate } from "@/utils/i18n";--export interface DayPanelProps {- /** `YYYY-MM-DD` */- date: string;- /** The day's memos in time order, straight from the month model. */- memos: Memo[];- /** Present when the panel can be dismissed (the side panel); the inline phone list cannot. */- onClose?: () => void;-}--/**- * One day's memos, oldest first, rendered from the month already in hand: no second fetch, and- * a day reads as it unfolded, like the rows in its grid cell. The cards are the ordinary memo- * cards, so editing, reactions and comments behave exactly as on Home. The day ends with a- * quiet "new memo" row that expands into the editor in place, the way journals append at the- * end of a day; the memo it saves seeds its creation time to that date and lands right above it.- */-export const DayPanel = ({ date, memos, onClose }: DayPanelProps) => {- const t = useTranslate();- const { i18n } = useTranslation();- const { isUserSettingsInitialized } = useAuth();- const { selectedSpaceName } = useSpaceContext();- const { compactMode } = useView();- // Remembering which day is being composed for closes the composer the moment the day- // changes, so a half-written memo can never silently move dates.- const [composingFor, setComposingFor] = useState<string>();- const composing = composingFor === date;-- const defaultCreateTime = useMemo(() => deriveDefaultCreateTimeFromDate(date), [date]);- const dateLabel = useMemo(- () => parseLocalDate(date)?.toLocaleDateString(i18n.language, { weekday: "long", month: "long", day: "numeric" }) ?? date,- [date, i18n.language],- );- const contents = useMemo(() => memos.map((memo) => memo.content), [memos]);- const userNames = useMemo(- () => Array.from(new Set(memos.flatMap((memo) => memo.reactions.map((reaction) => reaction.creator)))),- [memos],- );-- return (- <section aria-label={dateLabel} className="flex w-full flex-col">- <header className="mb-3 flex items-center gap-0.5 border-b border-border/70 pb-3">- <h2 className="min-w-0 flex-1 truncate text-base font-semibold tracking-tight text-foreground">{dateLabel}</h2>- {onClose && (- <button- type="button"- aria-label={t("calendar.close-day")}- className={cn(buttonVariants({ variant: "quiet", size: "icon-compact" }))}- onClick={onClose}- >- <XIcon strokeWidth={1.8} />- </button>- )}- </header>- <NewMemoProvider>- <MentionResolutionProvider contents={contents} userNames={userNames}>- {memos.map((memo) => (- <MemoView- key={memo.name}- memo={memo}- timeDisplay="time"- showVisibility- showPinned- showSpace={!selectedSpaceName}- compact={compactMode}- />- ))}- </MentionResolutionProvider>- {isUserSettingsInitialized &&- (composing ? (- <MemoEditor- cacheKey={`calendar-day-editor:${date}`}- autoFocus- placeholder={t("editor.any-thoughts")}- defaultCreateTime={defaultCreateTime}- defaultSpace={selectedSpaceName}- onConfirm={() => setComposingFor(undefined)}- onCancel={() => setComposingFor(undefined)}- />- ) : (- <button- type="button"- // The cards' own bottom margin sets the gap; the chip's edge lines up with theirs.- className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "self-start")}- onClick={() => setComposingFor(date)}- >- <PlusIcon strokeWidth={1.8} />- <span>{t("calendar.new-memo-on-day")}</span>- </button>- ))}- </NewMemoProvider>- </section>- );-};diff --git a/web/src/components/CalendarView/useDayPanelWidth.ts b/web/src/components/CalendarView/useDayPanelWidth.tsdeleted file mode 100644index c1450fc35..000000000--- a/web/src/components/CalendarView/useDayPanelWidth.ts+++ /dev/null@@ -1,19 +0,0 @@-import { type PersistedWidthConfig, usePersistedWidth } from "@/components/AppSidebar";--/** Custom property the panel publishes; `DayPanelAside` repeats the literal in its width class. */-export const DAY_PANEL_WIDTH_VAR = "--calendar-day-panel-width";-export const DAY_PANEL_DEFAULT_WIDTH = 384;-const DAY_PANEL_MIN_WIDTH = 320;-const DAY_PANEL_MAX_WIDTH = 640;-/** App sidebar, page padding and the gap beside the grid, plus seven legible 72px columns. */-const RESERVED_BESIDE_PANEL = 256 + 48 + 24 + 7 * 72;--const DAY_PANEL_WIDTH_CONFIG: PersistedWidthConfig = {- storageKey: "memos-calendar-day-panel-width",- defaultWidth: DAY_PANEL_DEFAULT_WIDTH,- minWidth: DAY_PANEL_MIN_WIDTH,- maxWidthFor: (viewportWidth) => Math.min(DAY_PANEL_MAX_WIDTH, viewportWidth - RESERVED_BESIDE_PANEL),-};--/** Width of the inline day panel beside the month grid, persisted like the sidebar's. */-export const useDayPanelWidth = () => usePersistedWidth(DAY_PANEL_WIDTH_CONFIG);diff --git a/web/src/components/MapView/MapPanel.tsx b/web/src/components/MapView/MapPanel.tsxdeleted file mode 100644index 5971492bc..000000000--- a/web/src/components/MapView/MapPanel.tsx+++ /dev/null@@ -1,120 +0,0 @@-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.tsxindex 3d1a77672..0bc9966e4 100644--- a/web/src/components/MapView/MapView.tsx+++ b/web/src/components/MapView/MapView.tsx@@ -4,27 +4,24 @@ 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 { MEMO_PANEL_INSET, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList, type MemoPanelSize } from "@/components/MemoPanel";import { createMemoNavigationState } from "@/components/MemoView/navigation";import { Button, buttonVariants } from "@/components/ui/button";-import { 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";+/** Enough map beside the card to keep a selection visible. */+const RESERVED_BESIDE_PANEL = 160;+export function MapView() {const t = useTranslate();const location = useLocation();@@ -34,16 +31,13 @@ export function MapView() {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 [panelSize, setPanelSize] = useState<MemoPanelSize>({ width: 0, height: 0 });+ // Only a real change may re-render the map tree.const onPanelSize = useCallback(- (next: { width: number; height: number }) =>+ (next: MemoPanelSize) =>setPanelSize((prev) => {const width = Math.round(next.width);const height = Math.round(next.height);@@ -53,8 +47,7 @@ export function MapView() {);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 [composing, setComposing] = useState(false);const viewport = readViewport(location.search);// Selection is keyed by its joined names so panning, which rewrites the search, leaves it identity-stable.const selectedKey = new URLSearchParams(location.search).getAll("memo").join("|");@@ -67,7 +60,6 @@ export function MapView() {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(@@ -132,7 +124,6 @@ export function MapView() {);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));@@ -157,67 +148,19 @@ export function MapView() {);};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",+ "--map-inset-end": desktop && open ? `calc(${MEMO_PANEL_WIDTH_CSS} + ${MEMO_PANEL_INSET}px)` : "0px",} as CSSProperties}data-map-page@@ -332,18 +275,31 @@ export function MapView() {</div></div>)}- <MapPanel+ <MemoPanelopen={open}- title={shown.heading.title}- subtitle={shown.heading.subtitle}- desktop={desktop}- container={frameRef}+ title={heading.title}+ subtitle={heading.subtitle}+ reservedWidth={RESERVED_BESIDE_PANEL}busy={saving}onClose={clearSelection}onSize={onPanelSize}>- {shown.children}- </MapPanel>+ <MemoPanelList+ memos={selectedMemos}+ selectionKey={selectedKey}+ emptyText={t(query.complete ? "map.no-results" : "map.loading")}+ compose={+ composeLocation && {+ cacheKey: `map-editor:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`,+ label: t("map.new-here"),+ defaults: { defaultLocation: composeLocation },+ onComposingChange: setComposing,+ onSavingChange: setSaving,+ onConfirm: (name) => void afterSave(name),+ }+ }+ />+ </MemoPanel></section>);}diff --git a/web/src/components/MemoPanel/MemoPanel.tsx b/web/src/components/MemoPanel/MemoPanel.tsxnew file mode 100644index 000000000..77a709581--- /dev/null+++ b/web/src/components/MemoPanel/MemoPanel.tsx@@ -0,0 +1,179 @@+import { Dialog } from "@base-ui/react/dialog";+import { XIcon } from "lucide-react";+import { type ReactNode, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { type PersistedWidthConfig, SidebarResizeHandle, usePersistedWidth, useSidebarWidth } from "@/components/AppSidebar";+import { buttonVariants } from "@/components/ui/button";+import useMediaQuery from "@/hooks/useMediaQuery";+import { cn } from "@/lib/utils";+import { useTranslate } from "@/utils/i18n";++/**+ * Custom property carrying the card's width. It lives on the document root, where both the card+ * and the page beside it can read it: a drag previews into it at frame rate and commits once on+ * release, so the page reflows live without a React render per frame. Tailwind cannot read this+ * constant, so the classes and `MEMO_PANEL_WIDTH_CSS` repeat the literal name.+ */+const PANEL_WIDTH_VAR = "--memo-panel-width";+/** The card's current width as a CSS expression, for pages that give way to it. */+export const MEMO_PANEL_WIDTH_CSS = `var(${PANEL_WIDTH_VAR})`;+/** The title's type, shared with hosts that show the same content inline without the card. */+export const MEMO_PANEL_TITLE_CLASS = "truncate text-base font-semibold tracking-tight text-foreground";+const ICON_CONTROL_CLASS = buttonVariants({ variant: "quiet", size: "icon-compact" });+const PANEL_DEFAULT_WIDTH = 400;+const PANEL_MIN_WIDTH = 320;+const PANEL_MAX_WIDTH = 640;+/** The gap the floating card keeps from the viewport edges, the `3` in `inset-y-3 end-3`. */+export const MEMO_PANEL_INSET = 12;+/** The bottom sheet's two heights as a share of the viewport: a peek, and nearly all of it. */+const SHEET_PEEK_SHARE = 0.45;+const SHEET_FULL_SHARE = 0.9;++export interface MemoPanelSize {+ width: number;+ height: number;+}++export interface MemoPanelProps {+ open: boolean;+ title: string;+ subtitle?: string;+ /**+ * The least the page needs beside the card at desktop widths, not counting the app sidebar or+ * the card's own insets, which the panel accounts for; it caps the shared persisted width.+ */+ reservedWidth: number;+ /** While true the panel refuses to close: a save is in flight and must not lose its host. */+ busy?: boolean;+ onClose: () => void;+ /** The surface's committed size, so the page can keep clear of it; zero while closed. */+ onSize?: (size: MemoPanelSize) => void;+ children: ReactNode;+}++/**+ * The floating surface a page opens beside its main view to read a selection of memos: a day+ * in the calendar, a place on the map. From md it is a resizable card at the end edge, non-modal+ * so the view behind stays clickable; below md it is a bottom sheet with a grab handle that+ * toggles between a peek and nearly full height. One persisted width serves every host, like+ * the sidebar's. The panel keeps showing its last content while it slides out, so a cleared+ * selection never flashes an empty state on the way.+ */+export function MemoPanel({ open, title, subtitle, reservedWidth, busy = false, onClose, onSize, children }: MemoPanelProps) {+ const t = useTranslate();+ const desktop = useMediaQuery("md");+ const ref = useRef<HTMLDivElement>(null);+ // The drag previews into the document root, where both the card and the page beside it read.+ const rootRef = useRef<HTMLElement>(document.documentElement);+ 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 sheetShare = expanded ? SHEET_FULL_SHARE : SHEET_PEEK_SHARE;++ const { width: sidebarWidth } = useSidebarWidth();+ const widthConfig = useMemo<PersistedWidthConfig>(+ () => ({+ storageKey: "memos-memo-panel-width",+ defaultWidth: PANEL_DEFAULT_WIDTH,+ minWidth: PANEL_MIN_WIDTH,+ maxWidthFor: (viewportWidth) => Math.min(PANEL_MAX_WIDTH, viewportWidth - sidebarWidth - 2 * MEMO_PANEL_INSET - reservedWidth),+ }),+ [sidebarWidth, reservedWidth],+ );+ const { width, minWidth, maxWidth, setWidth } = usePersistedWidth(widthConfig);+ useEffect(() => {+ const root = rootRef.current;+ root.style.setProperty(PANEL_WIDTH_VAR, `${width}px`);+ return () => {+ root.style.removeProperty(PANEL_WIDTH_VAR);+ };+ }, [width]);++ // Measured once per committed change, like the sidebar's: a drag previews through the custom+ // property and commits on release, so the page hears about it once rather than per frame.+ useLayoutEffect(() => {+ if (!onSize) return;+ if (!open || !element) {+ onSize({ width: 0, height: 0 });+ return;+ }+ const rect = element.getBoundingClientRect();+ onSize({ width: rect.width, height: rect.height });+ }, [onSize, open, element, desktop, width, sheetShare]);++ // The popup stays mounted through its exit transition; keep what it was showing for the ride.+ const lastShown = useRef({ title, subtitle, children });+ if (open) lastShown.current = { title, subtitle, children };+ const shown = lastShown.current;++ return (+ <Dialog.Root+ open={open}+ modal={false}+ disablePointerDismissal+ onOpenChange={(next, details) => {+ if (!next) {+ if (busy) details.cancel();+ else onClose();+ }+ }}+ >+ <Dialog.Portal>+ <Dialog.Popup+ ref={attachPanel}+ initialFocus={scrollRef}+ aria-describedby={undefined}+ style={!desktop ? { height: `${sheetShare * 100}dvh` } : undefined}+ className={cn(+ "fixed z-30 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(--memo-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 && (+ // The rail stops short of the corners so it reads as the straight run of the card's edge.+ <div className="absolute inset-y-3 start-0 w-0">+ <SidebarResizeHandle+ width={width}+ minWidth={minWidth}+ maxWidth={maxWidth}+ onWidthChange={setWidth}+ targetRef={rootRef}+ cssVariable={PANEL_WIDTH_VAR}+ defaultWidth={PANEL_DEFAULT_WIDTH}+ edge="start"+ label={t("common.resize-panel")}+ />+ </div>+ )}+ {!desktop && (+ <button+ type="button"+ className="flex h-7 shrink-0 items-center justify-center"+ aria-label={t(expanded ? "common.collapse-panel" : "common.expand-panel")}+ 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={MEMO_PANEL_TITLE_CLASS}>{shown.title}</Dialog.Title>+ {shown.subtitle && <p className="truncate text-xs text-muted-foreground">{shown.subtitle}</p>}+ </div>+ <Dialog.Close disabled={busy} render={<button type="button" className={ICON_CONTROL_CLASS} 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">+ {shown.children}+ </div>+ </Dialog.Popup>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/web/src/components/MemoPanel/MemoPanelList.tsx b/web/src/components/MemoPanel/MemoPanelList.tsxnew file mode 100644index 000000000..b8858e87c--- /dev/null+++ b/web/src/components/MemoPanel/MemoPanelList.tsx@@ -0,0 +1,110 @@+import { PlusIcon } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";+import MemoEditor from "@/components/MemoEditor";+import type { MemoEditorProps } from "@/components/MemoEditor/types/components";+import MemoView from "@/components/MemoView";+import type { MemoTimeDisplay } from "@/components/MemoView/types";+import { buttonVariants } from "@/components/ui/button";+import { useAuth } from "@/contexts/AuthContext";+import { NewMemoProvider } from "@/contexts/NewMemoContext";+import { useSpaceContext } from "@/contexts/SpaceContext";+import { useView } from "@/contexts/ViewContext";+import { cn } from "@/lib/utils";+import type { Memo } from "@/types/proto/api/v1/memo_service_pb";+import { useTranslate } from "@/utils/i18n";++// The cards' own bottom margin sets the gap; the row's edge lines up with theirs.+const COMPOSE_ROW_CLASS = cn(buttonVariants({ variant: "quiet", size: "sm" }), "self-start");++export interface MemoPanelCompose {+ cacheKey: string;+ /** The quiet row's label, e.g. "New memo on this day". */+ label: string;+ /** What the new memo inherits from the selection: its day, its place. */+ defaults?: Pick<MemoEditorProps, "defaultCreateTime" | "defaultLocation">;+ /** Whether the editor is open in place of the row, for hosts whose own gestures could dismiss it. */+ onComposingChange?: (composing: boolean) => void;+ onSavingChange?: (saving: boolean) => void;+ onConfirm?: (memoName: string) => void;+}++export interface MemoPanelListProps {+ memos: Memo[];+ /**+ * Identity of the selection the list shows. A change closes an open composer, so a+ * half-written memo can never silently move to another day or place.+ */+ selectionKey: string;+ timeDisplay?: MemoTimeDisplay;+ /** Shown in place of the cards when there are none; omit to show nothing. */+ emptyText?: string;+ /** Present when a memo can be appended to the selection. */+ compose?: MemoPanelCompose;+}++/**+ * A selection's memos as the ordinary memo cards, so editing, reactions and comments behave+ * exactly as on Home, ending with a quiet "new memo" row that expands into the editor in place,+ * the way journals append at the end of a day.+ */+export function MemoPanelList({ memos, selectionKey, timeDisplay, emptyText, compose }: MemoPanelListProps) {+ const t = useTranslate();+ const { isUserSettingsInitialized } = useAuth();+ const { selectedSpaceName } = useSpaceContext();+ const { compactMode } = useView();+ const [composingFor, setComposingFor] = useState<string>();+ const composing = composingFor === selectionKey;+ const onComposingChange = compose?.onComposingChange;+ useEffect(() => {+ onComposingChange?.(composing);+ return () => onComposingChange?.(false);+ }, [composing, onComposingChange]);++ const contents = useMemo(() => memos.map((memo) => memo.content), [memos]);+ const userNames = useMemo(+ () => Array.from(new Set(memos.flatMap((memo) => memo.reactions.map((reaction) => reaction.creator)))),+ [memos],+ );++ return (+ <NewMemoProvider>+ <MentionResolutionProvider contents={contents} userNames={userNames}>+ {memos.map((memo) => (+ <MemoView+ key={memo.name}+ memo={memo}+ timeDisplay={timeDisplay}+ showVisibility+ showPinned+ showSpace={!selectedSpaceName}+ compact={compactMode}+ />+ ))}+ </MentionResolutionProvider>+ {emptyText && memos.length === 0 && <p className="text-sm text-muted-foreground">{emptyText}</p>}+ {compose &&+ isUserSettingsInitialized &&+ (composing ? (+ <MemoEditor+ cacheKey={compose.cacheKey}+ autoFocus+ placeholder={t("editor.any-thoughts")}+ defaultSpace={selectedSpaceName}+ {...compose.defaults}+ onSavingChange={compose.onSavingChange}+ onConfirm={(name) => {+ setComposingFor(undefined);+ compose.onConfirm?.(name);+ }}+ onCancel={() => setComposingFor(undefined)}+ />+ ) : (+ <button type="button" className={COMPOSE_ROW_CLASS} onClick={() => setComposingFor(selectionKey)}>+ <PlusIcon strokeWidth={1.8} />+ <span>{compose.label}</span>+ </button>+ ))}+ </NewMemoProvider>+ );+}diff --git a/web/src/components/MemoPanel/index.ts b/web/src/components/MemoPanel/index.tsnew file mode 100644index 000000000..d7f485699--- /dev/null+++ b/web/src/components/MemoPanel/index.ts@@ -0,0 +1,9 @@+export {+ MEMO_PANEL_INSET,+ MEMO_PANEL_TITLE_CLASS,+ MEMO_PANEL_WIDTH_CSS,+ MemoPanel,+ type MemoPanelProps,+ type MemoPanelSize,+} from "./MemoPanel";+export { type MemoPanelCompose, MemoPanelList, type MemoPanelListProps } from "./MemoPanelList";diff --git a/web/src/locales/az.json b/web/src/locales/az.jsonindex c9105703e..22530c2ce 100644--- a/web/src/locales/az.json+++ b/web/src/locales/az.json@@ -1,8 +1,5 @@{"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",@@ -70,13 +67,11 @@"welcome-back": "Yenidən xoş gəlmisiniz."},"calendar": {- "close-day": "Günü bağla","more-memos": "+{{count}} daha","new-memo-on-day": "Bu gün üçün yeni qeyd","next-year": "Növbəti il","no-memos-in-month": "{{month}} ayında qeyd yoxdur","previous-year": "Əvvəlki il",- "resize-panel": "Gün panelinin ölçüsünü dəyiş","select-month": "Ay seç"},"demo": {@@ -169,6 +164,7 @@"clear": "Təmizlə","close": "Bağla","collapse": "Yığ",+ "collapse-panel": "Paneli yığ","confirm": "Təsdiqlə","copy": "Kopyala","create": "Yarat",@@ -190,6 +186,7 @@"email": "E-poçt","empty-placeholder": "Boş","expand": "Aç",+ "expand-panel": "Paneli genişləndir","explore": "Kəşf et","file": "Fayl","filter": "Süzgəc",@@ -229,6 +226,7 @@"remember-me": "Məni xatırla","rename": "Adını dəyiş","reset": "Sıfırla",+ "resize-panel": "Panelin ölçüsünü dəyiş","resize-sidebar": "Yan panelin ölçüsünü dəyiş","resources": "Resurslar","restore": "Bərpa et",diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex a4457d161..36eb95ac0 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -1,8 +1,5 @@{"map": {- "resize-panel": "Resize location panel",- "collapse": "Collapse panel",- "expand": "Expand panel","selection": "Selected memos","loaded": "{{count}} loaded","fit-all": "Show all results",@@ -70,13 +67,11 @@"welcome-back": "Welcome back."},"calendar": {- "close-day": "Close day","more-memos": "+{{count}} more","new-memo-on-day": "New memo on this day","next-year": "Next year","no-memos-in-month": "No memos in {{month}}","previous-year": "Previous year",- "resize-panel": "Resize day panel","select-month": "Select month"},"demo": {@@ -169,6 +164,7 @@"clear": "Clear","close": "Close","collapse": "Collapse",+ "collapse-panel": "Collapse panel","confirm": "Confirm","copy": "Copy","create": "Create",@@ -190,6 +186,7 @@"email": "Email","empty-placeholder": "Empty","expand": "Expand",+ "expand-panel": "Expand panel","explore": "Explore","file": "File","filter": "Filter",@@ -229,6 +226,7 @@"remember-me": "Remember me","rename": "Rename","reset": "Reset",+ "resize-panel": "Resize panel","resize-sidebar": "Resize sidebar","resources": "Resources","restore": "Restore",diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.jsonindex 277d9b2c5..606cb5aab 100644--- a/web/src/locales/zh-Hans.json+++ b/web/src/locales/zh-Hans.json@@ -1,8 +1,5 @@{"map": {- "resize-panel": "调整地点面板宽度",- "collapse": "收起面板",- "expand": "展开面板","selection": "选中的 Memo","loaded": "已加载 {{count}} 条","fit-all": "查看全部结果",@@ -70,13 +67,11 @@"welcome-back": "欢迎回来。"},"calendar": {- "close-day": "关闭当天","more-memos": "还有 {{count}} 条","new-memo-on-day": "在这一天新建备忘录","next-year": "下一年","no-memos-in-month": "{{month}} 没有备忘录","previous-year": "上一年",- "resize-panel": "调整当天面板宽度","select-month": "选择月份"},"demo": {@@ -102,6 +97,7 @@"clear": "清除","close": "关闭","collapse": "收起",+ "collapse-panel": "收起面板","confirm": "确定","copy": "复制","create": "创建",@@ -123,6 +119,7 @@"empty-placeholder": "空","email": "邮箱","expand": "展开",+ "expand-panel": "展开面板","explore": "发现","file": "文件","filter": "过滤器",@@ -161,6 +158,7 @@"remember-me": "保持登录","rename": "重命名","reset": "重置",+ "resize-panel": "调整面板宽度","resources": "资源库","restore": "恢复","role": "身份",diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.jsonindex 294545c51..85be86408 100644--- a/web/src/locales/zh-Hant.json+++ b/web/src/locales/zh-Hant.json@@ -50,13 +50,11 @@"welcome-back": "歡迎回來。"},"calendar": {- "close-day": "關閉當天","more-memos": "還有 {{count}} 條","new-memo-on-day": "在這一天新增備忘錄","next-year": "下一年","no-memos-in-month": "{{month}} 沒有備忘錄","previous-year": "上一年",- "resize-panel": "調整當天面板寬度","select-month": "選擇月份"},"demo": {diff --git a/web/tests/map-view.test.tsx b/web/tests/map-view.test.tsxindex 678e42e0c..ea40b6895 100644--- a/web/tests/map-view.test.tsx+++ b/web/tests/map-view.test.tsx@@ -10,8 +10,9 @@ 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 }) =>+vi.mock("@/components/MemoPanel/MemoPanel", () => ({+ MEMO_PANEL_INSET: 12,+ MemoPanel: ({ open, busy, children }: { open: boolean; busy: boolean; children: ReactNode }) =>open ? (<div data-testid="panel" data-busy={busy}>{children}