index.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. wrapperClassName?: string
  9. minHeight?: number
  10. maxHeight?: number
  11. autoFocus?: boolean
  12. controlFocus?: number
  13. onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
  14. onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
  15. }
  16. const AutoHeightTextarea = forwardRef(
  17. (
  18. { value, onChange, placeholder, className, wrapperClassName, minHeight = 36, maxHeight = 96, autoFocus, controlFocus, onKeyDown, onKeyUp }: IProps,
  19. outerRef: any,
  20. ) => {
  21. // eslint-disable-next-line react-hooks/rules-of-hooks
  22. const ref = outerRef || useRef<HTMLTextAreaElement>(null)
  23. const doFocus = () => {
  24. if (ref.current) {
  25. ref.current.setSelectionRange(value.length, value.length)
  26. ref.current.focus()
  27. return true
  28. }
  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 ${wrapperClassName}`}>
  51. <div className={cn(className, 'invisible whitespace-pre-wrap break-all overflow-y-auto')} style={{
  52. minHeight,
  53. maxHeight,
  54. paddingRight: (value && value.trim().length > 10000) ? 140 : 130,
  55. }}>
  56. {!value ? placeholder : value.replace(/\n$/, '\n ')}
  57. </div>
  58. <textarea
  59. ref={ref}
  60. autoFocus={autoFocus}
  61. className={cn(className, 'absolute inset-0 resize-none overflow-auto')}
  62. style={{
  63. paddingRight: (value && value.trim().length > 10000) ? 140 : 130,
  64. }}
  65. placeholder={placeholder}
  66. onChange={onChange}
  67. onKeyDown={onKeyDown}
  68. onKeyUp={onKeyUp}
  69. value={value}
  70. />
  71. </div>
  72. )
  73. },
  74. )
  75. AutoHeightTextarea.displayName = 'AutoHeightTextarea'
  76. export default AutoHeightTextarea