overleaf/services/web/frontend/js/features/file-view/components/file-view-pdf.tsx
Tim Down 8144d431a6 Merge pull request #15597 from overleaf/td-ide-page-preview-pdf-fix
Remove FileTreeManager from FileViewPdf

GitOrigin-RevId: ca58d8695ab8e8868f8025aab932d665742a4131
2023-11-07 09:04:35 +00:00

67 lines
1.8 KiB
TypeScript

import { FC, useCallback } from 'react'
import useIsMounted from '@/shared/hooks/use-is-mounted'
import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
import { debugConsole } from '@/utils/debugging'
const FileViewPdf: FC<{
fileId: string
onLoad: () => void
onError: () => void
}> = ({ fileId, onLoad, onError }) => {
const mountedRef = useIsMounted()
const { previewByPath, pathInFolder } = useFileTreePathContext()
const handleContainer = useCallback(
async (element: HTMLDivElement | null) => {
if (element) {
const { PDFJS } = await import(
'../../pdf-preview/util/pdf-js-versions'
).then(m => m.default as any)
// bail out if loading PDF.js took too long
if (!mountedRef.current) {
onError()
return
}
const path = pathInFolder(fileId)
const preview = path ? previewByPath(path) : null
if (!preview) {
onError()
return
}
const pdf = await PDFJS.getDocument(preview.url).promise
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i)
const viewport = page.getViewport({ scale: 1 })
const canvas = document.createElement('canvas')
canvas.classList.add('pdf-page')
canvas.width = viewport.width
canvas.height = viewport.height
element.append(canvas)
page.render({
canvasContext: canvas.getContext('2d'),
viewport,
})
}
onLoad()
return () => {
pdf.cleanup().catch(debugConsole.error)
pdf.destroy()
}
}
},
[mountedRef, pathInFolder, fileId, previewByPath, onLoad, onError]
)
return <div className="file-view-pdf" ref={handleContainer} />
}
export default FileViewPdf