Skip to content

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

fix(reading): preserve annotation offsets around heading anchors

Bingxi Zhao (Frank)28c0f7d2954d
diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsx
index ae321143b..0fa80fc18 100644
--- a/web/components/reading/TextUnitView.tsx
+++ b/web/components/reading/TextUnitView.tsx
@@ -40,7 +40,6 @@ import {
readerLinesWithHeadings,
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";
@@ -319,15 +318,6 @@ 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],
@@ -554,12 +544,7 @@ export function TextUnitView({
{t("This section has no extractable text.")}
</span>
) : (
- <RunsWithHeadings
- runs={runs}
- headings={pageHeadings}
- highlightedAnnotationId={highlightedAnnotationId}
- onAnnotationClick={onAnnotationClick}
- />
+ <TextWithHeadings text={text} headings={pageHeadings} />
)}
</article>
)}
@@ -600,21 +585,14 @@ function PreferenceButton({
);
}
-function RunsWithHeadings({
- runs,
+function TextWithHeadings({
+ text,
headings,
- highlightedAnnotationId,
- onAnnotationClick,
}: {
- runs: Array<{ text: string; mark: AnnotationItem | null }>;
+ text: string;
headings: ReaderHeading[];
- highlightedAnnotationId?: string | null;
- onAnnotationClick?: (annotation: AnnotationItem) => void;
}) {
- const lines = useMemo(
- () => readerLinesWithHeadings(runs, headings),
- [headings, runs],
- );
+ const lines = useMemo(() => readerLinesWithHeadings(text, headings), [headings, text]);
return (
<>
@@ -625,29 +603,21 @@ function RunsWithHeadings({
"h1" | "h2" | "h3" | "h4" | "h5" | "h6";
return (
<Fragment key={key}>
- {lineIndex > 0 && <br />}
+ {lineIndex > 0 && "\n"}
<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"
>
- <RunParts
- parts={line.parts}
- highlightedAnnotationId={highlightedAnnotationId}
- onAnnotationClick={onAnnotationClick}
- />
+ {line.text}
</Heading>
</Fragment>
);
}
return (
<Fragment key={key}>
- {lineIndex > 0 && <br />}
- <RunParts
- parts={line.parts}
- highlightedAnnotationId={highlightedAnnotationId}
- onAnnotationClick={onAnnotationClick}
- />
+ {lineIndex > 0 && "\n"}
+ {line.text}
</Fragment>
);
})}
@@ -655,44 +625,6 @@ function RunsWithHeadings({
);
}
-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.ts
index 82704e88a..d16934801 100644
--- a/web/lib/reading-outline.ts
+++ b/web/lib/reading-outline.ts
@@ -11,13 +11,9 @@ export interface ReaderHeading {
level: number;
}
-export interface ReaderTextPart<T> {
+export interface ReaderDisplayLine {
+ /** The original source line, including Markdown heading markers. */
text: string;
- mark: T | null;
-}
-
-export interface ReaderDisplayLine<T> {
- parts: ReaderTextPart<T>[];
heading: ReaderHeading | null;
}
@@ -35,81 +31,39 @@ 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>[],
+/**
+ * Attach outline entries to source lines without changing a single character.
+ *
+ * Recogito's TextPosition selectors resolve against ``article.textContent``.
+ * Keeping the Markdown markers and the original newline text nodes here makes
+ * that DOM text exactly equal to the text used when an annotation was saved.
+ */
+export function readerLinesWithHeadings(
+ text: string,
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([]);
- });
- }
-
+): ReaderDisplayLine[] {
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);
+ return text.split("\n").map((line) => {
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
if (fenceMatch) {
if (!fence) fence = fenceMatch[1];
- else if (text.trim().startsWith(fence)) fence = null;
- return { parts, heading: null };
+ else if (line.trim().startsWith(fence)) fence = null;
+ return { text: line, heading: null };
}
- if (fence) return { parts, heading: null };
+ if (fence) return { text: line, heading: null };
- const details = headingTextRange(text);
- if (!details) return { parts, heading: null };
+ const parsed = readerHeadingLine(line);
+ if (!parsed) return { text: line, heading: null };
const expected = headings[headingIndex++];
if (
!expected ||
- expected.title !== details.heading.title ||
- expected.level !== details.heading.level
+ expected.title !== parsed.title ||
+ expected.level !== parsed.level
) {
- return { parts, heading: null };
+ return { text: line, heading: null };
}
- return {
- parts: sliceParts(parts, details.start, details.end),
- heading: expected,
- };
+ return { text: line, heading: expected };
});
}
diff --git a/web/tests/e2e/reading-w3c-annotations.audit.ts b/web/tests/e2e/reading-w3c-annotations.audit.ts
index 6c137738c..ef7eab633 100644
--- a/web/tests/e2e/reading-w3c-annotations.audit.ts
+++ b/web/tests/e2e/reading-w3c-annotations.audit.ts
@@ -25,7 +25,7 @@ const annotation = {
note: "Wave behavior",
rects: [],
selectors: [
- { type: "TextPositionSelector", start: 10, end: 28 },
+ { type: "TextPositionSelector", start: 12, end: 30 },
{ type: "TextQuoteSelector", exact: "behave like a wave" },
],
author: "user",
@@ -80,7 +80,7 @@ test.beforeEach(async ({ page }) => {
return json({
locator: 1,
unit: "section",
- text: "Light can behave like a wave and sometimes like a particle.",
+ text: "# Light can behave like a wave\n\nand sometimes like a particle.",
});
}
return json({});
@@ -99,7 +99,12 @@ test("a rich text annotation reflows and activates its sidebar entry", async ({
const highlight = page.locator(".r6o-annotation").first();
await expect(highlight).toBeVisible();
- await expect(page.getByText("Light can behave like a wave")).toBeVisible();
+ const heading = page.locator('[data-reader-heading-id="dt-reader-heading-1-1"]');
+ await expect(heading).toBeVisible();
+ await expect(heading).toContainText("# Light can behave like a wave");
+ await expect(page.locator("article.r6o-annotatable")).toHaveText(
+ "# Light can behave like a wave\n\nand sometimes like a particle.",
+ );
await page.setViewportSize({ width: 1100, height: 700 });
await expect(highlight).toBeVisible();
diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.ts
index c84bbfc01..546993cd6 100644
--- a/web/tests/reading-outline.test.ts
+++ b/web/tests/reading-outline.test.ts
@@ -62,40 +62,19 @@ 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,
- );
+test("heading anchors preserve the exact source used by annotation selectors", () => {
+ const sourceText = " # Title ##\r\nBody\n```md\n# Code\n```\n## Next\n";
+ const headings = extractReaderHeadings([sourceText], 4);
+ const lines = readerLinesWithHeadings(sourceText, 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[3].heading, null);
+ assert.equal(lines[5].heading?.id, "dt-reader-heading-4-2");
+ assert.equal(
+ lines.map((line) => line.text).join("\n"),
+ sourceText,
+ "DOM text must retain Markdown markers, CRLF characters, and final newline",
);
-
- 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", () => {
@@ -133,4 +112,5 @@ test("reader outline is persistent, searchable, and wired to page headings", ()
assert.match(textReader, /container\.scrollTo\(/);
assert.match(textReader, /elementRect\.top - containerRect\.top/);
assert.doesNotMatch(textReader, /element\.offsetTop - 72/);
+ assert.doesNotMatch(textReader, /segmentTextByQuotes|<mark/);
});