pdf-js-viewer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import PropTypes from 'prop-types'
  2. import { memo, useCallback, useEffect, useRef, useState } from 'react'
  3. import { debounce } from 'lodash'
  4. import PdfViewerControls from './pdf-viewer-controls'
  5. import { useProjectContext } from '../../../shared/context/project-context'
  6. import usePersistedState from '../../../shared/hooks/use-persisted-state'
  7. import { buildHighlightElement } from '../util/highlights'
  8. import PDFJSWrapper from '../util/pdf-js-wrapper'
  9. import withErrorBoundary from '../../../infrastructure/error-boundary'
  10. import PdfPreviewErrorBoundaryFallback from './pdf-preview-error-boundary-fallback'
  11. import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
  12. import { captureException } from '../../../infrastructure/error-reporter'
  13. import { getPdfCachingMetrics } from '../util/metrics'
  14. import { userContentDomainAccessCheckFailed } from '../../user-content-domain-access-check'
  15. import { isURLOnUserContentDomain } from '../util/fetchFromCompileDomain'
  16. import { isNetworkError } from '../../../utils/isNetworkError'
  17. import OError from '@overleaf/o-error'
  18. function PdfJsViewer({ url, pdfFile }) {
  19. const { _id: projectId } = useProjectContext()
  20. const { setError, firstRenderDone, highlights, position, setPosition } =
  21. useCompileContext()
  22. // state values persisted in localStorage to restore on load
  23. const [scale, setScale] = usePersistedState(
  24. `pdf-viewer-scale:${projectId}`,
  25. 'page-width'
  26. )
  27. // local state values
  28. const [pdfJsWrapper, setPdfJsWrapper] = useState()
  29. const [initialised, setInitialised] = useState(false)
  30. // create the viewer when the container is mounted
  31. const handleContainer = useCallback(
  32. parent => {
  33. if (parent) {
  34. const wrapper = new PDFJSWrapper(parent.firstChild)
  35. wrapper
  36. .init()
  37. .then(() => {
  38. setPdfJsWrapper(wrapper)
  39. })
  40. .catch(error => {
  41. setError('pdf-viewer-loading-error')
  42. captureException(error)
  43. })
  44. return () => {
  45. setPdfJsWrapper(null)
  46. wrapper.destroy()
  47. }
  48. }
  49. },
  50. [setError]
  51. )
  52. const [startFetch, setStartFetch] = useState(0)
  53. // listen for events and trigger rendering.
  54. // Do everything in one effect to mitigate de-sync between events.
  55. useEffect(() => {
  56. if (!pdfJsWrapper || !firstRenderDone) return
  57. let timePDFFetched
  58. let timePDFRendered
  59. const submitLatencies = () => {
  60. if (!timePDFFetched) {
  61. // The pagerendered event was attached after pagesinit fired. :/
  62. return
  63. }
  64. const latencyFetch = Math.ceil(timePDFFetched - startFetch)
  65. let latencyRender
  66. if (timePDFRendered) {
  67. // The renderer does not yield in case the browser tab is hidden.
  68. // It will yield when the browser tab is visible again.
  69. // This will skew our performance metrics for rendering!
  70. // We are omitting the render time in case we detect this state.
  71. latencyRender = Math.ceil(timePDFRendered - timePDFFetched)
  72. }
  73. firstRenderDone({
  74. latencyFetch,
  75. latencyRender,
  76. // Let the pdfCachingMetrics round trip to account for pdf-detach.
  77. pdfCachingMetrics: getPdfCachingMetrics(),
  78. })
  79. }
  80. const handlePagesinit = () => {
  81. setInitialised(true)
  82. timePDFFetched = performance.now()
  83. if (document.hidden) {
  84. // Rendering does not start in case we are hidden. See comment above.
  85. submitLatencies()
  86. }
  87. }
  88. const handleRendered = () => {
  89. if (!document.hidden) {
  90. // The render time is not accurate in case we are hidden. See above.
  91. timePDFRendered = performance.now()
  92. }
  93. submitLatencies()
  94. // Only get the times for the first page.
  95. pdfJsWrapper.eventBus.off('pagerendered', handleRendered)
  96. }
  97. // `pagesinit` fires when the data for rendering the first page is ready.
  98. pdfJsWrapper.eventBus.on('pagesinit', handlePagesinit)
  99. // `pagerendered` fires when a page was actually rendered.
  100. pdfJsWrapper.eventBus.on('pagerendered', handleRendered)
  101. return () => {
  102. pdfJsWrapper.eventBus.off('pagesinit', handlePagesinit)
  103. pdfJsWrapper.eventBus.off('pagerendered', handleRendered)
  104. }
  105. }, [pdfJsWrapper, firstRenderDone, startFetch])
  106. // load the PDF document from the URL
  107. useEffect(() => {
  108. if (pdfJsWrapper && url) {
  109. setInitialised(false)
  110. setError(undefined)
  111. setStartFetch(performance.now())
  112. const abortController = new AbortController()
  113. const handleFetchError = err => {
  114. if (abortController.signal.aborted) return
  115. // The error is already logged at the call-site with additional context.
  116. if (err instanceof pdfJsWrapper.PDFJS.MissingPDFException) {
  117. if (
  118. // 404 is unrelated to new domain
  119. OError.getFullInfo(err).statusCode !== 404 &&
  120. isURLOnUserContentDomain(OError.getFullInfo(err).url)
  121. ) {
  122. setError('rendering-error-new-domain')
  123. } else {
  124. setError('rendering-error-expected')
  125. }
  126. } else {
  127. setError('rendering-error')
  128. }
  129. }
  130. pdfJsWrapper
  131. .loadDocument({ url, pdfFile, abortController, handleFetchError })
  132. .catch(error => {
  133. if (abortController.signal.aborted) return
  134. console.error(error)
  135. if (
  136. isURLOnUserContentDomain(url) &&
  137. error instanceof pdfJsWrapper.PDFJS.UnexpectedResponseException
  138. ) {
  139. setError('rendering-error-new-domain')
  140. } else if (
  141. isURLOnUserContentDomain(url) &&
  142. error.name === 'UnknownErrorException' &&
  143. (isNetworkError(error) || userContentDomainAccessCheckFailed())
  144. ) {
  145. // For some reason, pdfJsWrapper.PDFJS.UnknownErrorException is
  146. // not available for an instance check.
  147. setError('rendering-error-new-domain')
  148. } else {
  149. setError('rendering-error')
  150. }
  151. })
  152. return () => {
  153. abortController.abort()
  154. pdfJsWrapper.abortDocumentLoading()
  155. }
  156. }
  157. }, [pdfJsWrapper, url, pdfFile, setError, setStartFetch])
  158. // listen for scroll events
  159. useEffect(() => {
  160. let storePositionTimer
  161. if (initialised && pdfJsWrapper) {
  162. if (!pdfJsWrapper.isVisible()) {
  163. return
  164. }
  165. // store the scroll position in localStorage, for the synctex button
  166. const storePosition = debounce(pdfViewer => {
  167. // set position for "sync to code" button
  168. try {
  169. setPosition(pdfViewer.currentPosition)
  170. } catch (error) {
  171. // console.error(error)
  172. }
  173. }, 500)
  174. storePositionTimer = window.setTimeout(() => {
  175. storePosition(pdfJsWrapper)
  176. }, 100)
  177. const scrollListener = () => {
  178. storePosition(pdfJsWrapper)
  179. }
  180. pdfJsWrapper.container.addEventListener('scroll', scrollListener)
  181. return () => {
  182. pdfJsWrapper.container.removeEventListener('scroll', scrollListener)
  183. if (storePositionTimer) {
  184. window.clearTimeout(storePositionTimer)
  185. }
  186. storePosition.cancel()
  187. }
  188. }
  189. }, [setPosition, pdfJsWrapper, initialised])
  190. // listen for double-click events
  191. useEffect(() => {
  192. if (pdfJsWrapper) {
  193. const handleTextlayerrendered = textLayer => {
  194. const pageElement = textLayer.source.textLayerDiv.closest('.page')
  195. if (!pageElement.dataset.listeningForDoubleClick) {
  196. pageElement.dataset.listeningForDoubleClick = true
  197. const doubleClickListener = event => {
  198. const clickPosition = pdfJsWrapper.clickPosition(
  199. event,
  200. pageElement,
  201. textLayer
  202. )
  203. if (clickPosition) {
  204. window.dispatchEvent(
  205. new CustomEvent('synctex:sync-to-position', {
  206. detail: clickPosition,
  207. })
  208. )
  209. }
  210. }
  211. pageElement.addEventListener('dblclick', doubleClickListener)
  212. }
  213. }
  214. pdfJsWrapper.eventBus.on('textlayerrendered', handleTextlayerrendered)
  215. return () =>
  216. pdfJsWrapper.eventBus.off('textlayerrendered', handleTextlayerrendered)
  217. }
  218. }, [pdfJsWrapper])
  219. // restore the saved scale and scroll position
  220. const positionRef = useRef(position)
  221. useEffect(() => {
  222. positionRef.current = position
  223. }, [position])
  224. const scaleRef = useRef(scale)
  225. useEffect(() => {
  226. scaleRef.current = scale
  227. }, [scale])
  228. useEffect(() => {
  229. if (initialised && pdfJsWrapper) {
  230. if (!pdfJsWrapper.isVisible()) {
  231. return
  232. }
  233. if (positionRef.current) {
  234. pdfJsWrapper.scrollToPosition(positionRef.current, scaleRef.current)
  235. } else {
  236. pdfJsWrapper.viewer.currentScaleValue = scaleRef.current
  237. }
  238. }
  239. }, [initialised, pdfJsWrapper, scaleRef, positionRef])
  240. // transmit scale value to the viewer when it changes
  241. useEffect(() => {
  242. if (pdfJsWrapper) {
  243. pdfJsWrapper.viewer.currentScaleValue = scale
  244. }
  245. }, [scale, pdfJsWrapper])
  246. // when highlights are created, build the highlight elements
  247. useEffect(() => {
  248. const timers = []
  249. let intersectionObserver
  250. if (pdfJsWrapper && highlights?.length) {
  251. // watch for the highlight elements to scroll into view
  252. intersectionObserver = new IntersectionObserver(
  253. entries => {
  254. for (const entry of entries) {
  255. if (entry.isIntersecting) {
  256. intersectionObserver.unobserve(entry.target)
  257. // fade the element in and out
  258. entry.target.style.opacity = '0.5'
  259. timers.push(
  260. window.setTimeout(() => {
  261. entry.target.style.opacity = '0'
  262. }, 1000)
  263. )
  264. }
  265. }
  266. },
  267. {
  268. threshold: 1.0, // the whole element must be visible
  269. }
  270. )
  271. const elements = []
  272. for (const highlight of highlights) {
  273. try {
  274. const element = buildHighlightElement(highlight, pdfJsWrapper)
  275. elements.push(element)
  276. intersectionObserver.observe(element)
  277. } catch (error) {
  278. // ignore invalid highlights
  279. }
  280. }
  281. const [firstElement] = elements
  282. if (firstElement) {
  283. // scroll to the first highlighted element
  284. firstElement.scrollIntoView({
  285. block: 'center',
  286. inline: 'start',
  287. behavior: 'smooth',
  288. })
  289. }
  290. return () => {
  291. for (const timer of timers) {
  292. window.clearTimeout(timer)
  293. }
  294. for (const element of elements) {
  295. element.remove()
  296. }
  297. intersectionObserver?.disconnect()
  298. }
  299. }
  300. }, [highlights, pdfJsWrapper])
  301. // set the scale in response to zoom option changes
  302. const setZoom = useCallback(
  303. zoom => {
  304. switch (zoom) {
  305. case 'fit-width':
  306. setScale('page-width')
  307. break
  308. case 'fit-height':
  309. setScale('page-height')
  310. break
  311. case 'zoom-in':
  312. if (pdfJsWrapper) {
  313. setScale(pdfJsWrapper.viewer.currentScale * 1.25)
  314. }
  315. break
  316. case 'zoom-out':
  317. if (pdfJsWrapper) {
  318. setScale(pdfJsWrapper.viewer.currentScale * 0.75)
  319. }
  320. break
  321. }
  322. },
  323. [pdfJsWrapper, setScale]
  324. )
  325. // adjust the scale when the container is resized
  326. useEffect(() => {
  327. if (pdfJsWrapper && 'ResizeObserver' in window) {
  328. const resizeListener = () => {
  329. pdfJsWrapper.updateOnResize()
  330. }
  331. const resizeObserver = new ResizeObserver(resizeListener)
  332. resizeObserver.observe(pdfJsWrapper.container)
  333. window.addEventListener('resize', resizeListener)
  334. return () => {
  335. resizeObserver.disconnect()
  336. window.removeEventListener('resize', resizeListener)
  337. }
  338. }
  339. }, [pdfJsWrapper])
  340. const handleKeyDown = useCallback(
  341. event => {
  342. if (!initialised) {
  343. return
  344. }
  345. if (event.metaKey || event.ctrlKey) {
  346. switch (event.key) {
  347. case '=':
  348. event.preventDefault()
  349. setZoom('zoom-in')
  350. break
  351. case '-':
  352. event.preventDefault()
  353. setZoom('zoom-out')
  354. break
  355. case '0':
  356. event.preventDefault()
  357. setZoom('fit-width')
  358. break
  359. }
  360. }
  361. },
  362. [initialised, setZoom]
  363. )
  364. /* eslint-disable jsx-a11y/no-noninteractive-tabindex */
  365. /* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
  366. return (
  367. <div className="pdfjs-viewer pdfjs-viewer-outer" ref={handleContainer}>
  368. <div
  369. className="pdfjs-viewer-inner"
  370. role="tabpanel"
  371. tabIndex="0"
  372. onKeyDown={handleKeyDown}
  373. >
  374. <div className="pdfViewer" />
  375. </div>
  376. <div className="pdfjs-controls">
  377. <PdfViewerControls setZoom={setZoom} />
  378. </div>
  379. </div>
  380. )
  381. }
  382. PdfJsViewer.propTypes = {
  383. url: PropTypes.string.isRequired,
  384. pdfFile: PropTypes.object,
  385. }
  386. export default withErrorBoundary(memo(PdfJsViewer), () => (
  387. <PdfPreviewErrorBoundaryFallback type="pdf" />
  388. ))