Files
DeepTutor/web/components/reading/PdfPage.tsx
Bingxi Zhao (Frank) fa1edb75a2 fix: reconcile provider branding and locale contracts after PR integration
Register the verified SearchApi favicon with provenance, complete Italian many plurals and translated counts, and review the Italian/Hungarian language endonyms in Portuguese. Align labeled-stream fixtures with preserved Markdown examples and accepted thinking-tag aliases. Keep PDF layout memoization tied to the effective page ratio.
2026-11-14 23:47:30 +08:00

522 lines
20 KiB
TypeScript

'use client'
import { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { loadPdfjs, outputScale, type PdfDocument } from '@/lib/pdfjs-loader'
import type { AnnotationItem } from '@/lib/reading-api'
import {
cropLayout,
measurePageInkBox,
pageImageBoxes,
type NormalisedBox,
} from '@/lib/pdf-page-geometry'
import { canvasPixelRatio } from '@/lib/reading-zoom'
import { AnnotationLayer } from './AnnotationLayer'
export interface PdfPageProps {
doc: PdfDocument
locator: number
/** CSS width the page should occupy; height follows the page's aspect ratio. */
width: number
/** Placeholder aspect ratio (height / width) until the real page is measured. */
fallbackRatio: number
/** False while the page is far outside the viewport — keeps memory bounded. */
active: boolean
/**
* Keep pdf.js's parsed copy of the page while it is near, even off-canvas:
* scrolling back a page or two then repaints instead of parsing again.
* Further away it is handed back. Defaults to ``active``.
*/
retain?: boolean
annotations: AnnotationItem[]
highlightedAnnotationId?: string | null
/** Transient highlight from `reader_goto`, as normalised rects. */
flashRects?: Array<[number, number, number, number]>
onAnnotationClick?: (annotation: AnnotationItem) => void
/** Trim the page's own white side margins so the text block fills the pane. */
cropMargins?: boolean
/**
* Reports this page's share of the page its visible strip covers, so the
* reader can measure "one zoom stop" from the size actually on screen. The
* locator tags the report: several pages are mounted at once, and a
* neighbour's ratio must never stand in for the page being read.
*/
onCropRatio?: (locator: number, ratio: number) => void
/** Reports a picture the reader clicked, in page-normalised coordinates. */
onImageClick?: (locator: number, box: NormalisedBox) => void
/**
* Cache key for the ink and picture measurements: a page that changes
* material must never show the previous one's crop.
*/
inkKey?: string
}
/** Debounce before the single final repaint once a resize settles. */
const FINAL_REPAINT_DELAY_MS = 150
/** Set on the text layer root by React rather than pdf.js. */
const REACT_OWNED_TEXT_STYLES = new Set([
'--total-scale-factor',
'pointer-events',
'width',
'height',
])
function copyPdfjsRootMetadata(source: HTMLElement, target: HTMLElement) {
for (let index = 0; index < source.style.length; index += 1) {
const name = source.style.item(index)
if (!name || REACT_OWNED_TEXT_STYLES.has(name)) continue
target.style.setProperty(
name,
source.style.getPropertyValue(name),
source.style.getPropertyPriority(name)
)
}
for (const attribute of source.attributes) {
if (!attribute.name.startsWith('data-')) continue
target.setAttribute(attribute.name, attribute.value)
}
}
/**
* One rendered PDF page: canvas, selectable text layer, annotation overlay.
*
* Rendering is gated on `active` and every effect cancels its in-flight work,
* because scrolling a long document mounts and unmounts pages faster than
* pdf.js can finish: without cancellation the canvas of a page that scrolled
* away keeps decoding, and a late `render` can paint over a newer one.
*
* The page keeps its measured height while inactive, so deactivating it does not
* collapse the scroll container and yank the reader's position.
*/
/** Let pdf.js drop a page's decoded images and operator list. */
function releasePage(doc: PdfDocument, locator: number) {
void doc
.getPage(locator)
.then(page => page.cleanup())
.catch(() => undefined)
}
export function PdfPage({
doc,
locator,
width,
fallbackRatio,
active,
retain = active,
annotations,
highlightedAnnotationId,
flashRects,
onAnnotationClick,
cropMargins = false,
onCropRatio,
onImageClick,
inkKey = `${doc ? 'doc' : 'none'}:${locator}`,
}: PdfPageProps) {
const { t } = useTranslation()
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const textLayerRef = useRef<HTMLDivElement | null>(null)
// Whether this page was ever drawn, so only those are handed back.
const renderedRef = useRef(false)
const paintedLayoutRef = useRef<string | null>(null)
const [ratio, setRatio] = useState<number | null>(null)
const [baseWidth, setBaseWidth] = useState(0)
const [canvasFailed, setCanvasFailed] = useState(false)
const [textFailed, setTextFailed] = useState(false)
// Whether this page's ink was ever measured. Measuring parses the page, so a
// page measured but never painted holds pdf.js's decoded copy just like a
// rendered one and has to be handed back too.
const measuredRef = useRef(false)
// Same, for the operator list the picture hotspots come from.
const picturesMeasuredRef = useRef(false)
// `undefined` means "not measured yet"; `null` means "measured, nothing to
// crop". Painting waits for the answer so a page is not drawn once at full
// width and again at the cropped one.
const [inkState, setInkState] = useState<{
key: string
box: NormalisedBox | null
} | null>(null)
const inkBox = !cropMargins ? null : inkState?.key === inkKey ? inkState.box : undefined
// "Not measured yet" is a state of its own, not the same thing as "measured,
// nothing to crop": both used to resolve to the uncropped layout, so the
// paint effect ran once before the measurement and again after it — every
// page drawn twice, at two different widths when the crop landed.
const awaitingInk = cropMargins && inkBox === undefined
const [imageState, setImageState] = useState<{
key: string
boxes: NormalisedBox[]
} | null>(null)
const imageBoxes = imageState?.key === inkKey ? imageState.boxes : []
const pageRatio = ratio ?? fallbackRatio
const layout = useMemo(
() => cropLayout(width, pageRatio, cropMargins ? (inkBox ?? null) : null),
[width, pageRatio, cropMargins, inkBox]
)
// How much of the page this strip shows. Reported only while this page is
// active: every page measures its own margins, and the zoom step must start
// from what is under the reader's eyes.
//
// Reported in every mode, not only while cropping: a page drawn whole is
// showing all of itself, so the share is 1. Leaving the last text-mode ratio
// behind made one press of "+" after switching to Fit page divide the fit
// ratio by a crop that is no longer on screen — 1250px instead of 750px.
//
// The locator goes with it because the render window holds neighbours too:
// an untagged report let whichever page settled last define the step.
useEffect(() => {
if (!active || !onCropRatio) return
onCropRatio(locator, layout.visibleWidth / layout.fullWidth)
}, [active, locator, layout.visibleWidth, layout.fullWidth, onCropRatio])
// -- ink box -------------------------------------------------------------
// Measured only inside the render window. `PdfDocumentView` mounts a page for
// every locator, so measuring on mount would start a scratch render for a
// 600-page document as soon as it opened with Fit text — the expensive work
// belongs to the pages that can be seen, or are about to be.
const shouldMeasureInk = cropMargins && (active || retain)
useEffect(() => {
if (!shouldMeasureInk) return
let cancelled = false
// Marked before the await: the page is parsed for its ink as soon as
// `getPage` is called, and the cleanup below has to hand back one that was
// measured but never painted.
measuredRef.current = true
;(async () => {
const page = await doc.getPage(locator)
if (cancelled) return
const box = await measurePageInkBox(page, inkKey)
if (!cancelled) setInkState({ key: inkKey, box })
})().catch(() => {
if (!cancelled) setInkState({ key: inkKey, box: null })
})
return () => {
cancelled = true
}
}, [doc, locator, inkKey, shouldMeasureInk])
// -- pictures ------------------------------------------------------------
// The same render window as the ink measurement, for the same reason: reading
// a page's operator list parses it, and `PdfDocumentView` mounts one page per
// locator, so doing it on mount read 600 operator lists when a 600-page
// document opened. Pictures apply in every fit mode, so there is no crop to
// gate on — but the window is too wide: `getOperatorList` runs its own intent
// in the worker, which decodes every image on the page at full resolution and
// keeps it alive on the main thread until the page is cleaned up. Doing that
// for the whole retained window decoded thirteen pages' images at once, past
// the canvas budget the visible bitmaps obey. Only the page being read can be
// clicked anyway, so only it is measured.
const shouldMeasurePictures = active
useEffect(() => {
if (!shouldMeasurePictures) return
let cancelled = false
// Marked before the await: `getPage` parses the page, so one measured but
// never painted still holds pdf.js's copy and has to be handed back.
picturesMeasuredRef.current = true
;(async () => {
const pdfjs = await loadPdfjs()
const page = await doc.getPage(locator)
if (cancelled) return
const boxes = await pageImageBoxes(
page,
pdfjs.OPS as unknown as Record<string, number> | undefined
)
if (!cancelled) setImageState({ key: inkKey, boxes })
})().catch(() => {
// A page whose operators cannot be read simply has no hotspots.
if (!cancelled) setImageState({ key: inkKey, boxes: [] })
})
return () => {
cancelled = true
}
}, [doc, locator, inkKey, shouldMeasurePictures])
const textScale = baseWidth > 0 ? layout.fullWidth / baseWidth : 1
const paintKey = `${layout.fullWidth}:${layout.visibleWidth}:${layout.fullHeight}:${layout.offsetX}`
useEffect(() => {
if (!active || width <= 0) return
let cancelled = false
let renderTask: { cancel: () => void } | null = null
let cancelSchedule: (() => void) | null = null
;(async () => {
try {
const page = await doc.getPage(locator)
renderedRef.current = true
if (cancelled) return
const base = page.getViewport({ scale: 1 })
if (base.width > 0) {
setRatio(base.height / base.width)
setBaseWidth(base.width)
}
const paintCanvas = async () => {
const canvas = canvasRef.current
if (!canvas) return
if (awaitingInk) return
try {
const viewport = page.getViewport({ scale: layout.fullWidth / base.width })
// The bitmap holds only the visible strip, and the page is drawn
// shifted left by the cropped margin. Clamp this page's own bitmap
// against the budget: the caller clamps the *shared* width using page
// one's aspect, so a page whose own ratio is taller can still ask for
// a bitmap past the budget — which the browser drops as a blank page
// rather than an error. The ratio gives, the CSS box does not, so the
// layout width stays identical from page to page.
const dpr = canvasPixelRatio(layout.visibleWidth, layout.fullHeight, outputScale())
canvas.width = Math.max(1, Math.floor(layout.visibleWidth * dpr))
canvas.height = Math.max(1, Math.floor(layout.fullHeight * dpr))
canvas.style.width = `${layout.visibleWidth}px`
canvas.style.height = `${layout.fullHeight}px`
const shiftX = -layout.offsetX * dpr
// `canvas` only, never alongside `canvasContext`: pdf.js documents the
// context parameter as backwards-compatibility requiring
// `canvas: null`, and passing both is an unsupported combination.
renderTask = page.render({
canvas,
viewport,
transform: dpr !== 1 || layout.offsetX ? [dpr, 0, 0, dpr, shiftX, 0] : undefined,
})
await (renderTask as unknown as { promise: Promise<void> }).promise
if (cancelled) return
paintedLayoutRef.current = paintKey
setCanvasFailed(false)
} catch (error) {
// pdf.js throws RenderingCancelledException on a cancelled task —
// that is the normal path when scrolling, not a failure to report.
const name = (error as { name?: string } | null)?.name ?? ''
if (!cancelled && name !== 'RenderingCancelledException') {
setCanvasFailed(true)
}
}
}
if (paintedLayoutRef.current == null) {
void paintCanvas()
} else if (paintedLayoutRef.current !== paintKey) {
// Resize: keep the CSS-scaled bitmap until the width settles, then
// repaint once at the final size.
const handle = window.setTimeout(() => void paintCanvas(), FINAL_REPAINT_DELAY_MS)
cancelSchedule = () => window.clearTimeout(handle)
}
} catch (error) {
// pdf.js throws RenderingCancelledException on a cancelled task — that
// is the normal path when scrolling, not a failure to report.
const name = (error as { name?: string } | null)?.name ?? ''
if (!cancelled && name !== 'RenderingCancelledException') {
setCanvasFailed(true)
setTextFailed(true)
}
}
})()
return () => {
cancelled = true
cancelSchedule?.()
try {
renderTask?.cancel()
} catch {
// Already settled.
}
}
}, [active, doc, locator, width, layout, awaitingInk, paintKey])
// Build the text layer once per active period, independently of bitmap
// completion. Resizing changes only --total-scale-factor.
useEffect(() => {
const container = textLayerRef.current
if (!active || !container) return
let cancelled = false
let textLayer: { cancel: () => void } | null = null
container.replaceChildren()
const buildTextLayer = async () => {
try {
const [pdfjs, page] = await Promise.all([loadPdfjs(), doc.getPage(locator)])
renderedRef.current = true
if (cancelled) return
const textContent = await page.getTextContent()
if (cancelled) return
const staged = document.createElement('div')
staged.className = 'textLayer'
staged.style.setProperty('--total-scale-factor', '1')
const layer = new pdfjs.TextLayer({
textContentSource: textContent,
container: staged,
viewport: page.getViewport({ scale: 1 }),
})
textLayer = layer
await layer.render()
if (cancelled) return
copyPdfjsRootMetadata(staged, container)
container.replaceChildren(...staged.childNodes)
setTextFailed(false)
} catch (error) {
const name = (error as { name?: string } | null)?.name ?? ''
if (!cancelled && name !== 'AbortException') setTextFailed(true)
}
}
void buildTextLayer()
return () => {
cancelled = true
try {
textLayer?.cancel()
} catch {
// Already settled.
}
}
}, [active, doc, locator])
// Free the canvas bitmap when the page scrolls far away. Without this a
// 600-page document accumulates every page it ever showed.
useEffect(() => {
if (active) return
paintedLayoutRef.current = null
const canvas = canvasRef.current
if (canvas) {
canvas.width = 0
canvas.height = 0
}
textLayerRef.current?.replaceChildren()
}, [active])
// The bitmap is only half of it: pdf.js keeps each page's decoded images
// and operator list until told to let go — tens of MB a page for a scan.
useEffect(() => {
// `cleanup` waits for a cancelled render to settle before it frees.
// Only pages that were drawn: asking for the rest would load them.
if (retain || !(renderedRef.current || measuredRef.current || picturesMeasuredRef.current))
return
releasePage(doc, locator)
}, [retain, doc, locator])
useEffect(
() => () => {
paintedLayoutRef.current = null
if (renderedRef.current || measuredRef.current || picturesMeasuredRef.current)
releasePage(doc, locator)
},
[doc, locator]
)
const pageAnnotations = useMemo(
() => annotations.filter(a => a.locator === locator),
[annotations, locator]
)
return (
<div
data-reader-unit={locator}
data-page-width={layout.fullWidth}
data-page-offset-x={layout.offsetX}
className="relative mx-auto shrink-0 overflow-hidden rounded-[10px] bg-white shadow-[0_1px_3px_rgba(0,0,0,0.10),0_8px_24px_-12px_rgba(0,0,0,0.18)] ring-1 ring-black/[0.06]"
style={{ width: layout.visibleWidth, height: layout.fullHeight }}
>
{/* Whole-page coordinates live here; the clip above trims the margins. */}
<div
className="absolute top-0"
// Explicit height: every child is absolutely positioned, so without it
// this surface would collapse and the annotation overlay (inset-0) with
// it.
style={{
left: -layout.offsetX,
top: 0,
width: layout.fullWidth,
height: layout.fullHeight,
}}
>
<canvas
ref={canvasRef}
className="absolute block"
// The bitmap holds the visible strip only, so it starts where that
// strip starts inside the page.
style={{
left: layout.offsetX,
top: 0,
width: layout.visibleWidth,
height: layout.fullHeight,
}}
/>
{/*
Picture hotspots sit UNDER the text layer, not over it.
A page is one bitmap by the time it reaches the DOM, so the click target
is a positioned box. Placing that box above the text layer (which is
what DOM order gave us) meant an OCR scan — one picture covering the
whole page — put a button over every word: selection, highlights and
existing annotations all stopped responding. Underneath, the text layer
keeps the pointer and the hotspot only sees clicks that fall through a
gap in the text. Page-filling boxes are dropped in the geometry layer
for the same reason.
*/}
{onImageClick && imageBoxes.length > 0 && (
<div className="pointer-events-none absolute inset-0">
{imageBoxes.map((box, index) => (
<button
key={`image-${index}`}
type="button"
aria-label={t('Zoom image')}
// No `onMouseUp` guard: a selection that ends on the picture must
// still reach the reader, or dragging across an image loses the
// quote. The click is what opens the viewer.
onClick={event => {
event.stopPropagation()
onImageClick(locator, box)
}}
className="pointer-events-auto absolute cursor-zoom-in rounded-[3px] transition hover:bg-black/[0.05] hover:ring-1 hover:ring-[var(--primary)]/40"
style={{
left: `${box.x0 * 100}%`,
top: `${box.y0 * 100}%`,
width: `${(box.x1 - box.x0) * 100}%`,
height: `${(box.y1 - box.y0) * 100}%`,
}}
/>
))}
</div>
)}
<div
ref={textLayerRef}
className="textLayer absolute left-0 top-0 [&_span]:pointer-events-auto"
// Only text spans take pointer events; gaps must reach image hotspots.
style={
{
width: layout.fullWidth,
height: layout.fullHeight,
pointerEvents: 'none',
'--total-scale-factor': String(textScale),
} as CSSProperties
}
/>
<AnnotationLayer
annotations={pageAnnotations}
highlightedAnnotationId={highlightedAnnotationId}
flashRects={flashRects}
onAnnotationClick={onAnnotationClick}
/>
</div>
{!active && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<span className="font-mono text-[11px] text-black/25">{locator}</span>
</div>
)}
{canvasFailed && textFailed && (
<div className="absolute inset-0 flex items-center justify-center bg-white/90 px-6 text-center">
<span className="text-[12px] text-[var(--muted-foreground)]">
{t('This page could not be rendered.')}
</span>
</div>
)}
</div>
)
}