import React, { useEffect, useCallback } from 'react'; import { ANNOTATION_TYPE } from '../constants'; import Button from '../components/Button'; import Icon from '../components/Icon'; import { getAbsoluteCoordinate } from '../helpers/position'; import { parseAnnotationObject, appendUserIdAndDate, } from '../helpers/annotation'; import { BtnWrapper } from '../global/toolStyled'; import useActions from '../actions'; import useStore from '../store'; type Props = { title: string; isActive: boolean; onClick: () => void; }; const StickyNoteTool: React.FC = ({ title, isActive, onClick, }: Props) => { const [{ viewport, scale }, dispatch] = useStore(); const { addAnnots } = useActions(dispatch); const addStickyNote = ( pageEle: HTMLElement, event: MouseEvent | TouchEvent, ): void => { const pageNum = pageEle.getAttribute('data-page-num') || 0; const coordinate = getAbsoluteCoordinate(pageEle, event); const annotData = { obj_type: ANNOTATION_TYPE.text, obj_attr: { page: pageNum as number, position: { top: coordinate.y, left: coordinate.x, bottom: coordinate.y + 20, right: coordinate.x + 20, }, content: '', }, }; const stickyNote = appendUserIdAndDate( parseAnnotationObject(annotData, viewport.height, scale), ); addAnnots([stickyNote]); }; const handleMouseDown = useCallback( (event: MouseEvent | TouchEvent): void => { const pageEle = (event.target as HTMLElement).parentNode as HTMLElement; if (pageEle.hasAttribute('data-page-num')) { addStickyNote(pageEle, event); } }, [viewport, scale], ); useEffect(() => { const pdfViewer = document.getElementById('pdf_viewer') as HTMLDivElement; if (pdfViewer) { if (isActive) { window.addEventListener('mousedown', handleMouseDown); window.addEventListener('touchstart', handleMouseDown); } else { window.removeEventListener('mousedown', handleMouseDown); window.removeEventListener('touchstart', handleMouseDown); } } return (): void => { if (pdfViewer) { window.removeEventListener('touchstart', handleMouseDown); window.removeEventListener('mousedown', handleMouseDown); } }; }, [isActive, handleMouseDown]); return ( ); }; export default StickyNoteTool;