index.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { forwardRef, useEffect, useRef } from 'react'
  2. import cn from 'classnames'
  3. type IProps = {
  4. placeholder?: string
  5. value: string
  6. onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
  7. className?: string
  8. minHeight?: number
  9. maxHeight?: number
  10. autoFocus?: boolean
  11. controlFocus?: number
  12. onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
  13. onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
  14. }
  15. const AutoHeightTextarea = forwardRef(
  16. (
  17. { value, onChange, placeholder, className, minHeight = 36, maxHeight = 96, autoFocus, controlFocus, onKeyDown, onKeyUp }: IProps,
  18. outerRef: any,
  19. ) => {
  20. const ref = outerRef || useRef<HTMLTextAreaElement>(null)
  21. const doFocus = () => {
  22. if (ref.current) {
  23. // console.log('focus')
  24. ref.current.setSelectionRange(value.length, value.length)
  25. ref.current.focus()
  26. return true
  27. }
  28. // console.log(autoFocus, 'not focus')
  29. return false
  30. }
  31. const focus = () => {
  32. if (!doFocus()) {
  33. let hasFocus = false
  34. const runId = setInterval(() => {
  35. hasFocus = doFocus()
  36. if (hasFocus)
  37. clearInterval(runId)
  38. }, 100)
  39. }
  40. }
  41. useEffect(() => {
  42. if (autoFocus)
  43. focus()
  44. }, [])
  45. useEffect(() => {
  46. if (controlFocus)
  47. focus()
  48. }, [controlFocus])
  49. return (
  50. <div className='relative'>
  51. <div className={cn(className, 'invisible whitespace-pre-wrap break-all overflow-y-auto')} style={{ minHeight, maxHeight }}>
  52. {!value ? placeholder : value.replace(/\n$/, '\n ')}
  53. </div>
  54. <textarea
  55. ref={ref}
  56. autoFocus={autoFocus}
  57. className={cn(className, 'absolute inset-0 resize-none overflow-hidden')}
  58. placeholder={placeholder}
  59. onChange={onChange}
  60. onKeyDown={onKeyDown}
  61. onKeyUp={onKeyUp}
  62. value={value}
  63. />
  64. </div>
  65. )
  66. },
  67. )
  68. export default AutoHeightTextarea