123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- import React, { useEffect, useState, useRef } from 'react';
- import _ from 'lodash';
- import Viewer from '../components/Viewer';
- import PdfPage from './PdfPage';
- import { watchScroll, scaleCheck } from '../helpers/utility';
- import useGestureScale from '../hooks/useGestureScale';
- import useActions from '../actions';
- import useStore from '../store';
- type Props = {
- scrollToUpdate: (state: ScrollStateType) => void;
- };
- let timer = 0;
- const PdfPages: React.FC<Props> = ({ scrollToUpdate }: Props) => {
- const [elements, setElement] = useState<React.ReactNode[]>([]);
- const containerRef = useRef<HTMLDivElement>(null);
- const [
- {
- totalPage,
- currentPage,
- scale,
- viewport,
- rotation,
- displayMode,
- annotations,
- },
- dispatch,
- ] = useStore();
- const { changeScale } = useActions(dispatch);
- const [zoom] = useGestureScale(containerRef);
- const createPages = (): void => {
- const pagesContent: React.ReactNode[] = [];
- for (let i = 1; i <= totalPage; i += 1) {
- const key = `page-${i}`;
- const component = (
- <PdfPage
- key={key}
- index={i}
- renderingState={_.range(1, 3).includes(i) ? 'RENDERING' : 'LOADING'}
- />
- );
- pagesContent.push(component);
- }
- setElement(pagesContent);
- };
- const updatePages = (): void => {
- const renderingIndexQueue = _.range(currentPage - 1, currentPage + 2);
- let index = currentPage - 3;
- const end = currentPage + 3;
- while (currentPage) {
- if (elements[index]) {
- const pageNum = index + 1;
- const key = `page-${pageNum}`;
- elements[index] = (
- <PdfPage
- key={key}
- index={pageNum}
- renderingState={
- renderingIndexQueue.includes(pageNum) ? 'RENDERING' : 'LOADING'
- }
- />
- );
- }
- index += 1;
- if (index >= end) break;
- }
- if (elements.length) {
- setElement([...elements]);
- }
- };
- useEffect(() => {
- createPages();
- watchScroll(containerRef.current, scrollToUpdate);
- }, []);
- useEffect(() => {
- updatePages();
- }, [currentPage, viewport, rotation, annotations]);
- useEffect(() => {
- if (zoom !== 0) {
- const viewer = containerRef.current as HTMLElement;
- viewer.style.transform = `scale(${1 + zoom})`;
- clearTimeout(timer);
- timer = setTimeout(() => {
- const targetScale = Math.round(scale * 100 + zoom * 100);
- changeScale(scaleCheck(targetScale));
- viewer.style.transform = `scale(1)`;
- }, 500);
- }
- }, [zoom]);
- return (
- <Viewer
- ref={containerRef}
- viewport={viewport}
- rotation={rotation}
- displayMode={displayMode}
- >
- {elements}
- </Viewer>
- );
- };
- export default PdfPages;
|