RadioButtonTool.tsx 2.2 KB

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