Repository Public
1"use client";2/**3 * file: src/components/editor/nodes/PdfView.tsx4 * description: node view of the `pdf` block (SPEC §2) — an annotatable PDF reader. pdf.js is loaded with a dynamic import only when5 * the block comes into view (or on click); one page is rendered at a time (canvas fitted to the block width, devicePixelRatio-aware,6 * stale render tasks cancelled) with the pdf.js text layer above it so text can be selected. A selection becomes a highlight or a7 * note whose rects are stored relative to the page (0..1, origin top-left); `ink` annotations of other clients are drawn read-only8 * and, like every key this client does not know, written back untouched. `page` is the reading position (debounced). A failed load9 * never alters the node. The worker and the optional pdf.js assets are served from /vendor/pdfjs (same origin, CSP worker-src 'self').10 * Research link: when the file is the PDF attached to a reference, highlights and notes are also saved as that reference's extracts11 * (`useExtractLink`, ids derived in src/lib/research/pdf-extracts.ts so nothing is ever duplicated); the annotations stay in the page.12 * author: Simon-Pierre Boucher — contact@spboucher.ai13 */14import * as React from "react";15import type { PDFDocumentLoadingTask, PDFDocumentProxy, RenderTask, TextLayer } from "pdfjs-dist";16import Link from "next/link";17import { useQuery, useQueryClient } from "@tanstack/react-query";18import { BookMarked, ChevronLeft, ChevronRight, ExternalLink, FileText, FileUp, Highlighter, Maximize2, MessageSquarePlus, RotateCw, TextQuote, Trash2, X, ZoomIn, ZoomOut } from "lucide-react";19import type { PdfAnnotation, PdfAttrs } from "@/lib/editor/next-node-defs";20import { annotationAt, annotationLine, clampPage, cleanSelectionText, DEFAULT_HIGHLIGHT_COLOR, HIGHLIGHT_COLORS, inkPointsOf, listAnnotations, newAnnotation, normaliseRects, patchAnnotation, rectsOf, removeAnnotation, safeColor, sortAnnotations, type BoxLike, type NormRect } from "@/lib/editor/pdf-annotations";21import { extractsOf, type Extract } from "@/lib/research/cite";22import { extractOfAnnotation, linkedAnnotationIds, planExtractSync, removedExtractIds, type ExtractPlan } from "@/lib/research/pdf-extracts";23import { api } from "@/lib/client/api";24import { fileUrl, uploadFile } from "@/lib/client/upload";25import { toast } from "@/components/ui/toast";26import { cn } from "@/lib/utils";27import { NodeButton, NodeFrame, NodeState, useDebounced, type LeafViewProps } from "./frame";2829type PdfJs = typeof import("pdfjs-dist");30/** Same-origin copy of pdfjs-dist's `build/pdf.worker.min.mjs` (+ optional `cmaps/`, `standard_fonts/`, `wasm/`, `iccs/`). */31export const PDFJS_ASSETS = "/vendor/pdfjs";32let pdfjs: Promise<PdfJs> | null = null;33/** pdf.js is fetched on first use, once for all blocks. */34function loadPdfJs(): Promise<PdfJs> {35 return (pdfjs ??= import("pdfjs-dist").then((lib) => {36 if (!lib.GlobalWorkerOptions.workerSrc) lib.GlobalWorkerOptions.workerSrc = `${PDFJS_ASSETS}/pdf.worker.min.mjs`;37 return lib;38 }).catch((e) => { pdfjs = null; throw e; }));39}40/** Canvas backing stores above this area are refused by some phones: the output scale is lowered instead. */41const MAX_CANVAS_AREA = 16_000_000;42const ZOOM_MIN = 0.5, ZOOM_MAX = 4, ZOOM_STEP = 1.25;43const MAX_PDF_BYTES = 200 * 1024 * 1024;4445function describeLoadError(e: unknown): string {46 const name = (e as { name?: string })?.name ?? ""; const message = String((e as { message?: string })?.message ?? e ?? "");47 const status = (e as { status?: number })?.status;48 if (name === "PasswordException") return "This PDF is protected by a password and cannot be opened here.";49 if (name === "InvalidPDFException" || name === "FormatError") return "The file is damaged or is not a PDF.";50 if (name === "ResponseException" || name === "MissingPDFException") return status === 404 || (e as { missing?: boolean })?.missing ? "The file was not found — it may have been deleted." : status === 401 || status === 403 ? "You do not have access to this file." : `The file could not be downloaded${status ? ` (HTTP ${status})` : ""}.`;51 if (/worker/i.test(message)) return "The PDF engine could not start (worker file unavailable).";52 if (/fetch|network|load failed/i.test(message)) return "Network error while downloading the file.";53 return message ? `The PDF could not be opened: ${message}` : "The PDF could not be opened.";54}55const isCancel = (e: unknown) => { const n = (e as { name?: string })?.name; return n === "RenderingCancelledException" || n === "AbortException"; };56const pct = (n: number) => `${Math.round(n * 1e4) / 100}%`;5758/** Client rects of the selected text only (text nodes clipped to the range): block boxes, <br> and helper elements never count. */59function selectionTextRects(range: Range, host: HTMLElement): BoxLike[] {60 const out: BoxLike[] = []; const walker = document.createTreeWalker(host, NodeFilter.SHOW_TEXT); const sub = document.createRange();61 for (let n = walker.nextNode(); n; n = walker.nextNode()) {62 if (!range.intersectsNode(n)) continue;63 const length = (n.nodeValue ?? "").length; const start = n === range.startContainer ? range.startOffset : 0; const end = n === range.endContainer ? range.endOffset : length;64 if (end <= start) continue;65 sub.setStart(n, Math.min(start, length)); sub.setEnd(n, Math.min(end, length));66 for (const r of Array.from(sub.getClientRects())) out.push({ left: r.left, top: r.top, width: r.width, height: r.height });67 }68 return out;69}7071export function PdfView(props: LeafViewProps<PdfAttrs>) {72 const { attrs, selected, editable } = props;73 const name = typeof attrs.name === "string" ? attrs.name : "";74 return (75 <NodeFrame kind="pdf" label="PDF" icon={<FileText />} title={name} selected={selected}>76 {attrs.attachmentId ? <PdfReader key={attrs.attachmentId} {...props} attachmentId={attrs.attachmentId} />77 : editable ? <PdfPicker {...props} />78 : <NodeState icon={<FileText />} title="No PDF attached" />}79 </NodeFrame>80 );81}8283/** Empty block: choose a file, upload it with progress, then (and only then) write the attachment into the node. */84function PdfPicker({ update, pageId }: LeafViewProps<PdfAttrs>) {85 const input = React.useRef<HTMLInputElement>(null);86 const [progress, setProgress] = React.useState<number | null>(null);87 const [error, setError] = React.useState<string | null>(null);88 const abort = React.useRef<AbortController | null>(null); const alive = React.useRef(true);89 React.useEffect(() => { alive.current = true; return () => { alive.current = false; abort.current?.abort(); }; }, []);90 const choose = async (file: File | undefined) => {91 if (!file) return;92 if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)) { setError("Choose a PDF file."); return; }93 if (file.size > MAX_PDF_BYTES) { setError("File too large (200 MB max)."); return; }94 const controller = new AbortController(); abort.current = controller; setError(null); setProgress(0);95 try {96 const up = await uploadFile(file, pageId, { onProgress: (f) => { if (alive.current) setProgress(f); }, signal: controller.signal });97 if (alive.current) update({ attachmentId: up.id, name: up.name || file.name });98 } catch (e) {99 if (alive.current && (e as Error)?.name !== "AbortError") setError((e as Error)?.message || "Upload failed");100 } finally { if (abort.current === controller) abort.current = null; if (alive.current) setProgress(null); }101 };102 const uploading = progress !== null;103 return (104 <NodeState icon={<FileUp />} tone={error ? "danger" : "neutral"} title={uploading ? `Uploading… ${Math.round((progress ?? 0) * 100)} %` : error ?? "Add a PDF to read and annotate"}105 hint={uploading ? <progress className="pdfv-progress" max={1} value={progress ?? 0} aria-label="Upload progress" /> : "Highlights and notes are saved in the page; the file itself is never modified."}>106 <input ref={input} type="file" accept="application/pdf" hidden aria-hidden tabIndex={-1} onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; void choose(f); }} />107 {uploading ? <NodeButton label="Cancel upload" text onClick={() => abort.current?.abort()}><X /></NodeButton>108 : <NodeButton label="Choose a PDF" tone="accent" text onClick={() => input.current?.click()}><FileUp /></NodeButton>}109 </NodeState>110 );111}112113interface LinkedRef { id: string; citeKey: string; title: string; label?: string; fields?: unknown }114/**115 * Research link of a PDF block. Finds the reference whose attached PDF is this file (`GET /api/research/references?attachmentId=`) and,116 * while the page is editable, mirrors what the user does to the annotations into that reference's extracts: a new or edited highlight /117 * note is created or patched (extract id derived from the annotation, so a repeat addresses the same extract), a removed one is deleted.118 * Only changes made in this session are pushed on their own; annotations that existed before (or failed while offline) are offered119 * through `syncAll`. Calls are serialised; a failure never touches the annotations, which live in the page.120 */121function useExtractLink(attachmentId: string, annotations: PdfAnnotation[], editable: boolean) {122 const qc = useQueryClient();123 const q = useQuery({ queryKey: ["reference-of-attachment", attachmentId], staleTime: 60_000, retry: false, queryFn: () => api<LinkedRef[]>(`/api/research/references?attachmentId=${attachmentId}`).catch(() => [] as LinkedRef[]) });124 const ref = q.data?.[0] ?? null; const refId = ref?.id ?? null;125 const [extracts, setExtracts] = React.useState<Extract[]>([]); const [busy, setBusy] = React.useState(false); const [failed, setFailed] = React.useState(false);126 React.useEffect(() => { setExtracts(ref ? extractsOf(ref.fields) : []); }, [ref]);127 const extractsRef = React.useRef(extracts); extractsRef.current = extracts; const latest = React.useRef(annotations); latest.current = annotations;128 const synced = React.useRef<PdfAnnotation[] | null>(null); const chain = React.useRef<Promise<void>>(Promise.resolve());129 React.useEffect(() => { synced.current = null; }, [refId]);130 const run = React.useCallback((plan: ExtractPlan, removed: string[]) => {131 if (!refId || (!plan.create.length && !plan.update.length && !removed.length)) return chain.current;132 const url = `/api/research/references/${refId}/extracts`; setBusy(true);133 chain.current = chain.current.then(async () => {134 let ok = true; const apply = (r: { extracts?: Extract[] }) => { if (Array.isArray(r?.extracts)) { extractsRef.current = r.extracts; setExtracts(r.extracts); } };135 try {136 for (const c of plan.create) { const r = await api<{ extract: Extract; extracts: Extract[] }>(url, { method: "POST", json: { id: c.id, ...c.body }, idempotencyKey: false }); apply(r);137 // the id already existed (same annotation saved earlier) with other content: bring it up to date instead of adding138 if (r.extract && (r.extract.quote !== c.body.quote || (r.extract.page ?? null) !== c.body.page || (r.extract.note ?? null) !== c.body.note)) apply(await api(url, { method: "PATCH", json: { id: c.id, ...c.body } })); }139 for (const u of plan.update) apply(await api(url, { method: "PATCH", json: { id: u.id, ...u.body } }));140 for (const id of removed) apply(await api(`${url}?extractId=${id}`, { method: "DELETE" }));141 } catch { ok = false; }142 setFailed(!ok); setBusy(false);143 qc.invalidateQueries({ queryKey: ["research-ref", refId] }); qc.invalidateQueries({ queryKey: ["reference-of-attachment", attachmentId] });144 if (!ok) toast("Extracts not updated", { description: "Your annotations are saved in the page. Use “Save as extracts” on the PDF to try again.", tone: "danger" });145 });146 return chain.current;147 }, [refId, attachmentId, qc]);148 // user changes → extracts, a moment after the last change (typing a note is one update)149 React.useEffect(() => {150 if (!refId || !editable) { synced.current = null; return; }151 if (synced.current === null) { synced.current = annotations; return; }152 if (synced.current === annotations) return;153 const t = setTimeout(() => {154 const before = synced.current ?? [], now = latest.current; synced.current = now; const old = new Map(before.map((a) => [a.id, a]));155 const touched = now.filter((a) => { const b = old.get(a.id); return !b || JSON.stringify(extractOfAnnotation(b)) !== JSON.stringify(extractOfAnnotation(a)); });156 void run(planExtractSync(attachmentId, touched, extractsRef.current), removedExtractIds(attachmentId, before, now));157 }, 900);158 return () => clearTimeout(t);159 }, [annotations, refId, editable, attachmentId, run]);160 const linked = React.useMemo(() => linkedAnnotationIds(attachmentId, annotations, extracts), [attachmentId, annotations, extracts]);161 const eligible = React.useMemo(() => annotations.filter((a) => extractOfAnnotation(a)), [annotations]);162 const unlinked = eligible.filter((a) => !linked.has(a.id)).length;163 const syncAll = React.useCallback(() => { synced.current = latest.current; return run(planExtractSync(attachmentId, latest.current, extractsRef.current), []); }, [attachmentId, run]);164 return { ref, linked, unlinked, busy, failed, syncAll };165}166167interface PendingSelection { page: number; rects: NormRect[]; text: string; /** anchor of the toolbar, page-relative */ x: number; y: number }168169function PdfReader({ attrs, update, editable, attachmentId }: LeafViewProps<PdfAttrs> & { attachmentId: string }) {170 const rootRef = React.useRef<HTMLDivElement>(null); const stageRef = React.useRef<HTMLDivElement>(null); const pageRef = React.useRef<HTMLDivElement>(null);171 const canvasRef = React.useRef<HTMLCanvasElement>(null); const textRef = React.useRef<HTMLDivElement>(null);172173 // ---- lazy load: nothing is imported or downloaded until the block is near the viewport (or the user asks) ----174 const [active, setActive] = React.useState(false);175 React.useEffect(() => {176 if (active) return; const el = rootRef.current; if (!el) return;177 if (typeof IntersectionObserver === "undefined") { setActive(true); return; }178 const io = new IntersectionObserver((entries) => { if (entries.some((x) => x.isIntersecting)) setActive(true); }, { rootMargin: "200px 0px" });179 io.observe(el); return () => io.disconnect();180 }, [active]);181182 const [doc, setDoc] = React.useState<PDFDocumentProxy | null>(null);183 const libRef = React.useRef<PdfJs | null>(null);184 const [status, setStatus] = React.useState<"idle" | "loading" | "ready" | "error">("idle");185 const [error, setError] = React.useState<string | null>(null);186 const [attempt, setAttempt] = React.useState(0);187 const [numPages, setNumPages] = React.useState(0);188 React.useEffect(() => {189 if (!active) return; let cancelled = false; let task: PDFDocumentLoadingTask | null = null;190 setStatus("loading"); setError(null);191 loadPdfJs().then((lib) => {192 if (cancelled) return null; libRef.current = lib;193 task = lib.getDocument({ url: fileUrl(attachmentId), withCredentials: true, enableXfa: false, cMapUrl: `${PDFJS_ASSETS}/cmaps/`, cMapPacked: true, standardFontDataUrl: `${PDFJS_ASSETS}/standard_fonts/`, wasmUrl: `${PDFJS_ASSETS}/wasm/`, iccUrl: `${PDFJS_ASSETS}/iccs/` });194 return task.promise;195 }).then((d) => {196 if (!d || cancelled) return; // a cancelled load is destroyed by the cleanup below197 setNumPages(d.numPages); setPage((p) => clampPage(p, d.numPages)); setDoc(d); setStatus("ready");198 }).catch((e) => { if (!cancelled) { setError(describeLoadError(e)); setStatus("error"); } });199 return () => { cancelled = true; setDoc(null); void task?.destroy().catch(() => {}); };200 }, [active, attachmentId, attempt]);201202 // ---- reading position: local at once, written to the node a moment later (never in a read-only editor) ----203 const storedPage = clampPage(attrs.page, 1e6);204 const [page, setPage] = React.useState(storedPage);205 const writtenPage = React.useRef(storedPage);206 React.useEffect(() => { if (storedPage !== writtenPage.current) { writtenPage.current = storedPage; setPage(clampPage(storedPage, numPages || 1e6)); } }, [storedPage, numPages]);207 const savePage = useDebounced((p: number) => { if (editable && p !== writtenPage.current) { writtenPage.current = p; update({ page: p }); } }, 600);208 const [pageField, setPageField] = React.useState(String(page));209 React.useEffect(() => { setPageField(String(page)); }, [page]);210 const go = React.useCallback((n: number) => {211 const p = clampPage(n, numPages || 1e6); setPending(null); setPage(p); setPageField(String(p)); savePage(p);212 }, [numPages, savePage]);213214 // ---- geometry: fit the block width, follow resizes without thrashing ----215 const [width, setWidth] = React.useState(0);216 const [zoom, setZoom] = React.useState(1);217 React.useLayoutEffect(() => {218 const el = stageRef.current; if (!el) return;219 const measure = () => { const w = Math.floor(el.clientWidth); if (w > 0) setWidth((prev) => (Math.abs(prev - w) >= 1 ? w : prev)); };220 measure(); if (typeof ResizeObserver === "undefined") return;221 let timer: ReturnType<typeof setTimeout> | null = null;222 const ro = new ResizeObserver(() => { if (timer) clearTimeout(timer); timer = setTimeout(measure, 120); });223 ro.observe(el); return () => { ro.disconnect(); if (timer) clearTimeout(timer); };224 }, [status]);225226 const [pageSize, setPageSize] = React.useState<{ width: number; height: number } | null>(null);227 const [renderError, setRenderError] = React.useState<string | null>(null);228 const [rendering, setRendering] = React.useState(false);229 React.useEffect(() => {230 const lib = libRef.current; if (!doc || !lib || width <= 0) return;231 let cancelled = false; let task: RenderTask | null = null; let layer: TextLayer | null = null;232 setRendering(true); setRenderError(null);233 (async () => {234 const p = await doc.getPage(clampPage(page, doc.numPages)); if (cancelled) return;235 const base = p.getViewport({ scale: 1 }); const scale = (width / base.width) * zoom; const viewport = p.getViewport({ scale });236 const cssW = Math.floor(viewport.width), cssH = Math.floor(viewport.height);237 const out = Math.max(0.5, Math.min(window.devicePixelRatio || 1, 3, Math.sqrt(MAX_CANVAS_AREA / Math.max(1, cssW * cssH))));238 // Draw off-screen and swap when complete: the visible page never flashes blank and never shows a half-drawn stale page.239 const buffer = document.createElement("canvas"); buffer.width = Math.max(1, Math.floor(cssW * out)); buffer.height = Math.max(1, Math.floor(cssH * out));240 task = p.render({ canvas: buffer, viewport, transform: out !== 1 ? [out, 0, 0, out, 0, 0] : undefined, background: "#ffffff" });241 await task.promise; if (cancelled) return;242 const canvas = canvasRef.current, host = textRef.current; if (!canvas || !host) return;243 canvas.width = buffer.width; canvas.height = buffer.height; canvas.getContext("2d")?.drawImage(buffer, 0, 0); buffer.width = buffer.height = 0;244 setPageSize({ width: cssW, height: cssH }); setRendering(false);245 // Text layer (selection). pdf.js lays the runs out in page units and scales them with these custom properties.246 host.replaceChildren(); host.style.setProperty("--scale-factor", String(scale)); host.style.setProperty("--total-scale-factor", String(scale));247 layer = new lib.TextLayer({ textContentSource: p.streamTextContent(), container: host, viewport });248 const quarter = viewport.rotation % 180 !== 0; host.style.width = `${quarter ? cssH : cssW}px`; host.style.height = `${quarter ? cssW : cssH}px`;249 await layer.render(); if (cancelled) return;250 const end = document.createElement("div"); end.className = "pdfv-eoc"; host.append(end);251 })().catch((e) => { if (!cancelled && !isCancel(e)) { setRendering(false); setRenderError(describeLoadError(e)); } });252 return () => { cancelled = true; try { task?.cancel(); } catch { /* already finished */ } try { layer?.cancel(); } catch { /* already finished */ } };253 }, [doc, page, width, zoom]);254255 // ---- annotations ----256 const annotations = React.useMemo(() => listAnnotations(attrs.annotations), [attrs.annotations]);257 const onPage = React.useMemo(() => annotations.filter((a) => a.page === page), [annotations, page]);258 const sorted = React.useMemo(() => sortAnnotations(annotations), [annotations]);259 const [selectedId, setSelectedId] = React.useState<string | null>(null);260 const current = selectedId ? annotations.find((a) => a.id === selectedId) ?? null : null;261 const [color, setColor] = React.useState(DEFAULT_HIGHLIGHT_COLOR);262 const [pending, setPending] = React.useState<PendingSelection | null>(null);263 const research = useExtractLink(attachmentId, annotations, editable);264265 const readSelection = React.useCallback(() => {266 if (!editable) return;267 const host = textRef.current, sheet = pageRef.current, sel = window.getSelection();268 if (!host || !sheet || !sel || sel.rangeCount === 0 || sel.isCollapsed) { setPending(null); return; }269 const range = sel.getRangeAt(0);270 if (!host.contains(range.commonAncestorContainer)) { setPending(null); return; }271 const rects = normaliseRects(selectionTextRects(range, host), sheet.getBoundingClientRect()); const text = cleanSelectionText(sel.toString());272 if (!rects.length || !text) { setPending(null); return; }273 const last = rects[rects.length - 1];274 setPending({ page, rects, text, x: last[0] + last[2] / 2, y: last[1] + last[3] });275 }, [editable, page]);276 // The selection is read when a gesture ends, and (debounced) when it changes by other means: keyboard, touch handles.277 React.useEffect(() => {278 if (status !== "ready") return; let timer: ReturnType<typeof setTimeout> | null = null;279 const onChange = () => {280 if (!editable) return;281 const host = textRef.current, sel = document.getSelection(); if (!host) return;282 const inside = !!sel && sel.rangeCount > 0 && !!sel.anchorNode && host.contains(sel.anchorNode);283 if (timer) clearTimeout(timer); timer = setTimeout(inside ? readSelection : () => setPending((p) => (p ? null : p)), inside ? 180 : 0);284 };285 const onUp = () => { textRef.current?.classList.remove("selecting"); };286 document.addEventListener("selectionchange", onChange); document.addEventListener("pointerup", onUp);287 return () => { document.removeEventListener("selectionchange", onChange); document.removeEventListener("pointerup", onUp); if (timer) clearTimeout(timer); };288 }, [editable, status, readSelection]);289290 const create = (kind: "highlight" | "note") => {291 if (!editable || !pending) return;292 const a = newAnnotation({ page: pending.page, kind, color, rects: pending.rects, text: pending.text, note: "" });293 update({ annotations: [...(Array.isArray(attrs.annotations) ? attrs.annotations : []), a] });294 window.getSelection()?.removeAllRanges(); setPending(null); setSelectedId(kind === "note" ? a.id : null);295 };296 const patch = (id: string, p: Partial<PdfAnnotation>) => { if (editable) update({ annotations: patchAnnotation(attrs.annotations, id, p) as PdfAnnotation[] }); };297 const remove = (id: string) => { if (!editable) return; update({ annotations: removeAnnotation(attrs.annotations, id) as PdfAnnotation[] }); setSelectedId(null); };298 /** A click on the page that is not a selection: pick the highlight under the pointer (the text layer sits above the highlights). */299 const onPageClick = (e: React.MouseEvent) => {300 const sheet = pageRef.current; const sel = window.getSelection(); if (!sheet || (sel && !sel.isCollapsed)) return;301 const r = sheet.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) return;302 const hit = annotationAt(onPage, page, (e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);303 setSelectedId(hit ? hit.id : null);304 };305 const onStageKey = (e: React.KeyboardEvent) => {306 if (e.target !== e.currentTarget) return;307 if (e.key === "PageDown" || e.key === "ArrowRight") { e.preventDefault(); go(page + 1); } else if (e.key === "PageUp" || e.key === "ArrowLeft") { e.preventDefault(); go(page - 1); }308 };309310 const ready = status === "ready";311 const toolbarX = pending && pageSize ? Math.min(Math.max(pending.x * pageSize.width, Math.min(130, pageSize.width / 2)), Math.max(pageSize.width - 130, pageSize.width / 2)) : 0;312 const toolbarBelow = !pending || pending.y < 0.82;313314 return (315 <div className="pdfv" ref={rootRef}>316 {status === "idle" && <NodeState icon={<FileText />} title={attrs.name || "PDF document"} hint="The viewer loads when the block is on screen."><NodeButton label="Load PDF" text onClick={() => setActive(true)}><FileText /></NodeButton></NodeState>}317 {status === "loading" && <NodeState icon={<FileText />} title="Opening the PDF…" hint={attrs.name || undefined} />}318 {status === "error" && (319 <NodeState tone="danger" icon={<FileText />} title="This PDF cannot be displayed" hint={error}>320 <NodeButton label="Try again" text onClick={() => setAttempt((n) => n + 1)}><RotateCw /></NodeButton>321 <OpenOriginal attachmentId={attachmentId} text />322 </NodeState>323 )}324 {ready && (325 <>326 <div className="nb-toolbar pdfv-toolbar" role="toolbar" aria-label="PDF navigation">327 <NodeButton label="Previous page" disabled={page <= 1} onClick={() => go(page - 1)}><ChevronLeft /></NodeButton>328 <label className="pdfv-pagebox nb-meta">329 <span className="sr-only">Page number</span>330 <input className="nb-field pdfv-pagefield" type="text" inputMode="numeric" pattern="[0-9]*" aria-label="Page number" value={pageField}331 onChange={(e) => setPageField(e.target.value.replace(/[^0-9]/g, "").slice(0, 6))} onFocus={(e) => e.currentTarget.select()}332 onBlur={() => (pageField === "" ? setPageField(String(page)) : go(Number(pageField)))} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); if (pageField !== "") go(Number(pageField)); } }} />333 <span aria-label={`of ${numPages} pages`}>/ {numPages}</span>334 </label>335 <NodeButton label="Next page" disabled={page >= numPages} onClick={() => go(page + 1)}><ChevronRight /></NodeButton>336 <span className="pdfv-gap" />337 <NodeButton label="Zoom out" disabled={zoom <= ZOOM_MIN + 1e-6} onClick={() => setZoom((z) => Math.max(ZOOM_MIN, z / ZOOM_STEP))}><ZoomOut /></NodeButton>338 <NodeButton label="Fit to width" active={zoom === 1} onClick={() => setZoom(1)}><Maximize2 /></NodeButton>339 <NodeButton label="Zoom in" disabled={zoom >= ZOOM_MAX - 1e-6} onClick={() => setZoom((z) => Math.min(ZOOM_MAX, z * ZOOM_STEP))}><ZoomIn /></NodeButton>340 <span className="nb-meta pdfv-zoom" aria-live="polite">{Math.round(zoom * 100)} %</span>341 <OpenOriginal attachmentId={attachmentId} />342 </div>343 <div className="pdfv-stage nb-scroll" ref={stageRef} tabIndex={0} role="group" aria-label={`Page ${page} of ${numPages}`} aria-busy={rendering} onKeyDown={onStageKey}>344 <div className="pdfv-page" ref={pageRef} style={pageSize ? { width: pageSize.width, height: pageSize.height } : undefined} data-rendering={rendering ? "true" : undefined}>345 <canvas ref={canvasRef} className="pdfv-canvas" data-testid="pdf-canvas" data-page={page} aria-hidden />346 <div className="pdfv-marks" aria-hidden>347 {onPage.flatMap((a) => (a.kind === "ink" ? [] : rectsOf(a).map((r, i) => (348 <div key={`${a.id}-${i}`} className="pdfv-mark" data-testid="pdf-annotation" data-annotation-id={a.id} data-kind={a.kind} data-selected={a.id === selectedId ? "true" : undefined}349 style={{ left: pct(r[0]), top: pct(r[1]), width: pct(r[2]), height: pct(r[3]), "--pdfv-c": safeColor(a.color) } as React.CSSProperties} />))))}350 {onPage.some((a) => a.kind === "ink") && (351 <svg className="pdfv-ink" viewBox="0 0 1 1" preserveAspectRatio="none">352 {onPage.filter((a) => a.kind === "ink").map((a) => { const pts = inkPointsOf(a); return pts.length > 1 ? <polyline key={a.id} data-testid="pdf-annotation-ink" data-annotation-id={a.id} points={pts.map((p) => `${p[0]},${p[1]}`).join(" ")} fill="none" stroke={safeColor(a.color, "#1f2937")} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" /> : null; })}353 </svg>354 )}355 </div>356 <div ref={textRef} className="pdfv-text" data-testid="pdf-textlayer" onPointerDown={(e) => e.currentTarget.classList.add("selecting")} onPointerUp={readSelection} onKeyUp={readSelection} onClick={onPageClick} />357 {editable && pending && pending.page === page && pageSize && (358 <div className="pdfv-seltools" role="toolbar" aria-label="Annotate the selection" style={{ left: toolbarX, ...(toolbarBelow ? { top: pending.y * pageSize.height + 6 } : { bottom: (1 - pending.rects[0][1]) * pageSize.height + 6 }) }}>359 <ColorSwatches value={color} onChange={setColor} label="Highlight colour" />360 <NodeButton label="Highlight" text onClick={() => create("highlight")}><Highlighter /></NodeButton>361 <NodeButton label="Add note" text onClick={() => create("note")}><MessageSquarePlus /></NodeButton>362 </div>363 )}364 </div>365 </div>366 {renderError && <NodeState tone="danger" title="This page could not be drawn" hint={renderError} />}367 {research.ref && (368 <div className="pdfv-ref" data-testid="pdf-reference-link">369 <BookMarked aria-hidden /><span className="min-w-0 flex-1">PDF of <Link href={`/research?ref=${research.ref.id}`} className="pdfv-ref-name" title={research.ref.title}>{research.ref.label ?? research.ref.citeKey}</Link>{editable ? " — highlights and notes are saved as extracts of this reference." : "."}</span>370 {research.busy && <span className="nb-meta" role="status">Saving extracts…</span>}371 {editable && !research.busy && research.unlinked > 0 && <NodeButton label={`Save ${research.unlinked} annotation${research.unlinked === 1 ? "" : "s"} as extract${research.unlinked === 1 ? "" : "s"}`} text onClick={() => void research.syncAll()}><TextQuote /></NodeButton>}372 </div>373 )}374 {current && <AnnotationPanel key={current.id} annotation={current} editable={editable && current.kind !== "ink"} onPatch={(p) => patch(current.id, p)} onDelete={() => remove(current.id)} onClose={() => setSelectedId(null)} />}375 {sorted.length > 0 && (376 <ul className="pdfv-list" data-testid="pdf-annotation-list" aria-label="Annotations">377 {sorted.map((a) => (378 <li key={a.id}>379 <button type="button" className={cn("pdfv-row", a.id === selectedId && "is-active")} aria-current={a.id === selectedId ? "true" : undefined} title={annotationLine(a)} onMouseDown={(e) => e.preventDefault()}380 onClick={() => { if (a.page !== page) go(a.page); setSelectedId(a.id); }}>381 <span className="pdfv-dot" style={{ "--pdfv-c": safeColor(a.color) } as React.CSSProperties} data-kind={a.kind} aria-hidden />382 <span className="pdfv-rowtext">{annotationLine(a)}</span>383 {research.linked.has(a.id) && <span className="pdfv-extract" data-testid="pdf-annotation-extract" title={`Saved as an extract of ${research.ref?.label ?? "the reference"}`}><TextQuote aria-hidden /><span className="sr-only">Saved as an extract</span></span>}384 </button>385 </li>386 ))}387 </ul>388 )}389 </>390 )}391 </div>392 );393}394395/** Link to the untouched file (new tab; the body of a node view is left to the browser, so this is a real link). */396function OpenOriginal({ attachmentId, text }: { attachmentId: string; text?: boolean }) {397 return <a className={cn("nb-btn", text && "nb-btn-text")} href={fileUrl(attachmentId)} target="_blank" rel="noopener noreferrer" title="Open original" aria-label="Open original"><ExternalLink />{text && <span>Open original</span>}</a>;398}399400function ColorSwatches({ value, onChange, label }: { value: string; onChange: (c: string) => void; label: string }) {401 return (402 <span className="pdfv-swatches" role="radiogroup" aria-label={label}>403 {HIGHLIGHT_COLORS.map((c) => (404 <button key={c.color} type="button" role="radio" aria-checked={value === c.color} aria-label={c.label} title={c.label} className="pdfv-swatch" style={{ "--pdfv-c": c.color } as React.CSSProperties}405 onMouseDown={(e) => e.preventDefault()} onClick={() => onChange(c.color)} />406 ))}407 </span>408 );409}410411/** Editor of one highlight / note under the page: its quote, colour, note text and deletion. Ink (from another client) is shown only. */412function AnnotationPanel({ annotation, editable, onPatch, onDelete, onClose }: { annotation: PdfAnnotation; editable: boolean; onPatch: (p: Partial<PdfAnnotation>) => void; onDelete: () => void; onClose: () => void }) {413 const stored = typeof annotation.note === "string" ? annotation.note : "";414 const [note, setNote] = React.useState(stored);415 const written = React.useRef(stored);416 React.useEffect(() => { if (stored !== written.current) { written.current = stored; setNote(stored); } }, [stored]);417 const deleted = React.useRef(false);418 const save = useDebounced((v: string) => { if (!deleted.current && v !== written.current) { written.current = v; onPatch({ note: v }); } }, 400);419 const field = React.useRef<HTMLTextAreaElement>(null);420 React.useEffect(() => { if (editable && annotation.kind === "note" && stored === "") field.current?.focus({ preventScroll: true }); }, []); // eslint-disable-line react-hooks/exhaustive-deps421 const kind = annotation.kind === "ink" ? "Ink drawing" : annotation.kind === "note" ? "Note" : "Highlight";422 return (423 <div className="pdfv-panel" role="group" aria-label={`${kind} on page ${annotation.page}`}>424 <div className="pdfv-panel-head">425 <span className="nb-meta">{kind} · p.{annotation.page}</span>426 {editable && <ColorSwatches value={safeColor(annotation.color)} onChange={(c) => onPatch({ color: c })} label="Colour" />}427 <span className="pdfv-gap" />428 {editable && <NodeButton label="Delete annotation" tone="danger" onClick={() => { deleted.current = true; onDelete(); }}><Trash2 /></NodeButton>}429 <NodeButton label="Close" onClick={() => { save.flush(); onClose(); }}><X /></NodeButton>430 </div>431 {annotation.text && <blockquote className="pdfv-quote">{annotation.text}</blockquote>}432 {editable433 ? <textarea ref={field} className="pdfv-note" aria-label="Note" placeholder="Add a note…" rows={2} value={note} onChange={(e) => { setNote(e.target.value); save(e.target.value); }} onBlur={() => save.flush()} />434 : stored && <p className="pdfv-note-ro">{stored}</p>}435 </div>436 );437}438