From 5a7698ddef7dba06618aef933dd0d92d9103f025 Mon Sep 17 00:00:00 2001 From: Jakob Ackermann Date: Fri, 7 Jan 2022 16:32:46 +0000 Subject: [PATCH] [web] refactor updating of scroll position in pdf view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Timothée Alby GitOrigin-RevId: 932c880bcd41e68d231928bdcbbaeb06c60f6fd5 --- .../pdf-preview/components/pdf-js-viewer.js | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/services/web/frontend/js/features/pdf-preview/components/pdf-js-viewer.js b/services/web/frontend/js/features/pdf-preview/components/pdf-js-viewer.js index 5d84205f1c..84190b9fe5 100644 --- a/services/web/frontend/js/features/pdf-preview/components/pdf-js-viewer.js +++ b/services/web/frontend/js/features/pdf-preview/components/pdf-js-viewer.js @@ -1,5 +1,5 @@ import PropTypes from 'prop-types' -import { memo, useCallback, useEffect, useState } from 'react' +import { memo, useCallback, useEffect, useRef, useState } from 'react' import { debounce } from 'lodash' import PdfViewerControls from './pdf-viewer-controls' import { useProjectContext } from '../../../shared/context/project-context' @@ -14,7 +14,7 @@ import getMeta from '../../../utils/meta' function PdfJsViewer({ url }) { const { _id: projectId } = useProjectContext() - const { setError, firstRenderDone, highlights, setPosition } = + const { setError, firstRenderDone, highlights, position, setPosition } = useCompileContext() const [timePDFFetched, setTimePDFFetched] = useState() @@ -140,26 +140,28 @@ function PdfJsViewer({ url }) { }, [pdfJsWrapper]) // restore the saved scale and scroll position + const positionRef = useRef(position) + useEffect(() => { + positionRef.current = position + }, [position]) + + const scaleRef = useRef(scale) + useEffect(() => { + scaleRef.current = scale + }, [scale]) + useEffect(() => { if (initialised && pdfJsWrapper) { if (!pdfJsWrapper.isVisible()) { return } - - setScale(scale => { - setPosition(position => { - if (position) { - pdfJsWrapper.scrollToPosition(position, scale) - } else { - pdfJsWrapper.viewer.currentScaleValue = scale - } - return position - }) - - return scale - }) + if (positionRef.current) { + pdfJsWrapper.scrollToPosition(positionRef.current, scaleRef.current) + } else { + pdfJsWrapper.viewer.currentScaleValue = scaleRef.current + } } - }, [initialised, setScale, setPosition, pdfJsWrapper]) + }, [initialised, pdfJsWrapper, scaleRef, positionRef]) // transmit scale value to the viewer when it changes useEffect(() => {