Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(reading): add persistent document outline

XZH1150fcecce0d
diff --git a/web/components/reading/ReaderOutline.tsx b/web/components/reading/ReaderOutline.tsx
new file mode 100644
index 000000000..2e40a96d7
--- /dev/null
+++ b/web/components/reading/ReaderOutline.tsx
@@ -0,0 +1,249 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { ChevronDown, ChevronRight, Search, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { OutlineRow } from "@/lib/reading-api";
+import {
+ buildOutlineTree,
+ filterOutlineNodes,
+ type OutlineNode,
+ type ReaderHeading,
+} from "@/lib/reading-outline";
+
+interface ReaderOutlineProps {
+ rows: OutlineRow[];
+ pageHeadings: ReaderHeading[];
+ activeHeadingId?: string | null;
+ currentLocator: number;
+ onNavigate: (locator: number) => void;
+ onNavigateHeading: (heading: ReaderHeading) => void;
+ onClose: () => void;
+}
+
+export function ReaderOutline({
+ rows,
+ pageHeadings,
+ activeHeadingId,
+ currentLocator,
+ onNavigate,
+ onNavigateHeading,
+ onClose,
+}: ReaderOutlineProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const [collapsedNodes, setCollapsedNodes] = useState<Set<string>>(new Set());
+ const activeOutlineRef = useRef<HTMLButtonElement | null>(null);
+ const activeHeadingRef = useRef<HTMLButtonElement | null>(null);
+
+ const tree = useMemo(() => buildOutlineTree(rows), [rows]);
+ const visibleTree = useMemo(() => filterOutlineTree(tree, query), [query, tree]);
+ const activeIndex = useMemo(() => {
+ let active = -1;
+ rows.forEach((row, index) => {
+ if (row.locator <= currentLocator) active = index;
+ });
+ return active;
+ }, [rows, currentLocator]);
+ const hasCollapsibleNodes = tree.some((node) => node.children.length > 0);
+
+ useEffect(() => {
+ activeOutlineRef.current?.scrollIntoView({ block: "nearest" });
+ }, [activeIndex]);
+ useEffect(() => {
+ activeHeadingRef.current?.scrollIntoView({ block: "nearest" });
+ }, [activeHeadingId]);
+
+ const setAllCollapsed = (collapsed: boolean) => {
+ setCollapsedNodes(collapsed ? new Set(collectCollapsibleKeys(tree)) : new Set());
+ };
+
+ return (
+ <aside
+ aria-label={t("Contents")}
+ className="dt-reader-scroll absolute inset-y-0 left-0 z-20 flex w-72 shrink-0 flex-col border-r border-[var(--border)] bg-[var(--card)]/95 backdrop-blur md:relative md:z-auto md:w-64 md:bg-[var(--card)]/45 md:backdrop-blur-none lg:w-[17rem]"
+ >
+ <div className="flex h-10 shrink-0 items-center justify-between gap-2 border-b border-[var(--border)] px-2">
+ <span className="text-[11px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Contents")}
+ </span>
+ <div className="flex items-center gap-1">
+ {hasCollapsibleNodes && (
+ <>
+ <button
+ type="button"
+ onClick={() => setAllCollapsed(false)}
+ className="rounded px-1 py-0.5 text-[10px] text-[var(--muted-foreground)] transition hover:text-[var(--foreground)]"
+ >
+ {t("Expand all")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setAllCollapsed(true)}
+ className="rounded px-1 py-0.5 text-[10px] text-[var(--muted-foreground)] transition hover:text-[var(--foreground)]"
+ >
+ {t("Collapse all")}
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t("Close outline")}
+ className="rounded p-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ </div>
+ <label className="flex h-9 shrink-0 items-center gap-1.5 border-b border-[var(--border)] px-2 text-[var(--muted-foreground)]">
+ <Search size={12} />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("Filter contents")}
+ className="min-w-0 flex-1 bg-transparent text-[11.5px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
+ />
+ </label>
+ <nav className="min-h-0 flex-1 overflow-y-auto px-1.5 py-2">
+ <OutlineBranch
+ nodes={visibleTree}
+ rows={rows}
+ activeIndex={activeIndex}
+ collapsedNodes={query ? new Set() : collapsedNodes}
+ onToggle={(key) =>
+ setCollapsedNodes((current) => {
+ const next = new Set(current);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ })
+ }
+ onNavigate={onNavigate}
+ activeOutlineRef={activeOutlineRef}
+ />
+ {pageHeadings.length > 0 && (
+ <section className="mt-3 border-t border-[var(--border)] pt-2">
+ <h3 className="px-1.5 pb-1 text-[10px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("On this page")}
+ </h3>
+ <ul className="space-y-0.5">
+ {pageHeadings.map((heading) => (
+ <li key={heading.id} className="min-w-0">
+ <button
+ type="button"
+ ref={activeHeadingId === heading.id ? activeHeadingRef : undefined}
+ onClick={() => onNavigateHeading(heading)}
+ style={{ marginLeft: (heading.level - 1) * 9 }}
+ className={`flex w-full items-center gap-1.5 rounded-md py-[6px] pl-1.5 pr-1 text-left transition hover:bg-[var(--muted)] ${
+ activeHeadingId === heading.id
+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"
+ : "text-[var(--foreground)]/85"
+ }`}
+ >
+ <span className="min-w-0 flex-1 truncate text-[12px] leading-5">
+ {heading.title}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+ </nav>
+ </aside>
+ );
+}
+
+function OutlineBranch({
+ nodes,
+ rows,
+ activeIndex,
+ collapsedNodes,
+ onToggle,
+ onNavigate,
+ activeOutlineRef,
+ depth = 0,
+}: {
+ nodes: OutlineNode[];
+ rows: OutlineRow[];
+ activeIndex: number;
+ collapsedNodes: Set<string>;
+ onToggle: (key: string) => void;
+ onNavigate: (locator: number) => void;
+ activeOutlineRef: RefObject<HTMLButtonElement | null>;
+ depth?: number;
+}) {
+ const { t } = useTranslation();
+ return (
+ <ul className={`space-y-0.5 ${depth === 0 ? "" : "mt-0.5 pl-1.5"}`}>
+ {nodes.map((node) => {
+ const key = `${node.row.locator}-${node.row.title}`;
+ const isActive = rows[activeIndex] === node.row;
+ const collapsed = collapsedNodes.has(key);
+ return (
+ <li key={key} className="min-w-0">
+ <div
+ className={`group/nav flex items-center gap-1 rounded-md pr-1 transition hover:bg-[var(--muted)] ${
+ isActive ? "bg-[var(--primary)]/10" : ""
+ }`}
+ style={{ marginLeft: depth === 0 ? 0 : 10 }}
+ >
+ <button
+ type="button"
+ onClick={() => onNavigate(node.row.locator)}
+ ref={isActive ? activeOutlineRef : undefined}
+ className={`flex min-w-0 flex-1 items-center gap-1.5 py-[6px] pl-1.5 text-left ${
+ depth === 0
+ ? "font-medium text-[var(--foreground)]"
+ : "text-[var(--foreground)]/85"
+ }`}
+ >
+ {depth > 0 && (
+ <span aria-hidden="true" className="h-4 w-px shrink-0 bg-[var(--border)]" />
+ )}
+ <span className="min-w-0 flex-1 truncate text-[12px] leading-5">
+ {node.row.title}
+ </span>
+ </button>
+ {node.children.length > 0 && (
+ <button
+ type="button"
+ onClick={() => onToggle(key)}
+ aria-expanded={!collapsed}
+ aria-label={collapsed ? t("Expand section") : t("Collapse section")}
+ className="shrink-0 rounded p-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {collapsed ? <ChevronRight size={11} /> : <ChevronDown size={11} />}
+ </button>
+ )}
+ </div>
+ {node.children.length > 0 && !collapsed && (
+ <OutlineBranch
+ nodes={node.children}
+ rows={rows}
+ activeIndex={activeIndex}
+ collapsedNodes={collapsedNodes}
+ onToggle={onToggle}
+ onNavigate={onNavigate}
+ activeOutlineRef={activeOutlineRef}
+ depth={depth + 1}
+ />
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+function filterOutlineTree(nodes: OutlineNode[], query: string): OutlineNode[] {
+ return filterOutlineNodes(nodes, query);
+}
+
+function collectCollapsibleKeys(nodes: OutlineNode[]): string[] {
+ return nodes.flatMap((node) => [
+ `${node.row.locator}-${node.row.title}`,
+ ...collectCollapsibleKeys(node.children),
+ ]);
+}
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 4646103c0..80628af8f 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -28,6 +28,7 @@ import { AnnotationList } from "./AnnotationList";
import { AnnotationPopover } from "./AnnotationPopover";
import { EpubDocumentView } from "./EpubDocumentView";
import { MaterialPicker } from "./MaterialPicker";
+import { ReaderOutline } from "./ReaderOutline";
import {
PdfDocumentView,
type JumpRequest,
@@ -36,6 +37,7 @@ import {
import { ReaderResizeHandle } from "./ReaderResizeHandle";
import { ReadingExtensionBar } from "./ReadingExtensionBar";
import { TextUnitView, unitLabel } from "./TextUnitView";
+import type { ReaderHeading } from "@/lib/reading-outline";
/** Event the reader dispatches to prefill the composer from a selection. */
export const READER_ASK_EVENT = "dt:reader-ask";
@@ -92,10 +94,15 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
// user decided, and that wins from then on.
const [annotationPanel, setAnnotationPanel] = useState<boolean | null>(null);
const [showOutline, setShowOutline] = useState(false);
+ const [outlineUserChoice, setOutlineUserChoice] = useState<boolean | null>(null);
const [autoJump, setAutoJump] = useState(true);
const [exporting, setExporting] = useState(false);
const [currentLocator, setCurrentLocator] = useState(1);
+ const [pageHeadings, setPageHeadings] = useState<ReaderHeading[]>([]);
+ const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
+ const [headingJump, setHeadingJump] = useState<{ id: string; nonce: number } | null>(null);
const nonceRef = useRef(0);
+ const headingNonceRef = useRef(0);
// -- persisted auto-jump preference --------------------------------------
@@ -108,6 +115,60 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
}
}, []);
+ useEffect(() => {
+ if (!material) {
+ setShowOutline(false);
+ setOutlineUserChoice(null);
+ setPageHeadings([]);
+ setActiveHeadingId(null);
+ setHeadingJump(null);
+ return;
+ }
+ try {
+ const stored = window.localStorage.getItem(`dt.reader.outline.${material.material_id}`);
+ setOutlineUserChoice(stored === null ? null : stored === "open");
+ } catch {
+ setOutlineUserChoice(null);
+ }
+ }, [material]);
+
+ useEffect(() => {
+ if (!material || outlineUserChoice !== null) return;
+ const desktop = window.matchMedia("(min-width: 768px)").matches;
+ setShowOutline(
+ desktop && ((material.outline?.length ?? 0) >= 8 || pageHeadings.length >= 3),
+ );
+ }, [material, outlineUserChoice, pageHeadings.length]);
+
+ const toggleOutline = useCallback(() => {
+ setShowOutline((current) => {
+ const next = !current;
+ setOutlineUserChoice(next);
+ if (material) {
+ try {
+ window.localStorage.setItem(
+ `dt.reader.outline.${material.material_id}`,
+ next ? "open" : "closed",
+ );
+ } catch {
+ // Storage can be unavailable in private mode; the choice still works here.
+ }
+ }
+ return next;
+ });
+ }, [material]);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "b") {
+ event.preventDefault();
+ toggleOutline();
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [toggleOutline]);
+
const toggleAutoJump = useCallback(() => {
setAutoJump((current) => {
const next = !current;
@@ -320,11 +381,29 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
(material?.outline ?? []).filter((row) => row.title.trim().length > 0),
[material],
);
+ const hasContents = outlineRows.length > 0 || pageHeadings.length > 0;
return (
<div className="relative flex h-full min-w-0 flex-col border-r border-[var(--border)] bg-[var(--background)]">
<ReaderResizeHandle />
<header className="flex h-11 shrink-0 items-center gap-1 border-b border-[var(--border)] px-2.5">
+ {material && hasContents && (
+ <button
+ type="button"
+ title={t("Contents")}
+ aria-label={t("Contents")}
+ aria-pressed={showOutline}
+ onClick={toggleOutline}
+ className={`mr-1 inline-flex h-7 shrink-0 items-center gap-1.5 rounded-lg px-2 text-[11.5px] font-medium transition ${
+ showOutline
+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <List size={14} />
+ <span className="hidden sm:inline">{t("Contents")}</span>
+ </button>
+ )}
<FileText
size={14}
className="shrink-0 text-[var(--muted-foreground)]"
@@ -341,14 +420,6 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
<span className="shrink-0 font-mono text-[10.5px] tabular-nums text-[var(--muted-foreground)]">
{unitWord} {currentLocator}/{material.unit_count}
</span>
- {outlineRows.length > 0 && (
- <HeaderButton
- icon={List}
- label={t("Outline")}
- active={showOutline}
- onClick={() => setShowOutline((open) => !open)}
- />
- )}
<HeaderButton
icon={Crosshair}
label={
@@ -417,34 +488,24 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
/>
)}
- {showOutline && material && outlineRows.length > 0 && (
- <nav className="dt-reader-scroll max-h-[34%] shrink-0 overflow-y-auto border-b border-[var(--border)] bg-[var(--muted)]/25 px-2 py-1.5">
- <ul>
- {outlineRows.map((row, index) => (
- <li key={`${row.locator}-${index}`}>
- <button
- type="button"
- onClick={() => {
- requestJump(row.locator);
- setShowOutline(false);
- }}
- style={{ paddingLeft: `${6 + (row.level - 1) * 12}px` }}
- className="flex w-full items-baseline gap-2 rounded-md py-[3px] pr-2 text-left transition hover:bg-[var(--muted)]"
- >
- <span className="min-w-0 flex-1 truncate text-[11.5px] text-[var(--foreground)]">
- {row.title}
- </span>
- <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--muted-foreground)]">
- {row.locator}
- </span>
- </button>
- </li>
- ))}
- </ul>
- </nav>
- )}
-
- <div className="flex min-h-0 flex-1">
+ <div className="relative flex min-h-0 flex-1">
+ {showOutline && material && hasContents && (
+ <ReaderOutline
+ rows={outlineRows}
+ pageHeadings={pageHeadings}
+ activeHeadingId={activeHeadingId}
+ currentLocator={currentLocator}
+ onNavigate={(locator) => {
+ requestJump(locator);
+ if (!window.matchMedia("(min-width: 768px)").matches) setShowOutline(false);
+ }}
+ onNavigateHeading={(heading) => {
+ headingNonceRef.current += 1;
+ setHeadingJump({ id: heading.id, nonce: headingNonceRef.current });
+ }}
+ onClose={() => setShowOutline(false)}
+ />
+ )}
<div className="min-w-0 flex-1">
{loadingMaterial ? (
<div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">
@@ -496,6 +557,9 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
setActiveAnnotationId(annotation.annotation_id)
}
onVisibleLocatorChange={handleVisibleLocator}
+ onHeadingsChange={setPageHeadings}
+ onActiveHeadingChange={setActiveHeadingId}
+ headingJump={headingJump}
/>
)}
</div>
diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsx
index 77ce73df6..c66d8a456 100644
--- a/web/components/reading/TextUnitView.tsx
+++ b/web/components/reading/TextUnitView.tsx
@@ -1,6 +1,13 @@
"use client";
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ Fragment,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
ALargeSmall,
ChevronLeft,
@@ -27,6 +34,13 @@ import {
readerDisplayShortcut,
type ReaderTheme,
} from "@/lib/reading-display-preferences";
+import {
+ activeReaderHeading,
+ extractReaderHeadings,
+ readerHeadingLine,
+ type ReaderHeading,
+} from "@/lib/reading-outline";
+import { segmentTextByQuotes } from "@/lib/reading-quote-locator";
import { cleanQuote } from "@/lib/reading-selection";
import { toRecogitoTextAnnotation } from "@/lib/reading-w3c-annotations";
import type { JumpRequest, SelectionPayload } from "./PdfDocumentView";
@@ -52,6 +66,9 @@ export interface TextUnitViewProps {
onSelection: (payload: SelectionPayload | null) => void;
onAnnotationClick?: (annotation: AnnotationItem) => void;
onVisibleLocatorChange?: (locator: number) => void;
+ onHeadingsChange?: (headings: ReaderHeading[]) => void;
+ onActiveHeadingChange?: (headingId: string | null) => void;
+ headingJump?: { id: string; nonce: number } | null;
}
/**
@@ -73,6 +90,9 @@ export function TextUnitView({
onSelection,
onAnnotationClick,
onVisibleLocatorChange,
+ onHeadingsChange,
+ onActiveHeadingChange,
+ headingJump,
}: TextUnitViewProps) {
const { t } = useTranslation();
const readerRootRef = useRef<HTMLDivElement | null>(null);
@@ -169,6 +189,14 @@ export function TextUnitView({
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [changeFontSize, fontSize, resetPreferences]);
+ const [headingTops, setHeadingTops] = useState<Record<string, number>>({});
+ const headingsChangeRef = useRef(onHeadingsChange);
+ const activeHeadingChangeRef = useRef(onActiveHeadingChange);
+
+ useEffect(() => {
+ headingsChangeRef.current = onHeadingsChange;
+ activeHeadingChangeRef.current = onActiveHeadingChange;
+ }, [onActiveHeadingChange, onHeadingsChange]);
useEffect(() => {
setLocator(1);
@@ -292,6 +320,62 @@ export function TextUnitView({
text,
]);
+ const runs = useMemo(
+ () =>
+ segmentTextByQuotes(
+ text,
+ annotations.filter((annotation) => annotation.locator === locator),
+ ),
+ [annotations, locator, text],
+ );
+
+ const pageHeadings = useMemo(
+ () => extractReaderHeadings([text], locator),
+ [locator, text],
+ );
+
+ useEffect(() => {
+ if (loading || error || pageHeadings.length === 0) {
+ setHeadingTops({});
+ activeHeadingChangeRef.current?.(null);
+ return;
+ }
+ const article = containerRef.current?.querySelector("article");
+ if (!article) return;
+ const tops: Record<string, number> = {};
+ article
+ .querySelectorAll<HTMLElement>("[data-reader-heading-id]")
+ .forEach((element) => {
+ const id = element.dataset.readerHeadingId;
+ if (id) tops[id] = element.offsetTop;
+ });
+ setHeadingTops(tops);
+ }, [error, loading, pageHeadings]);
+
+ useEffect(() => {
+ headingsChangeRef.current?.(pageHeadings);
+ return () => headingsChangeRef.current?.([]);
+ }, [pageHeadings]);
+
+ useEffect(() => {
+ if (!headingJump) return;
+ const container = containerRef.current;
+ const element = container?.querySelector<HTMLElement>(
+ `#${CSS.escape(headingJump.id)}`,
+ );
+ if (!container || !element) return;
+ container.scrollTop = Math.max(0, element.offsetTop - 72);
+ activeHeadingChangeRef.current?.(headingJump.id);
+ }, [headingJump]);
+
+ const handleContainerScroll = useCallback(() => {
+ const container = containerRef.current;
+ if (!container || pageHeadings.length === 0) return;
+ activeHeadingChangeRef.current?.(
+ activeReaderHeading(pageHeadings, container.scrollTop, headingTops),
+ );
+ }, [headingTops, pageHeadings]);
+
const handlePointerUp = useCallback(() => {
const selection = window.getSelection();
if (!selection || selection.isCollapsed) {
@@ -448,6 +532,7 @@ export function TextUnitView({
ref={containerRef}
data-reader-unit={locator}
onMouseUp={handlePointerUp}
+ onScroll={handleContainerScroll}
className="dt-reader-scroll flex-1 overflow-y-auto overscroll-contain px-8 py-7"
>
{loading ? (
@@ -474,7 +559,12 @@ export function TextUnitView({
{t("This section has no extractable text.")}
</span>
) : (
- text
+ <RunsWithHeadings
+ runs={runs}
+ headings={pageHeadings}
+ highlightedAnnotationId={highlightedAnnotationId}
+ onAnnotationClick={onAnnotationClick}
+ />
)}
</article>
)}
@@ -515,6 +605,101 @@ function PreferenceButton({
);
}
+function RunsWithHeadings({
+ runs,
+ headings,
+ highlightedAnnotationId,
+ onAnnotationClick,
+}: {
+ runs: Array<{ text: string; mark: AnnotationItem | null }>;
+ headings: ReaderHeading[];
+ highlightedAnnotationId?: string | null;
+ onAnnotationClick?: (annotation: AnnotationItem) => void;
+}) {
+ const headingAnchors = useMemo(() => {
+ const anchors = new Map<string, ReaderHeading>();
+ let headingIndex = 0;
+ runs.forEach((run, runIndex) => {
+ run.text.split("\n").forEach((line, lineIndex) => {
+ const heading = run.mark ? null : readerHeadingLine(line);
+ const expected = heading ? headings[headingIndex] : undefined;
+ if (
+ heading &&
+ expected &&
+ expected.title === heading.title &&
+ expected.level === heading.level
+ ) {
+ anchors.set(`${runIndex}-${lineIndex}`, expected);
+ headingIndex += 1;
+ }
+ });
+ });
+ return anchors;
+ }, [headings, runs]);
+
+ return (
+ <>
+ {runs.map((run, runIndex) =>
+ run.text.split("\n").map((line, lineIndex) => {
+ const key = `${runIndex}-${lineIndex}`;
+ const heading = run.mark ? null : readerHeadingLine(line);
+ const expected = headingAnchors.get(key);
+ if (heading && expected) {
+ const Heading = `h${expected.level}` as
+ | "h1"
+ | "h2"
+ | "h3"
+ | "h4"
+ | "h5"
+ | "h6";
+ return (
+ <Fragment key={key}>
+ {lineIndex > 0 && <br />}
+ <Heading
+ id={expected.id}
+ data-reader-heading-id={expected.id}
+ className="mt-5 mb-2 font-serif text-[var(--foreground)] first:mt-0"
+ >
+ {expected.title}
+ </Heading>
+ </Fragment>
+ );
+ }
+ if (run.mark) {
+ return (
+ <mark
+ key={key}
+ title={run.mark.note || undefined}
+ onClick={() =>
+ onAnnotationClick?.(run.mark as AnnotationItem)
+ }
+ className={`cursor-pointer rounded-[2px] px-[1px] text-[var(--foreground)] ${
+ run.mark.annotation_id === highlightedAnnotationId
+ ? "ring-2 ring-[var(--ring)]"
+ : ""
+ }`}
+ style={{
+ background:
+ run.mark.kind === "underline"
+ ? "transparent"
+ : `rgb(${COLOR_INK[run.mark.color] ?? COLOR_INK.yellow} / 0.55)`,
+ borderBottom:
+ run.mark.kind === "underline"
+ ? `2px solid rgb(${COLOR_INK[run.mark.color] ?? COLOR_INK.yellow})`
+ : undefined,
+ }}
+ >
+ {lineIndex > 0 ? `\n${line}` : line}
+ </mark>
+ );
+ }
+ return <span key={key}>{lineIndex > 0 ? `\n${line}` : line}</span>;
+ }),
+ )}
+ </>
+ );
+}
+
/** Translatable label for a unit kind. Keys are literal so i18n can find them. */
export function unitLabel(unit: UnitKind): string {
switch (unit) {
diff --git a/web/lib/reading-outline.ts b/web/lib/reading-outline.ts
new file mode 100644
index 000000000..1364bc336
--- /dev/null
+++ b/web/lib/reading-outline.ts
@@ -0,0 +1,104 @@
+import type { OutlineRow } from "@/lib/reading-api";
+
+export interface OutlineNode {
+ row: OutlineRow;
+ children: OutlineNode[];
+}
+
+export interface ReaderHeading {
+ id: string;
+ title: string;
+ level: number;
+}
+
+export function headingAnchor(locator: number, index: number): string {
+ return `dt-reader-heading-${locator}-${index + 1}`;
+}
+
+const HEADING_PATTERN = /^(#{1,6})\s+(.+?)\s*#*$/;
+
+export function readerHeadingLine(line: string): ReaderHeading | null {
+ const match = HEADING_PATTERN.exec(line.trim());
+ if (!match) return null;
+ const title = match[2].replace(/\s+#+$/, "").trim();
+ if (!title) return null;
+ return { id: "", title, level: match[1].length };
+}
+
+/** Extract Markdown headings while ignoring fenced code blocks. */
+export function extractReaderHeadings(
+ sources: Array<string | undefined | null>,
+ locator: number,
+): ReaderHeading[] {
+ const headings: ReaderHeading[] = [];
+ for (const source of sources) {
+ if (!source) continue;
+ let fence: string | null = null;
+ for (const line of source.split(/\r?\n/)) {
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
+ if (fenceMatch) {
+ if (!fence) fence = fenceMatch[1];
+ else if (line.trim().startsWith(fence)) fence = null;
+ continue;
+ }
+ if (fence) continue;
+ const heading = readerHeadingLine(line);
+ if (heading) {
+ headings.push({
+ ...heading,
+ id: headingAnchor(locator, headings.length),
+ });
+ }
+ }
+ }
+ return headings;
+}
+
+export function activeReaderHeading(
+ headings: ReaderHeading[],
+ scrollTop: number,
+ headingTops: Readonly<Record<string, number>>,
+): string | null {
+ let active: string | null = null;
+ for (const heading of headings) {
+ const top = headingTops[heading.id];
+ if (top !== undefined && top - 72 <= scrollTop) active = heading.id;
+ }
+ return active;
+}
+
+export function filterOutlineNodes(
+ nodes: OutlineNode[],
+ query: string,
+): OutlineNode[] {
+ const needle = query.trim().toLowerCase();
+ if (!needle) return nodes;
+ const visit = (node: OutlineNode): OutlineNode | null => {
+ const children = node.children
+ .map(visit)
+ .filter((row): row is OutlineNode => row !== null);
+ return node.row.title.toLowerCase().includes(needle) || children.length
+ ? { row: node.row, children }
+ : null;
+ };
+ return nodes.map(visit).filter((row): row is OutlineNode => row !== null);
+}
+
+export function buildOutlineTree(rows: OutlineRow[]): OutlineNode[] {
+ const roots: OutlineNode[] = [];
+ const stack: { level: number; node: OutlineNode }[] = [];
+
+ rows.forEach((row) => {
+ let level = Math.max(1, row.level);
+ if (!stack.length) level = 1;
+ else level = Math.min(level, stack[stack.length - 1].level + 1);
+
+ const node: OutlineNode = { row, children: [] };
+ while (stack.length && stack[stack.length - 1].level >= level) stack.pop();
+ if (stack.length) stack[stack.length - 1].node.children.push(node);
+ else roots.push(node);
+ stack.push({ level, node });
+ });
+
+ return roots;
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 3dee125a9..3be651623 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3129,6 +3129,14 @@
"paused": "paused",
"Draft": "Draft",
"Outline": "Outline",
+ "Contents": "Contents",
+ "Close outline": "Close outline",
+ "On this page": "On this page",
+ "Expand all": "Expand all",
+ "Collapse all": "Collapse all",
+ "Filter contents": "Filter contents",
+ "Expand section": "Expand section",
+ "Collapse section": "Collapse section",
"Paused": "Paused",
"Brief": "Brief",
"Roughly half the prose per chapter — a fast orientation.": "Roughly half the prose per chapter — a fast orientation.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 78fbe43ea..e490ce938 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3129,6 +3129,14 @@
"paused": "已暂停",
"Draft": "草稿",
"Outline": "大纲",
+ "Contents": "目录",
+ "Close outline": "关闭目录",
+ "On this page": "本页导航",
+ "Expand all": "全部展开",
+ "Collapse all": "全部收起",
+ "Filter contents": "筛选目录",
+ "Expand section": "展开小节",
+ "Collapse section": "收起小节",
"Paused": "已暂停",
"Brief": "精简",
"Roughly half the prose per chapter — a fast orientation.": "每章篇幅约为一半,快速建立整体认识。",
diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.ts
new file mode 100644
index 000000000..330af570a
--- /dev/null
+++ b/web/tests/reading-outline.test.ts
@@ -0,0 +1,83 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import {
+ activeReaderHeading,
+ buildOutlineTree,
+ extractReaderHeadings,
+ filterOutlineNodes,
+} from "../lib/reading-outline";
+
+function source(relativePath: string): string {
+ return readFileSync(path.join(process.cwd(), relativePath), "utf8");
+}
+
+test("builds a nested outline without inventing impossible levels", () => {
+ const tree = buildOutlineTree([
+ { locator: 1, title: "Part", level: 1, synthesised: false },
+ { locator: 2, title: "Suddenly deep", level: 6, synthesised: false },
+ { locator: 3, title: "Nested", level: 3, synthesised: false },
+ ]);
+
+ assert.deepEqual(tree.map((node) => node.row.title), ["Part"]);
+ assert.deepEqual(tree[0].children.map((node) => node.row.title), [
+ "Suddenly deep",
+ ]);
+ assert.deepEqual(
+ tree[0].children[0].children.map((node) => node.row.title),
+ ["Nested"],
+ );
+});
+
+test("keeps an ancestor when only its child matches a filter", () => {
+ const tree = buildOutlineTree([
+ { locator: 1, title: "Installation", level: 1, synthesised: false },
+ { locator: 2, title: "Docker", level: 2, synthesised: false },
+ { locator: 3, title: "Providers", level: 2, synthesised: false },
+ ]);
+ const filtered = filterOutlineNodes(tree, "docker");
+
+ assert.equal(filtered.length, 1);
+ assert.equal(filtered[0].row.title, "Installation");
+ assert.equal(filtered[0].children.length, 1);
+ assert.equal(filtered[0].children[0].row.title, "Docker");
+});
+
+test("extracts Markdown headings and skips fenced code", () => {
+ const headings = extractReaderHeadings(
+ ["# Title\n\n```ts\n// # Not a heading\n```\n\n## Section ##"],
+ 3,
+ );
+
+ assert.deepEqual(headings, [
+ { id: "dt-reader-heading-3-1", title: "Title", level: 1 },
+ { id: "dt-reader-heading-3-2", title: "Section", level: 2 },
+ ]);
+});
+
+test("active heading follows the reading container", () => {
+ const headings = extractReaderHeadings(["# One\n## Two\n### Three"], 1);
+ const active = activeReaderHeading(headings, 500, {
+ "dt-reader-heading-1-1": 0,
+ "dt-reader-heading-1-2": 480,
+ "dt-reader-heading-1-3": 900,
+ });
+
+ assert.equal(active, "dt-reader-heading-1-2");
+});
+
+test("reader outline is persistent, searchable, and wired to page headings", () => {
+ const outline = source("components/reading/ReaderOutline.tsx");
+ const reader = source("components/reading/ReaderPane.tsx");
+ const textReader = source("components/reading/TextUnitView.tsx");
+
+ assert.match(outline, /aria-label=\{t\("Contents"\)\}/);
+ assert.match(outline, /Filter contents/);
+ assert.match(outline, /On this page/);
+ assert.match(reader, /dt\.reader\.outline\.\$\{material\.material_id\}/);
+ assert.match(reader, /event\.key\.toLowerCase\(\) === "b"/);
+ assert.match(reader, /onNavigateHeading/);
+ assert.match(textReader, /data-reader-heading-id/);
+ assert.match(textReader, /container\.scrollTop = Math\.max\(0, element\.offsetTop - 72\)/);
+});