DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(reading): separate outline views and stabilize heading jumps
XZH0e7ccc3ae3ef
diff --git a/web/components/reading/ReaderOutline.tsx b/web/components/reading/ReaderOutline.tsxindex 2e40a96d7..ec7ab28ed 100644--- a/web/components/reading/ReaderOutline.tsx+++ b/web/components/reading/ReaderOutline.tsx@@ -7,6 +7,7 @@ import type { OutlineRow } from "@/lib/reading-api";import {buildOutlineTree,filterOutlineNodes,+ filterReaderHeadings,type OutlineNode,type ReaderHeading,} from "@/lib/reading-outline";@@ -32,12 +33,17 @@ export function ReaderOutline({}: ReaderOutlineProps) {const { t } = useTranslation();const [query, setQuery] = useState("");+ const [activeTab, setActiveTab] = useState<"document" | "page">("document");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 visiblePageHeadings = useMemo(+ () => filterReaderHeadings(pageHeadings, query),+ [pageHeadings, query],+ );const activeIndex = useMemo(() => {let active = -1;rows.forEach((row, index) => {@@ -46,18 +52,31 @@ export function ReaderOutline({return active;}, [rows, currentLocator]);const hasCollapsibleNodes = tree.some((node) => node.children.length > 0);+ const hasBothViews = tree.length > 0 && pageHeadings.length > 0;+ const showDocumentView = activeTab === "document" && tree.length > 0;+ const showPageView =+ (activeTab === "page" || tree.length === 0) && pageHeadings.length > 0;useEffect(() => {- activeOutlineRef.current?.scrollIntoView({ block: "nearest" });- }, [activeIndex]);+ if (showDocumentView) {+ activeOutlineRef.current?.scrollIntoView({ block: "nearest" });+ }+ }, [activeIndex, showDocumentView]);useEffect(() => {- activeHeadingRef.current?.scrollIntoView({ block: "nearest" });- }, [activeHeadingId]);+ if (showPageView) {+ activeHeadingRef.current?.scrollIntoView({ block: "nearest" });+ }+ }, [activeHeadingId, showPageView]);const setAllCollapsed = (collapsed: boolean) => {setCollapsedNodes(collapsed ? new Set(collectCollapsibleKeys(tree)) : new Set());};+ const switchTab = (tab: "document" | "page") => {+ setActiveTab(tab);+ setQuery("");+ };+return (<asidearia-label={t("Contents")}@@ -65,10 +84,16 @@ export function ReaderOutline({><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")}+ {hasBothViews+ ? activeTab === "document"+ ? t("Document contents")+ : t("On this page")+ : tree.length > 0+ ? t("Contents")+ : t("On this page")}</span><div className="flex items-center gap-1">- {hasCollapsibleNodes && (+ {showDocumentView && hasCollapsibleNodes && (<><buttontype="button"@@ -96,6 +121,42 @@ export function ReaderOutline({</button></div></div>+ {hasBothViews && (+ <div+ role="tablist"+ aria-label={t("Contents")}+ className="grid shrink-0 grid-cols-2 gap-1 border-b border-[var(--border)] p-1.5"+ >+ <button+ type="button"+ role="tab"+ aria-controls="reader-outline-panel"+ aria-selected={activeTab === "document"}+ onClick={() => switchTab("document")}+ className={`h-7 rounded-md px-2 text-[11.5px] font-medium transition ${+ activeTab === "document"+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ }`}+ >+ {t("Document contents")}+ </button>+ <button+ type="button"+ role="tab"+ aria-controls="reader-outline-panel"+ aria-selected={activeTab === "page"}+ onClick={() => switchTab("page")}+ className={`h-7 rounded-md px-2 text-[11.5px] font-medium transition ${+ activeTab === "page"+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ }`}+ >+ {t("On this page")}+ </button>+ </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@@ -105,56 +166,78 @@ export function ReaderOutline({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+ id="reader-outline-panel"+ role="tabpanel"+ className="min-h-0 flex-1 overflow-y-auto px-1.5 py-2"+ >+ {showDocumentView && (+ <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}+ />+ )}+ {showPageView && (+ <PageHeadingList+ headings={visiblePageHeadings}+ activeHeadingId={activeHeadingId}+ onNavigate={onNavigateHeading}+ activeHeadingRef={activeHeadingRef}+ />)}</nav></aside>);}+function PageHeadingList({+ headings,+ activeHeadingId,+ onNavigate,+ activeHeadingRef,+}: {+ headings: ReaderHeading[];+ activeHeadingId?: string | null;+ onNavigate: (heading: ReaderHeading) => void;+ activeHeadingRef: RefObject<HTMLButtonElement | null>;+}) {+ return (+ <ul className="space-y-0.5">+ {headings.map((heading) => (+ <li key={heading.id} className="min-w-0">+ <button+ type="button"+ ref={activeHeadingId === heading.id ? activeHeadingRef : undefined}+ onClick={() => onNavigate(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>+ );+}+function OutlineBranch({nodes,rows,diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsxindex c66d8a456..b137f9e0c 100644--- a/web/components/reading/TextUnitView.tsx+++ b/web/components/reading/TextUnitView.tsx@@ -189,7 +189,6 @@ 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);@@ -334,24 +333,6 @@ export function TextUnitView({[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?.([]);@@ -361,20 +342,34 @@ export function TextUnitView({if (!headingJump) return;const container = containerRef.current;const element = container?.querySelector<HTMLElement>(- `#${CSS.escape(headingJump.id)}`,+ `[data-reader-heading-id="${CSS.escape(headingJump.id)}"]`,);if (!container || !element) return;- container.scrollTop = Math.max(0, element.offsetTop - 72);+ const containerRect = container.getBoundingClientRect();+ const elementRect = element.getBoundingClientRect();+ container.scrollTo({+ top: Math.max(+ 0,+ container.scrollTop + elementRect.top - containerRect.top - 24,+ ),+ });activeHeadingChangeRef.current?.(headingJump.id);}, [headingJump]);const handleContainerScroll = useCallback(() => {const container = containerRef.current;if (!container || pageHeadings.length === 0) return;+ const containerRect = container.getBoundingClientRect();activeHeadingChangeRef.current?.(- activeReaderHeading(pageHeadings, container.scrollTop, headingTops),+ activeReaderHeading(pageHeadings, (heading) => {+ const element = container.querySelector<HTMLElement>(+ `[data-reader-heading-id="${CSS.escape(heading.id)}"]`,+ );+ if (!element) return null;+ return element.getBoundingClientRect().top - containerRect.top;+ }),);- }, [headingTops, pageHeadings]);+ }, [pageHeadings]);const handlePointerUp = useCallback(() => {const selection = window.getSelection();diff --git a/web/lib/reading-outline.ts b/web/lib/reading-outline.tsindex 1364bc336..9dffea1e1 100644--- a/web/lib/reading-outline.ts+++ b/web/lib/reading-outline.ts@@ -56,17 +56,27 @@ export function extractReaderHeadings(export function activeReaderHeading(headings: ReaderHeading[],- scrollTop: number,- headingTops: Readonly<Record<string, number>>,+ getHeadingTop: (heading: ReaderHeading) => number | null,): 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;+ const top = getHeadingTop(heading);+ if (top !== null && top <= 48) active = heading.id;}return active;}+export function filterReaderHeadings(+ headings: ReaderHeading[],+ query: string,+): ReaderHeading[] {+ const needle = query.trim().toLowerCase();+ if (!needle) return headings;+ return headings.filter((heading) =>+ heading.title.toLowerCase().includes(needle),+ );+}+export function filterOutlineNodes(nodes: OutlineNode[],query: string,diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 3be651623..ccecc02a4 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3130,6 +3130,7 @@"Draft": "Draft","Outline": "Outline","Contents": "Contents",+ "Document contents": "Document contents","Close outline": "Close outline","On this page": "On this page","Expand all": "Expand all",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex e490ce938..73fa6edf3 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3130,6 +3130,7 @@"Draft": "草稿","Outline": "大纲","Contents": "目录",+ "Document contents": "文档目录","Close outline": "关闭目录","On this page": "本页导航","Expand all": "全部展开",diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.tsindex 330af570a..affe3582a 100644--- a/web/tests/reading-outline.test.ts+++ b/web/tests/reading-outline.test.ts@@ -6,6 +6,7 @@ import {activeReaderHeading,buildOutlineTree,extractReaderHeadings,+ filterReaderHeadings,filterOutlineNodes,} from "../lib/reading-outline";@@ -58,15 +59,26 @@ test("extracts Markdown headings and skips fenced code", () => {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,- });+ const active = activeReaderHeading(headings, (heading) =>+ heading.title === "One"+ ? -20+ : heading.title === "Two"+ ? 12+ : 80,+ );assert.equal(active, "dt-reader-heading-1-2");});+test("page-heading filtering stays scoped to the current tab", () => {+ const headings = extractReaderHeadings(["# Install\n## Docker\n## Use"], 2);++ assert.deepEqual(+ filterReaderHeadings(headings, "dock").map((heading) => heading.title),+ ["Docker"],+ );+});+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");@@ -75,9 +87,13 @@ test("reader outline is persistent, searchable, and wired to page headings", ()assert.match(outline, /aria-label=\{t\("Contents"\)\}/);assert.match(outline, /Filter contents/);assert.match(outline, /On this page/);+ assert.match(outline, /role="tablist"/);+ assert.match(outline, /filterReaderHeadings/);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\)/);+ assert.match(textReader, /container\.scrollTo\(/);+ assert.match(textReader, /elementRect\.top - containerRect\.top/);+ assert.doesNotMatch(textReader, /element\.offsetTop - 72/);});