{"size": 1900, "ext": "js", "max_stars_repo_path": "src/renderer/components/Editor/Text/TextOverlay.js", "max_stars_repo_name": "benjaminadk/gif", "max_stars_repo_stars_event_min_datetime": "2021-01-14T06:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T02:53:16.000Z", "max_issues_repo_path": "src/renderer/components/Editor/Text/TextOverlay.js", "max_issues_repo_name": "benjaminadk/gif", "max_issues_repo_issues_event_min_datetime": "2020-07-17T00:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:38:02.000Z", "max_forks_repo_path": "src/renderer/components/Editor/Text/TextOverlay.js", "max_forks_repo_name": "benjaminadk/gif", "max_forks_repo_forks_event_min_datetime": "2019-10-11T17:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:08:37.000Z"}
{"max_stars_count": 4, "max_issues_count": 6, "max_forks_count": 3, "avg_line_length": 22.619047619, "max_line_length": 77, "alphanum_fraction": 0.5578947368}
import React, { useRef, useEffect } from 'react'
import { Rnd } from 'react-rnd'

export default function TextOverlay({
  show,
  textText,
  textFont,
  textStyle,
  textSize,
  textColor,
  textWidth,
  textHeight,
  textX,
  textY,
  setTextWidth,
  setTextHeight,
  setTextX,
  setTextY
}) {
  const canvas = useRef(null)

  useEffect(() => {
    if (show) {
      const ctx = canvas.current.getContext('2d')
      ctx.font = `${textStyle} ${textSize}px ${textFont}`

      const textArray = textText.split('\n')

      var longest = 0
      var longestIndex
      for (const [i, text] of textArray.entries()) {
        const len = text.length
        if (len > longest) {
          longestIndex = i
          longest = len
        }
      }

      const width = Math.ceil(ctx.measureText(textArray[longestIndex]).width)
      canvas.current.width = width
      canvas.current.height = textSize * textArray.length

      setTextWidth(width + 5)
      setTextHeight(textSize * textArray.length + 5)

      ctx.textBaseline = 'top'
      ctx.fillStyle = textColor
      ctx.font = `${textStyle} ${textSize}px ${textFont}`

      for (const [i, text] of textArray.entries()) {
        ctx.fillText(text, 0, i * textSize)
      }
    }
  }, [show, textText, textStyle, textSize, textFont, textColor])

  if (show) {
    return (
      <Rnd
        style={{
          zIndex: 7,
          display: 'grid',
          alignItems: 'center',
          justifyItems: 'center',
          border: '2px dashed lightgrey'
        }}
        bounds='parent'
        size={{ width: textWidth, height: textHeight }}
        position={{ x: textX, y: textY }}
        onDrag={(e, d) => {
          setTextX(d.x)
          setTextY(d.y)
        }}
        enableResizing={false}
        minWidth={20}
        minHeight={20}
      >
        <canvas ref={canvas} />
      </Rnd>
    )
  } else {
    return null
  }
}
