HighlightTools.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import React, { useEffect, useState, useCallback } from 'react';
  2. import Icon from '../components/Icon';
  3. import Button from '../components/Button';
  4. import ExpansionPanel from '../components/ExpansionPanel';
  5. import HighlightOption from '../components/HighlightOption';
  6. import useActions from '../actions';
  7. import useStore from '../store';
  8. import { getMarkupWithSelection } from '../helpers/markup';
  9. type Props = {
  10. title: string;
  11. isActive: boolean;
  12. onClick: () => void;
  13. };
  14. const HighlightTools: React.FC<Props> = ({
  15. title,
  16. isActive,
  17. onClick,
  18. }: Props) => {
  19. const [data, setData] = useState({
  20. type: 'highlight',
  21. color: '#FCFF36',
  22. opacity: 40,
  23. });
  24. const [{ scale }, dispatch] = useStore();
  25. const { addAnnots } = useActions(dispatch);
  26. const setDataState = (obj: OptionPropsType): void => {
  27. setData(prev => ({
  28. ...prev,
  29. ...obj,
  30. }));
  31. };
  32. const selectRange = useCallback(
  33. (e: MouseEvent | TouchEvent): void => {
  34. if (e.target && isActive) {
  35. let textLayer = (e.target as HTMLElement).parentNode as HTMLElement;
  36. if (textLayer.getAttribute('data-id') !== 'text-layer') {
  37. textLayer = textLayer.querySelector(
  38. '[data-id="text-layer"]'
  39. ) as HTMLElement;
  40. }
  41. if (textLayer) {
  42. const newMarkup = getMarkupWithSelection({
  43. ...data,
  44. scale,
  45. textLayer,
  46. });
  47. if (newMarkup) {
  48. addAnnots([newMarkup]);
  49. }
  50. }
  51. }
  52. },
  53. [isActive, data, scale]
  54. );
  55. useEffect(() => {
  56. if (isActive) {
  57. document.addEventListener('touchend', selectRange);
  58. document.addEventListener('mouseup', selectRange);
  59. }
  60. return (): void => {
  61. document.removeEventListener('touchend', selectRange);
  62. document.removeEventListener('mouseup', selectRange);
  63. };
  64. }, [isActive, selectRange]);
  65. const Label = (
  66. <Button
  67. shouldFitContainer
  68. align="left"
  69. onClick={onClick}
  70. isActive={isActive}
  71. >
  72. <Icon glyph="highlight" style={{ marginRight: '10px' }} />
  73. {title}
  74. </Button>
  75. );
  76. return (
  77. <ExpansionPanel label={Label} isActive={isActive} showBottomBorder>
  78. <HighlightOption {...data} setDataState={setDataState} />
  79. </ExpansionPanel>
  80. );
  81. };
  82. export default HighlightTools;