StickyNoteTools.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import React, { useEffect, useCallback } from 'react';
  2. import { ANNOTATION_TYPE } from '../constants';
  3. import Button from '../components/Button';
  4. import Icon from '../components/Icon';
  5. import { getAbsoluteCoordinate } from '../helpers/position';
  6. import { parseAnnotationObject } from '../helpers/annotation';
  7. import { BtnWrapper } from '../global/toolStyled';
  8. import useActions from '../actions';
  9. import useStore from '../store';
  10. type Props = {
  11. title: string;
  12. isActive: boolean;
  13. onClick: () => void;
  14. };
  15. const StickyNoteTools: React.FC<Props> = ({
  16. title,
  17. isActive,
  18. onClick,
  19. }: Props) => {
  20. const [{ viewport, scale }, dispatch] = useStore();
  21. const { addAnnots } = useActions(dispatch);
  22. const addStickyNote = (
  23. pageEle: HTMLElement,
  24. event: MouseEvent | TouchEvent
  25. ): void => {
  26. const pageNum = pageEle.getAttribute('data-page-num') || 0;
  27. const coordinate = getAbsoluteCoordinate(pageEle, event);
  28. const annotData = {
  29. obj_type: ANNOTATION_TYPE.text,
  30. obj_attr: {
  31. page: pageNum as number,
  32. position: {
  33. top: coordinate.y,
  34. left: coordinate.x,
  35. bottom: coordinate.y + 20,
  36. right: coordinate.x + 20,
  37. },
  38. content: '',
  39. },
  40. };
  41. const stickyNote = parseAnnotationObject(annotData, viewport.height, scale);
  42. addAnnots([stickyNote], true);
  43. };
  44. const handleMouseDown = useCallback(
  45. (event: MouseEvent | TouchEvent): void => {
  46. // event.preventDefault();
  47. const pageEle = (event.target as HTMLElement).parentNode as HTMLElement;
  48. if (pageEle.hasAttribute('data-page-num')) {
  49. addStickyNote(pageEle, event);
  50. }
  51. },
  52. [viewport, scale]
  53. );
  54. useEffect(() => {
  55. const pdfViewer = document.getElementById('pdf_viewer') as HTMLDivElement;
  56. if (isActive && pdfViewer) {
  57. window.addEventListener('touchstart', handleMouseDown);
  58. window.addEventListener('mousedown', handleMouseDown);
  59. }
  60. return (): void => {
  61. if (pdfViewer) {
  62. window.removeEventListener('touchstart', handleMouseDown);
  63. window.removeEventListener('mousedown', handleMouseDown);
  64. }
  65. };
  66. }, [isActive, handleMouseDown]);
  67. return (
  68. <BtnWrapper>
  69. <Button
  70. shouldFitContainer
  71. align="left"
  72. onClick={onClick}
  73. isActive={isActive}
  74. >
  75. <Icon glyph="sticky-note" style={{ marginRight: '10px' }} />
  76. {title}
  77. </Button>
  78. </BtnWrapper>
  79. );
  80. };
  81. export default StickyNoteTools;