- {comments.length === 0 ? (
- showCreateButton && (
-
-
- );
-};
+ );
+ },
+);
+
+MemoCommentSection.displayName = "MemoCommentSection";
export default MemoCommentSection;
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
index 31e26033..b0fed719 100644
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
@@ -1,22 +1,34 @@
import copy from "copy-to-clipboard";
-import { BookmarkCheckIcon, BookmarkIcon, ChevronDownIcon, ImageIcon, LinkIcon, Share2Icon } from "lucide-react";
+import {
+ ArrowLeftIcon,
+ ChevronDownIcon,
+ CornerUpLeftIcon,
+ Edit3Icon,
+ ImageIcon,
+ LinkIcon,
+ MessageCircleIcon,
+ MessageSquarePlusIcon,
+ Share2Icon,
+} from "lucide-react";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
-import { Link } from "react-router-dom";
-import SidebarRow, { SIDEBAR_ROW_CLASSES, SidebarRowIconSlot } from "@/components/AppSidebar/SidebarRow";
+import { Link, useLocation } from "react-router-dom";
+import { getSidebarRouteKind } from "@/components/AppSidebar/routes";
+import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_COUNT_RAIL_CLASSES, SidebarRowIconSlot } from "@/components/AppSidebar/SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "@/components/AppSidebar/SidebarSection";
import { extractHeadings } from "@/components/MemoContent/pipeline";
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
-import { createMemoNavigationState, type MemoOriginScope } from "@/components/MemoView/navigation";
+import { createMemoNavigationState, isMemoCollectionOrigin, type MemoOriginScope } from "@/components/MemoView/navigation";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useInstance } from "@/contexts/InstanceContext";
+import { useSpaceContext } from "@/contexts/SpaceContext";
import { useOverflowTitle } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
-import { useUpdateMemo } from "@/hooks/useMemoQueries";
+import { MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";
import { cn } from "@/lib/utils";
import { State } from "@/types/proto/api/v1/common_pb";
-import { Memo, type MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
+import { Memo, type MemoRelation, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { isSuperUser } from "@/utils/user";
import MemoOutline from "./MemoOutline";
@@ -24,23 +36,33 @@ import MemoSharePanel from "./MemoSharePanel";
interface Props {
memo: Memo;
+ parentMemo?: Memo;
parentPage?: string;
parentScope?: MemoOriginScope;
+ hasExplicitOrigin?: boolean;
+ commentCount?: number;
className?: string;
+ onEdit?: () => void;
+ onCommentsOpen?: () => void;
+ onCommentCreate?: () => void;
onShareImageOpen?: () => void;
forceReadonly?: boolean;
}
+const normalizeSnippet = (value: string): string => value.replace(/\s+/g, " ").trim();
+
const BacklinkRow = ({
relation,
snippet,
parentPage,
parentScope,
+ referencedByLabel,
}: {
relation: MemoRelation;
snippet: string;
parentPage?: string;
parentScope?: MemoOriginScope;
+ referencedByLabel: string;
}) => {
const { ref, title } = useOverflowTitle
(snippet);
const relatedMemo = getRelationMemo(relation, "referenced");
@@ -50,6 +72,7 @@ const BacklinkRow = ({
return (
{
+const MemoDetailSidebar = ({
+ memo,
+ parentMemo,
+ parentPage,
+ parentScope,
+ hasExplicitOrigin = false,
+ commentCount,
+ className,
+ onEdit,
+ onCommentsOpen,
+ onCommentCreate,
+ onShareImageOpen,
+ forceReadonly = false,
+}: Props) => {
const t = useTranslate();
+ const location = useLocation();
const currentUser = useCurrentUser();
const { profile } = useInstance();
- const { mutateAsync: updateMemo } = useUpdateMemo();
+ const { clearSelectedSpace } = useSpaceContext();
const [sharePanelOpen, setSharePanelOpen] = useState(false);
const readonly = forceReadonly || (memo.creator !== currentUser?.name && !isSuperUser(currentUser));
- const canPin = !readonly && !memo.parent && memo.state === State.NORMAL;
- const canManageShares = !forceReadonly && !memo.parent && (memo.creator === currentUser?.name || isSuperUser(currentUser));
+ const canEdit = !!onEdit && !readonly && memo.state === State.NORMAL;
+ const canComment = !!onCommentCreate && !forceReadonly && !!currentUser && memo.state === State.NORMAL;
+ const canManageShares =
+ !forceReadonly &&
+ !memo.parent &&
+ memo.creator === currentUser?.name &&
+ memo.state === State.NORMAL &&
+ memo.visibility !== Visibility.SPACE;
const headings = useMemo(() => extractHeadings(memo.content), [memo.content]);
const { referenced } = useMemo(() => getRelationBuckets(memo.relations, memo.name), [memo.relations, memo.name]);
@@ -94,29 +137,122 @@ const MemoDetailSidebar = ({ memo, parentPage, parentScope, className, onShareIm
if (!relatedMemo) {
return "";
}
- return relatedMemo.snippet || resolvedMemos[relatedMemo.name]?.snippet || relatedMemo.name;
+ return normalizeSnippet(relatedMemo.snippet || resolvedMemos[relatedMemo.name]?.snippet || relatedMemo.name);
};
- const handleTogglePin = async () => {
- await updateMemo({ update: { name: memo.name, pinned: !memo.pinned }, updateMask: ["pinned"] });
- };
+ const originLabel = useMemo(() => {
+ const originPath = parentPage?.split(/[?#]/, 1)[0] || "/";
+ switch (getSidebarRouteKind(originPath)) {
+ case "explore":
+ return t("common.explore");
+ case "archived":
+ return t("common.archived");
+ case "attachments":
+ return t("common.attachments");
+ case "profile":
+ return t("common.profile");
+ case "views":
+ return t("common.views");
+ case "inbox":
+ return t("common.inbox");
+ case "settings":
+ return t("common.settings");
+ default:
+ return t("common.home");
+ }
+ }, [parentPage, t]);
+
+ const parentSnippet = parentMemo ? normalizeSnippet(parentMemo.snippet || parentMemo.content || parentMemo.name) : "";
+ const showComments = !forceReadonly && commentCount !== undefined && commentCount > 0;
+ const showOnThisMemo = headings.length > 1 || showComments;
+ const showConnections = !forceReadonly && (!!parentMemo || referenced.length > 0);
const handleCopyLink = () => {
- const host = profile.instanceUrl || window.location.origin;
- copy(`${host}/${memo.name}`);
+ const host = (profile.instanceUrl || window.location.origin).replace(/\/+$/, "");
+ const path = forceReadonly ? `${location.pathname}${location.search}` : `/${memo.name}`;
+ copy(`${host}${path.startsWith("/") ? path : `/${path}`}`);
toast.success(t("message.succeed-copy-link"));
};
return (
+ {!forceReadonly && parentPage && (
+
+ {
+ if (parentScope === "all" && isMemoCollectionOrigin(parentPage)) {
+ clearSelectedSpace();
+ }
+ }}
+ viewTransition
+ >
+
+
+ {hasExplicitOrigin ? t("memo.back-to", { source: originLabel }) : t("memo.go-to", { source: originLabel })}
+
+
+
+ )}
+
+ {showOnThisMemo && (
+
+ {headings.length > 1 && }
+ {showComments && (
+ {
+ if (!onCommentsOpen) return;
+ event.preventDefault();
+ onCommentsOpen();
+ }}
+ >
+
+ {t("memo.comment.self")}
+ {commentCount}
+
+ )}
+
+ )}
+
+ {showConnections && (
+
+ {parentMemo && (
+
+
+ {parentSnippet}
+
+ )}
+ {referenced.map((relation) => {
+ const relatedMemo = getRelationMemo(relation, "referenced");
+ return (
+
+ );
+ })}
+
+ )}
+
- {canPin && (
-
- )}
+ {canEdit && }
+ {canComment && }
- {headings.length > 1 && (
-
-
-
- )}
-
- {!forceReadonly && referenced.length > 0 && (
-
- {referenced.map((relation) => {
- const relatedMemo = getRelationMemo(relation, "referenced");
- return (
-
- );
- })}
-
- )}
-
{sharePanelOpen &&
setSharePanelOpen(false)} />}
);
diff --git a/web/src/components/MemoEditor/hooks/useMemoSave.ts b/web/src/components/MemoEditor/hooks/useMemoSave.ts
index 12c8a236..05b22a71 100644
--- a/web/src/components/MemoEditor/hooks/useMemoSave.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoSave.ts
@@ -74,6 +74,7 @@ export function useMemoSave({
}
if (parentMemoName) {
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.comments(parentMemoName) }));
+ invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(parentMemoName) }));
}
await Promise.all(invalidationPromises);
diff --git a/web/src/components/MemoView/MemoView.tsx b/web/src/components/MemoView/MemoView.tsx
index 54129e19..04e7d461 100644
--- a/web/src/components/MemoView/MemoView.tsx
+++ b/web/src/components/MemoView/MemoView.tsx
@@ -1,4 +1,15 @@
-import { type ComponentType, memo, Suspense, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ type ComponentType,
+ forwardRef,
+ memo,
+ Suspense,
+ useCallback,
+ useImperativeHandle,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useLocation } from "react-router-dom";
import { useResolvedUser } from "@/components/MemoContent/MentionResolutionContext";
import { loadMemoEditor } from "@/components/MemoEditor/loader";
@@ -15,12 +26,12 @@ import { MEMO_CARD_BASE_CLASSES } from "./constants";
import { useImagePreview } from "./hooks";
import { computeCommentAmount, MemoViewContext } from "./MemoViewContext";
import { isMemoDetailPath, resolveMemoOrigin } from "./navigation";
-import type { MemoViewProps } from "./types";
+import type { MemoViewHandle, MemoViewProps } from "./types";
const MemoShareImageDialog = lazyWithReload(() => import("../MemoActionMenu/MemoShareImageDialog"));
const PreviewImageDialog = lazyWithReload(() => import("../PreviewImageDialog"));
-const MemoView: React.FC = (props: MemoViewProps) => {
+const MemoView = forwardRef((props, ref) => {
const {
memo: memoData,
className,
@@ -57,17 +68,30 @@ const MemoView: React.FC = (props: MemoViewProps) => {
const toggleBlurVisibility = useCallback(() => setShowBlurredContent((prev) => !prev), []);
const { previewState, openPreview, setPreviewOpen } = useImagePreview();
+ const editorHostRef = useRef(null);
+
+ const focusMountedEditor = useCallback(() => {
+ const codeMirrorContent = editorHostRef.current?.querySelector('.cm-content[contenteditable="true"]');
+ const fallbackInput = editorHostRef.current?.querySelector("textarea, input");
+ (codeMirrorContent ?? fallbackInput)?.focus();
+ }, []);
const openEditor = useCallback(() => {
+ if (showEditor && EditorComponent) {
+ focusMountedEditor();
+ return;
+ }
void loadMemoEditor()
.then(({ default: MemoEditor }) => {
setEditorComponent(() => MemoEditor);
setShowEditor(true);
})
.catch(() => undefined);
- }, []);
+ }, [EditorComponent, focusMountedEditor, showEditor]);
const closeEditor = useCallback(() => setShowEditor(false), []);
+ useImperativeHandle(ref, () => ({ openEditor }), [openEditor]);
+
const isInMemoDetailPage = isMemoDetailPath(location.pathname, memoData.name);
const showCommentPreview = !isInMemoDetailPage && computeCommentAmount(memoData) > 0;
@@ -178,20 +202,24 @@ const MemoView: React.FC = (props: MemoViewProps) => {
return (
{showEditor && EditorComponent ? (
-
+
+
+
) : (
memoDisplay
)}
);
-};
+});
+
+MemoView.displayName = "MemoView";
export default memo(MemoView);
diff --git a/web/src/components/MemoView/components/MemoCommentListView.tsx b/web/src/components/MemoView/components/MemoCommentListView.tsx
index cd44e4e2..5b06b0b6 100644
--- a/web/src/components/MemoView/components/MemoCommentListView.tsx
+++ b/web/src/components/MemoView/components/MemoCommentListView.tsx
@@ -4,6 +4,7 @@ import { MemoPreview } from "@/components/MemoPreview";
import { useMemoComments } from "@/hooks/useMemoQueries";
import { useNearViewport } from "@/hooks/useNearViewport";
import { useUsersByNames } from "@/hooks/useUserQueries";
+import { MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";
import { extractMemoIdFromName } from "@/lib/resource-names";
import { useMemoViewContext, useMemoViewDerived } from "../MemoViewContext";
import { createMemoNavigationState } from "../navigation";
@@ -30,7 +31,7 @@ const MemoCommentListView: React.FC = () => {
Comments{commentAmount > 1 ? ` (${commentAmount})` : ""}
diff --git a/web/src/components/MemoView/index.ts b/web/src/components/MemoView/index.ts
index 5c3f6e90..8dbbf0f2 100644
--- a/web/src/components/MemoView/index.ts
+++ b/web/src/components/MemoView/index.ts
@@ -1,2 +1,2 @@
export { default, default as MemoView } from "./MemoView";
-export type { MemoViewProps } from "./types";
+export type { MemoViewHandle, MemoViewProps } from "./types";
diff --git a/web/src/components/MemoView/types.ts b/web/src/components/MemoView/types.ts
index cd9d52ec..b2f42a56 100644
--- a/web/src/components/MemoView/types.ts
+++ b/web/src/components/MemoView/types.ts
@@ -15,6 +15,10 @@ export interface MemoViewProps {
onShareImageDialogOpenChange?: (open: boolean) => void;
}
+export interface MemoViewHandle {
+ openEditor: () => void;
+}
+
export interface MemoHeaderProps {
showCreator?: boolean;
showVisibility?: boolean;
diff --git a/web/src/contexts/AppSidebarContext.tsx b/web/src/contexts/AppSidebarContext.tsx
index 80fca6f9..9cb25f3c 100644
--- a/web/src/contexts/AppSidebarContext.tsx
+++ b/web/src/contexts/AppSidebarContext.tsx
@@ -1,4 +1,4 @@
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import type { MemoOriginScope } from "@/components/MemoView/navigation";
import type { PrimaryMemoScope } from "@/lib/memo-views";
@@ -9,9 +9,15 @@ export type InboxFilter = "all" | "unread" | "archived";
export interface MemoDetailSidebarDescriptor {
memo: Memo;
+ parentMemo?: Memo;
from?: string;
fromScope?: MemoOriginScope;
+ hasExplicitOrigin?: boolean;
+ commentCount?: number;
readonly?: boolean;
+ onEdit?: () => void;
+ onCommentsOpen?: () => void;
+ onCommentCreate?: () => void;
onShareImageOpen?: () => void;
}
@@ -24,6 +30,8 @@ interface AppSidebarContextValue {
setMemoDetail: (descriptor?: MemoDetailSidebarDescriptor) => void;
mobileOpen: boolean;
setMobileOpen: (open: boolean) => void;
+ closeMobileThen: (action: () => void) => void;
+ completeMobileClose: (open: boolean) => void;
quickFindOpen: boolean;
setQuickFindOpen: (open: boolean) => void;
memoScope: PrimaryMemoScope;
@@ -38,19 +46,61 @@ export const AppSidebarProvider = ({ children }: { children: ReactNode }) => {
const [inboxFilter, setInboxFilter] = useState
("all");
const [memoDetail, setMemoDetailState] = useState();
const [mobileOpen, setMobileOpen] = useState(false);
+ const pendingMobileCloseActionRef = useRef<(() => void) | undefined>(undefined);
+ const scheduledMobileCloseActionFrameRef = useRef(undefined);
const [quickFindOpen, setQuickFindOpen] = useState(false);
const [memoScope, setMemoScope] = useState("home");
useEffect(() => {
+ pendingMobileCloseActionRef.current = undefined;
+ if (scheduledMobileCloseActionFrameRef.current !== undefined) {
+ window.cancelAnimationFrame(scheduledMobileCloseActionFrameRef.current);
+ scheduledMobileCloseActionFrameRef.current = undefined;
+ }
setMobileOpen(false);
setAttachmentSection("all");
setInboxFilter("all");
+
+ return () => {
+ pendingMobileCloseActionRef.current = undefined;
+ if (scheduledMobileCloseActionFrameRef.current !== undefined) {
+ window.cancelAnimationFrame(scheduledMobileCloseActionFrameRef.current);
+ scheduledMobileCloseActionFrameRef.current = undefined;
+ }
+ };
}, [location.pathname]);
const setMemoDetail = useCallback((descriptor?: MemoDetailSidebarDescriptor) => {
setMemoDetailState(descriptor);
}, []);
+ const closeMobileThen = useCallback(
+ (action: () => void) => {
+ if (!mobileOpen) {
+ action();
+ return;
+ }
+
+ pendingMobileCloseActionRef.current = action;
+ setMobileOpen(false);
+ },
+ [mobileOpen],
+ );
+
+ const completeMobileClose = useCallback((open: boolean) => {
+ if (open) return;
+ const action = pendingMobileCloseActionRef.current;
+ pendingMobileCloseActionRef.current = undefined;
+ if (!action) return;
+
+ // Base UI restores focus in a microtask after the Sheet unmounts. Run the destination
+ // action on the next frame so an editor's focus cannot be overwritten by that cleanup.
+ scheduledMobileCloseActionFrameRef.current = window.requestAnimationFrame(() => {
+ scheduledMobileCloseActionFrameRef.current = undefined;
+ action();
+ });
+ }, []);
+
const value = useMemo(
() => ({
attachmentSection,
@@ -61,12 +111,14 @@ export const AppSidebarProvider = ({ children }: { children: ReactNode }) => {
setMemoDetail,
mobileOpen,
setMobileOpen,
+ closeMobileThen,
+ completeMobileClose,
quickFindOpen,
setQuickFindOpen,
memoScope,
setMemoScope,
}),
- [attachmentSection, inboxFilter, memoDetail, setMemoDetail, mobileOpen, quickFindOpen, memoScope],
+ [attachmentSection, inboxFilter, memoDetail, setMemoDetail, mobileOpen, closeMobileThen, completeMobileClose, quickFindOpen, memoScope],
);
return {children};
diff --git a/web/src/lib/memo-comments.ts b/web/src/lib/memo-comments.ts
new file mode 100644
index 00000000..96ed01d9
--- /dev/null
+++ b/web/src/lib/memo-comments.ts
@@ -0,0 +1,5 @@
+export const MEMO_COMMENTS_ANCHOR_ID = "memo-comments";
+export const LEGACY_MEMO_COMMENTS_ANCHOR_ID = "comments";
+
+/** Keep memo headings from claiming the current or legacy comment-section fragments. */
+export const RESERVED_MEMO_COMMENTS_ANCHOR_IDS = [MEMO_COMMENTS_ANCHOR_ID, LEGACY_MEMO_COMMENTS_ANCHOR_ID] as const;
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index 56ed6fdc..b0431710 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -336,6 +336,7 @@
},
"memo": {
"archived-at": "Archived at",
+ "back-to": "Back to {{source}}",
"click-to-hide-sensitive-content": "Click to hide sensitive content",
"click-to-show-sensitive-content": "Click to show sensitive content",
"code": "Code",
@@ -361,7 +362,9 @@
"label": "Filters"
},
"compact-mode": "Compact mode",
+ "connections": "Connections",
"grid-compact-hint": "Grid layouts always use compact cards.",
+ "go-to": "Go to {{source}}",
"layout": "Layout",
"layout-auto": "Auto",
"layout-auto-description": "As many columns as fit the screen",
@@ -377,9 +380,11 @@
"new-badge": "New",
"newest-first": "Newest first",
"oldest-first": "Oldest first",
+ "on-this-memo": "On this memo",
"order": "Order",
"order-by": "Order by",
"outline": "Outline",
+ "parent-memo": "Parent memo",
"search-placeholder": "Search memos...",
"shown-time": "Shown time",
"share": {
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 08d78a00..20862819 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -262,6 +262,7 @@
},
"memo": {
"archived-at": "归档于",
+ "back-to": "返回{{source}}",
"click-to-hide-sensitive-content": "点击隐藏 NSFW 内容",
"click-to-show-sensitive-content": "点击显示 NSFW 内容",
"code": "代码",
@@ -286,7 +287,9 @@
"label": "过滤器"
},
"compact-mode": "紧凑模式",
+ "connections": "关联",
"grid-compact-hint": "网格布局始终使用紧凑卡片。",
+ "go-to": "前往{{source}}",
"layout": "布局",
"layout-auto": "自动",
"layout-auto-description": "根据屏幕宽度显示尽可能多的列",
@@ -302,8 +305,10 @@
"new-badge": "新",
"newest-first": "最新优先",
"oldest-first": "最早优先",
+ "on-this-memo": "本条备忘录",
"order": "顺序",
"order-by": "排序",
+ "parent-memo": "父备忘录",
"search-placeholder": "搜索备忘录",
"shown-time": "显示时间",
"show-less": "显示较少",
diff --git a/web/src/pages/MemoDetail.tsx b/web/src/pages/MemoDetail.tsx
index 0e949ee9..630e4db0 100644
--- a/web/src/pages/MemoDetail.tsx
+++ b/web/src/pages/MemoDetail.tsx
@@ -2,9 +2,10 @@ import { Code, ConnectError } from "@connectrpc/connect";
import { ArrowUpLeftFromCircleIcon } from "lucide-react";
import { useCallback, useEffect, useMemo as useReactMemo, useRef, useState } from "react";
import { Link, Navigate, useLocation, useParams } from "react-router-dom";
-import MemoCommentSection from "@/components/MemoCommentSection";
+import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection";
import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
-import MemoView from "@/components/MemoView";
+import MemoView, { type MemoViewHandle } from "@/components/MemoView";
+import { computeCommentAmount } from "@/components/MemoView/MemoViewContext";
import { createMemoNavigationState, type MemoOriginScope, resolveMemoDetailOrigin } from "@/components/MemoView/navigation";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
@@ -12,7 +13,9 @@ import { useInstance } from "@/contexts/InstanceContext";
import useMemoDetailError from "@/hooks/useMemoDetailError";
import { useInfiniteMemoComments, useMemo } from "@/hooks/useMemoQueries";
import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQueries";
+import { LEGACY_MEMO_COMMENTS_ANCHOR_ID, MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";
import { memoNamePrefix } from "@/lib/resource-names";
+import { ROUTES } from "@/router/routes";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { State } from "@/types/proto/api/v1/common_pb";
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
@@ -20,22 +23,59 @@ import { findMemoAnchorTarget } from "@/utils/markdown-manipulation";
const MemoSidebarRegistration = ({
memo,
+ parentMemo,
from,
fromScope,
+ hasExplicitOrigin,
+ commentCount,
readonly,
+ onEdit,
+ onCommentsOpen,
+ onCommentCreate,
onShareImageOpen,
}: {
memo: Memo;
+ parentMemo?: Memo;
from: string;
fromScope: MemoOriginScope;
+ hasExplicitOrigin: boolean;
+ commentCount?: number;
readonly: boolean;
+ onEdit: () => void;
+ onCommentsOpen: () => void;
+ onCommentCreate: () => void;
onShareImageOpen: () => void;
}) => {
const { setMemoDetail } = useAppSidebar();
useEffect(() => {
- setMemoDetail({ memo, from, fromScope, readonly, onShareImageOpen });
- }, [from, fromScope, memo, onShareImageOpen, readonly, setMemoDetail]);
+ setMemoDetail({
+ memo,
+ parentMemo,
+ from,
+ fromScope,
+ hasExplicitOrigin,
+ commentCount,
+ readonly,
+ onEdit,
+ onCommentsOpen,
+ onCommentCreate,
+ onShareImageOpen,
+ });
+ }, [
+ commentCount,
+ from,
+ fromScope,
+ hasExplicitOrigin,
+ memo,
+ onCommentCreate,
+ onCommentsOpen,
+ onEdit,
+ onShareImageOpen,
+ parentMemo,
+ readonly,
+ setMemoDetail,
+ ]);
useEffect(() => () => setMemoDetail(undefined), [setMemoDetail]);
@@ -43,13 +83,16 @@ const MemoSidebarRegistration = ({
};
const MemoDetail = () => {
- const { isInitialized: authInitialized } = useAuth();
+ const { currentUser, isInitialized: authInitialized } = useAuth();
const { isInitialized: instanceInitialized } = useInstance();
const [shareImageDialogOpen, setShareImageDialogOpen] = useState(false);
const params = useParams();
const location = useLocation();
const { state: locationState, hash } = location;
+ const memoViewRef = useRef(null);
+ const commentSectionRef = useRef(null);
const handleShareImageOpen = useCallback(() => setShareImageDialogOpen(true), []);
+ const handleEdit = useCallback(() => memoViewRef.current?.openEditor(), []);
// Detect share mode from the route parameter.
const shareToken = params.token;
@@ -67,7 +110,11 @@ const MemoDetail = () => {
const memo = isShareMode ? memoFromShare : memoFromDirect;
const error = isShareMode ? shareError : directError;
const isLoading = isShareMode ? shareLoading : directLoading;
- const { parentPage, parentScope } = resolveMemoDetailOrigin(locationState, { memoArchived: memo?.state === State.ARCHIVED });
+ const hasExplicitOrigin =
+ !!locationState && typeof locationState === "object" && typeof (locationState as { from?: unknown }).from === "string";
+ const resolvedOrigin = resolveMemoDetailOrigin(locationState, { memoArchived: memo?.state === State.ARCHIVED });
+ const parentPage = !hasExplicitOrigin && !currentUser && memo?.state !== State.ARCHIVED ? ROUTES.EXPLORE : resolvedOrigin.parentPage;
+ const parentScope = resolvedOrigin.parentScope;
const memoName = memo?.name ?? memoNameFromParams;
const displayMemo = useReactMemo(() => {
if (!memo) return undefined;
@@ -91,6 +138,17 @@ const MemoDetail = () => {
} = useInfiniteMemoComments(memoName, {
enabled: !isShareMode && !!memo,
});
+ const commentCount = memo ? Math.max(computeCommentAmount(memo), comments.length) : 0;
+
+ const handleCommentsOpen = useCallback(() => {
+ commentSectionRef.current?.scrollIntoView();
+ window.history.replaceState(window.history.state, "", `${location.pathname}${location.search}#${MEMO_COMMENTS_ANCHOR_ID}`);
+ }, [location.pathname, location.search]);
+
+ const handleCommentCreate = useCallback(() => {
+ handleCommentsOpen();
+ void commentSectionRef.current?.openEditor();
+ }, [handleCommentsOpen]);
// Scroll to the hash target once it's in the DOM. The effect re-runs as the memo loads (footnote
// anchors) and as comments arrive (comment anchors), since the target may render in either; the
@@ -100,7 +158,17 @@ const MemoDetail = () => {
if (!hash) return;
const scrollKey = `${memoName}\0${hash}`;
if (scrolledHashRef.current === scrollKey) return;
- const el = findMemoAnchorTarget(document, memoName, decodeURIComponent(hash.slice(1)));
+ const fragment = decodeURIComponent(hash.slice(1));
+ const commentSection = commentSectionRef.current;
+ if (commentSection && (fragment === MEMO_COMMENTS_ANCHOR_ID || fragment === LEGACY_MEMO_COMMENTS_ANCHOR_ID)) {
+ scrolledHashRef.current = scrollKey;
+ commentSection.scrollIntoView();
+ return;
+ }
+
+ // A legacy #comments link on a share-token page has no comment section. Let it
+ // resolve to a historical body heading instead of turning into a dead fragment.
+ const el = findMemoAnchorTarget(document, memoName, fragment);
if (!el) return;
scrolledHashRef.current = scrollKey;
el.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -127,15 +195,21 @@ const MemoDetail = () => {
{!isShareMode && parentMemo && (
-
+
{
)}
{
/>
{!isShareMode && (
();
for (const heading of root.querySelectorAll("h1, h2, h3, h4, h5, h6")) {
const baseSlug = legacySlugify(heading.textContent ?? "");
diff --git a/web/src/utils/rehype-plugins/rehype-heading-id.ts b/web/src/utils/rehype-plugins/rehype-heading-id.ts
index 69103569..5cb4bf31 100644
--- a/web/src/utils/rehype-plugins/rehype-heading-id.ts
+++ b/web/src/utils/rehype-plugins/rehype-heading-id.ts
@@ -1,6 +1,7 @@
import type { Element, Root } from "hast";
import { visit } from "unist-util-visit";
-import { createUniqueSlugGenerator, slugify } from "@/utils/markdown-manipulation";
+import { RESERVED_MEMO_COMMENTS_ANCHOR_IDS } from "@/lib/memo-comments";
+import { createUniqueSlugGenerator, ORIGINAL_HEADING_ID_ATTRIBUTE, slugify } from "@/utils/markdown-manipulation";
/** Anchor used for headings with no slugifiable characters (emoji- or punctuation-only titles). */
const FALLBACK_HEADING_SLUG = "heading";
@@ -33,7 +34,7 @@ export const rehypeHeadingId = () => {
// Reserve ids supplied by the source or generated by remark-rehype before assigning any new
// ones. Otherwise an earlier markdown heading can take `footnote-label`, forcing the linked
// screen-reader footnote label to be renamed without updating its aria-describedby references.
- const existingIds = new Set();
+ const existingIds = new Set(RESERVED_MEMO_COMMENTS_ANCHOR_IDS);
visit(tree, "element", (node: Element) => {
if (!isHeadingElement(node)) return;
const existingId = typeof node.properties?.id === "string" ? node.properties.id : "";
@@ -41,7 +42,7 @@ export const rehypeHeadingId = () => {
});
const makeUniqueSlug = createUniqueSlugGenerator(existingIds);
- const claimedExistingIds = new Set();
+ const claimedExistingIds = new Set(RESERVED_MEMO_COMMENTS_ANCHOR_IDS);
visit(tree, "element", (node: Element) => {
if (!isHeadingElement(node)) return;
@@ -55,7 +56,11 @@ export const rehypeHeadingId = () => {
claimedExistingIds.add(existingId);
node.properties.id = existingId;
} else {
- node.properties.id = makeUniqueSlug(existingId || slugify(getHeadingText(node)) || FALLBACK_HEADING_SLUG);
+ const nextId = makeUniqueSlug(existingId || slugify(getHeadingText(node)) || FALLBACK_HEADING_SLUG);
+ if (existingId && nextId !== existingId) {
+ node.properties[ORIGINAL_HEADING_ID_ATTRIBUTE] = existingId;
+ }
+ node.properties.id = nextId;
}
});
};
diff --git a/web/tests/app-sidebar-context.test.tsx b/web/tests/app-sidebar-context.test.tsx
index 6904816c..ea43ae40 100644
--- a/web/tests/app-sidebar-context.test.tsx
+++ b/web/tests/app-sidebar-context.test.tsx
@@ -1,15 +1,28 @@
-import { fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
import { MemoryRouter, useNavigate } from "react-router-dom";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AppSidebarProvider, useAppSidebar } from "@/contexts/AppSidebarContext";
const Harness = () => {
const navigate = useNavigate();
- const { attachmentSection, setAttachmentSection, inboxFilter, setInboxFilter } = useAppSidebar();
+ const {
+ attachmentSection,
+ setAttachmentSection,
+ inboxFilter,
+ setInboxFilter,
+ mobileOpen,
+ setMobileOpen,
+ closeMobileThen,
+ completeMobileClose,
+ } = useAppSidebar();
+ const [actionCount, setActionCount] = useState(0);
return (
+
+
setAttachmentSection("media")}>
Select media
@@ -19,11 +32,24 @@ const Harness = () => {
navigate("/inbox")}>
Change route
+ setMobileOpen(true)}>
+ Open mobile sidebar
+
+ closeMobileThen(() => setActionCount((count) => count + 1))}>
+ Run after close
+
+ completeMobileClose(false)}>
+ Finish mobile close
+
);
};
describe("AppSidebarProvider", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
it("keeps page controls local and resets them after a route change", () => {
render(
@@ -42,4 +68,70 @@ describe("AppSidebarProvider", () => {
expect(screen.getByTestId("attachment-section")).toHaveTextContent("all");
expect(screen.getByTestId("inbox-filter")).toHaveTextContent("all");
});
+
+ it("defers sidebar actions until the mobile close transition finishes", () => {
+ let frameCallback: FrameRequestCallback | undefined;
+ vi.stubGlobal(
+ "requestAnimationFrame",
+ vi.fn((callback: FrameRequestCallback) => {
+ frameCallback = callback;
+ return 1;
+ }),
+ );
+ vi.stubGlobal("cancelAnimationFrame", vi.fn());
+
+ render(
+
+
+
+
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Open mobile sidebar" }));
+ fireEvent.click(screen.getByRole("button", { name: "Run after close" }));
+ expect(screen.getByTestId("mobile-open")).toHaveTextContent("false");
+ expect(screen.getByTestId("action-count")).toHaveTextContent("0");
+
+ fireEvent.click(screen.getByRole("button", { name: "Finish mobile close" }));
+ expect(screen.getByTestId("action-count")).toHaveTextContent("0");
+ act(() => frameCallback?.(0));
+ expect(screen.getByTestId("action-count")).toHaveTextContent("1");
+
+ fireEvent.click(screen.getByRole("button", { name: "Run after close" }));
+ expect(screen.getByTestId("action-count")).toHaveTextContent("2");
+ });
+
+ it("cancels a pending mobile action when the route changes", () => {
+ const frameCallbacks = new Map();
+ let nextFrame = 0;
+ vi.stubGlobal(
+ "requestAnimationFrame",
+ vi.fn((callback: FrameRequestCallback) => {
+ nextFrame += 1;
+ frameCallbacks.set(nextFrame, callback);
+ return nextFrame;
+ }),
+ );
+ vi.stubGlobal(
+ "cancelAnimationFrame",
+ vi.fn((frame: number) => frameCallbacks.delete(frame)),
+ );
+
+ render(
+
+
+
+
+ ,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Open mobile sidebar" }));
+ fireEvent.click(screen.getByRole("button", { name: "Run after close" }));
+ fireEvent.click(screen.getByRole("button", { name: "Change route" }));
+ fireEvent.click(screen.getByRole("button", { name: "Finish mobile close" }));
+ act(() => frameCallbacks.forEach((callback) => callback(0)));
+
+ expect(screen.getByTestId("action-count")).toHaveTextContent("0");
+ });
});
diff --git a/web/tests/memo-action-navigation.test.tsx b/web/tests/memo-action-navigation.test.tsx
index 52e3e1ba..4a190bd8 100644
--- a/web/tests/memo-action-navigation.test.tsx
+++ b/web/tests/memo-action-navigation.test.tsx
@@ -15,7 +15,10 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("@/hooks/useMemoQueries", () => ({
- memoKeys: { comments: (name: string) => ["memos", name, "comments"] },
+ memoKeys: {
+ comments: (name: string) => ["memos", name, "comments"],
+ detail: (name: string) => ["memos", name, "detail"],
+ },
useUpdateMemo: () => ({ mutateAsync: mocks.updateMemo }),
useDeleteMemo: () => ({ mutateAsync: mocks.deleteMemo }),
}));
@@ -40,27 +43,28 @@ vi.mock("react-hot-toast", () => ({
default: { success: vi.fn(), error: vi.fn() },
}));
-const createMemo = (state: State): Memo =>
+const createMemo = (state: State, parent = ""): Memo =>
({
name: "memos/1",
content: "memo",
state,
- parent: "",
+ parent,
}) as Memo;
-const renderActions = (state: State, parentScope: MemoOriginScope) => {
+const renderActions = (state: State, parentScope: MemoOriginScope, parent = "") => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
const wrapper = ({ children }: { children: ReactNode }) => (
{children}
);
- return renderHook(
+ const rendered = renderHook(
() => {
const location = useLocation();
const handlers = useMemoActionHandlers({
- memo: createMemo(state),
+ memo: createMemo(state, parent),
parentScope,
setDeleteDialogOpen: vi.fn(),
});
@@ -68,6 +72,7 @@ const renderActions = (state: State, parentScope: MemoOriginScope) => {
},
{ wrapper },
);
+ return { ...rendered, invalidateQueries };
};
describe("Memo detail mutation navigation", () => {
@@ -112,4 +117,15 @@ describe("Memo detail mutation navigation", () => {
await waitFor(() => expect(result.current.pathname).toBe("/"));
expect(mocks.clearSelectedSpace).toHaveBeenCalledOnce();
});
+
+ it("refreshes a parent memo after deleting one of its comments", async () => {
+ const { result, invalidateQueries } = renderActions(State.NORMAL, "preserve", "memos/parent");
+
+ await act(async () => {
+ await result.current.handlers.confirmDeleteMemo();
+ });
+
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "memos/parent", "comments"] });
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "memos/parent", "detail"] });
+ });
});
diff --git a/web/tests/memo-comment-section.test.tsx b/web/tests/memo-comment-section.test.tsx
new file mode 100644
index 00000000..b34a6fc8
--- /dev/null
+++ b/web/tests/memo-comment-section.test.tsx
@@ -0,0 +1,95 @@
+import { create } from "@bufbuild/protobuf";
+import { render, screen } from "@testing-library/react";
+import { act, createRef } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection";
+import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import { State } from "@/types/proto/api/v1/common_pb";
+import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ currentUser: { name: "users/alice" } as { name: string } | undefined,
+ loadMemoEditor: vi.fn(),
+}));
+
+vi.mock("@/components/MemoEditor/loader", () => ({ loadMemoEditor: mocks.loadMemoEditor }));
+vi.mock("@/components/MemoView", () => ({ default: () => }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => mocks.currentUser }));
+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
+
+const MockMemoEditor = ({ autoFocus, parentMemoName }: MemoEditorProps) => (
+
+
+
+);
+
+describe("MemoCommentSection", () => {
+ beforeEach(() => {
+ mocks.currentUser = { name: "users/alice" };
+ mocks.loadMemoEditor.mockReset();
+ mocks.loadMemoEditor.mockResolvedValue({ default: MockMemoEditor });
+ });
+
+ it("does not offer or imperatively open a comment editor for archived memos", async () => {
+ const memo = create(MemoSchema, {
+ name: "memos/archived",
+ creator: "users/alice",
+ state: State.ARCHIVED,
+ });
+
+ const ref = createRef();
+ render();
+
+ await act(async () => {
+ await ref.current?.openEditor();
+ });
+
+ expect(screen.getByRole("heading", { name: "memo.comment.self" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "memo.comment.self" })).toHaveAttribute("id", "memo-comments");
+ expect(screen.queryByRole("button", { name: /memo.comment.write-a-comment/ })).not.toBeInTheDocument();
+ expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
+ });
+
+ it("opens and focuses the existing comment editor through its sidebar handle", async () => {
+ const memo = create(MemoSchema, {
+ name: "memos/detail",
+ creator: "users/alice",
+ state: State.NORMAL,
+ });
+ const ref = createRef();
+
+ render(
+ <>
+ Outside editor
+
+ >,
+ );
+ await act(async () => {
+ await ref.current?.openEditor();
+ });
+
+ expect(mocks.loadMemoEditor).toHaveBeenCalledOnce();
+ expect(screen.getByTestId("comment-editor")).toHaveAttribute("data-auto-focus", "true");
+ expect(screen.getByTestId("comment-editor")).toHaveAttribute("data-parent-memo-name", "memos/detail");
+
+ screen.getByRole("button", { name: "Outside editor" }).focus();
+ await act(async () => {
+ await ref.current?.openEditor();
+ });
+ expect(screen.getByRole("textbox", { name: "Comment editor" })).toHaveFocus();
+ });
+
+ it("uses the supplied total instead of the currently loaded page length", () => {
+ const memo = create(MemoSchema, {
+ name: "memos/detail",
+ creator: "users/alice",
+ state: State.NORMAL,
+ });
+ const comment = create(MemoSchema, { name: "memos/comment" });
+
+ render();
+
+ expect(screen.getByText("(24)")).toBeInTheDocument();
+ expect(screen.getAllByTestId("comment-memo")).toHaveLength(1);
+ });
+});
diff --git a/web/tests/memo-detail-sidebar.test.tsx b/web/tests/memo-detail-sidebar.test.tsx
index 4623b2c6..39dbe720 100644
--- a/web/tests/memo-detail-sidebar.test.tsx
+++ b/web/tests/memo-detail-sidebar.test.tsx
@@ -1,5 +1,5 @@
import { create } from "@bufbuild/protobuf";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MemoDetailSidebar from "@/components/MemoDetailSidebar/MemoDetailSidebar";
@@ -15,7 +15,8 @@ import {
} from "@/types/proto/api/v1/memo_service_pb";
const copyToClipboard = vi.hoisted(() => vi.fn());
-const updateMemo = vi.hoisted(() => vi.fn());
+const currentUserState = vi.hoisted(() => ({ value: { name: "users/alice" } as { name: string } | undefined }));
+const clearSelectedSpace = vi.hoisted(() => vi.fn());
vi.mock("copy-to-clipboard", () => ({ default: copyToClipboard }));
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
@@ -24,19 +25,31 @@ vi.mock("@/components/MemoDetailSidebar/MemoOutline", () => ({
}));
vi.mock("@/components/MemoDetailSidebar/MemoSharePanel", () => ({ default: () => }));
vi.mock("@/components/MemoMetadata/Relation/useResolvedRelationMemos", () => ({ useResolvedRelationMemos: () => ({}) }));
-vi.mock("@/contexts/InstanceContext", () => ({ useInstance: () => ({ profile: { instanceUrl: "https://memos.example" } }) }));
-vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/alice" }) }));
-vi.mock("@/hooks/useMemoQueries", () => ({ useUpdateMemo: () => ({ mutateAsync: updateMemo }) }));
-vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
+vi.mock("@/contexts/InstanceContext", () => ({ useInstance: () => ({ profile: { instanceUrl: "https://memos.example/" } }) }));
+vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ clearSelectedSpace }) }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => currentUserState.value }));
+vi.mock("@/utils/i18n", () => ({
+ useTranslate: () => (key: string, values?: { source?: string }) => (values?.source ? `${key}:${values.source}` : key),
+}));
+
+const renderSidebar = (sidebar: React.ReactNode, route = "/memos/detail") =>
+ render({sidebar});
+
+const createIncomingReference = (memoName: string, sourceName = "memos/incoming", snippet = "Incoming backlink") =>
+ create(MemoRelationSchema, {
+ type: MemoRelation_Type.REFERENCE,
+ memo: create(MemoRelation_MemoSchema, { name: sourceName, snippet }),
+ relatedMemo: create(MemoRelation_MemoSchema, { name: memoName }),
+ });
describe("MemoDetailSidebar", () => {
beforeEach(() => {
copyToClipboard.mockReset();
- updateMemo.mockReset();
- updateMemo.mockResolvedValue(undefined);
+ clearSelectedSpace.mockReset();
+ currentUserState.value = { name: "users/alice" };
});
- it("renders concise actions, outline, and backlinks without repeating body metadata", async () => {
+ it("organizes source, in-page navigation, connections, and frequent actions without repeating metadata", async () => {
const memo = create(MemoSchema, {
name: "memos/detail",
creator: "users/alice",
@@ -59,38 +72,56 @@ describe("MemoDetailSidebar", () => {
memo: create(MemoRelation_MemoSchema, { name: "memos/detail" }),
relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/outgoing", snippet: "Outgoing reference" }),
}),
- create(MemoRelationSchema, {
- type: MemoRelation_Type.REFERENCE,
- memo: create(MemoRelation_MemoSchema, { name: "memos/incoming", snippet: "Incoming backlink" }),
- relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/detail" }),
- }),
+ createIncomingReference("memos/detail"),
],
});
+ const parentMemo = create(MemoSchema, { name: "memos/parent", content: "Parent context" });
+ const onEdit = vi.fn();
+ const onCommentsOpen = vi.fn();
+ const onCommentCreate = vi.fn();
const onShareImageOpen = vi.fn();
- render(
-
-
- ,
+ renderSidebar(
+ ,
);
- expect(screen.getByText("common.actions")).toBeInTheDocument();
- expect(screen.getByText("memo.outline")).toBeInTheDocument();
- expect(screen.getByText("common.referenced-by")).toBeInTheDocument();
- expect(screen.getByRole("link", { name: "Incoming backlink" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "memo.back-to:common.explore" })).toHaveAttribute("href", "/explore?filter=tagSearch%3Awork");
+ expect(screen.getByText("memo.on-this-memo")).toBeInTheDocument();
+ expect(screen.getByTestId("outline")).toHaveTextContent("2");
+ expect(screen.getByRole("link", { name: /memo.comment.self/ })).toHaveTextContent("3");
+ expect(screen.getByRole("link", { name: /memo.comment.self/ })).toHaveAttribute("href", "#memo-comments");
+ expect(screen.getByText("memo.connections")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "memo.parent-memo: Parent context" })).toHaveAttribute("href", "/memos/parent");
+ expect(screen.getByRole("link", { name: "common.referenced-by: Incoming backlink" })).toHaveAttribute("href", "/memos/incoming");
expect(screen.queryByText("Outgoing reference")).not.toBeInTheDocument();
+ expect(screen.getByText("common.actions")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("link", { name: /memo.comment.self/ }));
+ expect(onCommentsOpen).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole("button", { name: "common.edit" }));
+ expect(onEdit).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole("button", { name: "memo.comment.write-a-comment" }));
+ expect(onCommentCreate).toHaveBeenCalledTimes(1);
+
+ expect(screen.queryByRole("button", { name: "common.pin" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.unpin" })).not.toBeInTheDocument();
expect(screen.queryByText("common.visibility")).not.toBeInTheDocument();
expect(screen.queryByText("common.created-at")).not.toBeInTheDocument();
expect(screen.queryByText("common.location")).not.toBeInTheDocument();
expect(screen.queryByText("common.attachments")).not.toBeInTheDocument();
expect(screen.queryByText("release-notes.pdf")).not.toBeInTheDocument();
expect(screen.queryByText("release/0.30")).not.toBeInTheDocument();
- expect(screen.getByTestId("outline")).toHaveTextContent("2");
-
- fireEvent.click(screen.getByRole("button", { name: "common.pin" }));
- await waitFor(() =>
- expect(updateMemo).toHaveBeenCalledWith({ update: { name: "memos/detail", pinned: true }, updateMask: ["pinned"] }),
- );
fireEvent.click(screen.getByRole("button", { name: "common.share" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "memo.copy-link" }));
@@ -105,51 +136,134 @@ describe("MemoDetailSidebar", () => {
expect(screen.getByTestId("share-panel")).toBeInTheDocument();
});
- it("keeps a readonly simple memo useful with only the share action", () => {
+ it("lets an authenticated visitor comment while reserving edit for the author", () => {
+ currentUserState.value = { name: "users/bob" };
const memo = create(MemoSchema, {
- name: "memos/readonly",
+ name: "memos/public",
creator: "users/alice",
state: State.NORMAL,
visibility: Visibility.PUBLIC,
- content: "# Overview\n\nBody",
- relations: [
- create(MemoRelationSchema, {
- type: MemoRelation_Type.REFERENCE,
- memo: create(MemoRelation_MemoSchema, { name: "memos/incoming", snippet: "Private backlink" }),
- relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/readonly" }),
- }),
- ],
+ content: "Body",
+ relations: [createIncomingReference("memos/public")],
});
- render(
-
-
- ,
+ renderSidebar(
+ ,
);
- expect(screen.getByRole("button", { name: "common.share" })).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "common.pin" })).not.toBeInTheDocument();
- expect(screen.queryByText("memo.outline")).not.toBeInTheDocument();
- expect(screen.queryByText("common.referenced-by")).not.toBeInTheDocument();
- expect(screen.queryByText("Private backlink")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.edit" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "memo.comment.write-a-comment" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "common.referenced-by: Incoming backlink" })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("link", { name: "memo.go-to:common.explore" }));
+ expect(clearSelectedSpace).toHaveBeenCalledOnce();
});
- it("keeps the outline available for readonly memos with multiple headings", () => {
+ it("keeps a simple memo useful without rendering empty navigation or connections", () => {
const memo = create(MemoSchema, {
- name: "memos/readonly-outline",
+ name: "memos/simple",
+ creator: "users/alice",
+ state: State.NORMAL,
+ content: "Body",
+ });
+
+ renderSidebar(
+ ,
+ );
+
+ expect(screen.getByRole("link", { name: "memo.go-to:common.home" })).toHaveAttribute("href", "/");
+ expect(screen.queryByText("memo.on-this-memo")).not.toBeInTheDocument();
+ expect(screen.queryByText("memo.connections")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.edit" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "memo.comment.write-a-comment" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.share" })).toBeInTheDocument();
+ });
+
+ it.each([
+ ["an archived memo", State.ARCHIVED, Visibility.PUBLIC],
+ ["a Space memo", State.NORMAL, Visibility.SPACE],
+ ])("does not offer share-link management for %s", async (_label, state, visibility) => {
+ const memo = create(MemoSchema, {
+ name: "memos/restricted-share",
+ creator: "users/alice",
+ state,
+ visibility,
+ content: "Body",
+ });
+
+ renderSidebar();
+ fireEvent.click(screen.getByRole("button", { name: "common.share" }));
+
+ expect(await screen.findByRole("menuitem", { name: "memo.copy-link" })).toBeInTheDocument();
+ expect(screen.queryByRole("menuitem", { name: "memo.share.open-panel" })).not.toBeInTheDocument();
+ });
+
+ it("keeps archived memo navigation and comments readable without offering write actions", () => {
+ const memo = create(MemoSchema, {
+ name: "memos/archived",
+ creator: "users/alice",
+ state: State.ARCHIVED,
+ content: "Archived body",
+ });
+
+ renderSidebar(
+ ,
+ );
+
+ expect(screen.getByRole("link", { name: "memo.go-to:common.archived" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /memo.comment.self/ })).toHaveTextContent("2");
+ expect(screen.queryByRole("button", { name: "common.edit" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "memo.comment.write-a-comment" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.share" })).toBeInTheDocument();
+ });
+
+ it("keeps shared memos private to their token context and copies the usable share URL", async () => {
+ const memo = create(MemoSchema, {
+ name: "memos/shared",
creator: "users/alice",
state: State.NORMAL,
visibility: Visibility.PUBLIC,
content: "# Overview\n\nBody\n\n## Details\n\nMore",
+ parent: "memos/parent",
+ relations: [createIncomingReference("memos/shared", "memos/private", "Private backlink")],
});
+ const parentMemo = create(MemoSchema, { name: "memos/parent", content: "Private parent" });
- render(
-
-
- ,
+ renderSidebar(
+ ,
+ "/memos/shares/share-token",
);
- expect(screen.getByText("memo.outline")).toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: /memo.back-to/ })).not.toBeInTheDocument();
+ expect(screen.getByText("memo.on-this-memo")).toBeInTheDocument();
expect(screen.getByTestId("outline")).toHaveTextContent("2");
+ expect(screen.queryByRole("link", { name: /memo.comment.self/ })).not.toBeInTheDocument();
+ expect(screen.queryByText("memo.connections")).not.toBeInTheDocument();
+ expect(screen.queryByText("Private parent")).not.toBeInTheDocument();
+ expect(screen.queryByText("Private backlink")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.edit" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "memo.comment.write-a-comment" })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "common.share" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "memo.copy-link" }));
+ expect(copyToClipboard).toHaveBeenCalledWith("https://memos.example/memos/shares/share-token");
+ expect(screen.queryByRole("menuitem", { name: "memo.share.open-panel" })).not.toBeInTheDocument();
});
});
diff --git a/web/tests/memo-outline-headings.test.tsx b/web/tests/memo-outline-headings.test.tsx
index 388d9cf0..c128c91f 100644
--- a/web/tests/memo-outline-headings.test.tsx
+++ b/web/tests/memo-outline-headings.test.tsx
@@ -3,6 +3,7 @@ import { MemoryRouter } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
import { extractHeadings } from "@/components/MemoContent/pipeline";
+import { findMemoAnchorTarget } from "@/utils/markdown-manipulation";
vi.mock("@/components/MemoContent/math", () => ({
hasMathSyntax: vi.fn(() => false),
@@ -89,6 +90,23 @@ describe("outline slugs against rendered heading ids", () => {
expect(container.querySelector("h1")).toHaveAttribute("id", "footnote-label-1");
});
+ it("reserves current and legacy comment-section anchors from memo headings", () => {
+ const headings = expectOutlineLandsOnRenderedHeadings(
+ '# Comments\n\n## Memo comments\n\n',
+ );
+
+ expect(headings.map((heading) => heading.slug)).toEqual(["comments-1", "memo-comments-1", "memo-comments-2"]);
+ });
+
+ it("keeps a historical raw comment-anchor id resolvable after reserving it", () => {
+ const container = renderMemo('');
+ const heading = container.querySelector("h2");
+
+ expect(heading).toHaveAttribute("id", "memo-comments-1");
+ expect(heading).toHaveAttribute("data-original-heading-id", "memo-comments");
+ expect(findMemoAnchorTarget(container, "memos/1", "memo-comments")).toBe(heading);
+ });
+
it("returns nothing for content that cannot contain a heading", () => {
// The cheap pre-check must not mistake a tag or a shebang for a heading, and must still
// catch an indented ATX heading.
diff --git a/web/tests/use-memo-save.test.tsx b/web/tests/use-memo-save.test.tsx
index c126b618..283aa269 100644
--- a/web/tests/use-memo-save.test.tsx
+++ b/web/tests/use-memo-save.test.tsx
@@ -58,4 +58,17 @@ describe("useMemoSave", () => {
expect(discardDraft).toHaveBeenCalledOnce();
expect(mocks.markNewMemo).toHaveBeenCalledWith("memos/new");
});
+
+ it("refreshes the parent memo total after creating a comment", async () => {
+ mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/comment" });
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
+ const wrapper = ({ children }: PropsWithChildren) => {children};
+ const { result } = renderHook(() => useMemoSave({ parentMemoName: "memos/parent", discardDraft: vi.fn() }), { wrapper });
+
+ await act(async () => result.current());
+
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "comments", "memos/parent"] });
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "detail", "memos/parent"] });
+ });
});