fix(web): restore sidebar and outline behavior (#6161)

This commit is contained in:
Johnny 2026-08-08 08:58:07 +08:00 committed by GitHub
parent e5ed6e7ec6
commit f75d49f9b6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
64 changed files with 689 additions and 166 deletions

View file

@ -47,9 +47,9 @@
"mdast-util-from-markdown": "^2.0.3", "mdast-util-from-markdown": "^2.0.3",
"mdast-util-gfm": "^3.1.0", "mdast-util-gfm": "^3.1.0",
"mermaid": "^11.14.0", "mermaid": "^11.14.0",
"micromark-extension-gfm": "^3.0.0",
"micromark-util-decode-string": "^2.0.1", "micromark-util-decode-string": "^2.0.1",
"micromark-util-normalize-identifier": "^2.0.1", "micromark-util-normalize-identifier": "^2.0.1",
"micromark-extension-gfm": "^3.0.0",
"react": "^19.2.6", "react": "^19.2.6",
"react-dom": "^19.2.6", "react-dom": "^19.2.6",
"react-hot-toast": "^2.6.0", "react-hot-toast": "^2.6.0",
@ -64,8 +64,11 @@
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"remark-math": "^6.0.0", "remark-math": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"tailwind-merge": "^3.5.0", "tailwind-merge": "^3.5.0",
"tailwindcss": "^4.2.4", "tailwindcss": "^4.2.4",
"unified": "^11.0.5",
"unist-util-visit": "^5.1.0" "unist-util-visit": "^5.1.0"
}, },
"devDependencies": { "devDependencies": {

View file

@ -152,12 +152,21 @@ importers:
remark-math: remark-math:
specifier: ^6.0.0 specifier: ^6.0.0
version: 6.0.0 version: 6.0.0
remark-parse:
specifier: ^11.0.0
version: 11.0.0
remark-rehype:
specifier: ^11.1.2
version: 11.1.2
tailwind-merge: tailwind-merge:
specifier: ^3.5.0 specifier: ^3.5.0
version: 3.5.0 version: 3.5.0
tailwindcss: tailwindcss:
specifier: ^4.2.4 specifier: ^4.2.4
version: 4.2.4 version: 4.2.4
unified:
specifier: ^11.0.5
version: 11.0.5
unist-util-visit: unist-util-visit:
specifier: ^5.1.0 specifier: ^5.1.0
version: 5.1.0 version: 5.1.0

View file

@ -249,7 +249,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =>
<StatisticsView statisticsData={statistics} navigationTarget={filterTarget} onDateSelect={() => setMobileOpen(false)} /> <StatisticsView statisticsData={statistics} navigationTarget={filterTarget} onDateSelect={() => setMobileOpen(false)} />
</section> </section>
{showViews && <ViewsSection />} {showViews && <ViewsSection />}
<TagsSection tagCount={tags} navigationTarget={filterTarget} onSelect={() => setMobileOpen(false)} /> <TagsSection tagCount={tags} navigationTarget={filterTarget} scope={statsUserName ?? context} onSelect={() => setMobileOpen(false)} />
</div> </div>
); );
}; };

View file

@ -15,6 +15,8 @@ interface Props {
onSelect?: () => void; onSelect?: () => void;
/** When set, tag clicks land on this route with the tag filter instead of filtering the current one. */ /** When set, tag clicks land on this route with the tag filter instead of filtering the current one. */
navigationTarget?: string; 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) => { 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 t = useTranslate();
const navigate = useNavigate(); const navigate = useNavigate();
const { filters, setFilters, getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext(); const { filters, setFilters, getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext();
@ -123,7 +125,7 @@ const TagsSection = ({ tagCount, onSelect, navigationTarget }: Props) => {
</span> </span>
</SidebarSectionHeader> </SidebarSectionHeader>
{treeMode ? ( {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"> <div className="space-y-0.5">
{tags.map(([tag, amount]) => ( {tags.map(([tag, amount]) => (

View file

@ -241,7 +241,9 @@ function FormField({
children: ReactNode; children: ReactNode;
}) { }) {
return ( 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>
{label} {label}
{required ? <span className="text-destructive">*</span> : null} {required ? <span className="text-destructive">*</span> : null}

View file

@ -2,19 +2,10 @@ import type { Element } from "hast";
import { type ComponentProps, memo, type ReactNode, Suspense } from "react"; import { type ComponentProps, memo, type ReactNode, Suspense } from "react";
import type { Components } from "react-markdown"; import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw"; import { buildRehypePlugins, buildRemarkPlugins } from "@/components/MemoContent/pipeline";
import rehypeSanitize from "rehype-sanitize";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown"; import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown";
import { lazyWithReload } from "@/utils/lazy"; 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 { CodeBlock } from "./CodeBlock";
import { SANITIZE_SCHEMA } from "./constants";
import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext"; import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext";
import { Mention } from "./Mention"; import { Mention } from "./Mention";
import { AnchorLink, Blockquote, Heading, HorizontalRule, Image, InlineCode, Link, List, ListItem, Paragraph } from "./markdown"; import { AnchorLink, Blockquote, Heading, HorizontalRule, Image, InlineCode, Link, List, ListItem, Paragraph } from "./markdown";
@ -159,16 +150,8 @@ export const MemoMarkdownRendererCore = ({
return ( return (
<MarkdownRenderContext.Provider value={rootMarkdownRenderContext}> <MarkdownRenderContext.Provider value={rootMarkdownRenderContext}>
<ReactMarkdown <ReactMarkdown
remarkPlugins={[ remarkPlugins={buildRemarkPlugins(mathRemarkPlugins)}
remarkDisableSetext, rehypePlugins={buildRehypePlugins(mathRehypePlugins)}
...mathRemarkPlugins,
remarkGfm,
remarkSplitMixedTaskLists,
remarkMemoSyntax,
remarkBreaks,
remarkPreserveType,
]}
rehypePlugins={[rehypeRaw, [rehypeSanitize, SANITIZE_SCHEMA], rehypeHeadingId, ...mathRehypePlugins]}
components={markdownComponents} components={markdownComponents}
> >
{content} {content}

View file

@ -16,6 +16,7 @@ const MemoContent = (props: MemoContentProps) => {
<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}> <div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
<div <div
data-memo-content data-memo-content
data-memo-name={props.memoName}
className={cn( className={cn(
"relative w-full max-w-full wrap-break-word text-base leading-6", "relative w-full max-w-full wrap-break-word text-base leading-6",
"[&>*:last-child]:mb-0", "[&>*:last-child]:mb-0",

View file

@ -1,6 +1,7 @@
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { markdownStyles } from "@/lib/markdownStyles"; import { markdownStyles } from "@/lib/markdownStyles";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { findAnchorTarget } from "@/utils/markdown-manipulation";
import type { ReactMarkdownProps } from "./types"; import type { ReactMarkdownProps } from "./types";
interface AnchorLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement>, ReactMarkdownProps { 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 // Scope the lookup to this memo's own container so duplicate footnote ids elsewhere in a feed
// can't steal the scroll. // can't steal the scroll.
const root = event.currentTarget.closest("[data-memo-content]"); const root = event.currentTarget.closest("[data-memo-content]");
const target = root?.querySelector(`#${CSS.escape(id)}`); const target = root && findAnchorTarget(root, id);
if (target) { if (target) {
event.preventDefault(); event.preventDefault();
target.scrollIntoView({ behavior: "smooth", block: "center" }); target.scrollIntoView({ behavior: "smooth", block: "center" });

View file

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

View file

@ -5,6 +5,7 @@ import toast from "react-hot-toast";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "@/components/AppSidebar/SidebarRow"; import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "@/components/AppSidebar/SidebarRow";
import SidebarSectionHeader from "@/components/AppSidebar/SidebarSectionHeader"; import SidebarSectionHeader from "@/components/AppSidebar/SidebarSectionHeader";
import { extractHeadings } from "@/components/MemoContent/pipeline";
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers"; import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos"; import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; 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 { State } from "@/types/proto/api/v1/common_pb";
import { Memo, type MemoRelation } from "@/types/proto/api/v1/memo_service_pb"; import { Memo, type MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n"; import { useTranslate } from "@/utils/i18n";
import { extractHeadings } from "@/utils/markdown-manipulation";
import { isSuperUser } from "@/utils/user"; import { isSuperUser } from "@/utils/user";
import MemoOutline from "./MemoOutline"; import MemoOutline from "./MemoOutline";
import MemoSharePanel from "./MemoSharePanel"; import MemoSharePanel from "./MemoSharePanel";
@ -31,7 +31,9 @@ interface Props {
const Section = ({ label, children }: { label: string; children: React.ReactNode }) => ( const Section = ({ label, children }: { label: string; children: React.ReactNode }) => (
<section className="w-full"> <section className="w-full">
<SidebarSectionHeader>{label}</SidebarSectionHeader> <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> </section>
); );
@ -145,7 +147,7 @@ const MemoDetailSidebar = ({ memo, className, onShareImageOpen, forceReadonly =
{headings.length > 1 && ( {headings.length > 1 && (
<Section label={t("memo.outline")}> <Section label={t("memo.outline")}>
<MemoOutline headings={headings} /> <MemoOutline headings={headings} memoName={memo.name} />
</Section> </Section>
)} )}

View file

@ -1,16 +1,18 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import type { HeadingItem } from "@/components/MemoContent/pipeline";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { HeadingItem } from "@/utils/markdown-manipulation"; import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";
interface MemoOutlineProps { interface MemoOutlineProps {
headings: HeadingItem[]; headings: HeadingItem[];
memoName: string;
} }
/** Distance from the viewport top of the "reading line" used to decide the active section. */ /** Distance from the viewport top of the "reading line" used to decide the active section. */
const READING_LINE_OFFSET = 100; const READING_LINE_OFFSET = 100;
/** Outline navigation for memo headings (h1–h4) with active-section tracking. */ /** 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 [activeSlug, setActiveSlug] = useState<string | null>(null);
const rafRef = useRef(0); const rafRef = useRef(0);
@ -20,8 +22,10 @@ const MemoOutline = ({ headings }: MemoOutlineProps) => {
const update = () => { const update = () => {
rafRef.current = 0; rafRef.current = 0;
let current: string | null = null; let current: string | null = null;
const memoContent = findMemoContentRoot(document, memoName);
if (!memoContent) return;
for (const heading of headings) { for (const heading of headings) {
const el = document.getElementById(heading.slug); const el = findAnchorTarget(memoContent, heading.slug);
if (!el) continue; if (!el) continue;
if (el.getBoundingClientRect().top > READING_LINE_OFFSET) break; if (el.getBoundingClientRect().top > READING_LINE_OFFSET) break;
current = heading.slug; current = heading.slug;
@ -44,11 +48,12 @@ const MemoOutline = ({ headings }: MemoOutlineProps) => {
cancelAnimationFrame(rafRef.current); cancelAnimationFrame(rafRef.current);
} }
}; };
}, [headings]); }, [headings, memoName]);
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, slug: string) => { const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, slug: string) => {
e.preventDefault(); e.preventDefault();
const el = document.getElementById(slug); const memoContent = findMemoContentRoot(document, memoName);
const el = memoContent && findAnchorTarget(memoContent, slug);
if (el) { if (el) {
setActiveSlug(slug); setActiveSlug(slug);
el.scrollIntoView({ behavior: "smooth", block: "start" }); el.scrollIntoView({ behavior: "smooth", block: "start" });

View file

@ -1,5 +1,5 @@
import { HashIcon } from "lucide-react"; import { ChevronRightIcon, HashIcon } from "lucide-react";
import { useMemo } from "react"; import { useEffect, useMemo } from "react";
import { import {
SIDEBAR_ROW_BOX_CLASSES, SIDEBAR_ROW_BOX_CLASSES,
SIDEBAR_ROW_COUNT_CLASSES, SIDEBAR_ROW_COUNT_CLASSES,
@ -7,7 +7,7 @@ import {
SIDEBAR_ROW_ICON_CLASSES, SIDEBAR_ROW_ICON_CLASSES,
sidebarRowStateClasses, sidebarRowStateClasses,
} from "@/components/AppSidebar/SidebarRow"; } from "@/components/AppSidebar/SidebarRow";
import { useOverflowTitle } from "@/hooks"; import { useLocalStorage, useOverflowTitle } from "@/hooks";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n"; import { useTranslate } from "@/utils/i18n";
@ -24,9 +24,19 @@ interface TagTreeNode {
interface Props { interface Props {
tagAmounts: [tag: string, amount: number][]; tagAmounts: [tag: string, amount: number][];
activeTag?: string; activeTag?: string;
/** Identifies whose tags these are, so expansion persists per tenant rather than per browser. */
scope: string;
onTagClick: (tag: string) => void; 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][]) => { export const buildTagTree = (tagAmounts: [tag: string, amount: number][]) => {
const root: TagTreeNode = { const root: TagTreeNode = {
key: "", key: "",
@ -62,20 +72,37 @@ export const buildTagTree = (tagAmounts: [tag: string, amount: number][]) => {
return root.subTags; 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 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 { interface TagItemProps {
tag: TagTreeNode; tag: TagTreeNode;
depth: number; depth: number;
activeTag?: string; activeTag?: string;
expanded: ReadonlySet<string>;
onTagClick: (tag: string) => void; 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 isTag = tag.amount !== undefined;
const isActive = activeTag === tag.text; const isActive = activeTag === tag.text;
const isAncestorOfActiveTag = activeTag?.startsWith(`${tag.text}/`) ?? false; const isAncestorOfActiveTag = activeTag?.startsWith(`${tag.text}/`) ?? false;
const hasSubTags = tag.subTags.length > 0; const hasSubTags = tag.subTags.length > 0;
const open = hasSubTags && expanded.has(tag.text);
const { ref: labelRef, title } = useOverflowTitle<HTMLSpanElement>(isTag ? `#${tag.text}` : tag.text); const { ref: labelRef, title } = useOverflowTitle<HTMLSpanElement>(isTag ? `#${tag.text}` : tag.text);
return ( return (
@ -84,6 +111,7 @@ const TagItem = ({ tag, depth, activeTag, onTagClick }: TagItemProps) => {
role="treeitem" role="treeitem"
aria-level={depth + 1} aria-level={depth + 1}
aria-selected={isActive || undefined} aria-selected={isActive || undefined}
aria-expanded={hasSubTags ? open : undefined}
className={cn( className={cn(
SIDEBAR_ROW_BOX_CLASSES, SIDEBAR_ROW_BOX_CLASSES,
isTag ? sidebarRowStateClasses(isActive) : "font-medium text-muted-foreground/65", 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> <span className={SIDEBAR_ROW_COUNT_CLASSES}>{tag.amount}</span>
</button> </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. // 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}> <button
{tag.key} type="button"
</span> 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> </div>
{hasSubTags && ( {open && (
<div className="mt-0.5 flex w-full min-w-0 flex-col gap-0.5" role="group"> <div className="mt-0.5 flex w-full min-w-0 flex-col gap-0.5" role="group">
{tag.subTags.map((subTag) => ( {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> </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 t = useTranslate();
const tags = useMemo(() => buildTagTree(tagAmounts), [tagAmounts]); 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 ( return (
<div className="relative flex h-auto w-full flex-col items-stretch gap-0.5" role="tree" aria-label={t("common.tags")}> <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) => ( {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> </div>
); );

View file

@ -85,7 +85,7 @@ const UserMenu = (props: Props) => {
try { try {
// Then clear user-specific localStorage items // Then clear user-specific localStorage items
// Preserve app-wide settings (theme, locale, view preferences, tag view settings) // 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[] = []; const keysToRemove: string[] = [];
for (let i = 0; i < localStorage.length; i++) { for (let i = 0; i < localStorage.length; i++) {

View file

@ -1,5 +1,11 @@
// Shared enter/exit motion for popup surfaces (dropdown menu, popover, tooltip), driven by // 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 // 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. // 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 = 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"; "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";

View file

@ -23,7 +23,6 @@
"archive": "الأرشيف", "archive": "الأرشيف",
"archived": "المؤرشفة", "archived": "المؤرشفة",
"attachments": "مرفقات", "attachments": "مرفقات",
"auto-expand": "توسيع تلقائي",
"avatar": "الصورة الشخصية", "avatar": "الصورة الشخصية",
"basic": "بسيط", "basic": "بسيط",
"beta": "تجريبي", "beta": "تجريبي",

View file

@ -61,7 +61,6 @@
"archive": "Архив", "archive": "Архив",
"archived": "Архивирано", "archived": "Архивирано",
"attachments": "Прикачени файлове", "attachments": "Прикачени файлове",
"auto-expand": "Автоматично разширяване",
"avatar": "Аватар", "avatar": "Аватар",
"basic": "Основен", "basic": "Основен",
"beta": "Бета", "beta": "Бета",

View file

@ -24,7 +24,6 @@
"archive": "Arxivar", "archive": "Arxivar",
"archived": "Arxivat", "archived": "Arxivat",
"attachments": "Adjunts", "attachments": "Adjunts",
"auto-expand": "Expansió automàtica",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Bàsic", "basic": "Bàsic",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archivovat", "archive": "Archivovat",
"archived": "Archivované", "archived": "Archivované",
"attachments": "Přílohy", "attachments": "Přílohy",
"auto-expand": "Automaticky rozbalit",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Základní", "basic": "Základní",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Arkiv", "archive": "Arkiv",
"archived": "Arkiveret", "archived": "Arkiveret",
"attachments": "Vedhæftede filer", "attachments": "Vedhæftede filer",
"auto-expand": "Automatisk udvidelse",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Grundlæggende", "basic": "Grundlæggende",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archivieren", "archive": "Archivieren",
"archived": "Archiviert", "archived": "Archiviert",
"attachments": "Anhänge", "attachments": "Anhänge",
"auto-expand": "Automatisch erweitern",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Allgemeines", "basic": "Allgemeines",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Αρχείο", "archive": "Αρχείο",
"archived": "Αρχειοθετήθηκε", "archived": "Αρχειοθετήθηκε",
"attachments": "Συνημμένα", "attachments": "Συνημμένα",
"auto-expand": "Αυτόματη επέκταση",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Βασικός", "basic": "Βασικός",
"beta": "Βήτα", "beta": "Βήτα",

View file

@ -24,7 +24,6 @@
"archive": "Archive", "archive": "Archive",
"archived": "Archived", "archived": "Archived",
"attachments": "Attachments", "attachments": "Attachments",
"auto-expand": "Auto expand",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Basic", "basic": "Basic",
"beta": "Beta", "beta": "Beta",

View file

@ -96,7 +96,6 @@
"archived": "Archived", "archived": "Archived",
"attachments": "Attachments", "attachments": "Attachments",
"author": "Author", "author": "Author",
"auto-expand": "Auto expand",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Basic", "basic": "Basic",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archivar", "archive": "Archivar",
"archived": "Archivado", "archived": "Archivado",
"attachments": "Adjuntos", "attachments": "Adjuntos",
"auto-expand": "Auto expandir",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Básico", "basic": "Básico",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Arhiiv", "archive": "Arhiiv",
"archived": "Arhiveeritud", "archived": "Arhiveeritud",
"attachments": "Manused", "attachments": "Manused",
"auto-expand": "Automaatne laiendamine",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Põhiline", "basic": "Põhiline",
"beta": "Beeta", "beta": "Beeta",

View file

@ -23,7 +23,6 @@
"archive": "آرشیو", "archive": "آرشیو",
"archived": "آرشیو شده", "archived": "آرشیو شده",
"attachments": "پیوست‌ها", "attachments": "پیوست‌ها",
"auto-expand": "گسترش خودکار",
"avatar": "آواتار", "avatar": "آواتار",
"basic": "ساده", "basic": "ساده",
"beta": "بتا", "beta": "بتا",

View file

@ -61,7 +61,6 @@
"archive": "Arkisto", "archive": "Arkisto",
"archived": "Arkistoitu", "archived": "Arkistoitu",
"attachments": "Liitteet", "attachments": "Liitteet",
"auto-expand": "Automaattinen laajennus",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Perus", "basic": "Perus",
"beta": "Beeta", "beta": "Beeta",

View file

@ -24,7 +24,6 @@
"archive": "Archiver", "archive": "Archiver",
"archived": "Archivé", "archived": "Archivé",
"attachments": "Pièces jointes", "attachments": "Pièces jointes",
"auto-expand": "Déplier automatiquement",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Basique", "basic": "Basique",
"beta": "Bêta", "beta": "Bêta",

View file

@ -24,7 +24,6 @@
"archive": "Arquivo", "archive": "Arquivo",
"archived": "Arquivada", "archived": "Arquivada",
"attachments": "Anexos", "attachments": "Anexos",
"auto-expand": "Depregar Auto",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Básico", "basic": "Básico",
"beta": "Beta", "beta": "Beta",

View file

@ -23,7 +23,6 @@
"archive": "संग्रहीत करें", "archive": "संग्रहीत करें",
"archived": "संग्रहीत", "archived": "संग्रहीत",
"attachments": "संलग्नक", "attachments": "संलग्नक",
"auto-expand": "स्वतः विस्तार",
"avatar": "अवतार", "avatar": "अवतार",
"basic": "मूल", "basic": "मूल",
"beta": "बीटा", "beta": "बीटा",

View file

@ -24,7 +24,6 @@
"archive": "Arhiviraj", "archive": "Arhiviraj",
"archived": "Arhivirano", "archived": "Arhivirano",
"attachments": "Privici", "attachments": "Privici",
"auto-expand": "Automatski proširi",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Osnovno", "basic": "Osnovno",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archiválás", "archive": "Archiválás",
"archived": "Archívum", "archived": "Archívum",
"attachments": "Mellékletek", "attachments": "Mellékletek",
"auto-expand": "Automatikus kinyitás",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Általános", "basic": "Általános",
"beta": "Béta", "beta": "Béta",

View file

@ -23,7 +23,6 @@
"archive": "Arsip", "archive": "Arsip",
"archived": "Diarsipkan", "archived": "Diarsipkan",
"attachments": "Lampiran", "attachments": "Lampiran",
"auto-expand": "Perluas otomatis",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Dasar", "basic": "Dasar",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archivia", "archive": "Archivia",
"archived": "Archiviati", "archived": "Archiviati",
"attachments": "Allegati", "attachments": "Allegati",
"auto-expand": "Espandi automaticamente",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Base", "basic": "Base",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "アーカイブにする", "archive": "アーカイブにする",
"archived": "アーカイブ済み", "archived": "アーカイブ済み",
"attachments": "添付ファイル", "attachments": "添付ファイル",
"auto-expand": "自動展開",
"avatar": "アイコン", "avatar": "アイコン",
"basic": "基本設定", "basic": "基本設定",
"beta": "ベータ", "beta": "ベータ",

View file

@ -24,7 +24,6 @@
"archive": "არქივი", "archive": "არქივი",
"archived": "დაარქივებული", "archived": "დაარქივებული",
"attachments": "დანართები", "attachments": "დანართები",
"auto-expand": "ავტომატური გაფართოება",
"avatar": "ავატარი", "avatar": "ავატარი",
"basic": "ძირითადი", "basic": "ძირითადი",
"beta": "ბეტა", "beta": "ბეტა",

View file

@ -23,7 +23,6 @@
"archive": "보관 처리", "archive": "보관 처리",
"archived": "보관 목록", "archived": "보관 목록",
"attachments": "첨부파일", "attachments": "첨부파일",
"auto-expand": "자동 펼치기",
"avatar": "아바타", "avatar": "아바타",
"basic": "기본", "basic": "기본",
"beta": "베타", "beta": "베타",

View file

@ -61,7 +61,6 @@
"archive": "Archyvas", "archive": "Archyvas",
"archived": "Suarchyvuota", "archived": "Suarchyvuota",
"attachments": "Priedai", "attachments": "Priedai",
"auto-expand": "Automatiškai išplėsti",
"avatar": "Avataras", "avatar": "Avataras",
"basic": "Pagrindinis", "basic": "Pagrindinis",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Arhīvs", "archive": "Arhīvs",
"archived": "Arhivēts", "archived": "Arhivēts",
"attachments": "Pielikumi", "attachments": "Pielikumi",
"auto-expand": "Automātiski izvērst",
"avatar": "Iemiesojums", "avatar": "Iemiesojums",
"basic": "Pamata", "basic": "Pamata",
"beta": "Beta", "beta": "Beta",

View file

@ -23,7 +23,6 @@
"archive": "संग्रहण", "archive": "संग्रहण",
"archived": "संग्रहित", "archived": "संग्रहित",
"attachments": "संलग्नक", "attachments": "संलग्नक",
"auto-expand": "स्वयं विस्तार",
"avatar": "अवतार", "avatar": "अवतार",
"basic": "मूलभूत", "basic": "मूलभूत",
"beta": "बीटा", "beta": "बीटा",

View file

@ -24,7 +24,6 @@
"archive": "Arkiver", "archive": "Arkiver",
"archived": "Arkivert", "archived": "Arkivert",
"attachments": "Vedlegg", "attachments": "Vedlegg",
"auto-expand": "Ekspander automatisk",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Grunnleggende", "basic": "Grunnleggende",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archiveren", "archive": "Archiveren",
"archived": "Gearchiveerd", "archived": "Gearchiveerd",
"attachments": "Bijlagen", "attachments": "Bijlagen",
"auto-expand": "Auto uitklappen",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Simpel", "basic": "Simpel",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Archiwum", "archive": "Archiwum",
"archived": "Zarchiwizowane", "archived": "Zarchiwizowane",
"attachments": "Załączniki", "attachments": "Załączniki",
"auto-expand": "Rozwiń automatycznie",
"avatar": "Awatar", "avatar": "Awatar",
"basic": "Podstawowy", "basic": "Podstawowy",
"beta": "Beta", "beta": "Beta",

View file

@ -23,7 +23,6 @@
"archive": "Arquivar", "archive": "Arquivar",
"archived": "Arquivo", "archived": "Arquivo",
"attachments": "Anexos", "attachments": "Anexos",
"auto-expand": "Expandir automaticamente",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Básico", "basic": "Básico",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Arquivar", "archive": "Arquivar",
"archived": "Arquivado", "archived": "Arquivado",
"attachments": "Anexos", "attachments": "Anexos",
"auto-expand": "Expandir automaticamente",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Básico", "basic": "Básico",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Arhivă", "archive": "Arhivă",
"archived": "Arhivat", "archived": "Arhivat",
"attachments": "Atasamente", "attachments": "Atasamente",
"auto-expand": "Extindere automată",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "De bază", "basic": "De bază",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Архивировать", "archive": "Архивировать",
"archived": "Архив", "archived": "Архив",
"attachments": "Файлы", "attachments": "Файлы",
"auto-expand": "Авто-раскрытие",
"avatar": "Аватар", "avatar": "Аватар",
"basic": "Базовые", "basic": "Базовые",
"beta": "Бета", "beta": "Бета",

View file

@ -61,7 +61,6 @@
"archive": "Archív", "archive": "Archív",
"archived": "Archivované", "archived": "Archivované",
"attachments": "Prílohy", "attachments": "Prílohy",
"auto-expand": "Automatické rozšírenie",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Základné", "basic": "Základné",
"beta": "Beta", "beta": "Beta",

View file

@ -24,7 +24,6 @@
"archive": "Arhiv", "archive": "Arhiv",
"archived": "Arhivirani", "archived": "Arhivirani",
"attachments": "Priloge", "attachments": "Priloge",
"auto-expand": "Samodejno razširi",
"avatar": "Avatar", "avatar": "Avatar",
"basic": "Osnovni", "basic": "Osnovni",
"beta": "Beta", "beta": "Beta",

View file

@ -61,7 +61,6 @@
"archive": "Архива", "archive": "Архива",
"archived": "Архивирано", "archived": "Архивирано",
"attachments": "Прилози", "attachments": "Прилози",
"auto-expand": "Аутоматско проширење",
"avatar": "Аватар", "avatar": "Аватар",
"basic": "Басиц", "basic": "Басиц",
"beta": "Бета", "beta": "Бета",

View file

@ -24,7 +24,6 @@
"archive": "Arkivera", "archive": "Arkivera",
"archived": "Arkiverad", "archived": "Arkiverad",
"attachments": "Bilagor", "attachments": "Bilagor",
"auto-expand": "Autoexpandera",
"avatar": "Profilbild", "avatar": "Profilbild",
"basic": "Grundläggande", "basic": "Grundläggande",
"beta": "Beta", "beta": "Beta",

View file

@ -23,7 +23,6 @@
"archive": "เก็บถาวร", "archive": "เก็บถาวร",
"archived": "เก็บถาวรแล้ว", "archived": "เก็บถาวรแล้ว",
"attachments": "ไฟล์แนบ", "attachments": "ไฟล์แนบ",
"auto-expand": "ขยายอัตโนมัติ",
"avatar": "สัญลักษณ์", "avatar": "สัญลักษณ์",
"basic": "ทั่วไป", "basic": "ทั่วไป",
"beta": "รุ่นเบต้า", "beta": "รุ่นเบต้า",

View file

@ -24,7 +24,6 @@
"archive": "Arşiv", "archive": "Arşiv",
"archived": "Arşivlendi", "archived": "Arşivlendi",
"attachments": "Ekler", "attachments": "Ekler",
"auto-expand": "Otomatik genişlet",
"avatar": "Profil Resmi", "avatar": "Profil Resmi",
"basic": "Temel", "basic": "Temel",
"beta": "Beta sürümü", "beta": "Beta sürümü",

View file

@ -24,7 +24,6 @@
"archive": "Архів", "archive": "Архів",
"archived": "Архівовано", "archived": "Архівовано",
"attachments": "Вкладення", "attachments": "Вкладення",
"auto-expand": "Авторозгортання",
"avatar": "Аватар", "avatar": "Аватар",
"basic": "Основний", "basic": "Основний",
"beta": "Бета-версія", "beta": "Бета-версія",

View file

@ -23,7 +23,6 @@
"archive": "Lưu trữ", "archive": "Lưu trữ",
"archived": "Đã lưu trữ", "archived": "Đã lưu trữ",
"attachments": "Tệp đính kèm", "attachments": "Tệp đính kèm",
"auto-expand": "Mở rộng tự động",
"avatar": "Ảnh đại diện", "avatar": "Ảnh đại diện",
"basic": "Cơ bản", "basic": "Cơ bản",
"beta": "Beta", "beta": "Beta",

View file

@ -62,7 +62,6 @@
"archive": "归档", "archive": "归档",
"archived": "已归档", "archived": "已归档",
"attachments": "附件", "attachments": "附件",
"auto-expand": "自动展开",
"avatar": "头像", "avatar": "头像",
"basic": "基础", "basic": "基础",
"beta": "测试", "beta": "测试",

View file

@ -78,7 +78,6 @@
"archive": "封存", "archive": "封存",
"archived": "已封存", "archived": "已封存",
"attachments": "附件", "attachments": "附件",
"auto-expand": "自動展開",
"avatar": "頭像", "avatar": "頭像",
"basic": "基礎", "basic": "基礎",
"beta": "測試版", "beta": "測試版",

View file

@ -14,6 +14,7 @@ import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQue
import { memoNamePrefix } from "@/lib/resource-names"; import { memoNamePrefix } from "@/lib/resource-names";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb"; import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import type { Memo } from "@/types/proto/api/v1/memo_service_pb"; import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
import { findMemoAnchorTarget } from "@/utils/markdown-manipulation";
const MemoSidebarRegistration = ({ const MemoSidebarRegistration = ({
memo, memo,
@ -92,12 +93,14 @@ const MemoDetail = () => {
// ref guards against re-scrolling the same hash on every later comments page-load. // ref guards against re-scrolling the same hash on every later comments page-load.
const scrolledHashRef = useRef(""); const scrolledHashRef = useRef("");
useEffect(() => { useEffect(() => {
if (!hash || scrolledHashRef.current === hash) return; if (!hash) return;
const el = document.getElementById(decodeURIComponent(hash.slice(1))); const scrollKey = `${memoName}\0${hash}`;
if (scrolledHashRef.current === scrollKey) return;
const el = findMemoAnchorTarget(document, memoName, decodeURIComponent(hash.slice(1)));
if (!el) return; if (!el) return;
scrolledHashRef.current = hash; scrolledHashRef.current = scrollKey;
el.scrollIntoView({ behavior: "smooth", block: "center" }); el.scrollIntoView({ behavior: "smooth", block: "center" });
}, [hash, memo, comments]); }, [hash, memo, memoName, comments]);
if (isShareMode) { if (isShareMode) {
const isNotFound = error instanceof ConnectError && (error.code === Code.NotFound || error.code === Code.Unauthenticated); const isNotFound = error instanceof ConnectError && (error.code === Code.NotFound || error.code === Code.Unauthenticated);

View file

@ -1,7 +1,7 @@
// Utilities for manipulating markdown strings using AST parsing // Utilities for manipulating markdown strings using AST parsing
// Uses mdast for accurate task detection that properly handles code blocks // 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 { fromMarkdown } from "mdast-util-from-markdown";
import { gfmFromMarkdown } from "mdast-util-gfm"; import { gfmFromMarkdown } from "mdast-util-gfm";
import { gfm } from "micromark-extension-gfm"; import { gfm } from "micromark-extension-gfm";
@ -88,16 +88,28 @@ export interface TaskItem {
indentation: number; indentation: number;
} }
export interface HeadingItem { /**
text: string; * Slugify a string into a URL-friendly anchor ID. Keeps Unicode letters, digits and combining
level: 1 | 2 | 3 | 4; * marks, so non-Latin headings stay readable and scripts that write vowels as combining marks
slug: string; * (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 return text
.toLowerCase() .toLowerCase()
.trim() .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[] { export function findAnchorTarget(root: ParentNode, fragment: string): Element | null {
const tree = fromMarkdown(markdown, { if (!fragment) return null;
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()], const direct = root.querySelector(`#${CSS.escape(fragment)}`);
}); if (direct) return direct;
const headings: HeadingItem[] = [];
const slugCounts = new Map<string, number>(); 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;
visit(tree, "heading", (node: Heading) => { const count = slugCounts.get(baseSlug) ?? 0;
if (node.depth < 1 || node.depth > 4) return; slugCounts.set(baseSlug, count + 1);
const slug = count === 0 ? baseSlug : `${baseSlug}-${count}`;
const text = getNodeText(node as unknown as MdastNode); if (slug === fragment) return heading;
if (!text) return; }
return null;
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 });
});
return headings;
} }
interface MdastNode { /** Find the rendered content container for a specific memo resource. */
type?: string; export function findMemoContentRoot(root: ParentNode, memoName: string): Element | null {
value?: string; for (const memoContent of root.querySelectorAll("[data-memo-content]")) {
children?: MdastNode[]; if (memoContent.getAttribute("data-memo-name") === memoName) return memoContent;
}
return null;
} }
function getNodeText(node: MdastNode): string { /** Resolve a fragment inside one memo before falling back to page-level targets such as comments. */
if (node.type === "html") return ""; export function findMemoAnchorTarget(root: ParentNode, memoName: string, fragment: string): Element | null {
if (node.value) return node.value; const memoContent = findMemoContentRoot(root, memoName);
if (node.children) return node.children.map(getNodeText).join(""); return (memoContent && findAnchorTarget(memoContent, fragment)) ?? findAnchorTarget(root, fragment);
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[] { export function extractTasks(markdown: string): TaskItem[] {

View file

@ -1,37 +1,62 @@
import type { Element, Root } from "hast"; import type { Element, Root } from "hast";
import { visit } from "unist-util-visit"; 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 = ""; let text = "";
for (const child of node.children) { for (const child of node.children) {
if (child.type === "text") { if (child.type === "text") {
text += child.value; text += child.value;
} else if (child.type === "element") { } else if (child.type === "element") {
text += getTextContent(child); text += getHeadingText(child);
} }
} }
return text; 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 = () => { export const rehypeHeadingId = () => {
return (tree: Root) => { 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 (!isHeadingElement(node)) return;
const existingId = typeof node.properties?.id === "string" ? node.properties.id : "";
if (existingId) existingIds.add(existingId);
});
const makeUniqueSlug = createUniqueSlugGenerator(existingIds);
const claimedExistingIds = new Set<string>();
visit(tree, "element", (node: Element) => { visit(tree, "element", (node: Element) => {
if (!/^h[1-6]$/.test(node.tagName)) return; if (!isHeadingElement(node)) return;
const text = getTextContent(node);
let slug = slugify(text);
if (!slug) return;
const count = slugCounts.get(slug) || 0;
slugCounts.set(slug, count + 1);
if (count > 0) slug = `${slug}-${count}`;
node.properties = node.properties || {}; 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);
}
}); });
}; };
}; };

View file

@ -1,16 +1,43 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { extractHeadings } from "@/utils/markdown-manipulation"; import { findAnchorTarget, findMemoAnchorTarget, slugify } from "@/utils/markdown-manipulation";
describe("extractHeadings", () => { describe("slugify", () => {
it("uses rendered text for headings containing inline HTML", () => { it("keeps non-Latin headings addressable", () => {
const headings = extractHeadings(`# <ruby>連濁<rt>れんだく</rt></ruby>: "Why Hito-Bito isn't Hito-Hito"`); expect(slugify("連濁")).toBe("連濁");
});
expect(headings).toEqual([ it("keeps combining marks so Indic vowels survive", () => {
{ expect(slugify("हिन्दी")).toBe("हिन्दी");
text: `連濁れんだく: "Why Hito-Bito isn't Hito-Hito"`, });
level: 1,
slug: "why-hito-bito-isnt-hito-hito", 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);
}); });
}); });

View file

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

View file

@ -26,6 +26,7 @@ describe("sidebar row grammar", () => {
["a", 2], ["a", 2],
["a/b", 1], ["a/b", 1],
]} ]}
scope="home"
onTagClick={vi.fn()} onTagClick={vi.fn()}
/>, />,
); );
@ -42,6 +43,9 @@ describe("sidebar row grammar", () => {
["a", 2], ["a", 2],
["a/b", 1], ["a/b", 1],
]} ]}
// The active tag keeps the nested row expanded into view.
activeTag="a/b"
scope="home"
onTagClick={vi.fn()} onTagClick={vi.fn()}
/>, />,
); );

View file

@ -1,29 +1,199 @@
import { fireEvent, render, screen } from "@testing-library/react"; 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"; import TagTree from "@/components/TagTree";
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
const storedExpansion = (scope = "home") => JSON.parse(localStorage.getItem(`tag-tree-expanded:${scope}`) ?? "null");
describe("TagTree rendering", () => { describe("TagTree rendering", () => {
it("shows every nested tag without disclosure icons", () => { beforeEach(() => {
const onTagClick = vi.fn(); localStorage.clear();
const { container } = render( });
it("starts collapsed and expands via the disclosure chevron", () => {
render(
<TagTree <TagTree
tagAmounts={[ tagAmounts={[
["a", 2], ["a", 2],
["a/b", 1], ["a/b", 1],
["getting-started", 1], ["getting-started", 1],
]} ]}
scope="home"
onTagClick={vi.fn()}
/>,
);
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(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} onTagClick={onTagClick}
/>, />,
); );
expect(screen.getAllByRole("treeitem")).toHaveLength(3); fireEvent.click(screen.getByLabelText("common.expand #a"));
expect(screen.getByText("b")).toBeVisible();
expect(container.querySelectorAll("svg.lucide-hash")).toHaveLength(3);
expect(container.querySelector("svg.lucide-chevron-right")).not.toBeInTheDocument();
fireEvent.click(screen.getByText("b").closest("button") as HTMLButtonElement); fireEvent.click(screen.getByText("b").closest("button") as HTMLButtonElement);
expect(onTagClick).toHaveBeenCalledWith("a/b"); 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"]);
});
}); });