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
47
48
49
50
51
52
53
54
import { useEffect, useRef } from 'react'
import cn from '@/utils/classnames'
 
type AutoHeightTextareaProps =
  & React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>
  & { outerClassName?: string }
 
const AutoHeightTextarea = (
  {
    ref: outRef,
    outerClassName,
    value,
    className,
    placeholder,
    autoFocus,
    disabled,
    ...rest
  }: AutoHeightTextareaProps & {
    ref: React.RefObject<HTMLTextAreaElement>;
  },
) => {
  const innerRef = useRef<HTMLTextAreaElement>(null)
  const ref = outRef || innerRef
 
  useEffect(() => {
    if (autoFocus && !disabled && value) {
      if (typeof ref !== 'function') {
        ref.current?.setSelectionRange(`${value}`.length, `${value}`.length)
        ref.current?.focus()
      }
    }
  }, [autoFocus, disabled, ref])
  return (
    (<div className={outerClassName}>
      <div className='relative'>
        <div className={cn(className, 'invisible whitespace-pre-wrap break-all')}>
          {!value ? placeholder : `${value}`.replace(/\n$/, '\n ')}
        </div>
        <textarea
          ref={ref}
          placeholder={placeholder}
          className={cn(className, 'absolute inset-0 h-full w-full resize-none appearance-none border-none outline-none disabled:bg-transparent')}
          value={value}
          disabled={disabled}
          {...rest}
        />
      </div>
    </div>)
  )
}
 
AutoHeightTextarea.displayName = 'AutoHeightTextarea'
 
export default AutoHeightTextarea