DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(reading): keep heading anchors through highlights
Bingxi Zhao (Frank)2a8617008f5b
diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsxindex b137f9e0c..ae321143b 100644--- a/web/components/reading/TextUnitView.tsx+++ b/web/components/reading/TextUnitView.tsx@@ -37,7 +37,7 @@ import {import {activeReaderHeading,extractReaderHeadings,- readerHeadingLine,+ readerLinesWithHeadings,type ReaderHeading,} from "@/lib/reading-outline";import { segmentTextByQuotes } from "@/lib/reading-quote-locator";@@ -611,90 +611,88 @@ function RunsWithHeadings({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]);+ const lines = useMemo(+ () => readerLinesWithHeadings(runs, headings),+ [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,- }}+ {lines.map((line, lineIndex) => {+ const key = `line-${lineIndex}`;+ if (line.heading) {+ const Heading = `h${line.heading.level}` as+ "h1" | "h2" | "h3" | "h4" | "h5" | "h6";+ return (+ <Fragment key={key}>+ {lineIndex > 0 && <br />}+ <Heading+ id={line.heading.id}+ data-reader-heading-id={line.heading.id}+ className="mt-5 mb-2 font-serif text-[var(--foreground)] first:mt-0">- {lineIndex > 0 ? `\n${line}` : line}- </mark>- );- }- return <span key={key}>{lineIndex > 0 ? `\n${line}` : line}</span>;- }),- )}+ <RunParts+ parts={line.parts}+ highlightedAnnotationId={highlightedAnnotationId}+ onAnnotationClick={onAnnotationClick}+ />+ </Heading>+ </Fragment>+ );+ }+ return (+ <Fragment key={key}>+ {lineIndex > 0 && <br />}+ <RunParts+ parts={line.parts}+ highlightedAnnotationId={highlightedAnnotationId}+ onAnnotationClick={onAnnotationClick}+ />+ </Fragment>+ );+ })}</>);}+function RunParts({+ parts,+ highlightedAnnotationId,+ onAnnotationClick,+}: {+ parts: Array<{ text: string; mark: AnnotationItem | null }>;+ highlightedAnnotationId?: string | null;+ onAnnotationClick?: (annotation: AnnotationItem) => void;+}) {+ return parts.map((part, index) => {+ if (!part.mark) return <span key={index}>{part.text}</span>;+ return (+ <mark+ key={index}+ title={part.mark.note || undefined}+ onClick={() => onAnnotationClick?.(part.mark as AnnotationItem)}+ className={`cursor-pointer rounded-[2px] px-[1px] text-[var(--foreground)] ${+ part.mark.annotation_id === highlightedAnnotationId+ ? "ring-2 ring-[var(--ring)]"+ : ""+ }`}+ style={{+ background:+ part.mark.kind === "underline"+ ? "transparent"+ : `rgb(${COLOR_INK[part.mark.color] ?? COLOR_INK.yellow} / 0.55)`,+ borderBottom:+ part.mark.kind === "underline"+ ? `2px solid rgb(${COLOR_INK[part.mark.color] ?? COLOR_INK.yellow})`+ : undefined,+ }}+ >+ {part.text}+ </mark>+ );+ });+}+/** 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.tsindex 9dffea1e1..82704e88a 100644--- a/web/lib/reading-outline.ts+++ b/web/lib/reading-outline.ts@@ -11,6 +11,16 @@ export interface ReaderHeading {level: number;}+export interface ReaderTextPart<T> {+ text: string;+ mark: T | null;+}++export interface ReaderDisplayLine<T> {+ parts: ReaderTextPart<T>[];+ heading: ReaderHeading | null;+}+export function headingAnchor(locator: number, index: number): string {return `dt-reader-heading-${locator}-${index + 1}`;}@@ -25,6 +35,84 @@ export function readerHeadingLine(line: string): ReaderHeading | null {return { id: "", title, level: match[1].length };}+function headingTextRange(+ line: string,+): { heading: ReaderHeading; start: number; end: number } | null {+ const leading = line.search(/\S/);+ if (leading < 0) return null;+ const trimmed = line.trim();+ const prefix = /^(#{1,6})\s+/.exec(trimmed);+ const heading = readerHeadingLine(line);+ if (!prefix || !heading) return null;+ const start = leading + prefix[0].length;+ return { heading, start, end: start + heading.title.length };+}++function sliceParts<T>(+ parts: ReaderTextPart<T>[],+ start: number,+ end: number,+): ReaderTextPart<T>[] {+ const selected: ReaderTextPart<T>[] = [];+ let offset = 0;+ for (const part of parts) {+ const partEnd = offset + part.text.length;+ const from = Math.max(start, offset);+ const to = Math.min(end, partEnd);+ if (from < to) {+ selected.push({+ text: part.text.slice(from - offset, to - offset),+ mark: part.mark,+ });+ }+ offset = partEnd;+ }+ return selected;+}++/** Rebuild logical lines after annotation segmentation, then attach headings. */+export function readerLinesWithHeadings<T>(+ runs: ReaderTextPart<T>[],+ headings: ReaderHeading[],+): ReaderDisplayLine<T>[] {+ const lines: ReaderTextPart<T>[][] = [[]];+ for (const run of runs) {+ const chunks = run.text.split("\n");+ chunks.forEach((chunk, index) => {+ if (chunk) lines[lines.length - 1].push({ text: chunk, mark: run.mark });+ if (index < chunks.length - 1) lines.push([]);+ });+ }++ let fence: string | null = null;+ let headingIndex = 0;+ return lines.map((parts) => {+ const text = parts.map((part) => part.text).join("");+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(text);+ if (fenceMatch) {+ if (!fence) fence = fenceMatch[1];+ else if (text.trim().startsWith(fence)) fence = null;+ return { parts, heading: null };+ }+ if (fence) return { parts, heading: null };++ const details = headingTextRange(text);+ if (!details) return { parts, heading: null };+ const expected = headings[headingIndex++];+ if (+ !expected ||+ expected.title !== details.heading.title ||+ expected.level !== details.heading.level+ ) {+ return { parts, heading: null };+ }+ return {+ parts: sliceParts(parts, details.start, details.end),+ heading: expected,+ };+ });+}+/** Extract Markdown headings while ignoring fenced code blocks. */export function extractReaderHeadings(sources: Array<string | undefined | null>,diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.tsindex affe3582a..c84bbfc01 100644--- a/web/tests/reading-outline.test.ts+++ b/web/tests/reading-outline.test.ts@@ -8,6 +8,7 @@ import {extractReaderHeadings,filterReaderHeadings,filterOutlineNodes,+ readerLinesWithHeadings,} from "../lib/reading-outline";function source(relativePath: string): string {@@ -21,10 +22,14 @@ test("builds a nested outline without inventing impossible levels", () => {{ 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.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"],@@ -57,14 +62,46 @@ test("extracts Markdown headings and skips fenced code", () => {]);});+test("heading anchors survive annotation run boundaries", () => {+ const headings = extractReaderHeadings(["# Title\nBody\n## Next"], 4);+ const mark = { id: "annotation" };+ const lines = readerLinesWithHeadings(+ [+ { text: "# Ti", mark: null },+ { text: "tle", mark },+ { text: "\nBody\n## Next", mark: null },+ ],+ headings,+ );++ assert.equal(lines[0].heading?.id, "dt-reader-heading-4-1");+ assert.deepEqual(lines[0].parts, [+ { text: "Ti", mark: null },+ { text: "tle", mark },+ ]);+ assert.equal(lines[2].heading?.id, "dt-reader-heading-4-2");+});++test("a fully highlighted heading cannot hide later anchors", () => {+ const headings = extractReaderHeadings(["# First\n## Second"], 2);+ const mark = { id: "annotation" };+ const lines = readerLinesWithHeadings(+ [+ { text: "# First\n", mark },+ { text: "## Second", mark: null },+ ],+ headings,+ );++ assert.equal(lines[0].heading?.id, "dt-reader-heading-2-1");+ assert.equal(lines[0].parts[0].mark, mark);+ assert.equal(lines[1].heading?.id, "dt-reader-heading-2-2");+});+test("active heading follows the reading container", () => {const headings = extractReaderHeadings(["# One\n## Two\n### Three"], 1);const active = activeReaderHeading(headings, (heading) =>- heading.title === "One"- ? -20- : heading.title === "Two"- ? 12- : 80,+ heading.title === "One" ? -20 : heading.title === "Two" ? 12 : 80,);assert.equal(active, "dt-reader-heading-1-2");