Skip to content

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

feat(reading): render reflowing annotations with Recogito

XZH6ebde8693b76
diff --git a/web/app/globals.css b/web/app/globals.css
index 59aef7cf5..5f4a7ca65 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -989,6 +989,47 @@ a[href^="#dt-locator-"]:hover {
background: transparent;
}
+/* Recogito Text Annotator's required overlay styles, scoped to the Reader.
+ The package's global stylesheet also changes html/body overscroll and every
+ selection in the app, so importing it would leak reader behaviour into chat.
+ Source: @recogito/text-annotator 4.2.5 (BSD-3-Clause). */
+.dt-reader-scroll .r6o-annotatable {
+ position: relative;
+ -webkit-tap-highlight-color: transparent;
+}
+
+.dt-reader-scroll .r6o-annotatable.no-focus-outline {
+ outline: none;
+}
+
+.dt-reader-scroll .r6o-annotatable .r6o-span-highlight-layer {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ pointer-events: none;
+ user-select: none;
+ mix-blend-mode: multiply;
+}
+
+.dt-reader-scroll .r6o-annotatable .r6o-span-highlight-layer.hidden {
+ display: none;
+}
+
+.dt-reader-scroll .r6o-annotatable .r6o-span-highlight-layer .r6o-annotation {
+ position: absolute;
+ display: block;
+ box-sizing: content-box;
+ border-style: solid;
+ border-width: 0;
+}
+
+.dt-reader-scroll .r6o-annotatable .hovered * {
+ cursor: pointer;
+}
+
/* Sidebar tooltip */
.dt-tooltip-wrapper {
@apply relative inline-flex;
diff --git a/web/components/reading/PdfDocumentView.tsx b/web/components/reading/PdfDocumentView.tsx
index 3cfab5557..685e941ce 100644
--- a/web/components/reading/PdfDocumentView.tsx
+++ b/web/components/reading/PdfDocumentView.tsx
@@ -4,7 +4,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { loadPdfjs, type PdfDocument } from "@/lib/pdfjs-loader";
-import type { AnnotationItem, NormalisedRect } from "@/lib/reading-api";
+import type {
+ AnnotationItem,
+ NormalisedRect,
+ ReadingTextSelector,
+} from "@/lib/reading-api";
import { rawMaterialUrl } from "@/lib/reading-api";
import { domRangeForQuote } from "@/lib/reading-quote-locator";
import {
@@ -24,6 +28,7 @@ export interface SelectionPayload {
quote: string;
rects: NormalisedRect[];
sourceAnchor?: string;
+ selectors?: ReadingTextSelector[];
/** Viewport coordinates of the selection, for popover placement. */
anchor: { x: number; y: number };
}
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 4b3f59cee..5273ab512 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -247,6 +247,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
note,
rects: selection.rects,
source_anchor: selection.sourceAnchor ?? "",
+ selectors: selection.selectors ?? [],
},
{
annotation_id: temporaryId,
@@ -257,6 +258,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
note,
rects: selection.rects,
source_anchor: selection.sourceAnchor ?? "",
+ selectors: selection.selectors ?? [],
author: "user",
created_at: now,
updated_at: now,
diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsx
index 71853c7fa..a3a3b769d 100644
--- a/web/components/reading/TextUnitView.tsx
+++ b/web/components/reading/TextUnitView.tsx
@@ -1,12 +1,12 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { AnnotationItem, UnitKind } from "@/lib/reading-api";
import { getUnitText } from "@/lib/reading-api";
-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";
const COLOR_INK: Record<string, string> = {
@@ -51,6 +51,17 @@ export function TextUnitView({
}: TextUnitViewProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement | null>(null);
+ const articleRef = useRef<HTMLElement | null>(null);
+ const textSelectorToolsRef = useRef<{
+ rangeToSelector: (
+ range: Range,
+ container: HTMLElement,
+ ) => { quote: string; start: number; end: number };
+ getQuoteContext: (
+ range: Range,
+ container: HTMLElement,
+ ) => { prefix: string; suffix: string };
+ } | null>(null);
const [locator, setLocator] = useState(1);
const [text, setText] = useState("");
const [loading, setLoading] = useState(true);
@@ -103,14 +114,80 @@ export function TextUnitView({
if (containerRef.current) containerRef.current.scrollTop = 0;
}, [jump, unitCount]);
- const runs = useMemo(
- () =>
- segmentTextByQuotes(
- text,
- annotations.filter((a) => a.locator === locator),
- ),
- [text, annotations, locator],
- );
+ useEffect(() => {
+ const article = articleRef.current;
+ if (!article || loading || error) return;
+ let cancelled = false;
+ let annotator: { destroy: () => void } | null = null;
+
+ void import("@recogito/text-annotator")
+ .then((module) => {
+ if (cancelled) return;
+ textSelectorToolsRef.current = {
+ rangeToSelector: module.rangeToSelector,
+ getQuoteContext: module.getQuoteContext,
+ };
+ const instance = module.createTextAnnotator(article, {
+ annotatingEnabled: false,
+ renderer: "SPANS",
+ style: (annotation) => {
+ const properties = annotation.properties as
+ | { annotationId?: string; color?: string; kind?: string }
+ | undefined;
+ const color = COLOR_INK[properties?.color ?? ""] ?? COLOR_INK.yellow;
+ if (properties?.kind === "underline") {
+ return {
+ fill: "transparent",
+ underlineColor: `rgb(${color})`,
+ underlineThickness: 2,
+ };
+ }
+ return {
+ fill: `rgb(${color})`,
+ fillOpacity:
+ properties?.annotationId === highlightedAnnotationId ? 0.8 : 0.55,
+ };
+ },
+ });
+ annotator = instance;
+ const rows = annotations
+ .filter((annotation) => annotation.locator === locator)
+ .map((annotation) =>
+ toRecogitoTextAnnotation(annotation, article.textContent ?? ""),
+ )
+ .filter((annotation) => annotation !== null);
+ instance.setAnnotations(rows);
+ instance.on("clickAnnotation", (selected) => {
+ const id = selected.id;
+ const annotation = annotations.find((row) => row.annotation_id === id);
+ if (annotation) onAnnotationClick?.(annotation);
+ });
+ if (highlightedAnnotationId) {
+ instance.scrollIntoView(
+ highlightedAnnotationId,
+ containerRef.current ?? article,
+ );
+ }
+ })
+ .catch(() => {
+ // The text remains readable and selection falls back to legacy quotes.
+ if (!cancelled) textSelectorToolsRef.current = null;
+ });
+
+ return () => {
+ cancelled = true;
+ annotator?.destroy();
+ textSelectorToolsRef.current = null;
+ };
+ }, [
+ annotations,
+ error,
+ highlightedAnnotationId,
+ loading,
+ locator,
+ onAnnotationClick,
+ text,
+ ]);
const handlePointerUp = useCallback(() => {
const selection = window.getSelection();
@@ -119,11 +196,16 @@ export function TextUnitView({
return;
}
const range = selection.getRangeAt(0);
- if (!containerRef.current?.contains(range.commonAncestorContainer)) {
+ if (!text.trim() || !articleRef.current?.contains(range.commonAncestorContainer)) {
onSelection(null);
return;
}
- const quote = cleanQuote(selection.toString());
+ const tools = textSelectorToolsRef.current;
+ const selector = tools?.rangeToSelector(range, articleRef.current);
+ const quote =
+ selector && selector.quote.length <= 2000
+ ? selector.quote
+ : cleanQuote(selection.toString());
if (!quote) {
onSelection(null);
return;
@@ -135,11 +217,26 @@ export function TextUnitView({
quote,
// No geometry: a reflowing text view has none worth storing.
rects: [],
+ selectors:
+ selector && selector.quote === quote
+ ? [
+ {
+ type: "TextQuoteSelector",
+ exact: selector.quote,
+ ...tools?.getQuoteContext(range, articleRef.current),
+ },
+ {
+ type: "TextPositionSelector",
+ start: selector.start,
+ end: selector.end,
+ },
+ ]
+ : [],
anchor: last
? { x: last.left + last.width / 2, y: last.top }
: { x: 0, y: 0 },
});
- }, [locator, onSelection]);
+ }, [locator, onSelection, text]);
const canPrev = locator > 1;
const canNext = locator < unitCount;
@@ -190,42 +287,16 @@ export function TextUnitView({
) : error ? (
<p className="text-[12px] text-[var(--muted-foreground)]">{error}</p>
) : (
- <article className="mx-auto max-w-[68ch] whitespace-pre-wrap font-serif text-[15px] leading-[1.75] text-[var(--foreground)] selection:bg-[var(--primary)]/20">
- {runs.length === 0 ? (
+ <article
+ ref={articleRef}
+ className="mx-auto max-w-[68ch] whitespace-pre-wrap font-serif text-[15px] leading-[1.75] text-[var(--foreground)] selection:bg-[var(--primary)]/20"
+ >
+ {!text.trim() ? (
<span className="text-[var(--muted-foreground)]">
{t("This section has no extractable text.")}
</span>
) : (
- runs.map((run, index) =>
- run.mark ? (
- <mark
- key={index}
- 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,
- }}
- >
- {run.text}
- </mark>
- ) : (
- <span key={index}>{run.text}</span>
- ),
- )
+ text
)}
</article>
)}
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index aba46c40b..cf52b46b3 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -68,6 +68,19 @@ export interface UnitReference {
*/
export type NormalisedRect = [number, number, number, number];
+export type ReadingTextSelector =
+ | {
+ type: "TextQuoteSelector";
+ exact: string;
+ prefix?: string;
+ suffix?: string;
+ }
+ | {
+ type: "TextPositionSelector";
+ start: number;
+ end: number;
+ };
+
export interface AnnotationItem {
annotation_id: string;
locator: number;
@@ -77,6 +90,7 @@ export interface AnnotationItem {
note: string;
rects: NormalisedRect[];
source_anchor: string;
+ selectors?: ReadingTextSelector[];
/** "user" or "assistant" — the model can annotate too. */
author: string;
created_at: number;
@@ -92,6 +106,7 @@ export interface AnnotationDraft {
note?: string;
rects?: NormalisedRect[];
source_anchor?: string;
+ selectors?: ReadingTextSelector[];
}
export interface ReadingPosition {
diff --git a/web/lib/reading-w3c-annotations.ts b/web/lib/reading-w3c-annotations.ts
new file mode 100644
index 000000000..09b339031
--- /dev/null
+++ b/web/lib/reading-w3c-annotations.ts
@@ -0,0 +1,165 @@
+import type {
+ AnnotationItem,
+ ReadingTextSelector,
+} from "@/lib/reading-api";
+
+export interface W3CTextAnnotation {
+ "@context": "http://www.w3.org/ns/anno.jsonld";
+ id: string;
+ type: "Annotation";
+ body: Array<{
+ type: "TextualBody";
+ purpose: "commenting" | "highlighting";
+ value: string;
+ }>;
+ target: {
+ source: string;
+ selector: ReadingTextSelector[];
+ };
+}
+
+export interface RecogitoTextAnnotation {
+ id: string;
+ bodies: [];
+ target: {
+ annotation: string;
+ selector: Array<{ quote: string; start: number; end: number }>;
+ };
+ properties: {
+ annotationId: string;
+ color: string;
+ kind: AnnotationItem["kind"];
+ };
+}
+
+/**
+ * Resolve a persisted W3C quote/position pair against the currently rendered
+ * text. Position is accepted only when it still covers the quote; otherwise a
+ * unique quote plus prefix/suffix context is used to re-anchor it.
+ */
+export function resolveTextSelectors(
+ text: string,
+ annotation: Pick<AnnotationItem, "quote" | "selectors">,
+): ReadingTextSelector[] | null {
+ const stored = annotation.selectors ?? [];
+ const quoteSelector = stored.find(
+ (selector) => selector.type === "TextQuoteSelector",
+ );
+ const positionSelector = stored.find(
+ (selector) => selector.type === "TextPositionSelector",
+ );
+ const exact =
+ quoteSelector?.type === "TextQuoteSelector"
+ ? quoteSelector.exact
+ : annotation.quote;
+ if (!exact) return null;
+
+ if (
+ positionSelector?.type === "TextPositionSelector" &&
+ positionSelector.start >= 0 &&
+ positionSelector.end <= text.length &&
+ text.slice(positionSelector.start, positionSelector.end) === exact
+ ) {
+ return [
+ quoteSelector?.type === "TextQuoteSelector"
+ ? quoteSelector
+ : quoteAt(text, exact, positionSelector.start),
+ positionSelector,
+ ];
+ }
+
+ const candidates = occurrences(text, exact);
+ const contextual = candidates.filter((start) => {
+ if (quoteSelector?.type !== "TextQuoteSelector") return true;
+ const prefixMatches =
+ !quoteSelector.prefix || text.slice(0, start).endsWith(quoteSelector.prefix);
+ const suffixMatches =
+ !quoteSelector.suffix ||
+ text.slice(start + exact.length).startsWith(quoteSelector.suffix);
+ return prefixMatches && suffixMatches;
+ });
+ const matches = contextual.length ? contextual : candidates;
+ if (matches.length !== 1) return null;
+ const start = matches[0];
+ return [
+ quoteAt(text, exact, start),
+ { type: "TextPositionSelector", start, end: start + exact.length },
+ ];
+}
+
+export function toW3CTextAnnotation(
+ annotation: AnnotationItem,
+ renderedText: string,
+ source: string,
+): W3CTextAnnotation | null {
+ const selector = resolveTextSelectors(renderedText, annotation);
+ if (!selector) return null;
+ return {
+ "@context": "http://www.w3.org/ns/anno.jsonld",
+ id: annotation.annotation_id,
+ type: "Annotation",
+ body: [
+ {
+ type: "TextualBody",
+ purpose: annotation.note ? "commenting" : "highlighting",
+ value: annotation.note,
+ },
+ ],
+ target: { source, selector },
+ };
+}
+
+export function toRecogitoTextAnnotation(
+ annotation: AnnotationItem,
+ renderedText: string,
+): RecogitoTextAnnotation | null {
+ const selectors = resolveTextSelectors(renderedText, annotation);
+ const quote = selectors?.find(
+ (selector) => selector.type === "TextQuoteSelector",
+ );
+ const position = selectors?.find(
+ (selector) => selector.type === "TextPositionSelector",
+ );
+ if (
+ quote?.type !== "TextQuoteSelector" ||
+ position?.type !== "TextPositionSelector"
+ ) {
+ return null;
+ }
+ return {
+ id: annotation.annotation_id,
+ bodies: [],
+ target: {
+ annotation: annotation.annotation_id,
+ selector: [
+ { quote: quote.exact, start: position.start, end: position.end },
+ ],
+ },
+ properties: {
+ annotationId: annotation.annotation_id,
+ color: annotation.color,
+ kind: annotation.kind,
+ },
+ };
+}
+
+function quoteAt(text: string, exact: string, start: number): ReadingTextSelector {
+ return {
+ type: "TextQuoteSelector",
+ exact,
+ prefix: text.slice(Math.max(0, start - 10), start),
+ suffix: text.slice(start + exact.length, start + exact.length + 10),
+ };
+}
+
+function occurrences(text: string, quote: string): number[] {
+ const found: number[] = [];
+ let start = 0;
+ while (start <= text.length - quote.length) {
+ const match = text.indexOf(quote, start);
+ if (match < 0) break;
+ found.push(match);
+ start = match + Math.max(1, quote.length);
+ }
+ return found;
+}
diff --git a/web/package-lock.json b/web/package-lock.json
index 2d112a520..ce26fd956 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -8,6 +8,7 @@
"name": "opentutor-web",
"version": "1.0.0",
"dependencies": {
+ "@recogito/text-annotator": "4.2.5",
"chart.js": "^4.5.1",
"clsx": "^2.1.1",
"cytoscape": "^3.33.1",
@@ -62,6 +63,65 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@annotorious/core": {
+ "version": "3.8.9",
+ "resolved": "https://registry.npmjs.org/@annotorious/core/-/core-3.8.9.tgz",
+ "integrity": "sha512-XmiWIBNo4Uq/VuC0AXmLN2kxxvZMyPGanyCICctiW086xNXfwbjKE5DphZ3Y3Fjc0lKY1Lzq3N9FmU7wE+XPMg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "dequal": "^2.0.3",
+ "nanoevents": "^10.0.0",
+ "nanoid": "^6.0.1",
+ "nanostores": "^1.4.2",
+ "uuid": "^14.0.1"
+ }
+ },
+ "node_modules/@annotorious/core/node_modules/nanoevents": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/nanoevents/-/nanoevents-10.0.0.tgz",
+ "integrity": "sha512-PmIJ3BNxOzgVgnS1r/Pvyj6eZx/xUV2JCPogh0brD6smDIwjRlr1KBl9yoRX323PlfaNrBDDnfCgC9SL00OjSg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": "^22.0.0 || ^24.0.0 || >=26.0.0"
+ }
+ },
+ "node_modules/@annotorious/core/node_modules/nanoid": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz",
+ "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.js"
+ },
+ "engines": {
+ "node": "^22 || ^24 || >=26"
+ }
+ },
+ "node_modules/@annotorious/core/node_modules/uuid": {
+ "version": "14.0.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.2.tgz",
+ "integrity": "sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist-node/bin/uuid"
+ }
+ },
"node_modules/@antfu/install-pkg": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz",
@@ -1656,6 +1716,36 @@
"node": ">=18"
}
},
+ "node_modules/@recogito/text-annotator": {
+ "version": "4.2.5",
+ "resolved": "https://registry.npmjs.org/@recogito/text-annotator/-/text-annotator-4.2.5.tgz",
+ "integrity": "sha512-fyAtVtPwZ4ZCMY4VELW906v32g9dz7mYGAqR2ljV9ofSkLSihFstn7qQrR+8m5YYNMyi14CcIRxqOO4mq496Vw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@annotorious/core": "^3.8.6",
+ "colord": "^2.9.3",
+ "debounce": "^3.0.0",
+ "dequal": "^2.0.3",
+ "hotkeys-js": "^4.0.4",
+ "nanoevents": "^9.1.0",
+ "poll": "^3.2.2",
+ "rbush": "^4.0.1",
+ "uuid": "^14.0.0"
+ }
+ },
+ "node_modules/@recogito/text-annotator/node_modules/uuid": {
+ "version": "14.0.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.2.tgz",
+ "integrity": "sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist-node/bin/uuid"
+ }
+ },
"node_modules/@rtsao/scc": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
@@ -3603,6 +3693,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/colord": {
+ "version": "2.10.0",
+ "resolved": "https://registry.npmjs.org/colord/-/colord-2.10.0.tgz",
+ "integrity": "sha512-AidJptpBJmjTclAp9BkLwJi0T93fo5epJnbaZslpg6QVzpHjAiveF55mE9AcUJiGMqRHgMDY8soMsQtuNYMHfw==",
+ "license": "MIT"
+ },
"node_modules/comma-separated-tokens": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
@@ -4329,6 +4425,18 @@
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
"license": "MIT"
},
+ "node_modules/debounce": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/debounce/-/debounce-3.0.0.tgz",
+ "integrity": "sha512-64byRbF0/AirwbuHqB3/ZpMG9/nckDa6ZA0yd6UnaQNwbbemCOwvz2sL5sjXLHhZHADyiwLm0M5qMhltUUx+TA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -6178,6 +6286,15 @@
"integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==",
"license": "CC0-1.0"
},
+ "node_modules/hotkeys-js": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/hotkeys-js/-/hotkeys-js-4.0.5.tgz",
+ "integrity": "sha512-Os0VaEH8gvOSzwZnEDU2yn7G868OfFiLydUHIe2uln7Fi9Ii1xhOCoPGu27RkZYWYqM93gC4xoyONCZE9iiwLw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://jaywcjlove.github.io/#/sponsor"
+ }
+ },
"node_modules/html-parse-stringify": {
"version": "3.0.1",
"resolved": "https://registry.npmmirror.com/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
@@ -8480,6 +8597,15 @@
"thenify-all": "^1.0.0"
}
},
+ "node_modules/nanoevents": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/nanoevents/-/nanoevents-9.1.0.tgz",
+ "integrity": "sha512-Jd0fILWG44a9luj8v5kED4WI+zfkkgwKyRQKItTtlPfEsh7Lznfi1kr8/iZ+XAIss4Qq5GqRB0qtWbaz9ceO/A==",
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ }
+ },
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
@@ -8498,6 +8624,21 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/nanostores": {
+ "version": "1.5.2",
+ "resolved": "https://registry.npmjs.org/nanostores/-/nanostores-1.5.2.tgz",
+ "integrity": "sha512-B0UbxzK1s0CN8Xht6r+7iT5+xV8PTaRERR1nATeplRv1Rw5YLWfVAid0hkqY3EceqpG4RjTk8GAwIxQY39Rnwg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
"node_modules/napi-postinstall": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz",
@@ -9067,6 +9208,12 @@
"points-on-curve": "0.2.0"
}
},
+ "node_modules/poll": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/poll/-/poll-3.2.2.tgz",
+ "integrity": "sha512-qckJRcLqqsX72Uu/Sa/GbzWUXB/zZcyMNccwdGFQnYoewnXUdWyMWkHUmaiBAvm950ujJJ15OiFFy+gtBm1K+A==",
+ "license": "MIT"
+ },
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@@ -9318,6 +9465,12 @@
],
"license": "MIT"
},
+ "node_modules/quickselect": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
+ "integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",
+ "license": "ISC"
+ },
"node_modules/raf": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
@@ -9328,6 +9481,15 @@
"performance-now": "^2.1.0"
}
},
+ "node_modules/rbush": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/rbush/-/rbush-4.0.1.tgz",
+ "integrity": "sha512-IP0UpfeWQujYC8Jg162rMNc01Rf0gWMMAb2Uxus/Q0qOFw4lCcq6ZnQEZwUoJqWyUGJ9th7JjwI4yIWo+uvoAQ==",
+ "license": "MIT",
+ "dependencies": {
+ "quickselect": "^3.0.0"
+ }
+ },
"node_modules/react": {
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
diff --git a/web/package.json b/web/package.json
index 34ccc8e2f..a41859ea9 100644
--- a/web/package.json
+++ b/web/package.json
@@ -21,6 +21,7 @@
"build:brand-icons": "tsx ./scripts/build-brand-icons.mts"
},
"dependencies": {
+ "@recogito/text-annotator": "4.2.5",
"chart.js": "^4.5.1",
"clsx": "^2.1.1",
"cytoscape": "^3.33.1",
diff --git a/web/tests/reading-w3c-annotations.test.ts b/web/tests/reading-w3c-annotations.test.ts
new file mode 100644
index 000000000..7c506c603
--- /dev/null
+++ b/web/tests/reading-w3c-annotations.test.ts
@@ -0,0 +1,104 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { AnnotationItem } from "@/lib/reading-api";
+import {
+ resolveTextSelectors,
+ toRecogitoTextAnnotation,
+ toW3CTextAnnotation,
+} from "@/lib/reading-w3c-annotations";
+
+function annotation(overrides: Partial<AnnotationItem> = {}): AnnotationItem {
+ return {
+ annotation_id: "mark-1",
+ locator: 1,
+ kind: "highlight",
+ color: "yellow",
+ quote: "portable quote",
+ note: "",
+ rects: [],
+ author: "user",
+ created_at: 1,
+ updated_at: 1,
+ ...overrides,
+ };
+}
+
+test("a valid stored position remains the primary selector", () => {
+ const selectors = resolveTextSelectors(
+ "Start portable quote end",
+ annotation({
+ selectors: [
+ { type: "TextQuoteSelector", exact: "portable quote" },
+ { type: "TextPositionSelector", start: 6, end: 20 },
+ ],
+ }),
+ );
+
+ assert.deepEqual(selectors?.[1], {
+ type: "TextPositionSelector",
+ start: 6,
+ end: 20,
+ });
+});
+
+test("a stale position re-anchors by unique quote", () => {
+ const selectors = resolveTextSelectors(
+ "A new introduction. portable quote end",
+ annotation({
+ selectors: [
+ { type: "TextQuoteSelector", exact: "portable quote" },
+ { type: "TextPositionSelector", start: 0, end: 14 },
+ ],
+ }),
+ );
+
+ assert.deepEqual(selectors?.[1], {
+ type: "TextPositionSelector",
+ start: 20,
+ end: 34,
+ });
+});
+
+test("prefix and suffix disambiguate repeated Chinese text", () => {
+ const selectors = resolveTextSelectors(
+ "甲相同文字乙;丙相同文字丁",
+ annotation({
+ quote: "相同文字",
+ selectors: [
+ {
+ type: "TextQuoteSelector",
+ exact: "相同文字",
+ prefix: "丙",
+ suffix: "丁",
+ },
+ ],
+ }),
+ );
+
+ assert.deepEqual(selectors?.[1], {
+ type: "TextPositionSelector",
+ start: 8,
+ end: 12,
+ });
+});
+
+test("an ambiguous legacy quote stays unresolved instead of marking the wrong text", () => {
+ assert.equal(
+ resolveTextSelectors("portable quote then portable quote", annotation()),
+ null,
+ );
+});
+
+test("resolved selectors map to both W3C and Recogito annotation contracts", () => {
+ const stored = annotation({ note: "remember this", color: "blue" });
+ const text = "Start portable quote end";
+
+ const w3c = toW3CTextAnnotation(stored, text, "urn:deeptutor:unit:1");
+ const recogito = toRecogitoTextAnnotation(stored, text);
+
+ assert.equal(w3c?.target.source, "urn:deeptutor:unit:1");
+ assert.equal(w3c?.body[0].purpose, "commenting");
+ assert.equal(recogito?.properties.annotationId, "mark-1");
+ assert.equal(recogito?.target.selector[0].start, 6);
+});