Skip to content

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

feat(reading): add citation capture

Benjaminb277247036ff
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index af9b1f69c..e4e86a095 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -135,7 +135,7 @@ class AnnotationPayload(BaseModel):
annotation_id: str = ""
locator: int = Field(ge=1)
- kind: Literal["highlight", "underline", "note"] = "highlight"
+ kind: Literal["highlight", "underline", "note", "citation"] = "highlight"
color: str = "yellow"
quote: str = Field(default="", max_length=2000)
note: str = ""
diff --git a/deeptutor/reading/export.py b/deeptutor/reading/export.py
index 6bc4f7ae0..61220eee9 100644
--- a/deeptutor/reading/export.py
+++ b/deeptutor/reading/export.py
@@ -225,6 +225,9 @@ def _export_markdown(
current = annotation.locator
lines.append(f"## {unit_word} {current}")
lines.append("")
+ if annotation.kind == "citation":
+ lines.append("**Citation**")
+ lines.append("")
quote = " ".join((annotation.quote or "").split())
if quote:
lines.append(f"> {quote}")
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index c5fd458eb..8c21ac35f 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -24,7 +24,7 @@ from typing import Any, Literal
UnitKind = Literal["page", "chapter", "slide", "section"]
RenderMode = Literal["text", "pdf", "epub"]
-AnnotationKind = Literal["highlight", "underline", "note"]
+AnnotationKind = Literal["highlight", "underline", "note", "citation"]
TextSelectorType = Literal["TextQuoteSelector", "TextPositionSelector"]
MAX_TEXT_SELECTOR_CHARS = 2000
@@ -371,7 +371,7 @@ class Annotation:
return cls(
annotation_id=str(data.get("annotation_id") or ""),
locator=max(1, int(data.get("locator") or 1)),
- kind=kind if kind in ("highlight", "underline", "note") else "highlight", # type: ignore[arg-type]
+ kind=(kind if kind in ("highlight", "underline", "note", "citation") else "highlight"), # type: ignore[arg-type]
color=color if color in ANNOTATION_COLORS else DEFAULT_ANNOTATION_COLOR,
quote=str(data.get("quote") or ""),
note=str(data.get("note") or ""),
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index 35e10879c..3794ed107 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -874,6 +874,24 @@ def test_markdown_export_lists_marks_in_locator_order(store: ReadingStore, pdf_p
assert "first" in text
+def test_markdown_export_labels_saved_citations(store: ReadingStore, pdf_path: Path) -> None:
+ manifest = store.ingest(pdf_path)
+ store.save_annotation(
+ manifest.material_id,
+ Annotation(
+ annotation_id="",
+ locator=1,
+ kind="citation",
+ quote="Introduction",
+ ),
+ )
+
+ text = export_material(store, manifest.material_id, fmt="markdown").data.decode("utf-8")
+
+ assert "**Citation**" in text
+ assert "> Introduction" in text
+
+
def test_markdown_export_handles_a_material_with_no_annotations(
store: ReadingStore, tmp_path: Path
) -> None:
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 880993d78..b8a1f5dbf 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -378,6 +378,30 @@ def test_annotation_round_trips_w3c_text_selectors(client: TestClient) -> None:
]
+def test_citation_round_trips_through_the_existing_annotation_api(
+ client: TestClient,
+) -> None:
+ material = _upload(client)
+ base = f"/api/v1/reading/materials/{material['material_id']}/annotations"
+
+ created = client.put(
+ base,
+ json={
+ "locator": 1,
+ "kind": "citation",
+ "quote": "Sequence models",
+ "selectors": [
+ {"type": "TextQuoteSelector", "exact": "Sequence models"},
+ {"type": "TextPositionSelector", "start": 13, "end": 28},
+ ],
+ },
+ )
+
+ assert created.status_code == 200, created.text
+ assert created.json()["kind"] == "citation"
+ assert client.get(base).json()[0]["kind"] == "citation"
+
+
def test_annotation_rejects_mismatched_quote_selector(client: TestClient) -> None:
material = _upload(client)
response = client.put(
diff --git a/web/components/reading/AnnotationList.tsx b/web/components/reading/AnnotationList.tsx
index e835c4ca6..dd4e8b5f3 100644
--- a/web/components/reading/AnnotationList.tsx
+++ b/web/components/reading/AnnotationList.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useMemo } from "react";
-import { Bot, Sparkles, Trash2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { Bookmark, Bot, Highlighter, Sparkles, Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { AnnotationItem, UnitKind } from "@/lib/reading-api";
import { unitLabel } from "./TextUnitView";
@@ -25,9 +25,9 @@ export interface AnnotationListProps {
/**
* The marks made on this material, grouped by locator.
*
- * Grouped rather than flat because a reader thinks in "what did I mark on page
- * 12", and because it makes the assistant's own marks legible in context next to
- * the user's own.
+ * Citations deliberately share the annotation store, selectors and source
+ * positions. The tab is only a filtered view: it does not create a second
+ * persistence model that could drift from the document's other marks.
*/
export function AnnotationList({
annotations,
@@ -37,105 +37,176 @@ export function AnnotationList({
onDelete,
}: AnnotationListProps) {
const { t } = useTranslation();
+ const [view, setView] = useState<"annotations" | "citations">("annotations");
+
+ const visibleAnnotations = useMemo(
+ () =>
+ annotations.filter((annotation) =>
+ view === "citations"
+ ? annotation.kind === "citation"
+ : annotation.kind !== "citation",
+ ),
+ [annotations, view],
+ );
const groups = useMemo(() => {
const byLocator = new Map<number, AnnotationItem[]>();
- for (const annotation of annotations) {
+ for (const annotation of visibleAnnotations) {
const bucket = byLocator.get(annotation.locator) ?? [];
bucket.push(annotation);
byLocator.set(annotation.locator, bucket);
}
return [...byLocator.entries()].sort((a, b) => a[0] - b[0]);
- }, [annotations]);
+ }, [visibleAnnotations]);
- if (!annotations.length) {
- return (
- <div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
- <Sparkles size={18} className="text-[var(--muted-foreground)]/60" />
- <p className="text-[12px] font-medium text-[var(--foreground)]">
- {t("No annotations yet")}
- </p>
- <p className="max-w-[220px] text-[11px] leading-relaxed text-[var(--muted-foreground)]">
- {t("Select text in the document to highlight it or attach a note.")}
- </p>
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div
+ role="tablist"
+ aria-label={t("Saved reading marks")}
+ className="grid shrink-0 grid-cols-2 gap-1 border-b border-[var(--border)] p-2"
+ >
+ <ViewTab
+ active={view === "annotations"}
+ icon={Highlighter}
+ label={t("Annotations")}
+ onClick={() => setView("annotations")}
+ />
+ <ViewTab
+ active={view === "citations"}
+ icon={Bookmark}
+ label={t("Citations")}
+ onClick={() => setView("citations")}
+ />
</div>
- );
- }
- return (
- <div className="dt-reader-scroll h-full overflow-y-auto px-2.5 py-2">
- {groups.map(([locator, rows]) => (
- <section key={locator} className="mb-3 last:mb-1">
- <h4 className="sticky top-0 z-10 mb-1 bg-[var(--background)]/95 px-1 py-1 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--muted-foreground)] backdrop-blur">
- {t(unitLabel(unit))} {locator}
- </h4>
- <ul className="space-y-1">
- {rows.map((annotation) => (
- <li key={annotation.annotation_id}>
- <div
- role="button"
- tabIndex={0}
- onClick={() => onSelect(annotation)}
- onKeyDown={(event) => {
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault();
- onSelect(annotation);
- }
- }}
- className={`group/anno relative w-full cursor-pointer rounded-lg border px-2.5 py-2 text-left transition ${
- annotation.annotation_id === activeId
- ? "border-[var(--ring)] bg-[var(--muted)]/60"
- : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"
- }`}
- >
- <span
- aria-hidden
- className="absolute left-0 top-2 bottom-2 w-[3px] rounded-full"
- style={{
- background: SWATCH[annotation.color] ?? SWATCH.yellow,
- }}
- />
- {annotation.quote && (
- <p className="line-clamp-3 pl-1.5 text-[12px] leading-[1.55] text-[var(--foreground)]">
- {annotation.quote}
- </p>
- )}
- {annotation.note && (
- <p className="mt-1 line-clamp-3 pl-1.5 text-[11px] leading-[1.5] text-[var(--muted-foreground)]">
- {annotation.note}
- </p>
- )}
- <div className="mt-1 flex items-center gap-1.5 pl-1.5">
- {annotation.author === "assistant" && (
- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/10 px-1.5 py-[1px] text-[10px] font-medium text-[var(--primary)]">
- <Bot size={9} />
- {t("AI")}
- </span>
- )}
- {annotation.kind === "underline" && (
- <span className="text-[10px] text-[var(--muted-foreground)]">
- {t("Underline")}
- </span>
- )}
- </div>
- <button
- type="button"
- title={t("Delete annotation")}
- aria-label={t("Delete annotation")}
- onClick={(event) => {
- event.stopPropagation();
- onDelete(annotation);
- }}
- className="absolute right-1.5 top-1.5 inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] focus-visible:opacity-100 group-hover/anno:opacity-100"
- >
- <Trash2 size={12} />
- </button>
- </div>
- </li>
- ))}
- </ul>
- </section>
- ))}
+ {!visibleAnnotations.length ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 px-6 text-center">
+ <Sparkles size={18} className="text-[var(--muted-foreground)]/60" />
+ <p className="text-[12px] font-medium text-[var(--foreground)]">
+ {t(
+ view === "citations" ? "No citations yet" : "No annotations yet",
+ )}
+ </p>
+ <p className="max-w-[220px] text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ view === "citations"
+ ? "Select text in the document to save a citation."
+ : "Select text in the document to highlight it or attach a note.",
+ )}
+ </p>
+ </div>
+ ) : (
+ <div className="dt-reader-scroll min-h-0 flex-1 overflow-y-auto px-2.5 py-2">
+ {groups.map(([locator, rows]) => (
+ <section key={locator} className="mb-3 last:mb-1">
+ <h4 className="sticky top-0 z-10 mb-1 bg-[var(--background)]/95 px-1 py-1 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--muted-foreground)] backdrop-blur">
+ {t(unitLabel(unit))} {locator}
+ </h4>
+ <ul className="space-y-1">
+ {rows.map((annotation) => (
+ <li key={annotation.annotation_id}>
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={() => onSelect(annotation)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onSelect(annotation);
+ }
+ }}
+ className={`group/anno relative w-full cursor-pointer rounded-lg border px-2.5 py-2 text-left transition ${
+ annotation.annotation_id === activeId
+ ? "border-[var(--ring)] bg-[var(--muted)]/60"
+ : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ <span
+ aria-hidden
+ className="absolute left-0 top-2 bottom-2 w-[3px] rounded-full"
+ style={{
+ background: SWATCH[annotation.color] ?? SWATCH.yellow,
+ }}
+ />
+ {annotation.quote && (
+ <p className="line-clamp-3 pl-1.5 text-[12px] leading-[1.55] text-[var(--foreground)]">
+ {annotation.quote}
+ </p>
+ )}
+ {annotation.note && (
+ <p className="mt-1 line-clamp-3 pl-1.5 text-[11px] leading-[1.5] text-[var(--muted-foreground)]">
+ {annotation.note}
+ </p>
+ )}
+ <div className="mt-1 flex items-center gap-1.5 pl-1.5">
+ {annotation.author === "assistant" && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/10 px-1.5 py-[1px] text-[10px] font-medium text-[var(--primary)]">
+ <Bot size={9} />
+ {t("AI")}
+ </span>
+ )}
+ {annotation.kind === "underline" && (
+ <span className="text-[10px] text-[var(--muted-foreground)]">
+ {t("Underline")}
+ </span>
+ )}
+ {annotation.kind === "citation" && (
+ <span className="inline-flex items-center gap-1 text-[10px] text-[var(--muted-foreground)]">
+ <Bookmark size={9} />
+ {t("Citation")}
+ </span>
+ )}
+ </div>
+ <button
+ type="button"
+ title={t("Delete annotation")}
+ aria-label={t("Delete annotation")}
+ onClick={(event) => {
+ event.stopPropagation();
+ onDelete(annotation);
+ }}
+ className="absolute right-1.5 top-1.5 inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] focus-visible:opacity-100 group-hover/anno:opacity-100"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </section>
+ ))}
+ </div>
+ )}
</div>
);
}
+
+function ViewTab({
+ active,
+ icon: Icon,
+ label,
+ onClick,
+}: {
+ active: boolean;
+ icon: typeof Highlighter;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={onClick}
+ className={`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 text-[11px] font-medium transition ${
+ active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Icon size={12} />
+ <span className="truncate">{label}</span>
+ </button>
+ );
+}
diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsx
index 553a116d1..ac96b1c1d 100644
--- a/web/components/reading/AnnotationPopover.tsx
+++ b/web/components/reading/AnnotationPopover.tsx
@@ -2,6 +2,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
+ BookmarkPlus,
Highlighter,
MessageSquareQuote,
StickyNote,
@@ -25,6 +26,7 @@ export interface AnnotationPopoverProps {
onHighlight: (color: AnnotationColor) => void;
onUnderline: (color: AnnotationColor) => void;
onNote: (note: string, color: AnnotationColor) => void;
+ onCitation: (color: AnnotationColor) => void;
onAsk: () => void;
onDismiss: () => void;
}
@@ -47,6 +49,7 @@ export function AnnotationPopover({
onHighlight,
onUnderline,
onNote,
+ onCitation,
onAsk,
onDismiss,
}: AnnotationPopoverProps) {
@@ -139,6 +142,11 @@ export function AnnotationPopover({
active={noteOpen}
onClick={() => setNoteOpen((open) => !open)}
/>
+ <IconButton
+ icon={BookmarkPlus}
+ label={t("Save citation")}
+ onClick={() => onCitation(color)}
+ />
<IconButton
icon={MessageSquareQuote}
label={t("Ask about this")}
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 80628af8f..8ed5c4e70 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -94,13 +94,18 @@ 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 [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 [headingJump, setHeadingJump] = useState<{
+ id: string;
+ nonce: number;
+ } | null>(null);
const nonceRef = useRef(0);
const headingNonceRef = useRef(0);
@@ -125,7 +130,9 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
return;
}
try {
- const stored = window.localStorage.getItem(`dt.reader.outline.${material.material_id}`);
+ const stored = window.localStorage.getItem(
+ `dt.reader.outline.${material.material_id}`,
+ );
setOutlineUserChoice(stored === null ? null : stored === "open");
} catch {
setOutlineUserChoice(null);
@@ -136,7 +143,8 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
if (!material || outlineUserChoice !== null) return;
const desktop = window.matchMedia("(min-width: 768px)").matches;
setShowOutline(
- desktop && ((material.outline?.length ?? 0) >= 8 || pageHeadings.length >= 3),
+ desktop &&
+ ((material.outline?.length ?? 0) >= 8 || pageHeadings.length >= 3),
);
}, [material, outlineUserChoice, pageHeadings.length]);
@@ -293,7 +301,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
const commitSelection = useCallback(
(
- kind: "highlight" | "underline" | "note",
+ kind: "highlight" | "underline" | "note" | "citation",
color: AnnotationColor,
note = "",
) => {
@@ -497,11 +505,15 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
currentLocator={currentLocator}
onNavigate={(locator) => {
requestJump(locator);
- if (!window.matchMedia("(min-width: 768px)").matches) setShowOutline(false);
+ if (!window.matchMedia("(min-width: 768px)").matches)
+ setShowOutline(false);
}}
onNavigateHeading={(heading) => {
headingNonceRef.current += 1;
- setHeadingJump({ id: heading.id, nonce: headingNonceRef.current });
+ setHeadingJump({
+ id: heading.id,
+ nonce: headingNonceRef.current,
+ });
}}
onClose={() => setShowOutline(false)}
/>
@@ -587,6 +599,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
onHighlight={(color) => commitSelection("highlight", color)}
onUnderline={(color) => commitSelection("underline", color)}
onNote={(note, color) => commitSelection("note", color, note)}
+ onCitation={(color) => commitSelection("citation", color)}
onAsk={askAboutSelection}
onDismiss={() => setSelection(null)}
/>
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index a52c35f83..8777ac7ab 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -9,7 +9,7 @@ import { apiFetch, apiUrl } from "@/lib/api";
// "chapter 3" without ever branching on the file type itself.
export type UnitKind = "page" | "chapter" | "slide" | "section";
-export type AnnotationKind = "highlight" | "underline" | "note";
+export type AnnotationKind = "highlight" | "underline" | "note" | "citation";
export type ExportFormat = "auto" | "pdf" | "markdown";
export type RenderMode = "text" | "pdf" | "epub";
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index bc6f28b3f..1fc1d7357 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3235,6 +3235,7 @@
"Highlight": "Highlight",
"Underline": "Underline",
"Add note": "Add note",
+ "Save citation": "Save citation",
"Ask about this": "Ask about this",
"Your note…": "Your note…",
"Save note": "Save note",
@@ -3244,6 +3245,11 @@
"Pink": "Pink",
"Purple": "Purple",
"No annotations yet": "No annotations yet",
+ "Citations": "Citations",
+ "Citation": "Citation",
+ "No citations yet": "No citations yet",
+ "Saved reading marks": "Saved reading marks",
+ "Select text in the document to save a citation.": "Select text in the document to save a citation.",
"Select text in the document to highlight it or attach a note.": "Select text in the document to highlight it or attach a note.",
"Delete annotation": "Delete annotation",
"{{count}} annotations": "{{count}} annotations",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index cca26990d..af8442b67 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3235,6 +3235,7 @@
"Highlight": "高亮",
"Underline": "下划线",
"Add note": "添加批注",
+ "Save citation": "保存引用",
"Ask about this": "就此提问",
"Your note…": "写下你的批注…",
"Save note": "保存批注",
@@ -3244,6 +3245,11 @@
"Pink": "粉色",
"Purple": "紫色",
"No annotations yet": "还没有标注",
+ "Citations": "引用",
+ "Citation": "引用",
+ "No citations yet": "还没有引用",
+ "Saved reading marks": "已保存的阅读标记",
+ "Select text in the document to save a citation.": "在文档里选中文字即可保存引用。",
"Select text in the document to highlight it or attach a note.": "在文档里选中文字即可高亮或添加批注。",
"Delete annotation": "删除标注",
"{{count}} annotations": "{{count}} 条标注",
diff --git a/web/tests/reading-citation-capture.test.ts b/web/tests/reading-citation-capture.test.ts
new file mode 100644
index 000000000..9cd3aedb0
--- /dev/null
+++ b/web/tests/reading-citation-capture.test.ts
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+function source(file: string): string {
+ return fs.readFileSync(path.resolve(process.cwd(), file), "utf8");
+}
+
+test("citation capture extends the existing annotation contract", () => {
+ assert.match(
+ source("lib/reading-api.ts"),
+ /AnnotationKind = [^;]*"citation"/,
+ );
+ assert.match(
+ source("components/reading/ReaderPane.tsx"),
+ /commitSelection\("citation", color\)/,
+ );
+ assert.match(
+ source("components/reading/AnnotationPopover.tsx"),
+ /label=\{t\("Save citation"\)\}/,
+ );
+});
+
+test("citations have a dedicated view in the existing annotation sidebar", () => {
+ const list = source("components/reading/AnnotationList.tsx");
+ assert.match(list, /view === "citations"/);
+ assert.match(list, /annotation\.kind === "citation"/);
+ assert.match(list, /label=\{t\("Citations"\)\}/);
+});