diff --git a/packages/webui/components/drawing-canvas.tsx b/packages/webui/components/drawing-canvas.tsx index 45008a1c..5f263a82 100644 --- a/packages/webui/components/drawing-canvas.tsx +++ b/packages/webui/components/drawing-canvas.tsx @@ -17,6 +17,8 @@ interface DrawingCanvasProps { height: number mediaDimensions: { width: number; height: number } imageUrl?: string + /** A live canvas to draw instead of an image URL (e.g. a PDF.js page render). */ + canvasElement?: HTMLCanvasElement | null videoElement?: HTMLVideoElement annotations: Annotation[] scale: number @@ -37,6 +39,7 @@ const DrawingCanvas = ({ height, mediaDimensions, imageUrl, + canvasElement, videoElement, annotations, scale, @@ -60,6 +63,14 @@ const DrawingCanvas = ({ const currentRectRef = useRef(null) const currentArrowRef = useRef(null) + // Force a redraw whenever the live canvas source is swapped, so the layer + // picks up the new page raster (Konva redraws the source each batchDraw). + useEffect(() => { + if (canvasElement && imageRef.current) { + imageRef.current.getLayer()?.batchDraw() + } + }, [canvasElement]) + // Handle Video Redraw useEffect(() => { if (videoElement && imageRef.current) { @@ -465,7 +476,7 @@ const DrawingCanvas = ({ diff --git a/packages/webui/components/viewers/pdf/pdf-viewer.tsx b/packages/webui/components/viewers/pdf/pdf-viewer.tsx index fdc22161..86fffc7e 100644 --- a/packages/webui/components/viewers/pdf/pdf-viewer.tsx +++ b/packages/webui/components/viewers/pdf/pdf-viewer.tsx @@ -9,6 +9,15 @@ import { centeredPan, fitScale, zoomAtPoint } from '../pan-zoom' import { usePanZoomGestures } from '../use-pan-zoom' import pdfworker from '@/ui/public/pdf.worker.min.mjs' with { type: 'file' } +import './text-layer.css' + +/** + * Cap on the page render canvas area (in device pixels) to bound memory usage + * when re-rasterizing at high zoom levels. + */ +const MAX_RENDER_PIXELS = 32_000_000 +/** Hard cap on the page render scale (device pixels per CSS pixel at zoom 1). */ +const MAX_RENDER_SCALE = 16 if (typeof window !== 'undefined' && pdfjsLib.GlobalWorkerOptions) { const workerPath = @@ -48,8 +57,11 @@ export const PdfViewer = React.forwardRef( startTime && !isNaN(startTime) ? Math.max(1, Math.round(startTime)) : 1, ) const [totalPages, setTotalPages] = useState(1) - const [pageImageUrl, setPageImageUrl] = useState('') + const [pageCanvas, setPageCanvas] = useState(null) const [pageDimensions, setPageDimensions] = useState({ width: 800, height: 1000 }) + /** Scale at which the active page is rasterized; tracks the current zoom. */ + const [renderScale, setRenderScale] = useState(2) + const textLayerContainerRef = useRef(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) @@ -183,7 +195,9 @@ export const PdfViewer = React.forwardRef( } }, [fileUrl, startTime]) - // Render active PDF page into image + // Render the active PDF page directly onto a canvas (vector output, not a + // frozen PNG). The scale tracks the current zoom so text stays crisp when + // zoomed in; re-rendering is debounced via `renderScale`. useEffect(() => { if (!pdfDoc) return @@ -195,7 +209,6 @@ export const PdfViewer = React.forwardRef( .then((page) => { if (!active) return const unscaledViewport = page.getViewport({ scale: 1.0 }) - const renderScale = 2.0 const viewport = page.getViewport({ scale: renderScale }) const canvas = document.createElement('canvas') @@ -214,7 +227,9 @@ export const PdfViewer = React.forwardRef( renderTask.promise .then(() => { if (!active) return - setPageImageUrl(canvas.toDataURL('image/png')) + // Swap in the freshly rendered canvas only once complete, so the + // previous frame stays visible while re-rasterizing. + setPageCanvas(canvas) setPageDimensions({ width: unscaledViewport.width, height: unscaledViewport.height, @@ -244,8 +259,68 @@ export const PdfViewer = React.forwardRef( renderTask.cancel() } } + }, [pdfDoc, currentPage, renderScale]) + + // Debounce zoom changes: once the user stops zooming, re-rasterize the + // vector page at a scale that yields 1:1 device pixels for the current + // zoom (capped to keep canvas memory bounded). + useEffect(() => { + const id = window.setTimeout(() => { + const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1 + const pageArea = pageDimensions.width * pageDimensions.height + const maxByArea = pageArea > 0 ? Math.sqrt(MAX_RENDER_PIXELS / pageArea) : MAX_RENDER_SCALE + const next = Math.min(Math.max(0.5, zoom * dpr), maxByArea, MAX_RENDER_SCALE) + setRenderScale(next) + }, 150) + return () => window.clearTimeout(id) + }, [zoom, pageDimensions]) + + // Build the pdf.js TextLayer overlay for the current page: invisible, + // natively selectable text spans positioned exactly over the page canvas. + // The overlay sits on top of the Konva stage so the selection highlight + // is visible; pointer events are gated on `isDrawing` (see the JSX), so + // left-drag selects text when not in draw mode and draws when in draw mode. + useEffect(() => { + const container = textLayerContainerRef.current + if (!pdfDoc || !container) return + + let active = true + let textLayer: InstanceType | null = null + + // Drop the previous page's text runs. + container.innerHTML = '' + + pdfDoc + .getPage(currentPage) + .then((page) => { + if (!active) return + textLayer = new pdfjsLib.TextLayer({ + textContentSource: page.streamTextContent(), + container, + viewport: page.getViewport({ scale: 1.0 }), + }) + // Cancellation rejects the render promise; ignore it here. + textLayer.render().catch(() => {}) + }) + .catch((err) => { + if (!active) return + console.error('Failed to build text layer:', err) + }) + + return () => { + active = false + textLayer?.cancel() + } }, [pdfDoc, currentPage]) + // Keep the text layer's DOM transform in lockstep with the Konva stage so + // the invisible text spans stay exactly over the rendered page. + useEffect(() => { + const el = textLayerContainerRef.current + if (!el) return + el.style.transform = `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` + }, [pan, zoom]) + const conW = containerSize.width const conH = containerSize.height const pdfW = pageDimensions.width @@ -333,7 +408,7 @@ export const PdfViewer = React.forwardRef( width={conW} height={conH} mediaDimensions={pageDimensions} - imageUrl={pageImageUrl} + canvasElement={pageCanvas} annotations={displayAnnotations} scale={zoom} offset={pan} @@ -344,6 +419,28 @@ export const PdfViewer = React.forwardRef( onAddAnnotation={addAnnotation} /> )} + {/* Invisible selectable text overlay, transformed to match the Konva + stage. It sits ON TOP of the page canvas so the native selection + highlight is visible; pointer events are enabled only when not + drawing, so drags reach the stage below in draw mode. */} +
{ + // The container is user-select:none, so Chromium no longer + // clears the selection when clicking empty space (only text + // spans move the caret). Restore the expected behavior: a + // press on the container/br (not a text span) deselects. + if (e.target instanceof HTMLElement && e.target.tagName !== 'SPAN') { + window.getSelection()?.removeAllRanges() + } + }} + style={{ + transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`, + transformOrigin: '0 0', + pointerEvents: isDrawing ? 'none' : 'auto', + }} + />
` elements. Without the rules below nothing is + * positioned or sized, so this subset is required for text selection to work. + * + * We render the text layer at viewport scale 1 and transform the whole + * container with the same translate/scale the Konva stage applies, hence + * `--total-scale-factor: 1` (the spans stay in page coordinates). + */ +.pdf-text-layer { + position: absolute; + inset: 0; + overflow: clip; + text-align: initial; + line-height: 1; + letter-spacing: normal; + word-spacing: normal; + transform-origin: 0 0; + caret-color: CanvasText; + /* The container itself must not be selectable: when a drag ends in empty + space Chromium would otherwise target the container as the caret + position and extend the selection across rows. Only the spans are + selectable (see below), so the caret clamps to the nearest text. */ + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + /* Above the page canvas (z-0) so the selection highlight is visible, but + below the loading overlay (z-20). */ + z-index: 10; + --total-scale-factor: 1; + --scale-round-x: 1px; + --scale-round-y: 1px; + --min-font-size: 1; + --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); + --min-font-size-inv: calc(1 / var(--min-font-size)); +} + +.pdf-text-layer :is(span, br) { + color: transparent; + position: absolute; + white-space: pre; + cursor: text; + transform-origin: 0% 0%; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} + +/* pdf.js appends a
after each line-ending text run; without explicit + left/top they sit at the container's top-left (static position) and would + paint a stray selection highlight when a range spans multiple rows. */ +.pdf-text-layer br::-moz-selection { + background: transparent; +} +.pdf-text-layer br::selection { + background: transparent; +} + +.pdf-text-layer > :not(.markedContent), +.pdf-text-layer .markedContent span:not(.markedContent) { + z-index: 1; + --font-height: 0; + font-size: calc(var(--text-scale-factor) * var(--font-height)); + --scale-x: 1; + --rotate: 0deg; + transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); +} + +.pdf-text-layer .markedContent { + display: contents; +}