import React, { useEffect, useState, useRef } from 'react'; import Watermark from '../Watermark'; import { renderPdfPage } from '../../helpers/pdf'; import { renderMatches } from '../../helpers/search'; import { PageWrapper, PdfCanvas, AnnotationLayer, TextLayer, WatermarkLayer, Inner, } from './styled'; let pdfPage: PdfPageType | null = null; type Props = { pageNum: number; renderingState: RenderingStateType; getPage: GetPageType; viewport: ViewportType; rotation: number; scale: number; annotations: React.ReactNode[]; watermark: WatermarkType; queryString: string; matchesMap: MatchType[]; }; const PageView: React.FC = ({ pageNum, getPage, viewport, renderingState = 'LOADING', rotation, scale, annotations = [], watermark = {}, queryString, matchesMap, }: Props) => { const rootEle = useRef(null); const [renderTask, setRenderTask] = useState(null); const renderPage = async (): Promise => { if (getPage) { getPage().then((obj: PdfPageType) => { pdfPage = obj; const setTextDivs = (elements: HTMLElement[]) => { if (queryString && matchesMap.length) { matchesMap.forEach((item) => { if (pageNum === item.page) { const id = `${item.page}_${item.index}`; renderMatches(elements, getPage, item.index, queryString, id); } }); } }; if (rootEle.current) { renderPdfPage({ rootEle: rootEle.current, pdfPage: obj, viewport, setRenderTask, setTextDivs, }); } }); } }; useEffect(() => { if (renderingState === 'LOADING' && pdfPage) { pdfPage.cleanup(); } if (renderingState === 'RENDERING' && renderTask) { renderTask.cancel(); } if (renderingState === 'RENDERING') { renderPage(); } }, [renderingState, viewport, queryString, matchesMap]); useEffect(() => { if (queryString === '' && !matchesMap.length) { renderPage(); } }, [queryString, matchesMap]); return ( {renderingState === 'LOADING' ? ( 載入中... ) : ( <> {watermark.text || watermark.imagepath ? ( ) : ( '' )} {annotations} )} ); }; export default PageView;