CheckboxTool.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 {
  7. parseAnnotationObject,
  8. appendUserIdAndDate,
  9. } from '../helpers/annotation';
  10. import useActions from '../actions';
  11. import useStore from '../store';
  12. import { BtnWrapper } from '../global/toolStyled';
  13. type Props = {
  14. title: string;
  15. isActive: boolean;
  16. onClick: () => void;
  17. };
  18. const CheckboxTool: React.FC<Props> = ({ title, isActive, onClick }: Props) => {
  19. const [{ scale, viewport }, dispatch] = useStore();
  20. const { addAnnots } = useActions(dispatch);
  21. const addCheckbox = (
  22. pageEle: HTMLElement,
  23. event: MouseEvent | TouchEvent,
  24. ): void => {
  25. const pageNum = pageEle.getAttribute('data-page-num') || 0;
  26. const coordinate = getAbsoluteCoordinate(pageEle, event);
  27. const annotData = {
  28. obj_type: ANNOTATION_TYPE.checkbox,
  29. obj_attr: {
  30. page: pageNum as number,
  31. style: '0',
  32. position: {
  33. top: coordinate.y,
  34. left: coordinate.x,
  35. bottom: coordinate.y + 50,
  36. right: coordinate.x + 50,
  37. },
  38. },
  39. };
  40. const newCheckbox = appendUserIdAndDate(
  41. parseAnnotationObject(annotData, viewport.height, scale),
  42. );
  43. addAnnots([newCheckbox]);
  44. };
  45. const handleClick = useCallback(
  46. (event: MouseEvent | TouchEvent): void => {
  47. const pageEle = (event.target as HTMLElement).parentNode as HTMLElement;
  48. if (pageEle.hasAttribute('data-page-num')) {
  49. addCheckbox(pageEle, event);
  50. }
  51. },
  52. [viewport, scale],
  53. );
  54. useEffect(() => {
  55. if (isActive) {
  56. document.addEventListener('click', handleClick);
  57. }
  58. return () => {
  59. document.removeEventListener('click', handleClick);
  60. };
  61. }, [isActive]);
  62. return (
  63. <BtnWrapper>
  64. <Button
  65. shouldFitContainer
  66. align="left"
  67. isActive={isActive}
  68. onClick={onClick}
  69. >
  70. <Icon glyph="checkbox" style={{ marginRight: '10px' }} />
  71. {title}
  72. </Button>
  73. </BtnWrapper>
  74. );
  75. };
  76. export default CheckboxTool;