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>(new Set()); + const activeOutlineRef = useRef(null); + const activeHeadingRef = useRef(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 ( + + ); +} + +function OutlineBranch({ + nodes, + rows, + activeIndex, + collapsedNodes, + onToggle, + onNavigate, + activeOutlineRef, + depth = 0, +}: { + nodes: OutlineNode[]; + rows: OutlineRow[]; + activeIndex: number; + collapsedNodes: Set; + onToggle: (key: string) => void; + onNavigate: (locator: number) => void; + activeOutlineRef: RefObject; + depth?: number; +}) { + const { t } = useTranslation(); + return ( +
    + {nodes.map((node) => { + const key = `${node.row.locator}-${node.row.title}`; + const isActive = rows[activeIndex] === node.row; + const collapsed = collapsedNodes.has(key); + return ( +
  • +
    + + {node.children.length > 0 && ( + + )} +
    + {node.children.length > 0 && !collapsed && ( + + )} +
  • + ); + })} +
+ ); +} + +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(null); const [showOutline, setShowOutline] = useState(false); + const [outlineUserChoice, setOutlineUserChoice] = useState(null); const [autoJump, setAutoJump] = useState(true); const [exporting, setExporting] = useState(false); const [currentLocator, setCurrentLocator] = useState(1); + const [pageHeadings, setPageHeadings] = useState([]); + const [activeHeadingId, setActiveHeadingId] = useState(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 (
+ {material && hasContents && ( + + )} {unitWord} {currentLocator}/{material.unit_count} - {outlineRows.length > 0 && ( - setShowOutline((open) => !open)} - /> - )} )} - {showOutline && material && outlineRows.length > 0 && ( - - )} - -
+
+ {showOutline && material && hasContents && ( + { + 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)} + /> + )}
{loadingMaterial ? (
@@ -496,6 +557,9 @@ export function ReaderPane({ onClose }: ReaderPaneProps) { setActiveAnnotationId(annotation.annotation_id) } onVisibleLocatorChange={handleVisibleLocator} + onHeadingsChange={setPageHeadings} + onActiveHeadingChange={setActiveHeadingId} + headingJump={headingJump} /> )}
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(null); @@ -169,6 +189,14 @@ export function TextUnitView({ window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [changeFontSize, fontSize, resetPreferences]); + const [headingTops, setHeadingTops] = useState>({}); + 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 = {}; + article + .querySelectorAll("[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( + `#${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.")} ) : ( - text + )} )} @@ -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(); + 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 ( + + {lineIndex > 0 &&
} + + {expected.title} + +
+ ); + } + if (run.mark) { + return ( + + 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} + + ); + } + return {lineIndex > 0 ? `\n${line}` : line}; + }), + )} + + ); +} + /** 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, + 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>, +): 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\)/); +});