PdfPages.tsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import React, { useEffect, useRef } from 'react';
  2. import Viewer from '../components/Viewer';
  3. import PdfPage from './PdfPage';
  4. import { watchScroll, scaleCheck } from '../helpers/utility';
  5. import useGestureScale from '../hooks/useGestureScale';
  6. import useActions from '../actions';
  7. import useStore from '../store';
  8. type Props = {
  9. scrollToUpdate: (state: ScrollStateType) => void;
  10. };
  11. let timer = 0;
  12. const PdfPages: React.FC<Props> = ({ scrollToUpdate }: Props) => {
  13. const containerRef = useRef<HTMLDivElement>(null);
  14. const [{ totalPage, scale, viewport, rotation }, dispatch] = useStore();
  15. const { changeScale } = useActions(dispatch);
  16. const [zoom] = useGestureScale(containerRef);
  17. useEffect(() => {
  18. watchScroll(containerRef.current, scrollToUpdate);
  19. }, []);
  20. useEffect(() => {
  21. if (zoom !== 0) {
  22. const viewer = containerRef.current as HTMLElement;
  23. viewer.style.transform = `scale(${1 + zoom})`;
  24. clearTimeout(timer);
  25. timer = setTimeout(() => {
  26. const targetScale = Math.round(scale * 100 + zoom * 100);
  27. changeScale(scaleCheck(targetScale));
  28. viewer.style.transform = `scale(1)`;
  29. }, 500);
  30. }
  31. }, [zoom]);
  32. return (
  33. <Viewer ref={containerRef} viewport={viewport} rotation={rotation}>
  34. {totalPage &&
  35. Array(totalPage)
  36. .fill(1)
  37. .map((x, i) => <PdfPage key={`page-${i + x}`} index={i + x} />)}
  38. </Viewer>
  39. );
  40. };
  41. export default PdfPages;