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

View file

@ -152,12 +152,21 @@ importers:
remark-math:
specifier: ^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:
specifier: ^3.5.0
version: 3.5.0
tailwindcss:
specifier: ^4.2.4
version: 4.2.4
unified:
specifier: ^11.0.5
version: 11.0.5
unist-util-visit:
specifier: ^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)} />
</section>
{showViews && <ViewsSection />}
<TagsSection tagCount={tags} navigationTarget={filterTarget} onSelect={() => setMobileOpen(false)} />
<TagsSection tagCount={tags} navigationTarget={filterTarget} scope={statsUserName ?? context} onSelect={() => setMobileOpen(false)} />
</div>
);
};

View file

@ -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]) => (

View file

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

View file

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

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
data-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",

View file

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

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

View file

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

View file

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

View file

@ -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++) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -14,6 +14,7 @@ import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQue
import { 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);

View file

@ -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()],
});
export function findAnchorTarget(root: ParentNode, fragment: string): Element | null {
if (!fragment) return null;
const direct = root.querySelector(`#${CSS.escape(fragment)}`);
if (direct) return direct;
const headings: HeadingItem[] = [];
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) => {
if (node.depth < 1 || node.depth > 4) return;
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 });
});
return headings;
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;
}
interface MdastNode {
type?: string;
value?: string;
children?: MdastNode[];
/** 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;
}
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 "";
/** 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);
}
/** 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[] {

View file

@ -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 (!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) => {
if (!/^h[1-6]$/.test(node.tagName)) 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}`;
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);
}
});
};
};

View file

@ -1,16 +1,43 @@
import { describe, expect, it } from "vitest";
import { extractHeadings } from "@/utils/markdown-manipulation";
import { findAnchorTarget, findMemoAnchorTarget, slugify } 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"`);
describe("slugify", () => {
it("keeps non-Latin headings addressable", () => {
expect(slugify("連濁")).toBe("連濁");
});
expect(headings).toEqual([
{
text: `連濁れんだく: "Why Hito-Bito isn't Hito-Hito"`,
level: 1,
slug: "why-hito-bito-isnt-hito-hito",
},
]);
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);
});
});

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/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()}
/>,
);

View file

@ -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(
<TagTree
tagAmounts={[
["a", 2],
["a/b", 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}
/>,
);
expect(screen.getAllByRole("treeitem")).toHaveLength(3);
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.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"]);
});
});