wwf
2025-05-20 938c3e5a587ce950a94964ea509b9e7f8834dfae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import {
  useCallback,
  useRef,
  useState,
} from 'react'
 
export const useTextAreaHeight = () => {
  const wrapperRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement | undefined>(undefined)
  const textValueRef = useRef<HTMLDivElement>(null)
  const holdSpaceRef = useRef<HTMLDivElement>(null)
  const [isMultipleLine, setIsMultipleLine] = useState(false)
 
  const handleComputeHeight = useCallback(() => {
    const textareaElement = textareaRef.current
 
    if (wrapperRef.current && textareaElement && textValueRef.current && holdSpaceRef.current) {
      const { width: wrapperWidth } = wrapperRef.current.getBoundingClientRect()
      const { height: textareaHeight } = textareaElement.getBoundingClientRect()
      const { width: textValueWidth } = textValueRef.current.getBoundingClientRect()
      const { width: holdSpaceWidth } = holdSpaceRef.current.getBoundingClientRect()
      if (textareaHeight > 32) {
        setIsMultipleLine(true)
      }
      else {
        if (textValueWidth + holdSpaceWidth >= wrapperWidth)
          setIsMultipleLine(true)
        else
          setIsMultipleLine(false)
      }
    }
  }, [])
 
  const handleTextareaResize = useCallback(() => {
    handleComputeHeight()
  }, [handleComputeHeight])
 
  return {
    wrapperRef,
    textareaRef,
    textValueRef,
    holdSpaceRef,
    handleTextareaResize,
    isMultipleLine,
  }
}