feat(sidebar): redesign memo detail navigation (#6261)

This commit is contained in:
Johnny 2026-09-02 20:20:22 +08:00 committed by GitHub
parent 245e5e3a3e
commit d79b2e1dc3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 947 additions and 253 deletions

View file

@ -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 (
<MemoDetailSidebar
memo={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}>
<SheetContent
side={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"

View file

@ -146,6 +146,7 @@ export const useMemoActionHandlers = ({ memo, parentScope, onEdit, setDeleteDial
toast.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") {

View file

@ -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" />
)}
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>
)}
{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 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>
</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>
)}
{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>
);
};
);
},
);
MemoCommentSection.displayName = "MemoCommentSection";
export default MemoCommentSection;

View file

@ -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, 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 (
<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>
<DropdownMenuTrigger
aria-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>
);

View file

@ -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);

View file

@ -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);

View file

@ -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"
>

View file

@ -1,2 +1,2 @@
export { default, default as MemoView } from "./MemoView";
export type { MemoViewProps } from "./types";
export type { MemoViewHandle, MemoViewProps } from "./types";

View file

@ -15,6 +15,10 @@ export interface MemoViewProps {
onShareImageDialogOpenChange?: (open: boolean) => void;
}
export interface MemoViewHandle {
openEditor: () => void;
}
export interface MemoHeaderProps {
showCreator?: boolean;
showVisibility?: boolean;

View file

@ -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>;

View file

@ -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;

View file

@ -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": {

View file

@ -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": "显示较少",

View file

@ -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}>
<MemoSidebarRegistration
memo={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">
<Link
className="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}

View file

@ -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 blocks
function 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 ?? "");

View file

@ -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;
}
});
};

View file

@ -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");
});
});

View file

@ -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"] });
});
});

View file

@ -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);
});
});

View file

@ -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")],
});
render(
<MemoryRouter>
<MemoDetailSidebar memo={memo} forceReadonly />
</MemoryRouter>,
renderSidebar(
<MemoDetailSidebar memo={memo} parentPage="/explore" parentScope="all" commentCount={1} onEdit={vi.fn()} onCommentCreate={vi.fn()} />,
);
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(
<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();
});
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/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();
});
});

View file

@ -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.

View file

@ -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"] });
});
});