Improve PDF double-click listener (#19556)

GitOrigin-RevId: 3d8f316481d8be30ffe1a04a270b978b4720ccbe
This commit is contained in:
Alf Eaton 2024-07-29 13:29:59 +01:00 committed by Copybot
parent 4c76667379
commit 21e458df2a
2 changed files with 20 additions and 17 deletions

View file

@ -1,4 +1,11 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react' import {
memo,
MouseEventHandler,
useCallback,
useEffect,
useRef,
useState,
} from 'react'
import { debounce, throttle } from 'lodash' import { debounce, throttle } from 'lodash'
import PdfViewerControlsToolbar from './pdf-viewer-controls-toolbar' import PdfViewerControlsToolbar from './pdf-viewer-controls-toolbar'
import { useProjectContext } from '../../../shared/context/project-context' import { useProjectContext } from '../../../shared/context/project-context'
@ -244,16 +251,14 @@ function PdfJsViewer({ url, pdfFile }: PdfJsViewerProps) {
const textLayerDiv = const textLayerDiv =
textLayer.source.textLayerDiv ?? textLayer.source.textLayer.div textLayer.source.textLayerDiv ?? textLayer.source.textLayer.div
const pageElement = textLayerDiv.closest('.page') if (!textLayerDiv.dataset.listeningForDoubleClick) {
textLayerDiv.dataset.listeningForDoubleClick = true
if (!pageElement.dataset.listeningForDoubleClick) { const doubleClickListener: MouseEventHandler = event => {
pageElement.dataset.listeningForDoubleClick = true
const doubleClickListener = (event: Event) => {
const clickPosition = pdfJsWrapper.clickPosition( const clickPosition = pdfJsWrapper.clickPosition(
event, event,
pageElement, textLayerDiv.closest('.page').querySelector('canvas'),
textLayer textLayer.pageNumber - 1
) )
if (clickPosition) { if (clickPosition) {
@ -270,7 +275,7 @@ function PdfJsViewer({ url, pdfFile }: PdfJsViewerProps) {
} }
} }
pageElement.addEventListener('dblclick', doubleClickListener) textLayerDiv.addEventListener('dblclick', doubleClickListener)
} }
} }

View file

@ -162,16 +162,14 @@ export default class PDFJSWrapper {
} }
// get the page and offset of a click event // get the page and offset of a click event
clickPosition(event, pageElement, textLayer) { clickPosition(event, canvas, page) {
const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1) if (!canvas) {
const pageCanvas = pageElement.querySelector('canvas')
if (!pageCanvas) {
return return
} }
const pageRect = pageCanvas.getBoundingClientRect() const { viewport } = this.viewer.getPageView(page)
const pageRect = canvas.getBoundingClientRect()
const dx = event.clientX - pageRect.left const dx = event.clientX - pageRect.left
const dy = event.clientY - pageRect.top const dy = event.clientY - pageRect.top
@ -179,7 +177,7 @@ export default class PDFJSWrapper {
const [left, top] = viewport.convertToPdfPoint(dx, dy) const [left, top] = viewport.convertToPdfPoint(dx, dy)
return { return {
page: textLayer.pageNumber - 1, page,
offset: { offset: {
left, left,
top: viewport.viewBox[3] - top, top: viewport.viewBox[3] - top,