index.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import React, { useEffect, useState } from 'react';
  2. import OuterRect from '../OuterRect';
  3. import SvgShapeElement from '../SvgShapeElement';
  4. import { rectCalc, parsePositionForBackend } from '../../helpers/position';
  5. import { AnnotationContainer } from '../../global/otherStyled';
  6. const Shape: React.FC<AnnotationElementPropsType> = ({
  7. id,
  8. obj_type,
  9. obj_attr: {
  10. bdcolor = '',
  11. fcolor = '',
  12. bdwidth = 0,
  13. transparency = 0,
  14. ftransparency = 0,
  15. position,
  16. },
  17. scale,
  18. viewport,
  19. isCollapse,
  20. onUpdate,
  21. }: AnnotationElementPropsType) => {
  22. const [moving, setMoving] = useState(false);
  23. const [localePos, setLocalePos] = useState({
  24. top: 0,
  25. left: 0,
  26. width: 0,
  27. height: 0,
  28. });
  29. const handleScaleOrMove = ({
  30. top,
  31. left,
  32. width = 0,
  33. height = 0,
  34. }: CoordType): void => {
  35. setMoving(true);
  36. const newPosition = {
  37. top,
  38. left,
  39. height,
  40. width,
  41. };
  42. setLocalePos(newPosition);
  43. };
  44. const handleMouseUp = () => {
  45. setMoving(false);
  46. };
  47. useEffect(() => {
  48. const rect = rectCalc(position as PositionType, viewport.height, scale);
  49. setLocalePos(rect);
  50. }, [viewport, scale]);
  51. useEffect(() => {
  52. if (!moving) {
  53. const newPosition = {
  54. top: localePos.top,
  55. left: localePos.left,
  56. right: localePos.left + localePos.width,
  57. bottom: localePos.top + localePos.height,
  58. };
  59. onUpdate({
  60. position: parsePositionForBackend(
  61. obj_type,
  62. newPosition as PositionType,
  63. viewport.height,
  64. scale,
  65. ),
  66. });
  67. }
  68. }, [moving, localePos]);
  69. return (
  70. <>
  71. <AnnotationContainer
  72. id={id}
  73. top={`${localePos.top}px`}
  74. left={`${localePos.left}px`}
  75. width={`${localePos.width}px`}
  76. height={`${localePos.height}px`}
  77. >
  78. <SvgShapeElement
  79. shape={obj_type}
  80. width={localePos.width}
  81. height={localePos.height}
  82. bdcolor={bdcolor}
  83. transparency={transparency}
  84. bdwidth={bdwidth * scale}
  85. fcolor={fcolor}
  86. ftransparency={ftransparency}
  87. />
  88. </AnnotationContainer>
  89. {!isCollapse ? (
  90. <OuterRect
  91. top={localePos.top}
  92. left={localePos.left}
  93. width={localePos.width}
  94. height={localePos.height}
  95. onMove={handleScaleOrMove}
  96. onScale={handleScaleOrMove}
  97. onMouseUp={handleMouseUp}
  98. />
  99. ) : (
  100. ''
  101. )}
  102. </>
  103. );
  104. };
  105. export default Shape;