TextfieldTool.tsx 2.2 KB

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