diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsx index c44a0110..7bea8109 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 ( ); @@ -620,9 +627,9 @@ export const MobileAppHeader = () => { export const MobileAppSidebar = () => { const direction = useDirection(); - const { mobileOpen, setMobileOpen } = useAppSidebar(); + const { mobileOpen, setMobileOpen, completeMobileClose } = useAppSidebar(); return ( - + 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>(); +export interface MemoCommentSectionHandle { + openEditor: () => Promise; + scrollIntoView: () => void; +} - const showCreateButton = currentUser && !showEditor; +const MemoCommentSection = forwardRef( + ( + { + 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>(); + const sectionRef = useRef(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('.cm-content[contenteditable="true"]'); + const fallbackInput = sectionRef.current?.querySelector("textarea, input"); + (codeMirrorContent ?? fallbackInput)?.focus(); + }, []); - return ( -
-

- {t("memo.comment.self")} -

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