xonecas.io
53129
Pa

PAT / files

PAT / src / hooks / useAutoResizeTextarea.ts

1021 bytes
1import { useEffect, useRef } from "react";
2
3export function useAutoResizeTextarea(
4  value: string,
5  minLines = 3,
6  maxLines = 10
7): React.RefObject<HTMLTextAreaElement> {
8  const textareaRef = useRef<HTMLTextAreaElement>(null);
9
10  useEffect(() => {
11    const textarea = textareaRef.current;
12    if (!textarea) return;
13
14    textarea.style.height = "auto";
15
16    const computedStyle = getComputedStyle(textarea);
17    const lineHeight = parseFloat(computedStyle.lineHeight) || 24;
18    const paddingTop = parseFloat(computedStyle.paddingTop) || 8;
19    const paddingBottom = parseFloat(computedStyle.paddingBottom) || 8;
20
21    const minHeight = lineHeight * minLines + paddingTop + paddingBottom;
22    const maxHeight = lineHeight * maxLines + paddingTop + paddingBottom;
23
24    const calculatedHeight = textarea.scrollHeight + lineHeight;
25    const newHeight = Math.min(maxHeight, Math.max(minHeight, calculatedHeight));
26    textarea.style.height = `${newHeight}px`;
27  }, [value, minLines, maxLines]);
28
29  return textareaRef;
30}