Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
fix(web): restore sidebar and outline behavior (#6161)
Johnnyf75d49f9b617
diff --git a/web/package.json b/web/package.jsonindex 5d3c1390e..4256b68b4 100644--- a/web/package.json+++ b/web/package.json@@ -47,9 +47,9 @@"mdast-util-from-markdown": "^2.0.3","mdast-util-gfm": "^3.1.0","mermaid": "^11.14.0",+ "micromark-extension-gfm": "^3.0.0","micromark-util-decode-string": "^2.0.1","micromark-util-normalize-identifier": "^2.0.1",- "micromark-extension-gfm": "^3.0.0","react": "^19.2.6","react-dom": "^19.2.6","react-hot-toast": "^2.6.0",@@ -64,8 +64,11 @@"remark-breaks": "^4.0.0","remark-gfm": "^4.0.1","remark-math": "^6.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.1.2","tailwind-merge": "^3.5.0","tailwindcss": "^4.2.4",+ "unified": "^11.0.5","unist-util-visit": "^5.1.0"},"devDependencies": {diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yamlindex e6f048761..7d92b97f6 100644--- a/web/pnpm-lock.yaml+++ b/web/pnpm-lock.yaml@@ -152,12 +152,21 @@ importers:remark-math:specifier: ^6.0.0version: 6.0.0+ remark-parse:+ specifier: ^11.0.0+ version: 11.0.0+ remark-rehype:+ specifier: ^11.1.2+ version: 11.1.2tailwind-merge:specifier: ^3.5.0version: 3.5.0tailwindcss:specifier: ^4.2.4version: 4.2.4+ unified:+ specifier: ^11.0.5+ version: 11.0.5unist-util-visit:specifier: ^5.1.0version: 5.1.0diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsxindex c750b54a5..d6a85a2b1 100644--- a/web/src/components/AppSidebar/AppSidebar.tsx+++ b/web/src/components/AppSidebar/AppSidebar.tsx@@ -249,7 +249,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =><StatisticsView statisticsData={statistics} navigationTarget={filterTarget} onDateSelect={() => setMobileOpen(false)} /></section>{showViews && <ViewsSection />}- <TagsSection tagCount={tags} navigationTarget={filterTarget} onSelect={() => setMobileOpen(false)} />+ <TagsSection tagCount={tags} navigationTarget={filterTarget} scope={statsUserName ?? context} onSelect={() => setMobileOpen(false)} /></div>);};diff --git a/web/src/components/AppSidebar/TagsSection.tsx b/web/src/components/AppSidebar/TagsSection.tsxindex 6a6ab9c2b..4ee450a82 100644--- a/web/src/components/AppSidebar/TagsSection.tsx+++ b/web/src/components/AppSidebar/TagsSection.tsx@@ -15,6 +15,8 @@ interface Props {onSelect?: () => void;/** When set, tag clicks land on this route with the tag filter instead of filtering the current one. */navigationTarget?: string;+ /** Whose tags these are; keeps tree expansion state from bleeding between users and views. */+ scope: string;}const TagPath = forwardRef<HTMLSpanElement, { tag: string }>(({ tag }, ref) => {@@ -58,7 +60,7 @@ const FlatTagRow = ({ tag, amount, active, onClick }: FlatTagRowProps) => {);};-const TagsSection = ({ tagCount, onSelect, navigationTarget }: Props) => {+const TagsSection = ({ tagCount, onSelect, navigationTarget, scope }: Props) => {const t = useTranslate();const navigate = useNavigate();const { filters, setFilters, getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext();@@ -123,7 +125,7 @@ const TagsSection = ({ tagCount, onSelect, navigationTarget }: Props) => {</span></SidebarSectionHeader>{treeMode ? (- <TagTree tagAmounts={tags} activeTag={activeTag} onTagClick={handleTagClick} />+ <TagTree key={scope} tagAmounts={tags} activeTag={activeTag} scope={scope} onTagClick={handleTagClick} />) : (<div className="space-y-0.5">{tags.map(([tag, amount]) => (diff --git a/web/src/components/CreateIdentityProviderDialog.tsx b/web/src/components/CreateIdentityProviderDialog.tsxindex 961441fa9..76187d67e 100644--- a/web/src/components/CreateIdentityProviderDialog.tsx+++ b/web/src/components/CreateIdentityProviderDialog.tsx@@ -241,7 +241,9 @@ function FormField({children: ReactNode;}) {return (- <div className="space-y-2">+ // flex gap, not space-y: fields wrap Select triggers, whose focus guards would otherwise+ // pick up the stack's margin and shift the field while the popup is open (see ui/popup.ts).+ <div className="flex flex-col gap-2"><Label>{label}{required ? <span className="text-destructive">*</span> : null}diff --git a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx b/web/src/components/MemoContent/MemoMarkdownRenderer.tsxindex a1286e21a..18989e70c 100644--- a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx+++ b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx@@ -2,19 +2,10 @@ import type { Element } from "hast";import { type ComponentProps, memo, type ReactNode, Suspense } from "react";import type { Components } from "react-markdown";import ReactMarkdown from "react-markdown";-import rehypeRaw from "rehype-raw";-import rehypeSanitize from "rehype-sanitize";-import remarkBreaks from "remark-breaks";-import remarkGfm from "remark-gfm";+import { buildRehypePlugins, buildRemarkPlugins } from "@/components/MemoContent/pipeline";import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown";import { lazyWithReload } from "@/utils/lazy";-import { rehypeHeadingId } from "@/utils/rehype-plugins/rehype-heading-id";-import { remarkDisableSetext } from "@/utils/remark-plugins/remark-disable-setext";-import { remarkPreserveType } from "@/utils/remark-plugins/remark-preserve-type";-import { remarkSplitMixedTaskLists } from "@/utils/remark-plugins/remark-split-mixed-task-lists";-import { remarkMemoSyntax } from "@/utils/remark-plugins/remark-tag";import { CodeBlock } from "./CodeBlock";-import { SANITIZE_SCHEMA } from "./constants";import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext";import { Mention } from "./Mention";import { AnchorLink, Blockquote, Heading, HorizontalRule, Image, InlineCode, Link, List, ListItem, Paragraph } from "./markdown";@@ -159,16 +150,8 @@ export const MemoMarkdownRendererCore = ({return (<MarkdownRenderContext.Provider value={rootMarkdownRenderContext}><ReactMarkdown- remarkPlugins={[- remarkDisableSetext,- ...mathRemarkPlugins,- remarkGfm,- remarkSplitMixedTaskLists,- remarkMemoSyntax,- remarkBreaks,- remarkPreserveType,- ]}- rehypePlugins={[rehypeRaw, [rehypeSanitize, SANITIZE_SCHEMA], rehypeHeadingId, ...mathRehypePlugins]}+ remarkPlugins={buildRemarkPlugins(mathRemarkPlugins)}+ rehypePlugins={buildRehypePlugins(mathRehypePlugins)}components={markdownComponents}>{content}diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsxindex ea649e98a..9fa7062c9 100644--- a/web/src/components/MemoContent/index.tsx+++ b/web/src/components/MemoContent/index.tsx@@ -16,6 +16,7 @@ const MemoContent = (props: MemoContentProps) => {<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}><divdata-memo-content+ data-memo-name={props.memoName}className={cn("relative w-full max-w-full wrap-break-word text-base leading-6","[&>*:last-child]:mb-0",diff --git a/web/src/components/MemoContent/markdown/AnchorLink.tsx b/web/src/components/MemoContent/markdown/AnchorLink.tsxindex c7c803427..433700de5 100644--- a/web/src/components/MemoContent/markdown/AnchorLink.tsx+++ b/web/src/components/MemoContent/markdown/AnchorLink.tsx@@ -1,6 +1,7 @@import { Link } from "react-router-dom";import { markdownStyles } from "@/lib/markdownStyles";import { cn } from "@/lib/utils";+import { findAnchorTarget } from "@/utils/markdown-manipulation";import type { ReactMarkdownProps } from "./types";interface AnchorLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement>, ReactMarkdownProps {@@ -29,7 +30,7 @@ export const AnchorLink = ({ href, memoName, compact, children, className, node:// Scope the lookup to this memo's own container so duplicate footnote ids elsewhere in a feed// can't steal the scroll.const root = event.currentTarget.closest("[data-memo-content]");- const target = root?.querySelector(`#${CSS.escape(id)}`);+ const target = root && findAnchorTarget(root, id);if (target) {event.preventDefault();target.scrollIntoView({ behavior: "smooth", block: "center" });diff --git a/web/src/components/MemoContent/pipeline.ts b/web/src/components/MemoContent/pipeline.tsnew file mode 100644index 000000000..543b4e106--- /dev/null+++ b/web/src/components/MemoContent/pipeline.ts@@ -0,0 +1,97 @@+import type { Element, Root as HastRoot } from "hast";+import rehypeRaw from "rehype-raw";+import rehypeSanitize from "rehype-sanitize";+import remarkBreaks from "remark-breaks";+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";+import { type PluggableList, unified } from "unified";+import { visit } from "unist-util-visit";+import { getHeadingText, isHeadingElement, rehypeHeadingId } from "@/utils/rehype-plugins/rehype-heading-id";+import { remarkDisableSetext } from "@/utils/remark-plugins/remark-disable-setext";+import { remarkPreserveType } from "@/utils/remark-plugins/remark-preserve-type";+import { remarkSplitMixedTaskLists } from "@/utils/remark-plugins/remark-split-mixed-task-lists";+import { remarkMemoSyntax } from "@/utils/remark-plugins/remark-tag";+import { SANITIZE_SCHEMA } from "./constants";++/**+ * The memo markdown pipeline, in one place. The renderer and the outline both build from these,+ * so anything that changes which headings exist or what they read as — disabling setext,+ * unwrapping raw HTML, sanitizing away elements — applies to both or neither.+ */+export const buildRemarkPlugins = (mathRemarkPlugins: PluggableList = []): PluggableList => [+ remarkDisableSetext,+ ...mathRemarkPlugins,+ remarkGfm,+ remarkSplitMixedTaskLists,+ remarkMemoSyntax,+ remarkBreaks,+ remarkPreserveType,+];++export const buildRehypePlugins = (mathRehypePlugins: PluggableList = []): PluggableList => [+ rehypeRaw,+ [rehypeSanitize, SANITIZE_SCHEMA],+ rehypeHeadingId,+ ...mathRehypePlugins,+];++export interface HeadingItem {+ text: string;+ level: 1 | 2 | 3 | 4;+ slug: string;+}++/**+ * Screen-reader-only headings are generated scaffolding, not memo content — remark-rehype labels+ * the footnote section with one. They are rendered (and keep an anchor) but stay out of the outline.+ */+function isVisuallyHidden(node: Element): boolean {+ const className = node.properties?.className;+ return Array.isArray(className) && className.includes("sr-only");+}++/**+ * Every heading is either ATX (up to three spaces, then 1–6 `#` and a space) or written as raw+ * HTML — setext is disabled, and no plugin in the chain invents one. Content matching neither+ * cannot produce a heading, which lets the common short memo skip the parse below. False+ * positives (a `#` inside a code fence) only cost the work we would otherwise have done anyway.+ */+const MAYBE_HAS_HEADING = /^[ \t]{0,3}#{1,6}[ \t]|<h[1-6][\s/>]/im;++/**+ * Extract h1–h4 headings for outline navigation by running the memo through the same pipeline+ * the renderer uses and reading the ids `rehypeHeadingId` assigned. The slugs are the rendered+ * ids rather than a second guess at them, so an outline link always has somewhere to land.+ *+ * Math plugins are left out: they are lazy-loaded for bundle size, and the only heading text they+ * change is `$…$` delimiters, which slugify strips either way.+ */+export function extractHeadings(markdown: string): HeadingItem[] {+ if (!MAYBE_HAS_HEADING.test(markdown)) return [];++ const processor = unified()+ .use(remarkParse)+ .use(buildRemarkPlugins())+ // rehype-raw needs the raw HTML kept in the tree, exactly as react-markdown configures it.+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(buildRehypePlugins());++ const tree = processor.runSync(processor.parse(markdown)) as HastRoot;+ const headings: HeadingItem[] = [];++ visit(tree, "element", (node: Element) => {+ if (!isHeadingElement(node) || isVisuallyHidden(node)) return;++ const level = Number(node.tagName.slice(1));+ if (level > 4) return;++ const text = getHeadingText(node);+ const slug = typeof node.properties?.id === "string" ? node.properties.id : "";+ if (!text || !slug) return;++ headings.push({ text, level: level as 1 | 2 | 3 | 4, slug });+ });++ return headings;+}diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsxindex c35171242..6ee456311 100644--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx@@ -5,6 +5,7 @@ import toast from "react-hot-toast";import { Link } from "react-router-dom";import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "@/components/AppSidebar/SidebarRow";import SidebarSectionHeader from "@/components/AppSidebar/SidebarSectionHeader";+import { extractHeadings } from "@/components/MemoContent/pipeline";import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";@@ -16,7 +17,6 @@ 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 { useTranslate } from "@/utils/i18n";-import { extractHeadings } from "@/utils/markdown-manipulation";import { isSuperUser } from "@/utils/user";import MemoOutline from "./MemoOutline";import MemoSharePanel from "./MemoSharePanel";@@ -31,7 +31,9 @@ interface Props {const Section = ({ label, children }: { label: string; children: React.ReactNode }) => (<section className="w-full"><SidebarSectionHeader>{label}</SidebarSectionHeader>- <div className="space-y-0.5">{children}</div>+ {/* flex gap, not space-y: open popups insert fixed-position focus guards next to+ their trigger, and space-y's :not(:last-child) margin would count them (#6154). */}+ <div className="flex flex-col gap-0.5">{children}</div></section>);@@ -145,7 +147,7 @@ const MemoDetailSidebar = ({ memo, className, onShareImageOpen, forceReadonly ={headings.length > 1 && (<Section label={t("memo.outline")}>- <MemoOutline headings={headings} />+ <MemoOutline headings={headings} memoName={memo.name} /></Section>)}diff --git a/web/src/components/MemoDetailSidebar/MemoOutline.tsx b/web/src/components/MemoDetailSidebar/MemoOutline.tsxindex 7cacf1748..e22336c93 100644--- a/web/src/components/MemoDetailSidebar/MemoOutline.tsx+++ b/web/src/components/MemoDetailSidebar/MemoOutline.tsx@@ -1,16 +1,18 @@import { useEffect, useMemo, useRef, useState } from "react";+import type { HeadingItem } from "@/components/MemoContent/pipeline";import { cn } from "@/lib/utils";-import type { HeadingItem } from "@/utils/markdown-manipulation";+import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";interface MemoOutlineProps {headings: HeadingItem[];+ memoName: string;}/** Distance from the viewport top of the "reading line" used to decide the active section. */const READING_LINE_OFFSET = 100;/** Outline navigation for memo headings (h1–h4) with active-section tracking. */-const MemoOutline = ({ headings }: MemoOutlineProps) => {+const MemoOutline = ({ headings, memoName }: MemoOutlineProps) => {const [activeSlug, setActiveSlug] = useState<string | null>(null);const rafRef = useRef(0);@@ -20,8 +22,10 @@ const MemoOutline = ({ headings }: MemoOutlineProps) => {const update = () => {rafRef.current = 0;let current: string | null = null;+ const memoContent = findMemoContentRoot(document, memoName);+ if (!memoContent) return;for (const heading of headings) {- const el = document.getElementById(heading.slug);+ const el = findAnchorTarget(memoContent, heading.slug);if (!el) continue;if (el.getBoundingClientRect().top > READING_LINE_OFFSET) break;current = heading.slug;@@ -44,11 +48,12 @@ const MemoOutline = ({ headings }: MemoOutlineProps) => {cancelAnimationFrame(rafRef.current);}};- }, [headings]);+ }, [headings, memoName]);const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, slug: string) => {e.preventDefault();- const el = document.getElementById(slug);+ const memoContent = findMemoContentRoot(document, memoName);+ const el = memoContent && findAnchorTarget(memoContent, slug);if (el) {setActiveSlug(slug);el.scrollIntoView({ behavior: "smooth", block: "start" });diff --git a/web/src/components/TagTree.tsx b/web/src/components/TagTree.tsxindex d1c8cabc5..d88f69666 100644--- a/web/src/components/TagTree.tsx+++ b/web/src/components/TagTree.tsx@@ -1,5 +1,5 @@-import { HashIcon } from "lucide-react";-import { useMemo } from "react";+import { ChevronRightIcon, HashIcon } from "lucide-react";+import { useEffect, useMemo } from "react";import {SIDEBAR_ROW_BOX_CLASSES,SIDEBAR_ROW_COUNT_CLASSES,@@ -7,7 +7,7 @@ import {SIDEBAR_ROW_ICON_CLASSES,sidebarRowStateClasses,} from "@/components/AppSidebar/SidebarRow";-import { useOverflowTitle } from "@/hooks";+import { useLocalStorage, useOverflowTitle } from "@/hooks";import { cn } from "@/lib/utils";import { useTranslate } from "@/utils/i18n";@@ -24,9 +24,19 @@ interface TagTreeNode {interface Props {tagAmounts: [tag: string, amount: number][];activeTag?: string;+ /** Identifies whose tags these are, so expansion persists per tenant rather than per browser. */+ scope: string;onTagClick: (tag: string) => void;}+/** Persisted per scope: which branches are open, and the selection already revealed. */+interface TagTreeExpansion {+ expanded: string[];+ revealedFor?: string;+}++const EMPTY_EXPANSION: TagTreeExpansion = { expanded: [] };+export const buildTagTree = (tagAmounts: [tag: string, amount: number][]) => {const root: TagTreeNode = {key: "",@@ -62,20 +72,37 @@ export const buildTagTree = (tagAmounts: [tag: string, amount: number][]) => {return root.subTags;};+const parentPathsOf = (tag: string): string[] => {+ const segments = tag.split("/");+ return segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join("/"));+};+const TagMark = () => <HashIcon aria-hidden="true" className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />;+const Chevron = ({ open }: { open: boolean }) => (+ <ChevronRightIcon+ aria-hidden="true"+ className={cn("size-3.5 shrink-0 text-muted-foreground/70 transition-transform", open && "rotate-90")}+ strokeWidth={1.8}+ />+);+interface TagItemProps {tag: TagTreeNode;depth: number;activeTag?: string;+ expanded: ReadonlySet<string>;onTagClick: (tag: string) => void;+ onToggle: (path: string) => void;}-const TagItem = ({ tag, depth, activeTag, onTagClick }: TagItemProps) => {+const TagItem = ({ tag, depth, activeTag, expanded, onTagClick, onToggle }: TagItemProps) => {+ const t = useTranslate();const isTag = tag.amount !== undefined;const isActive = activeTag === tag.text;const isAncestorOfActiveTag = activeTag?.startsWith(`${tag.text}/`) ?? false;const hasSubTags = tag.subTags.length > 0;+ const open = hasSubTags && expanded.has(tag.text);const { ref: labelRef, title } = useOverflowTitle<HTMLSpanElement>(isTag ? `#${tag.text}` : tag.text);return (@@ -84,6 +111,7 @@ const TagItem = ({ tag, depth, activeTag, onTagClick }: TagItemProps) => {role="treeitem"aria-level={depth + 1}aria-selected={isActive || undefined}+ aria-expanded={hasSubTags ? open : undefined}className={cn(SIDEBAR_ROW_BOX_CLASSES,isTag ? sidebarRowStateClasses(isActive) : "font-medium text-muted-foreground/65",@@ -108,17 +136,51 @@ const TagItem = ({ tag, depth, activeTag, onTagClick }: TagItemProps) => {<span className={SIDEBAR_ROW_COUNT_CLASSES}>{tag.amount}</span></button>) : (+ // A structural segment only exists to reach its children, so the whole row is the+ // disclosure — one control, rather than a row and a chevron doing the same thing.// Aligns with the tag rows below it: past the 15px mark plus the row's 8px gap.- <span ref={labelRef} className="min-w-0 flex-1 truncate ps-[23px]" title={title}>- {tag.key}- </span>+ <button+ type="button"+ aria-label={`${open ? t("common.collapse") : t("common.expand")} ${tag.text}`}+ aria-expanded={open}+ className={cn("flex h-full min-w-0 flex-1 items-center gap-2 text-left", SIDEBAR_ROW_FOCUS_CLASSES)}+ onClick={() => onToggle(tag.text)}+ >+ <span ref={labelRef} className="min-w-0 flex-1 truncate ps-[23px]" title={title}>+ {tag.key}+ </span>+ <Chevron open={open} />+ </button>+ )}+ {isTag && hasSubTags && (+ // A tag row's label filters, so its disclosure needs a control of its own.+ <button+ type="button"+ aria-label={`${open ? t("common.collapse") : t("common.expand")} #${tag.text}`}+ aria-expanded={open}+ className={cn(+ "-mr-1 flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground/70 hover:bg-background/70 hover:text-foreground",+ SIDEBAR_ROW_FOCUS_CLASSES,+ )}+ onClick={() => onToggle(tag.text)}+ >+ <Chevron open={open} />+ </button>)}</div>- {hasSubTags && (+ {open && (<div className="mt-0.5 flex w-full min-w-0 flex-col gap-0.5" role="group">{tag.subTags.map((subTag) => (- <TagItem key={subTag.text} tag={subTag} depth={depth + 1} activeTag={activeTag} onTagClick={onTagClick} />+ <TagItem+ key={subTag.text}+ tag={subTag}+ depth={depth + 1}+ activeTag={activeTag}+ expanded={expanded}+ onTagClick={onTagClick}+ onToggle={onToggle}+ />))}</div>)}@@ -126,14 +188,49 @@ const TagItem = ({ tag, depth, activeTag, onTagClick }: TagItemProps) => {);};-const TagTree = ({ tagAmounts, activeTag, onTagClick }: Props) => {+const TagTree = ({ tagAmounts, activeTag, scope, onTagClick }: Props) => {const t = useTranslate();const tags = useMemo(() => buildTagTree(tagAmounts), [tagAmounts]);+ // Scoped per tenant: the paths are one account's tag names, so another user's profile tree+ // must not decide what your own library shows.+ const [state, setState] = useLocalStorage<TagTreeExpansion>(`tag-tree-expanded:${scope}`, EMPTY_EXPANSION);+ const expandedPaths = state?.expanded ?? EMPTY_EXPANSION.expanded;+ const expanded = useMemo(() => new Set(expandedPaths), [expandedPaths]);++ const handleToggle = (path: string) => {+ setState((current) => {+ const paths = current?.expanded ?? [];+ return { ...current, expanded: paths.includes(path) ? paths.filter((item) => item !== path) : [...paths, path] };+ });+ };++ // Reveal the active tag when a filter arrives from elsewhere (URL, memo content). `revealedFor`+ // is persisted so this happens once per selection: collapsing afterwards sticks even though the+ // effect runs again on every mount, and re-picking the same tag later reveals it again.+ useEffect(() => {+ setState((current) => {+ if (!activeTag) return current?.revealedFor === undefined ? current : { ...current, revealedFor: undefined };+ if (current?.revealedFor === activeTag) return current;++ const parents = parentPathsOf(activeTag);+ const paths = current?.expanded ?? [];+ const missing = parents.some((path) => !paths.includes(path));+ return { expanded: missing ? [...new Set([...paths, ...parents])] : paths, revealedFor: activeTag };+ });+ }, [activeTag, setState]);return (<div className="relative flex h-auto w-full flex-col items-stretch gap-0.5" role="tree" aria-label={t("common.tags")}>{tags.map((tag) => (- <TagItem key={tag.text} tag={tag} depth={0} activeTag={activeTag} onTagClick={onTagClick} />+ <TagItem+ key={tag.text}+ tag={tag}+ depth={0}+ activeTag={activeTag}+ expanded={expanded}+ onTagClick={onTagClick}+ onToggle={handleToggle}+ />))}</div>);diff --git a/web/src/components/UserMenu.tsx b/web/src/components/UserMenu.tsxindex 9394b427b..81d191073 100644--- a/web/src/components/UserMenu.tsx+++ b/web/src/components/UserMenu.tsx@@ -85,7 +85,7 @@ const UserMenu = (props: Props) => {try {// Then clear user-specific localStorage items// Preserve app-wide settings (theme, locale, view preferences, tag view settings)- const keysToPreserve = ["memos-theme", "memos-locale", "memos-view-setting", "tag-view-as-tree", "tag-tree-auto-expand"];+ const keysToPreserve = ["memos-theme", "memos-locale", "memos-view-setting", "tag-view-as-tree"];const keysToRemove: string[] = [];for (let i = 0; i < localStorage.length; i++) {diff --git a/web/src/components/ui/popup.ts b/web/src/components/ui/popup.tsindex e3fa24721..a923701f9 100644--- a/web/src/components/ui/popup.ts+++ b/web/src/components/ui/popup.ts@@ -1,5 +1,11 @@// Shared enter/exit motion for popup surfaces (dropdown menu, popover, tooltip), driven by// Base UI's data-starting-style/data-ending-style attributes. Keep in one place so all// popups animate identically; select.tsx uses a closer-range variant of the same pattern.+//+// Layout note for consumers: while a popup is open, Base UI inserts focus-guard spans as+// siblings of the trigger. They are fixed-position and take no space, but they do make the+// trigger stop being `:last-child` — so a `space-y-*` parent starts applying its margin to it+// and everything below shifts (#6154). Space a stack that contains a popup trigger with+// `flex flex-col gap-*`, which ignores out-of-flow children.export const popupMotionClasses ="transition-[opacity,scale,translate] duration-150 data-starting-style:scale-95 data-starting-style:opacity-0 data-ending-style:scale-95 data-ending-style:opacity-0 data-[side=bottom]:data-starting-style:-translate-y-2 data-[side=bottom]:data-ending-style:-translate-y-2 data-[side=left]:data-starting-style:translate-x-2 data-[side=left]:data-ending-style:translate-x-2 data-[side=right]:data-starting-style:-translate-x-2 data-[side=right]:data-ending-style:-translate-x-2 data-[side=top]:data-starting-style:translate-y-2 data-[side=top]:data-ending-style:translate-y-2";diff --git a/web/src/locales/ar.json b/web/src/locales/ar.jsonindex bb52ad0b7..0847e7209 100644--- a/web/src/locales/ar.json+++ b/web/src/locales/ar.json@@ -23,7 +23,6 @@"archive": "الأرشيف","archived": "المؤرشفة","attachments": "مرفقات",- "auto-expand": "توسيع تلقائي","avatar": "الصورة الشخصية","basic": "بسيط","beta": "تجريبي",diff --git a/web/src/locales/bg.json b/web/src/locales/bg.jsonindex 72a3d2092..12808473f 100644--- a/web/src/locales/bg.json+++ b/web/src/locales/bg.json@@ -61,7 +61,6 @@"archive": "Архив","archived": "Архивирано","attachments": "Прикачени файлове",- "auto-expand": "Автоматично разширяване","avatar": "Аватар","basic": "Основен","beta": "Бета",diff --git a/web/src/locales/ca.json b/web/src/locales/ca.jsonindex b4a9604a6..807d5c85f 100644--- a/web/src/locales/ca.json+++ b/web/src/locales/ca.json@@ -24,7 +24,6 @@"archive": "Arxivar","archived": "Arxivat","attachments": "Adjunts",- "auto-expand": "Expansió automàtica","avatar": "Avatar","basic": "Bàsic","beta": "Beta",diff --git a/web/src/locales/cs.json b/web/src/locales/cs.jsonindex fe765de7d..ef431e30d 100644--- a/web/src/locales/cs.json+++ b/web/src/locales/cs.json@@ -24,7 +24,6 @@"archive": "Archivovat","archived": "Archivované","attachments": "Přílohy",- "auto-expand": "Automaticky rozbalit","avatar": "Avatar","basic": "Základní","beta": "Beta",diff --git a/web/src/locales/da.json b/web/src/locales/da.jsonindex 7a3ac07c1..8728051e1 100644--- a/web/src/locales/da.json+++ b/web/src/locales/da.json@@ -61,7 +61,6 @@"archive": "Arkiv","archived": "Arkiveret","attachments": "Vedhæftede filer",- "auto-expand": "Automatisk udvidelse","avatar": "Avatar","basic": "Grundlæggende","beta": "Beta",diff --git a/web/src/locales/de.json b/web/src/locales/de.jsonindex 60ab97d83..172fdf61b 100644--- a/web/src/locales/de.json+++ b/web/src/locales/de.json@@ -24,7 +24,6 @@"archive": "Archivieren","archived": "Archiviert","attachments": "Anhänge",- "auto-expand": "Automatisch erweitern","avatar": "Avatar","basic": "Allgemeines","beta": "Beta",diff --git a/web/src/locales/el.json b/web/src/locales/el.jsonindex 450be3410..ceace0abf 100644--- a/web/src/locales/el.json+++ b/web/src/locales/el.json@@ -61,7 +61,6 @@"archive": "Αρχείο","archived": "Αρχειοθετήθηκε","attachments": "Συνημμένα",- "auto-expand": "Αυτόματη επέκταση","avatar": "Avatar","basic": "Βασικός","beta": "Βήτα",diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.jsonindex cb79617d3..0fe1938dc 100644--- a/web/src/locales/en-GB.json+++ b/web/src/locales/en-GB.json@@ -24,7 +24,6 @@"archive": "Archive","archived": "Archived","attachments": "Attachments",- "auto-expand": "Auto expand","avatar": "Avatar","basic": "Basic","beta": "Beta",diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex 3947a8fae..6576ec0eb 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -96,7 +96,6 @@"archived": "Archived","attachments": "Attachments","author": "Author",- "auto-expand": "Auto expand","avatar": "Avatar","basic": "Basic","beta": "Beta",diff --git a/web/src/locales/es.json b/web/src/locales/es.jsonindex ac7c42953..daf40f64a 100644--- a/web/src/locales/es.json+++ b/web/src/locales/es.json@@ -24,7 +24,6 @@"archive": "Archivar","archived": "Archivado","attachments": "Adjuntos",- "auto-expand": "Auto expandir","avatar": "Avatar","basic": "Básico","beta": "Beta",diff --git a/web/src/locales/et.json b/web/src/locales/et.jsonindex 79e4134ee..549c1a990 100644--- a/web/src/locales/et.json+++ b/web/src/locales/et.json@@ -61,7 +61,6 @@"archive": "Arhiiv","archived": "Arhiveeritud","attachments": "Manused",- "auto-expand": "Automaatne laiendamine","avatar": "Avatar","basic": "Põhiline","beta": "Beeta",diff --git a/web/src/locales/fa.json b/web/src/locales/fa.jsonindex 0009a0a97..6320075e5 100644--- a/web/src/locales/fa.json+++ b/web/src/locales/fa.json@@ -23,7 +23,6 @@"archive": "آرشیو","archived": "آرشیو شده","attachments": "پیوستها",- "auto-expand": "گسترش خودکار","avatar": "آواتار","basic": "ساده","beta": "بتا",diff --git a/web/src/locales/fi.json b/web/src/locales/fi.jsonindex d75f5c723..c2c867191 100644--- a/web/src/locales/fi.json+++ b/web/src/locales/fi.json@@ -61,7 +61,6 @@"archive": "Arkisto","archived": "Arkistoitu","attachments": "Liitteet",- "auto-expand": "Automaattinen laajennus","avatar": "Avatar","basic": "Perus","beta": "Beeta",diff --git a/web/src/locales/fr.json b/web/src/locales/fr.jsonindex 8385c9cd4..864978054 100644--- a/web/src/locales/fr.json+++ b/web/src/locales/fr.json@@ -24,7 +24,6 @@"archive": "Archiver","archived": "Archivé","attachments": "Pièces jointes",- "auto-expand": "Déplier automatiquement","avatar": "Avatar","basic": "Basique","beta": "Bêta",diff --git a/web/src/locales/gl.json b/web/src/locales/gl.jsonindex 5f1f4b395..10310e00b 100644--- a/web/src/locales/gl.json+++ b/web/src/locales/gl.json@@ -24,7 +24,6 @@"archive": "Arquivo","archived": "Arquivada","attachments": "Anexos",- "auto-expand": "Depregar Auto","avatar": "Avatar","basic": "Básico","beta": "Beta",diff --git a/web/src/locales/hi.json b/web/src/locales/hi.jsonindex f67589563..a3247e207 100644--- a/web/src/locales/hi.json+++ b/web/src/locales/hi.json@@ -23,7 +23,6 @@"archive": "संग्रहीत करें","archived": "संग्रहीत","attachments": "संलग्नक",- "auto-expand": "स्वतः विस्तार","avatar": "अवतार","basic": "मूल","beta": "बीटा",diff --git a/web/src/locales/hr.json b/web/src/locales/hr.jsonindex 15aa34ce9..b0a7ef99a 100644--- a/web/src/locales/hr.json+++ b/web/src/locales/hr.json@@ -24,7 +24,6 @@"archive": "Arhiviraj","archived": "Arhivirano","attachments": "Privici",- "auto-expand": "Automatski proširi","avatar": "Avatar","basic": "Osnovno","beta": "Beta",diff --git a/web/src/locales/hu.json b/web/src/locales/hu.jsonindex 3d809b67f..db9ca3f6f 100644--- a/web/src/locales/hu.json+++ b/web/src/locales/hu.json@@ -24,7 +24,6 @@"archive": "Archiválás","archived": "Archívum","attachments": "Mellékletek",- "auto-expand": "Automatikus kinyitás","avatar": "Avatar","basic": "Általános","beta": "Béta",diff --git a/web/src/locales/id.json b/web/src/locales/id.jsonindex 7fe656903..571094581 100644--- a/web/src/locales/id.json+++ b/web/src/locales/id.json@@ -23,7 +23,6 @@"archive": "Arsip","archived": "Diarsipkan","attachments": "Lampiran",- "auto-expand": "Perluas otomatis","avatar": "Avatar","basic": "Dasar","beta": "Beta",diff --git a/web/src/locales/it.json b/web/src/locales/it.jsonindex d3bac3b1f..6253fecdf 100644--- a/web/src/locales/it.json+++ b/web/src/locales/it.json@@ -24,7 +24,6 @@"archive": "Archivia","archived": "Archiviati","attachments": "Allegati",- "auto-expand": "Espandi automaticamente","avatar": "Avatar","basic": "Base","beta": "Beta",diff --git a/web/src/locales/ja.json b/web/src/locales/ja.jsonindex d74809f1c..86bbd0cd0 100644--- a/web/src/locales/ja.json+++ b/web/src/locales/ja.json@@ -24,7 +24,6 @@"archive": "アーカイブにする","archived": "アーカイブ済み","attachments": "添付ファイル",- "auto-expand": "自動展開","avatar": "アイコン","basic": "基本設定","beta": "ベータ",diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.jsonindex 7a6743930..ea801c8a5 100644--- a/web/src/locales/ka-GE.json+++ b/web/src/locales/ka-GE.json@@ -24,7 +24,6 @@"archive": "არქივი","archived": "დაარქივებული","attachments": "დანართები",- "auto-expand": "ავტომატური გაფართოება","avatar": "ავატარი","basic": "ძირითადი","beta": "ბეტა",diff --git a/web/src/locales/ko.json b/web/src/locales/ko.jsonindex 22317e0f1..75785987a 100644--- a/web/src/locales/ko.json+++ b/web/src/locales/ko.json@@ -23,7 +23,6 @@"archive": "보관 처리","archived": "보관 목록","attachments": "첨부파일",- "auto-expand": "자동 펼치기","avatar": "아바타","basic": "기본","beta": "베타",diff --git a/web/src/locales/lt.json b/web/src/locales/lt.jsonindex ef00617f1..f7851b9ff 100644--- a/web/src/locales/lt.json+++ b/web/src/locales/lt.json@@ -61,7 +61,6 @@"archive": "Archyvas","archived": "Suarchyvuota","attachments": "Priedai",- "auto-expand": "Automatiškai išplėsti","avatar": "Avataras","basic": "Pagrindinis","beta": "Beta",diff --git a/web/src/locales/lv.json b/web/src/locales/lv.jsonindex a34bce58e..d70311439 100644--- a/web/src/locales/lv.json+++ b/web/src/locales/lv.json@@ -61,7 +61,6 @@"archive": "Arhīvs","archived": "Arhivēts","attachments": "Pielikumi",- "auto-expand": "Automātiski izvērst","avatar": "Iemiesojums","basic": "Pamata","beta": "Beta",diff --git a/web/src/locales/mr.json b/web/src/locales/mr.jsonindex bb95b667b..d41d06600 100644--- a/web/src/locales/mr.json+++ b/web/src/locales/mr.json@@ -23,7 +23,6 @@"archive": "संग्रहण","archived": "संग्रहित","attachments": "संलग्नक",- "auto-expand": "स्वयं विस्तार","avatar": "अवतार","basic": "मूलभूत","beta": "बीटा",diff --git a/web/src/locales/nb.json b/web/src/locales/nb.jsonindex d816bf12e..51d92d057 100644--- a/web/src/locales/nb.json+++ b/web/src/locales/nb.json@@ -24,7 +24,6 @@"archive": "Arkiver","archived": "Arkivert","attachments": "Vedlegg",- "auto-expand": "Ekspander automatisk","avatar": "Avatar","basic": "Grunnleggende","beta": "Beta",diff --git a/web/src/locales/nl.json b/web/src/locales/nl.jsonindex c43a75307..29c66e3f4 100644--- a/web/src/locales/nl.json+++ b/web/src/locales/nl.json@@ -24,7 +24,6 @@"archive": "Archiveren","archived": "Gearchiveerd","attachments": "Bijlagen",- "auto-expand": "Auto uitklappen","avatar": "Avatar","basic": "Simpel","beta": "Beta",diff --git a/web/src/locales/pl.json b/web/src/locales/pl.jsonindex 5ef574799..5f54d312b 100644--- a/web/src/locales/pl.json+++ b/web/src/locales/pl.json@@ -24,7 +24,6 @@"archive": "Archiwum","archived": "Zarchiwizowane","attachments": "Załączniki",- "auto-expand": "Rozwiń automatycznie","avatar": "Awatar","basic": "Podstawowy","beta": "Beta",diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.jsonindex a0460c806..8a359d40d 100644--- a/web/src/locales/pt-BR.json+++ b/web/src/locales/pt-BR.json@@ -23,7 +23,6 @@"archive": "Arquivar","archived": "Arquivo","attachments": "Anexos",- "auto-expand": "Expandir automaticamente","avatar": "Avatar","basic": "Básico","beta": "Beta",diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.jsonindex 88c3a2e61..35438a65f 100644--- a/web/src/locales/pt-PT.json+++ b/web/src/locales/pt-PT.json@@ -24,7 +24,6 @@"archive": "Arquivar","archived": "Arquivado","attachments": "Anexos",- "auto-expand": "Expandir automaticamente","avatar": "Avatar","basic": "Básico","beta": "Beta",diff --git a/web/src/locales/ro.json b/web/src/locales/ro.jsonindex 5f2869b32..3badc855a 100644--- a/web/src/locales/ro.json+++ b/web/src/locales/ro.json@@ -61,7 +61,6 @@"archive": "Arhivă","archived": "Arhivat","attachments": "Atasamente",- "auto-expand": "Extindere automată","avatar": "Avatar","basic": "De bază","beta": "Beta",diff --git a/web/src/locales/ru.json b/web/src/locales/ru.jsonindex 496cd2784..09b23a314 100644--- a/web/src/locales/ru.json+++ b/web/src/locales/ru.json@@ -24,7 +24,6 @@"archive": "Архивировать","archived": "Архив","attachments": "Файлы",- "auto-expand": "Авто-раскрытие","avatar": "Аватар","basic": "Базовые","beta": "Бета",diff --git a/web/src/locales/sk.json b/web/src/locales/sk.jsonindex b0a5f8ad9..1fe6110c8 100644--- a/web/src/locales/sk.json+++ b/web/src/locales/sk.json@@ -61,7 +61,6 @@"archive": "Archív","archived": "Archivované","attachments": "Prílohy",- "auto-expand": "Automatické rozšírenie","avatar": "Avatar","basic": "Základné","beta": "Beta",diff --git a/web/src/locales/sl.json b/web/src/locales/sl.jsonindex b94a75e77..d84060f57 100644--- a/web/src/locales/sl.json+++ b/web/src/locales/sl.json@@ -24,7 +24,6 @@"archive": "Arhiv","archived": "Arhivirani","attachments": "Priloge",- "auto-expand": "Samodejno razširi","avatar": "Avatar","basic": "Osnovni","beta": "Beta",diff --git a/web/src/locales/sr.json b/web/src/locales/sr.jsonindex e01fff4f3..eb0c5651e 100644--- a/web/src/locales/sr.json+++ b/web/src/locales/sr.json@@ -61,7 +61,6 @@"archive": "Архива","archived": "Архивирано","attachments": "Прилози",- "auto-expand": "Аутоматско проширење","avatar": "Аватар","basic": "Басиц","beta": "Бета",diff --git a/web/src/locales/sv.json b/web/src/locales/sv.jsonindex 85a71f992..c4e4a024a 100644--- a/web/src/locales/sv.json+++ b/web/src/locales/sv.json@@ -24,7 +24,6 @@"archive": "Arkivera","archived": "Arkiverad","attachments": "Bilagor",- "auto-expand": "Autoexpandera","avatar": "Profilbild","basic": "Grundläggande","beta": "Beta",diff --git a/web/src/locales/th.json b/web/src/locales/th.jsonindex 5765628c0..d2810f40c 100644--- a/web/src/locales/th.json+++ b/web/src/locales/th.json@@ -23,7 +23,6 @@"archive": "เก็บถาวร","archived": "เก็บถาวรแล้ว","attachments": "ไฟล์แนบ",- "auto-expand": "ขยายอัตโนมัติ","avatar": "สัญลักษณ์","basic": "ทั่วไป","beta": "รุ่นเบต้า",diff --git a/web/src/locales/tr.json b/web/src/locales/tr.jsonindex 0cb3b27ce..d2013dcb0 100644--- a/web/src/locales/tr.json+++ b/web/src/locales/tr.json@@ -24,7 +24,6 @@"archive": "Arşiv","archived": "Arşivlendi","attachments": "Ekler",- "auto-expand": "Otomatik genişlet","avatar": "Profil Resmi","basic": "Temel","beta": "Beta sürümü",diff --git a/web/src/locales/uk.json b/web/src/locales/uk.jsonindex 053544a56..dc23a4459 100644--- a/web/src/locales/uk.json+++ b/web/src/locales/uk.json@@ -24,7 +24,6 @@"archive": "Архів","archived": "Архівовано","attachments": "Вкладення",- "auto-expand": "Авторозгортання","avatar": "Аватар","basic": "Основний","beta": "Бета-версія",diff --git a/web/src/locales/vi.json b/web/src/locales/vi.jsonindex a15f91d94..c91d29d6f 100644--- a/web/src/locales/vi.json+++ b/web/src/locales/vi.json@@ -23,7 +23,6 @@"archive": "Lưu trữ","archived": "Đã lưu trữ","attachments": "Tệp đính kèm",- "auto-expand": "Mở rộng tự động","avatar": "Ảnh đại diện","basic": "Cơ bản","beta": "Beta",diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.jsonindex d93559ffc..7b509d73a 100644--- a/web/src/locales/zh-Hans.json+++ b/web/src/locales/zh-Hans.json@@ -62,7 +62,6 @@"archive": "归档","archived": "已归档","attachments": "附件",- "auto-expand": "自动展开","avatar": "头像","basic": "基础","beta": "测试",diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.jsonindex 4a7f23699..8c52a99a0 100644--- a/web/src/locales/zh-Hant.json+++ b/web/src/locales/zh-Hant.json@@ -78,7 +78,6 @@"archive": "封存","archived": "已封存","attachments": "附件",- "auto-expand": "自動展開","avatar": "頭像","basic": "基礎","beta": "測試版",diff --git a/web/src/pages/MemoDetail.tsx b/web/src/pages/MemoDetail.tsxindex 05758e47d..70c9f2322 100644--- a/web/src/pages/MemoDetail.tsx+++ b/web/src/pages/MemoDetail.tsx@@ -14,6 +14,7 @@ import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQueimport { memoNamePrefix } from "@/lib/resource-names";import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";import type { Memo } from "@/types/proto/api/v1/memo_service_pb";+import { findMemoAnchorTarget } from "@/utils/markdown-manipulation";const MemoSidebarRegistration = ({memo,@@ -92,12 +93,14 @@ const MemoDetail = () => {// ref guards against re-scrolling the same hash on every later comments page-load.const scrolledHashRef = useRef("");useEffect(() => {- if (!hash || scrolledHashRef.current === hash) return;- const el = document.getElementById(decodeURIComponent(hash.slice(1)));+ if (!hash) return;+ const scrollKey = `${memoName}\0${hash}`;+ if (scrolledHashRef.current === scrollKey) return;+ const el = findMemoAnchorTarget(document, memoName, decodeURIComponent(hash.slice(1)));if (!el) return;- scrolledHashRef.current = hash;+ scrolledHashRef.current = scrollKey;el.scrollIntoView({ behavior: "smooth", block: "center" });- }, [hash, memo, comments]);+ }, [hash, memo, memoName, comments]);if (isShareMode) {const isNotFound = error instanceof ConnectError && (error.code === Code.NotFound || error.code === Code.Unauthenticated);diff --git a/web/src/utils/markdown-manipulation.ts b/web/src/utils/markdown-manipulation.tsindex f1461547c..d9cbd19b9 100644--- a/web/src/utils/markdown-manipulation.ts+++ b/web/src/utils/markdown-manipulation.ts@@ -1,7 +1,7 @@// Utilities for manipulating markdown strings using AST parsing// Uses mdast for accurate task detection that properly handles code blocks-import type { Heading, ListItem } from "mdast";+import type { ListItem } from "mdast";import { fromMarkdown } from "mdast-util-from-markdown";import { gfmFromMarkdown } from "mdast-util-gfm";import { gfm } from "micromark-extension-gfm";@@ -88,16 +88,28 @@ export interface TaskItem {indentation: number;}-export interface HeadingItem {- text: string;- level: 1 | 2 | 3 | 4;- slug: string;+/**+ * Slugify a string into a URL-friendly anchor ID. Keeps Unicode letters, digits and combining+ * marks, so non-Latin headings stay readable and scripts that write vowels as combining marks+ * (Devanagari, Thai, Arabic) are not reduced to their bare consonants.+ */+export function slugify(text: string): string {+ return text+ .normalize("NFC")+ .toLowerCase()+ .trim()+ .replace(/[^\p{L}\p{N}\p{M}\s_-]/gu, "")+ .replace(/[\s_]+/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-|-$/g, "");}/**- * Slugify a string into a URL-friendly anchor ID.+ * How headings were slugified before anchors kept Unicode: every non-ASCII character was dropped,+ * so "## Café" was `#caf`. Those anchors are in the wild — the outline writes the fragment into the+ * address bar, so they have been shared and bookmarked since v0.27.0.*/-export function slugify(text: string): string {+function legacySlugify(text: string): string {return text.toLowerCase().trim()@@ -108,45 +120,56 @@ export function slugify(text: string): string {}/**- * Extract h1–h4 headings from markdown content for outline navigation.+ * Resolve an in-page fragment to its element, retrying against the pre-Unicode slug scheme so+ * anchors minted by older versions still land.*/-export function extractHeadings(markdown: string): HeadingItem[] {- const tree = fromMarkdown(markdown, {- extensions: [gfm()],- mdastExtensions: [gfmFromMarkdown()],- });-- const headings: HeadingItem[] = [];- const slugCounts = new Map<string, number>();+export function findAnchorTarget(root: ParentNode, fragment: string): Element | null {+ if (!fragment) return null;- visit(tree, "heading", (node: Heading) => {- if (node.depth < 1 || node.depth > 4) return;+ const direct = root.querySelector(`#${CSS.escape(fragment)}`);+ if (direct) return direct;- const text = getNodeText(node as unknown as MdastNode);- if (!text) return;-- let slug = slugify(text);- const count = slugCounts.get(slug) || 0;- slugCounts.set(slug, count + 1);- if (count > 0) slug = `${slug}-${count}`;-- headings.push({ text, level: node.depth as 1 | 2 | 3 | 4, slug });- });+ const slugCounts = new Map<string, number>();+ for (const heading of root.querySelectorAll("h1, h2, h3, h4, h5, h6")) {+ const baseSlug = legacySlugify(heading.textContent ?? "");+ if (!baseSlug) continue;++ const count = slugCounts.get(baseSlug) ?? 0;+ slugCounts.set(baseSlug, count + 1);+ const slug = count === 0 ? baseSlug : `${baseSlug}-${count}`;+ if (slug === fragment) return heading;+ }+ return null;+}- return headings;+/** Find the rendered content container for a specific memo resource. */+export function findMemoContentRoot(root: ParentNode, memoName: string): Element | null {+ for (const memoContent of root.querySelectorAll("[data-memo-content]")) {+ if (memoContent.getAttribute("data-memo-name") === memoName) return memoContent;+ }+ return null;}-interface MdastNode {- type?: string;- value?: string;- children?: MdastNode[];+/** Resolve a fragment inside one memo before falling back to page-level targets such as comments. */+export function findMemoAnchorTarget(root: ParentNode, memoName: string, fragment: string): Element | null {+ const memoContent = findMemoContentRoot(root, memoName);+ return (memoContent && findAnchorTarget(memoContent, fragment)) ?? findAnchorTarget(root, fragment);}-function getNodeText(node: MdastNode): string {- if (node.type === "html") return "";- if (node.value) return node.value;- if (node.children) return node.children.map(getNodeText).join("");- return "";+/** Create a document-scoped generator that prevents generated suffixes from colliding with reserved or literal slugs. */+export function createUniqueSlugGenerator(reservedSlugs: Iterable<string> = []): (baseSlug: string) => string {+ const usedSlugs = new Set(reservedSlugs);++ return (baseSlug: string) => {+ let slug = baseSlug;+ let suffix = 0;+ while (usedSlugs.has(slug)) {+ suffix += 1;+ slug = `${baseSlug}-${suffix}`;+ }+ usedSlugs.add(slug);+ return slug;+ };}export function extractTasks(markdown: string): TaskItem[] {diff --git a/web/src/utils/rehype-plugins/rehype-heading-id.ts b/web/src/utils/rehype-plugins/rehype-heading-id.tsindex 6023d0c79..69103569a 100644--- a/web/src/utils/rehype-plugins/rehype-heading-id.ts+++ b/web/src/utils/rehype-plugins/rehype-heading-id.ts@@ -1,37 +1,62 @@import type { Element, Root } from "hast";import { visit } from "unist-util-visit";-import { slugify } from "@/utils/markdown-manipulation";+import { createUniqueSlugGenerator, slugify } from "@/utils/markdown-manipulation";-function getTextContent(node: Element): string {+/** Anchor used for headings with no slugifiable characters (emoji- or punctuation-only titles). */+const FALLBACK_HEADING_SLUG = "heading";++export const isHeadingElement = (node: Element): boolean => /^h[1-6]$/.test(node.tagName);++/** Rendered text of a heading: element children contribute their text, everything else nothing. */+export function getHeadingText(node: Element): string {let text = "";for (const child of node.children) {if (child.type === "text") {text += child.value;} else if (child.type === "element") {- text += getTextContent(child);+ text += getHeadingText(child);}}return text;}-/** Rehype plugin that adds unique slugified `id` attributes to heading elements. */+/**+ * Rehype plugin that adds unique slugified `id` attributes to heading elements. This is the+ * single place a heading anchor is decided: the memo outline reads these ids back off the tree+ * rather than deriving its own, so an outline link always has somewhere to land.+ *+ * Every heading consumes a slug — including h5/h6 and titles that slugify to nothing — because+ * the duplicate suffixes depend on how many headings came before.+ */export const rehypeHeadingId = () => {return (tree: Root) => {- const slugCounts = new Map<string, number>();-+ // 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>();visit(tree, "element", (node: Element) => {- if (!/^h[1-6]$/.test(node.tagName)) return;+ if (!isHeadingElement(node)) return;+ const existingId = typeof node.properties?.id === "string" ? node.properties.id : "";+ if (existingId) existingIds.add(existingId);+ });- const text = getTextContent(node);- let slug = slugify(text);- if (!slug) return;+ const makeUniqueSlug = createUniqueSlugGenerator(existingIds);+ const claimedExistingIds = new Set<string>();- const count = slugCounts.get(slug) || 0;- slugCounts.set(slug, count + 1);- if (count > 0) slug = `${slug}-${count}`;+ visit(tree, "element", (node: Element) => {+ if (!isHeadingElement(node)) return;node.properties = node.properties || {};- node.properties.id = slug;+ const existingId = typeof node.properties.id === "string" ? node.properties.id : "";+ // An id that is already there is linked to from somewhere — remark-rehype points each+ // footnote reference's aria-describedby at its generated label. Keep it, and reserve it so a+ // later heading cannot be given the same slug.+ if (existingId && !claimedExistingIds.has(existingId)) {+ claimedExistingIds.add(existingId);+ node.properties.id = existingId;+ } else {+ node.properties.id = makeUniqueSlug(existingId || slugify(getHeadingText(node)) || FALLBACK_HEADING_SLUG);+ }});};};diff --git a/web/tests/markdown-manipulation.test.ts b/web/tests/markdown-manipulation.test.tsindex beaaa2738..b5b0d5516 100644--- a/web/tests/markdown-manipulation.test.ts+++ b/web/tests/markdown-manipulation.test.ts@@ -1,16 +1,43 @@import { describe, expect, it } from "vitest";-import { extractHeadings } from "@/utils/markdown-manipulation";--describe("extractHeadings", () => {- it("uses rendered text for headings containing inline HTML", () => {- const headings = extractHeadings(`# <ruby>連濁<rt>れんだく</rt></ruby>: "Why Hito-Bito isn't Hito-Hito"`);-- expect(headings).toEqual([- {- text: `連濁れんだく: "Why Hito-Bito isn't Hito-Hito"`,- level: 1,- slug: "why-hito-bito-isnt-hito-hito",- },- ]);+import { findAnchorTarget, findMemoAnchorTarget, slugify } from "@/utils/markdown-manipulation";++describe("slugify", () => {+ it("keeps non-Latin headings addressable", () => {+ expect(slugify("連濁")).toBe("連濁");+ });++ it("keeps combining marks so Indic vowels survive", () => {+ expect(slugify("हिन्दी")).toBe("हिन्दी");+ });++ it("normalizes so decomposed and composed spellings share an anchor", () => {+ expect(slugify("café")).toBe(slugify("café"));+ });++ it("drops punctuation and collapses whitespace", () => {+ expect(slugify(`Why Hito-Bito isn't Hito-Hito`)).toBe("why-hito-bito-isnt-hito-hito");+ });+});++describe("findAnchorTarget", () => {+ it("resolves duplicate anchors minted by the legacy ASCII slugger", () => {+ const root = document.createElement("div");+ root.innerHTML = '<h2 id="café">Café</h2><h2 id="café-1">Café</h2>';++ expect(findAnchorTarget(root, "caf-1")).toBe(root.children[1]);+ });++ it("prefers a matching heading inside the requested memo over a page-level id", () => {+ const root = document.createElement("div");+ root.innerHTML = '<div id="root"></div><div data-memo-content data-memo-name="memos/1"><h2 id="root">Title</h2></div>';++ expect(findMemoAnchorTarget(root, "memos/1", "root")).toBe(root.querySelector("h2"));+ });++ it("falls back to page-level targets outside the memo", () => {+ const root = document.createElement("div");+ root.innerHTML = '<div data-memo-content data-memo-name="memos/1"></div><div id="comment-1"></div>';++ expect(findMemoAnchorTarget(root, "memos/1", "comment-1")).toBe(root.lastElementChild);});});diff --git a/web/tests/memo-outline-headings.test.tsx b/web/tests/memo-outline-headings.test.tsxnew file mode 100644index 000000000..388d9cf08--- /dev/null+++ b/web/tests/memo-outline-headings.test.tsx@@ -0,0 +1,106 @@+import { render } from "@testing-library/react";+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";++vi.mock("@/components/MemoContent/math", () => ({+ hasMathSyntax: vi.fn(() => false),+}));++/**+ * The outline and the rendered heading ids come from one pipeline run, so these cases are about+ * keeping that so: each one previously produced an outline slug that no rendered heading carried.+ */+const renderMemo = (content: string) => {+ const { container } = render(+ <MemoryRouter>+ <MemoMarkdownRenderer content={content} memoName="memos/1" resolvedMentionUsernames={new Set<string>()} />+ </MemoryRouter>,+ );+ return container;+};++const expectOutlineLandsOnRenderedHeadings = (content: string) => {+ const container = renderMemo(content);+ const headings = extractHeadings(content);+ const renderedIds = Array.from(container.querySelectorAll("h1, h2, h3, h4, h5, h6"), (heading) => heading.id).filter(Boolean);++ expect(new Set(renderedIds).size, "rendered heading ids must be unique").toBe(renderedIds.length);+ for (const heading of headings) {+ expect(container.querySelector(`[id="${CSS.escape(heading.slug)}"]`), `no element carries id "${heading.slug}"`).not.toBeNull();+ }+ return headings;+};++describe("outline slugs against rendered heading ids", () => {+ it("handles inline HTML, duplicates and repeated suffixes", () => {+ const headings = expectOutlineLandsOnRenderedHeadings(+ `# <ruby>連濁<rt>れんだく</rt></ruby>: intro\n\n## Dup\n\n##### Dup\n\n## Dup\n\n### 連\n\n### 連\n\n### 連-1\n\nbody`,+ );++ expect(headings[0]).toEqual({ text: "連濁れんだく: intro", level: 1, slug: "連濁れんだく-intro" });+ // The h5 consumes "dup-1" even though it never reaches the outline.+ expect(headings.filter((heading) => heading.text === "Dup").map((heading) => heading.slug)).toEqual(["dup", "dup-2"]);+ // A literal "連-1" heading must not collide with the suffix generated for the second "連".+ expect(headings.filter((heading) => heading.level === 3).map((heading) => heading.slug)).toEqual(["連", "連-1", "連-1-1"]);+ });++ it("ignores setext headings, which the renderer disables", () => {+ const headings = expectOutlineLandsOnRenderedHeadings("Title\n-----\n\n# Title");++ expect(headings).toEqual([{ text: "Title", level: 1, slug: "title" }]);+ });++ it("lists headings written as raw HTML alongside markdown ones", () => {+ const headings = expectOutlineLandsOnRenderedHeadings("<h2>Dup</h2>\n\n## Dup");++ expect(headings.map((heading) => heading.slug)).toEqual(["dup", "dup-1"]);+ });++ it("keeps an author-supplied id and numbers around it", () => {+ const headings = expectOutlineLandsOnRenderedHeadings('<h2 id="custom">Dup</h2>\n\n## custom');++ expect(headings.map((heading) => heading.slug)).toEqual(["custom", "custom-1"]);+ });++ it("uses the sanitized text when an element is stripped with its content", () => {+ const headings = expectOutlineLandsOnRenderedHeadings("# Alert <script>alert(1)</script>");++ expect(headings).toHaveLength(1);+ expect(headings[0].text).not.toContain("alert(1)");+ expect(headings[0].slug).toBe("alert");+ });++ it("includes the footnote marker the rendered heading shows, and omits the footnote label", () => {+ const headings = expectOutlineLandsOnRenderedHeadings("# Intro[^1]\n\n## Intro\n\n[^1]: note");++ expect(headings.map((heading) => heading.slug)).toEqual(["intro1", "intro"]);+ expect(headings.some((heading) => heading.text === "Footnotes")).toBe(false);+ });++ it("reserves the referenced footnote label id before assigning heading slugs", () => {+ const container = renderMemo("# Footnote label\n\nText[^1]\n\n[^1]: note");+ const reference = container.querySelector("[data-footnote-ref]");+ const label = container.querySelector(".footnotes > h2");++ expect(reference).toHaveAttribute("aria-describedby", "footnote-label");+ expect(label).toHaveAttribute("id", "footnote-label");+ expect(container.querySelector("h1")).toHaveAttribute("id", "footnote-label-1");+ });++ 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.+ expect(extractHeadings("just a note about #work and #life")).toEqual([]);+ expect(extractHeadings("```sh\n#!/bin/bash\necho hi\n```")).toEqual([]);+ expect(extractHeadings(" ## Indented")).toEqual([{ text: "Indented", level: 2, slug: "indented" }]);+ expect(extractHeadings("#\tTabbed")).toEqual([{ text: "Tabbed", level: 1, slug: "tabbed" }]);+ });++ it("gives headings with no slugifiable characters a usable anchor", () => {+ const headings = expectOutlineLandsOnRenderedHeadings("# Intro\n\n# 🎉🎉\n\n# ✨");++ expect(headings.map((heading) => heading.slug)).toEqual(["intro", "heading", "heading-1"]);+ });+});diff --git a/web/tests/sidebar-row-grammar.test.tsx b/web/tests/sidebar-row-grammar.test.tsxindex 144e049e2..c5fd256e7 100644--- a/web/tests/sidebar-row-grammar.test.tsx+++ b/web/tests/sidebar-row-grammar.test.tsx@@ -26,6 +26,7 @@ describe("sidebar row grammar", () => {["a", 2],["a/b", 1],]}+ scope="home"onTagClick={vi.fn()}/>,);@@ -42,6 +43,9 @@ describe("sidebar row grammar", () => {["a", 2],["a/b", 1],]}+ // The active tag keeps the nested row expanded into view.+ activeTag="a/b"+ scope="home"onTagClick={vi.fn()}/>,);diff --git a/web/tests/tag-tree-render.test.tsx b/web/tests/tag-tree-render.test.tsxindex bf07af1e4..5d16759d1 100644--- a/web/tests/tag-tree-render.test.tsx+++ b/web/tests/tag-tree-render.test.tsx@@ -1,29 +1,199 @@import { fireEvent, render, screen } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import TagTree from "@/components/TagTree";vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));+const storedExpansion = (scope = "home") => JSON.parse(localStorage.getItem(`tag-tree-expanded:${scope}`) ?? "null");+describe("TagTree rendering", () => {- it("shows every nested tag without disclosure icons", () => {- const onTagClick = vi.fn();- const { container } = render(+ beforeEach(() => {+ localStorage.clear();+ });++ it("starts collapsed and expands via the disclosure chevron", () => {+ render(<TagTreetagAmounts={[["a", 2],["a/b", 1],["getting-started", 1],]}- onTagClick={onTagClick}+ scope="home"+ onTagClick={vi.fn()}/>,);- expect(screen.getAllByRole("treeitem")).toHaveLength(3);+ expect(screen.getAllByRole("treeitem")).toHaveLength(2);+ expect(screen.queryByText("b")).not.toBeInTheDocument();++ const disclosure = screen.getByLabelText("common.expand #a");+ expect(disclosure).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(disclosure);expect(screen.getByText("b")).toBeVisible();- expect(container.querySelectorAll("svg.lucide-hash")).toHaveLength(3);- expect(container.querySelector("svg.lucide-chevron-right")).not.toBeInTheDocument();+ expect(storedExpansion().expanded).toEqual(["a"]);+ expect(screen.getByLabelText("common.collapse #a")).toHaveAttribute("aria-expanded", "true");+ fireEvent.click(screen.getByLabelText("common.collapse #a"));+ expect(screen.queryByText("b")).not.toBeInTheDocument();+ });++ it("filters on the full path when a nested tag is clicked", () => {+ const onTagClick = vi.fn();+ render(+ <TagTree+ tagAmounts={[+ ["a", 2],+ ["a/b", 1],+ ]}+ scope="home"+ onTagClick={onTagClick}+ />,+ );++ fireEvent.click(screen.getByLabelText("common.expand #a"));fireEvent.click(screen.getByText("b").closest("button") as HTMLButtonElement);expect(onTagClick).toHaveBeenCalledWith("a/b");});++ it("filters on tag label click without toggling the branch", () => {+ const onTagClick = vi.fn();+ render(+ <TagTree+ tagAmounts={[+ ["a", 2],+ ["a/b", 1],+ ]}+ scope="home"+ onTagClick={onTagClick}+ />,+ );++ fireEvent.click(screen.getByText("a").closest("button") as HTMLButtonElement);+ expect(onTagClick).toHaveBeenCalledWith("a");+ expect(screen.queryByText("b")).not.toBeInTheDocument();+ });++ it("gives a structural row one control that both labels and toggles it", () => {+ render(<TagTree tagAmounts={[["personal/travel/singapore", 1]]} scope="home" onTagClick={vi.fn()} />);++ // The row is the disclosure, so it is the only tab stop on that line.+ const personalDisclosure = screen.getByLabelText(/common\.(expand|collapse) personal$/);+ expect(personalDisclosure).toHaveAttribute("aria-expanded", "false");++ fireEvent.click(personalDisclosure);+ expect(screen.getByText("travel")).toBeVisible();+ expect(screen.getByLabelText("common.collapse personal")).toHaveAttribute("aria-expanded", "true");++ fireEvent.click(screen.getByText("travel").closest("button") as HTMLButtonElement);+ expect(screen.getByText("singapore")).toBeVisible();+ });++ it("reveals the ancestors of the active tag", () => {+ render(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b/c", 1],+ ]}+ activeTag="a/b/c"+ scope="home"+ onTagClick={vi.fn()}+ />,+ );++ expect(screen.getByText("c")).toBeVisible();+ expect(screen.getByText("c").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");+ });++ it("keeps a deliberate collapse across remounts while the filter stays active", () => {+ const tree = (+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ activeTag="a/b"+ scope="home"+ onTagClick={vi.fn()}+ />+ );+ const { unmount } = render(tree);++ fireEvent.click(screen.getByLabelText("common.collapse #a"));+ expect(screen.queryByText("b")).not.toBeInTheDocument();+ unmount();++ // The mobile sheet unmounts the sidebar on close, so the reveal effect runs again on reopen.+ render(tree);+ expect(screen.queryByText("b")).not.toBeInTheDocument();+ });++ it("reveals again when the same tag is re-selected after clearing the filter", () => {+ const { rerender } = render(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ activeTag="a/b"+ scope="home"+ onTagClick={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByLabelText("common.collapse #a"));++ rerender(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ scope="home"+ onTagClick={vi.fn()}+ />,+ );+ rerender(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ activeTag="a/b"+ scope="home"+ onTagClick={vi.fn()}+ />,+ );++ expect(screen.getByText("b")).toBeVisible();+ });++ it("keeps expansion state separate per scope", () => {+ const { unmount } = render(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ scope="users/alice"+ onTagClick={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByLabelText("common.expand #a"));+ expect(screen.getByText("b")).toBeVisible();+ unmount();++ render(+ <TagTree+ tagAmounts={[+ ["a", 1],+ ["a/b", 1],+ ]}+ scope="users/bob"+ onTagClick={vi.fn()}+ />,+ );+ expect(screen.queryByText("b")).not.toBeInTheDocument();+ expect(storedExpansion("users/alice").expanded).toEqual(["a"]);+ });});