feat(webui): direct canvas PDF rendering with selectable text (#299)

* feat(webui): render pdf pages via live canvas with selectable text

Replace the rasterize-to-PNG pipeline in the PDF viewer with direct
canvas rendering that tracks the current zoom, so text stays crisp when
zoomed in, and overlay a pdf.js TextLayer that makes text natively
selectable when not in draw mode.

- pdf-viewer: render pages onto a live canvas at a zoom-proportional
  scale (debounced, memory-capped) instead of a fixed 2x PNG snapshot
- pdf-viewer: add pdf.js TextLayer overlay per page, transformed in
  lockstep with the Konva stage so spans stay aligned while panning
  and zooming
- drawing-canvas: accept an optional live canvas element and force a
  layer redraw when it is swapped
- add text-layer.css with the minimal pdf.js text layer styles
- add e2e spec verifying text selection in view mode and that draw
  mode routes drags to the canvas

* fix(webui): show pdf text selection highlight above the page canvas

The pdf.js text layer was stacked below the opaque Konva page canvas, so
the native selection highlight was painted underneath it and invisible
(selection itself worked). Move the overlay above the canvas and gate its
pointer-events on draw mode: auto when not drawing (select text), none in
draw mode so drags reach the Konva stage below (draw markup).

Verified with screenshot pixel analysis: the selected region now renders
the highlight (blue) where it was pure grayscale before.

* fix(webui): transparent selection background for pdf text layer br elements

* fix(webui): stop pdf text selection over-selecting in empty space

The text layer container was user-selectable (user-select: auto), so when
a drag's caret moved into empty space Chromium targeted the container and
extended the selection to a container-content boundary, selecting across
rows (e.g. dragging from line 1 into the gap selected lines 1-2).

Make the container user-select: none while keeping the text spans
user-select: text, so the caret clamps to the nearest selectable text and
the selection stays put when dragging into empty space.

* fix(webui): deselect pdf text when clicking empty space

With user-select: none on the text layer container, Chromium no longer
clears the selection when clicking non-selectable areas. Clear it manually
on mousedown over the container or <br> (not a text span) so clicking
empty space between lines or outside text deselects, matching native
behavior.
This commit is contained in:
Yiling-J
2026-08-12 13:58:02 +08:00
committed by GitHub
parent 5ad3fdbf69
commit 1cd94a77c6
3 changed files with 188 additions and 6 deletions
+12 -1
View File
@@ -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<Konva.Rect>(null)
const currentArrowRef = useRef<Konva.Arrow>(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 = ({
<Layer>
<KonvaImage
ref={imageRef}
image={videoElement || loadedImage}
image={videoElement || canvasElement || loadedImage}
width={mediaDimensions.width}
height={mediaDimensions.height}
/>
@@ -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<MediaController, FileViewerProps>(
startTime && !isNaN(startTime) ? Math.max(1, Math.round(startTime)) : 1,
)
const [totalPages, setTotalPages] = useState(1)
const [pageImageUrl, setPageImageUrl] = useState<string>('')
const [pageCanvas, setPageCanvas] = useState<HTMLCanvasElement | null>(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<HTMLDivElement | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -183,7 +195,9 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}, [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<MediaController, FileViewerProps>(
.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<MediaController, FileViewerProps>(
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<MediaController, FileViewerProps>(
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<typeof pdfjsLib.TextLayer> | 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<MediaController, FileViewerProps>(
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<MediaController, FileViewerProps>(
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. */}
<div
ref={textLayerContainerRef}
className="pdf-text-layer"
onMouseDown={(e) => {
// 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',
}}
/>
</div>
</div>
<PdfControlBar
@@ -0,0 +1,74 @@
/*
* Minimal pdf.js text-layer styles, adapted from pdfjs-dist's viewer CSS.
*
* The pdf.js `TextLayer` class lays out invisible text runs by setting inline
* styles (left/top as percentages, font-family, --font-height, --scale-x,
* --rotate) on `<span>` 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 <br> 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;
}