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
feat(sidebar): redesign memo detail navigation (#6261)
Johnnyd79b2e1dc34e
diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsxindex c44a01103..7bea81092 100644--- a/web/src/components/AppSidebar/AppSidebar.tsx+++ b/web/src/components/AppSidebar/AppSidebar.tsx@@ -274,15 +274,22 @@ const SettingsSidebarContent = () => {};const MemoDetailSidebarContent = () => {- const { memoDetail } = useAppSidebar();+ const { memoDetail, closeMobileThen } = useAppSidebar();if (!memoDetail) return null;+ const runAndClose = (action: (() => void) | undefined) => (action ? () => closeMobileThen(action) : undefined);return (<MemoDetailSidebarmemo={memoDetail.memo}+ parentMemo={memoDetail.parentMemo}parentPage={memoDetail.from}parentScope={memoDetail.fromScope}+ hasExplicitOrigin={memoDetail.hasExplicitOrigin}+ commentCount={memoDetail.commentCount}forceReadonly={memoDetail.readonly}- onShareImageOpen={memoDetail.onShareImageOpen}+ onEdit={runAndClose(memoDetail.onEdit)}+ onCommentsOpen={runAndClose(memoDetail.onCommentsOpen)}+ onCommentCreate={runAndClose(memoDetail.onCommentCreate)}+ onShareImageOpen={runAndClose(memoDetail.onShareImageOpen)}className="pb-2"/>);@@ -620,9 +627,9 @@ export const MobileAppHeader = () => {export const MobileAppSidebar = () => {const direction = useDirection();- const { mobileOpen, setMobileOpen } = useAppSidebar();+ const { mobileOpen, setMobileOpen, completeMobileClose } = useAppSidebar();return (- <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>+ <Sheet open={mobileOpen} onOpenChange={setMobileOpen} onOpenChangeComplete={completeMobileClose}><SheetContentside={direction === "rtl" ? "right" : "left"}className="w-[min(18rem,calc(100vw-2rem))] gap-0 border-border p-0 shadow-2xl [&>[data-slot=sheet-close]]:sr-only"diff --git a/web/src/components/MemoActionMenu/hooks.ts b/web/src/components/MemoActionMenu/hooks.tsindex 8652ca678..599f31174 100644--- a/web/src/components/MemoActionMenu/hooks.ts+++ b/web/src/components/MemoActionMenu/hooks.ts@@ -146,6 +146,7 @@ export const useMemoActionHandlers = ({ memo, parentScope, onEdit, setDeleteDialtoast.success(t("message.deleted-successfully"));if (memo.parent) {queryClient.invalidateQueries({ queryKey: memoKeys.comments(memo.parent) });+ queryClient.invalidateQueries({ queryKey: memoKeys.detail(memo.parent) });}if (isInMemoDetailPage) {if (parentScope === "all") {diff --git a/web/src/components/MemoCommentSection.tsx b/web/src/components/MemoCommentSection.tsxindex ff234875e..6bfe6842c 100644--- a/web/src/components/MemoCommentSection.tsx+++ b/web/src/components/MemoCommentSection.tsx@@ -1,18 +1,21 @@import { LoaderCircleIcon, MessageCircleIcon } from "lucide-react";-import { type ComponentType, useCallback, useState } from "react";+import { type ComponentType, forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";import { loadMemoEditor } from "@/components/MemoEditor/loader";import type { MemoEditorProps } from "@/components/MemoEditor/types";import MemoView from "@/components/MemoView";import type { MemoOriginScope } from "@/components/MemoView/navigation";import { Button } from "@/components/ui/button";import useCurrentUser from "@/hooks/useCurrentUser";+import { MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";import { extractMemoIdFromName } from "@/lib/resource-names";+import { State } from "@/types/proto/api/v1/common_pb";import type { Memo } from "@/types/proto/api/v1/memo_service_pb";import { useTranslate } from "@/utils/i18n";interface Props {memo: Memo;comments: Memo[];+ commentCount?: number;parentPage?: string;parentScope?: MemoOriginScope;hasMoreComments?: boolean;@@ -20,123 +23,154 @@ interface Props {onLoadMoreComments?: () => void;}-const MemoCommentSection = ({- memo,- comments,- parentPage,- parentScope,- hasMoreComments,- isFetchingMoreComments,- onLoadMoreComments,-}: Props) => {- const t = useTranslate();- const currentUser = useCurrentUser();- const [showEditor, setShowEditor] = useState(false);- const [isEditorLoading, setIsEditorLoading] = useState(false);- const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();+export interface MemoCommentSectionHandle {+ openEditor: () => Promise<void>;+ scrollIntoView: () => void;+}- const showCreateButton = currentUser && !showEditor;+const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(+ (+ {+ memo,+ comments,+ commentCount = comments.length,+ parentPage,+ parentScope,+ hasMoreComments,+ isFetchingMoreComments,+ onLoadMoreComments,+ },+ ref,+ ) => {+ const t = useTranslate();+ const currentUser = useCurrentUser();+ const [showEditor, setShowEditor] = useState(false);+ const [isEditorLoading, setIsEditorLoading] = useState(false);+ const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();+ const sectionRef = useRef<HTMLDivElement>(null);- const handleCommentCreated = async (_memoCommentName: string) => {- setShowEditor(false);- };+ const canCreateComment = !!currentUser && memo.state === State.NORMAL;+ const showCreateButton = canCreateComment && !showEditor;- const preloadEditor = useCallback(() => {- void loadMemoEditor().catch(() => undefined);- }, []);+ const handleCommentCreated = async (_memoCommentName: string) => {+ setShowEditor(false);+ };- const openEditor = useCallback(async () => {- if (isEditorLoading) {- return;- }+ const preloadEditor = useCallback(() => {+ void loadMemoEditor().catch(() => undefined);+ }, []);- setIsEditorLoading(true);- try {- const { default: MemoEditor } = await loadMemoEditor();- setEditorComponent(() => MemoEditor);- setShowEditor(true);- } catch {- // Chunk failures are handled by loadWithReload; keep the current UI mounted.- } finally {- setIsEditorLoading(false);- }- }, [isEditorLoading]);+ const focusMountedEditor = useCallback(() => {+ const codeMirrorContent = sectionRef.current?.querySelector<HTMLElement>('.cm-content[contenteditable="true"]');+ const fallbackInput = sectionRef.current?.querySelector<HTMLElement>("textarea, input");+ (codeMirrorContent ?? fallbackInput)?.focus();+ }, []);- return (- <div className="pt-8 pb-16 w-full">- <h2 id="comments" className="sr-only">- {t("memo.comment.self")}- </h2>- <div className="relative mx-auto grow w-full min-h-full flex flex-col justify-start items-start gap-y-1">- {comments.length === 0 ? (- showCreateButton && (- <div className="w-full flex flex-row justify-center items-center py-6">- <Button- variant="ghost"- onPointerEnter={preloadEditor}- onFocus={preloadEditor}- onClick={openEditor}- disabled={isEditorLoading}- >- <span className="text-muted-foreground">{t("memo.comment.write-a-comment")}</span>- {isEditorLoading ? (- <LoaderCircleIcon className="ml-2 h-5 w-5 animate-spin text-muted-foreground" />- ) : (- <MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />- )}- </Button>+ const openEditor = useCallback(async () => {+ if (!canCreateComment || isEditorLoading) {+ return;+ }+ if (showEditor && EditorComponent) {+ focusMountedEditor();+ return;+ }++ setIsEditorLoading(true);+ try {+ const { default: MemoEditor } = await loadMemoEditor();+ setEditorComponent(() => MemoEditor);+ setShowEditor(true);+ } catch {+ // Chunk failures are handled by loadWithReload; keep the current UI mounted.+ } finally {+ setIsEditorLoading(false);+ }+ }, [EditorComponent, canCreateComment, focusMountedEditor, isEditorLoading, showEditor]);++ const scrollIntoView = useCallback(() => {+ sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, []);++ useImperativeHandle(ref, () => ({ openEditor, scrollIntoView }), [openEditor, scrollIntoView]);++ return (+ <div ref={sectionRef} className="pt-8 pb-16 w-full" data-memo-comments-section>+ <h2 id={MEMO_COMMENTS_ANCHOR_ID} className="sr-only">+ {t("memo.comment.self")}+ </h2>+ <div className="relative mx-auto grow w-full min-h-full flex flex-col justify-start items-start gap-y-1">+ {comments.length === 0 ? (+ showCreateButton && (+ <div className="w-full flex flex-row justify-center items-center py-6">+ <Button+ variant="ghost"+ onPointerEnter={preloadEditor}+ onFocus={preloadEditor}+ onClick={openEditor}+ disabled={isEditorLoading}+ >+ <span className="text-muted-foreground">{t("memo.comment.write-a-comment")}</span>+ {isEditorLoading ? (+ <LoaderCircleIcon className="ml-2 h-5 w-5 animate-spin text-muted-foreground" />+ ) : (+ <MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />+ )}+ </Button>+ </div>+ )+ ) : (+ <div className="w-full flex flex-row justify-between items-center h-8 pl-3 mb-2">+ <div className="flex flex-row justify-start items-center">+ <MessageCircleIcon className="w-5 h-auto text-muted-foreground mr-1" />+ <span className="text-muted-foreground text-sm">{t("memo.comment.self")}</span>+ <span className="text-muted-foreground text-sm ml-1">({commentCount})</span>+ </div>+ {showCreateButton && (+ <Button+ variant="ghost"+ className="text-muted-foreground"+ onPointerEnter={preloadEditor}+ onFocus={preloadEditor}+ onClick={openEditor}+ disabled={isEditorLoading}+ >+ {isEditorLoading && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}+ {t("memo.comment.write-a-comment")}+ </Button>+ )}+ </div>+ )}+ {showEditor && EditorComponent && (+ <div className="w-full mb-2">+ <EditorComponent+ cacheKey={`${memo.name}-comment`}+ placeholder={t("editor.add-your-comment-here")}+ parentMemoName={memo.name}+ autoFocus+ onConfirm={handleCommentCreated}+ onCancel={() => setShowEditor(false)}+ /></div>- )- ) : (- <div className="w-full flex flex-row justify-between items-center h-8 pl-3 mb-2">- <div className="flex flex-row justify-start items-center">- <MessageCircleIcon className="w-5 h-auto text-muted-foreground mr-1" />- <span className="text-muted-foreground text-sm">{t("memo.comment.self")}</span>- <span className="text-muted-foreground text-sm ml-1">({comments.length})</span>+ )}+ {comments.map((comment) => (+ <div className="w-full" key={comment.name} id={extractMemoIdFromName(comment.name)}>+ <MemoView memo={comment} parentPage={parentPage} parentScope={parentScope} showCreator showSpace compact /></div>- {showCreateButton && (- <Button- variant="ghost"- className="text-muted-foreground"- onPointerEnter={preloadEditor}- onFocus={preloadEditor}- onClick={openEditor}- disabled={isEditorLoading}- >- {isEditorLoading && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}- {t("memo.comment.write-a-comment")}+ ))}+ {hasMoreComments && (+ <div className="w-full mt-4 flex justify-center">+ <Button variant="outline" className="rounded-full px-4" onClick={onLoadMoreComments} disabled={isFetchingMoreComments}>+ {isFetchingMoreComments && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}+ {t(isFetchingMoreComments ? "resource.fetching-data" : "memo.load-more")}</Button>- )}- </div>- )}- {showEditor && EditorComponent && (- <div className="w-full mb-2">- <EditorComponent- cacheKey={`${memo.name}-comment`}- placeholder={t("editor.add-your-comment-here")}- parentMemoName={memo.name}- autoFocus- onConfirm={handleCommentCreated}- onCancel={() => setShowEditor(false)}- />- </div>- )}- {comments.map((comment) => (- <div className="w-full" key={comment.name} id={extractMemoIdFromName(comment.name)}>- <MemoView memo={comment} parentPage={parentPage} parentScope={parentScope} showCreator showSpace compact />- </div>- ))}- {hasMoreComments && (- <div className="w-full mt-4 flex justify-center">- <Button variant="outline" className="rounded-full px-4" onClick={onLoadMoreComments} disabled={isFetchingMoreComments}>- {isFetchingMoreComments && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}- {t(isFetchingMoreComments ? "resource.fetching-data" : "memo.load-more")}- </Button>- </div>- )}+ </div>+ )}+ </div></div>- </div>- );-};+ );+ },+);++MemoCommentSection.displayName = "MemoCommentSection";export default MemoCommentSection;diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsxindex 31e260339..b0fed7195 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<HTMLSpanElement>(snippet);const relatedMemo = getRelationMemo(relation, "referenced");@@ -50,6 +72,7 @@ const BacklinkRow = ({return (<Link+ aria-label={`${referencedByLabel}: ${snippet}`}className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}to={`/${relatedMemo.name}`}state={parentPage && parentScope ? createMemoNavigationState(parentPage, parentScope) : undefined}@@ -64,16 +87,36 @@ const BacklinkRow = ({);};-const MemoDetailSidebar = ({ memo, parentPage, parentScope, className, onShareImageOpen, forceReadonly = false }: Props) => {+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, onShareImif (!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 (<div className={cn("relative w-full select-none", SIDEBAR_SECTION_STACK_CLASSES, className)}>+ {!forceReadonly && parentPage && (+ <SidebarSection+ ariaLabel={hasExplicitOrigin ? t("memo.back-to", { source: originLabel }) : t("memo.go-to", { source: originLabel })}+ >+ <Link+ className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}+ to={parentPage}+ onClick={() => {+ if (parentScope === "all" && isMemoCollectionOrigin(parentPage)) {+ clearSelectedSpace();+ }+ }}+ viewTransition+ >+ <SidebarRowIconSlot icon={ArrowLeftIcon} />+ <span className="min-w-0 flex-1 truncate text-start">+ {hasExplicitOrigin ? t("memo.back-to", { source: originLabel }) : t("memo.go-to", { source: originLabel })}+ </span>+ </Link>+ </SidebarSection>+ )}++ {showOnThisMemo && (+ <SidebarSection label={t("memo.on-this-memo")}>+ {headings.length > 1 && <MemoOutline headings={headings} memoName={memo.name} />}+ {showComments && (+ <a+ className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}+ href={`#${MEMO_COMMENTS_ANCHOR_ID}`}+ onClick={(event) => {+ if (!onCommentsOpen) return;+ event.preventDefault();+ onCommentsOpen();+ }}+ >+ <SidebarRowIconSlot icon={MessageCircleIcon} />+ <span className="min-w-0 flex-1 truncate text-start">{t("memo.comment.self")}</span>+ <span className={SIDEBAR_ROW_COUNT_RAIL_CLASSES}>{commentCount}</span>+ </a>+ )}+ </SidebarSection>+ )}++ {showConnections && (+ <SidebarSection label={t("memo.connections")}>+ {parentMemo && (+ <Link+ aria-label={`${t("memo.parent-memo")}: ${parentSnippet}`}+ className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}+ to={`/${parentMemo.name}`}+ state={parentPage && parentScope ? createMemoNavigationState(parentPage, parentScope) : undefined}+ title={parentSnippet}+ viewTransition+ >+ <SidebarRowIconSlot icon={CornerUpLeftIcon} />+ <span className="min-w-0 flex-1 truncate text-start">{parentSnippet}</span>+ </Link>+ )}+ {referenced.map((relation) => {+ const relatedMemo = getRelationMemo(relation, "referenced");+ return (+ <BacklinkRow+ key={`referenced-${relatedMemo?.name}`}+ relation={relation}+ snippet={backlinkSnippet(relation)}+ parentPage={parentPage}+ parentScope={parentScope}+ referencedByLabel={t("common.referenced-by")}+ />+ );+ })}+ </SidebarSection>+ )}+<SidebarSection label={t("common.actions")}>- {canPin && (- <SidebarRow- icon={memo.pinned ? BookmarkCheckIcon : BookmarkIcon}- label={memo.pinned ? t("common.unpin") : t("common.pin")}- onClick={handleTogglePin}- />- )}+ {canEdit && <SidebarRow icon={Edit3Icon} label={t("common.edit")} onClick={onEdit} />}+ {canComment && <SidebarRow icon={MessageSquarePlusIcon} label={t("memo.comment.write-a-comment")} onClick={onCommentCreate} />}<DropdownMenu><DropdownMenuTriggeraria-label={t("common.share")}@@ -150,29 +286,6 @@ const MemoDetailSidebar = ({ memo, parentPage, parentScope, className, onShareIm</DropdownMenu></SidebarSection>- {headings.length > 1 && (- <SidebarSection label={t("memo.outline")}>- <MemoOutline headings={headings} memoName={memo.name} />- </SidebarSection>- )}-- {!forceReadonly && referenced.length > 0 && (- <SidebarSection label={t("common.referenced-by")}>- {referenced.map((relation) => {- const relatedMemo = getRelationMemo(relation, "referenced");- return (- <BacklinkRow- key={`referenced-${relatedMemo?.name}`}- relation={relation}- snippet={backlinkSnippet(relation)}- parentPage={parentPage}- parentScope={parentScope}- />- );- })}- </SidebarSection>- )}-{sharePanelOpen && <MemoSharePanel memoName={memo.name} open={sharePanelOpen} onClose={() => setSharePanelOpen(false)} />}</div>);diff --git a/web/src/components/MemoEditor/hooks/useMemoSave.ts b/web/src/components/MemoEditor/hooks/useMemoSave.tsindex 12c8a2367..05b22a716 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.tsxindex 54129e19b..04e7d461e 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<MemoViewProps> = (props: MemoViewProps) => {+const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {const {memo: memoData,className,@@ -57,17 +68,30 @@ const MemoView: React.FC<MemoViewProps> = (props: MemoViewProps) => {const toggleBlurVisibility = useCallback(() => setShowBlurredContent((prev) => !prev), []);const { previewState, openPreview, setPreviewOpen } = useImagePreview();+ const editorHostRef = useRef<HTMLDivElement>(null);++ const focusMountedEditor = useCallback(() => {+ const codeMirrorContent = editorHostRef.current?.querySelector<HTMLElement>('.cm-content[contenteditable="true"]');+ const fallbackInput = editorHostRef.current?.querySelector<HTMLElement>("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<MemoViewProps> = (props: MemoViewProps) => {return (<MemoViewContext.Provider value={contextValue}>{showEditor && EditorComponent ? (- <EditorComponent- autoFocus- className="mb-2"- cacheKey={`inline-memo-editor-${memoData.name}`}- memo={memoData}- parentMemoName={memoData.parent || undefined}- onConfirm={closeEditor}- onCancel={closeEditor}- />+ <div ref={editorHostRef} className="w-full">+ <EditorComponent+ autoFocus+ className="mb-2"+ cacheKey={`inline-memo-editor-${memoData.name}`}+ memo={memoData}+ parentMemoName={memoData.parent || undefined}+ onConfirm={closeEditor}+ onCancel={closeEditor}+ />+ </div>) : (memoDisplay)}</MemoViewContext.Provider>);-};+});++MemoView.displayName = "MemoView";export default memo(MemoView);diff --git a/web/src/components/MemoView/components/MemoCommentListView.tsx b/web/src/components/MemoView/components/MemoCommentListView.tsxindex cd44e4e24..5b06b0b62 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 = () => {<div className="flex items-center justify-between mb-1"><span className="text-xs text-muted-foreground">Comments{commentAmount > 1 ? ` (${commentAmount})` : ""}</span><Link- to={`/${memo.name}#comments`}+ to={`/${memo.name}#${MEMO_COMMENTS_ANCHOR_ID}`}state={createMemoNavigationState(parentPage, parentScope)}className="flex items-center gap-0.5 text-xs text-muted-foreground/80 hover:underline underline-offset-2 transition-colors">diff --git a/web/src/components/MemoView/index.ts b/web/src/components/MemoView/index.tsindex 5c3f6e909..8dbbf0f27 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.tsindex cd9d52ecc..b2f42a569 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.tsxindex 80fca6f94..9cb25f3c6 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<InboxFilter>("all");const [memoDetail, setMemoDetailState] = useState<MemoDetailSidebarDescriptor>();const [mobileOpen, setMobileOpen] = useState(false);+ const pendingMobileCloseActionRef = useRef<(() => void) | undefined>(undefined);+ const scheduledMobileCloseActionFrameRef = useRef<number | undefined>(undefined);const [quickFindOpen, setQuickFindOpen] = useState(false);const [memoScope, setMemoScope] = useState<PrimaryMemoScope>("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 <AppSidebarContext.Provider value={value}>{children}</AppSidebarContext.Provider>;diff --git a/web/src/lib/memo-comments.ts b/web/src/lib/memo-comments.tsnew file mode 100644index 000000000..96ed01d92--- /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.jsonindex 56ed6fdc8..b04317101 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.jsonindex 08d78a00a..208628197 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.tsxindex 0e949ee9b..630e4db07 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<MemoViewHandle>(null);+ const commentSectionRef = useRef<MemoCommentSectionHandle>(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 = () => {<MentionResolutionProvider contents={mentionResolutionContents} userNames={userResolutionNames}><MemoSidebarRegistrationmemo={displayMemo}+ parentMemo={parentMemo}from={parentPage}fromScope={parentScope}+ hasExplicitOrigin={hasExplicitOrigin}+ commentCount={isShareMode ? undefined : commentCount}readonly={isShareMode}+ onEdit={handleEdit}+ onCommentsOpen={handleCommentsOpen}+ onCommentCreate={handleCommentCreate}onShareImageOpen={handleShareImageOpen}/><div className="w-full max-w-2xl px-4 sm:px-6"><div className="w-full">{!isShareMode && parentMemo && (- <div className="w-auto inline-block mb-2">+ <div className="w-auto inline-block mb-2 md:hidden"><LinkclassName="px-3 py-1 border border-border rounded-lg max-w-xs w-auto text-sm flex flex-row justify-start items-center flex-nowrap text-muted-foreground hover:shadow hover:opacity-80"to={`/${parentMemo.name}`}@@ -148,6 +222,7 @@ const MemoDetail = () => {</div>)}<MemoView+ ref={memoViewRef}key={displayMemo.name}memo={displayMemo}compact={false}@@ -162,8 +237,10 @@ const MemoDetail = () => {/>{!isShareMode && (<MemoCommentSection+ ref={commentSectionRef}memo={displayMemo}comments={comments}+ commentCount={commentCount}parentPage={parentPage}parentScope={parentScope}hasMoreComments={hasNextComments}diff --git a/web/src/utils/markdown-manipulation.ts b/web/src/utils/markdown-manipulation.tsindex d9cbd19b9..60027501e 100644--- a/web/src/utils/markdown-manipulation.ts+++ b/web/src/utils/markdown-manipulation.ts@@ -12,6 +12,8 @@ interface TaskInfo {checked: boolean;}+export const ORIGINAL_HEADING_ID_ATTRIBUTE = "data-original-heading-id";+// Extract all task list items from markdown using AST parsing// This correctly ignores task-like patterns inside code blocksfunction extractTasksFromAst(markdown: string): TaskInfo[] {@@ -129,6 +131,12 @@ export function findAnchorTarget(root: ParentNode, fragment: string): Element |const direct = root.querySelector(`#${CSS.escape(fragment)}`);if (direct) return direct;+ // Reserved page anchors can force an author-supplied heading id to be suffixed. Keep+ // historical links working by resolving the original id recorded by the heading plugin.+ for (const heading of root.querySelectorAll(`[${ORIGINAL_HEADING_ID_ATTRIBUTE}]`)) {+ if (heading.getAttribute(ORIGINAL_HEADING_ID_ATTRIBUTE) === fragment) return heading;+ }+const slugCounts = new Map<string, number>();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.tsindex 69103569a..5cb4bf31a 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<string>();+ const existingIds = new Set<string>(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<string>();+ const claimedExistingIds = new Set<string>(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.tsxindex 6904816c1..ea43ae409 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 (<div><output data-testid="attachment-section">{attachmentSection}</output><output data-testid="inbox-filter">{inboxFilter}</output>+ <output data-testid="mobile-open">{String(mobileOpen)}</output>+ <output data-testid="action-count">{actionCount}</output><button type="button" onClick={() => setAttachmentSection("media")}>Select media</button>@@ -19,11 +32,24 @@ const Harness = () => {<button type="button" onClick={() => navigate("/inbox")}>Change route</button>+ <button type="button" onClick={() => setMobileOpen(true)}>+ Open mobile sidebar+ </button>+ <button type="button" onClick={() => closeMobileThen(() => setActionCount((count) => count + 1))}>+ Run after close+ </button>+ <button type="button" onClick={() => completeMobileClose(false)}>+ Finish mobile close+ </button></div>);};describe("AppSidebarProvider", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });+it("keeps page controls local and resets them after a route change", () => {render(<MemoryRouter initialEntries={["/attachments"]}>@@ -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(+ <MemoryRouter initialEntries={["/memos/detail"]}>+ <AppSidebarProvider>+ <Harness />+ </AppSidebarProvider>+ </MemoryRouter>,+ );++ 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<number, FrameRequestCallback>();+ 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(+ <MemoryRouter initialEntries={["/memos/detail"]}>+ <AppSidebarProvider>+ <Harness />+ </AppSidebarProvider>+ </MemoryRouter>,+ );++ 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.tsxindex 52e3e1ba5..4a190bd8d 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 }) => (<QueryClientProvider client={queryClient}><MemoryRouter initialEntries={["/memos/1"]}>{children}</MemoryRouter></QueryClientProvider>);- 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.tsxnew file mode 100644index 000000000..b34a6fc8d--- /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: () => <div data-testid="comment-memo" /> }));+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => mocks.currentUser }));+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));++const MockMemoEditor = ({ autoFocus, parentMemoName }: MemoEditorProps) => (+ <div data-testid="comment-editor" data-auto-focus={autoFocus} data-parent-memo-name={parentMemoName}>+ <textarea aria-label="Comment editor" />+ </div>+);++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<MemoCommentSectionHandle>();+ render(<MemoCommentSection ref={ref} memo={memo} comments={[]} />);++ 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<MemoCommentSectionHandle>();++ render(+ <>+ <button type="button">Outside editor</button>+ <MemoCommentSection ref={ref} memo={memo} comments={[]} />+ </>,+ );+ 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(<MemoCommentSection memo={memo} comments={[comment]} commentCount={24} />);++ 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.tsxindex 4623b2c6c..39dbe7209 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: () => <div data-testid="share-panel" /> }));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(<MemoryRouter initialEntries={[route]}>{sidebar}</MemoryRouter>);++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(- <MemoryRouter>- <MemoDetailSidebar memo={memo} onShareImageOpen={onShareImageOpen} />- </MemoryRouter>,+ renderSidebar(+ <MemoDetailSidebar+ memo={memo}+ parentMemo={parentMemo}+ parentPage="/explore?filter=tagSearch%3Awork"+ parentScope="preserve"+ hasExplicitOrigin+ commentCount={3}+ onEdit={onEdit}+ onCommentsOpen={onCommentsOpen}+ onCommentCreate={onCommentCreate}+ onShareImageOpen={onShareImageOpen}+ />,);- 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")],+ });++ renderSidebar(+ <MemoDetailSidebar memo={memo} parentPage="/explore" parentScope="all" commentCount={1} onEdit={vi.fn()} onCommentCreate={vi.fn()} />,+ );++ 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 a simple memo useful without rendering empty navigation or connections", () => {+ const memo = create(MemoSchema, {+ name: "memos/simple",+ creator: "users/alice",+ state: State.NORMAL,+ content: "Body",});- render(- <MemoryRouter>- <MemoDetailSidebar memo={memo} forceReadonly />- </MemoryRouter>,+ renderSidebar(+ <MemoDetailSidebar memo={memo} parentPage="/" parentScope="all" commentCount={0} onEdit={vi.fn()} onCommentCreate={vi.fn()} />,);+ 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();- 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();});- it("keeps the outline available for readonly memos with multiple headings", () => {+ 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(<MemoDetailSidebar memo={memo} parentPage="/" parentScope="all" commentCount={0} />);+ 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/readonly-outline",+ name: "memos/archived",+ creator: "users/alice",+ state: State.ARCHIVED,+ content: "Archived body",+ });++ renderSidebar(+ <MemoDetailSidebar+ memo={memo}+ parentPage="/archived"+ parentScope="preserve"+ commentCount={2}+ onEdit={vi.fn()}+ onCommentCreate={vi.fn()}+ />,+ );++ 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(- <MemoryRouter>- <MemoDetailSidebar memo={memo} forceReadonly />- </MemoryRouter>,+ renderSidebar(+ <MemoDetailSidebar+ memo={memo}+ parentMemo={parentMemo}+ parentPage="/explore"+ parentScope="all"+ hasExplicitOrigin+ commentCount={4}+ forceReadonly+ onEdit={vi.fn()}+ onCommentCreate={vi.fn()}+ />,+ "/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.tsxindex 388d9cf08..c128c91ff 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<h3 id="memo-comments">Explicit comment anchor</h3>',+ );++ 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('<h2 id="memo-comments">A custom section</h2>');+ 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.tsxindex c126b6184..283aa269c 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) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+ 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"] });+ });});