| 16 | } |
| 17 | |
| 18 | function useAutoResizeTextarea({ |
| 19 | minHeight, |
| 20 | maxHeight, |
| 21 | }: UseAutoResizeTextareaProps) { |
| 22 | const textareaRef = useRef<HTMLTextAreaElement>(null); |
| 23 | |
| 24 | const adjustHeight = useCallback( |
| 25 | (reset?: boolean) => { |
| 26 | const textarea = textareaRef.current; |
| 27 | if (!textarea) return; |
| 28 | |
| 29 | if (reset) { |
| 30 | textarea.style.height = `${minHeight}px`; |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | // Temporarily shrink to get the right scrollHeight |
| 35 | textarea.style.height = `${minHeight}px`; |
| 36 | |
| 37 | // Calculate new height |
| 38 | const newHeight = Math.max( |
| 39 | minHeight, |
| 40 | Math.min( |
| 41 | textarea.scrollHeight, |
| 42 | maxHeight ?? Number.POSITIVE_INFINITY |
| 43 | ) |
| 44 | ); |
| 45 | |
| 46 | textarea.style.height = `${newHeight}px`; |
| 47 | }, |
| 48 | [minHeight, maxHeight] |
| 49 | ); |
| 50 | |
| 51 | useEffect(() => { |
| 52 | // Set initial height |
| 53 | const textarea = textareaRef.current; |
| 54 | if (textarea) { |
| 55 | textarea.style.height = `${minHeight}px`; |
| 56 | } |
| 57 | }, [minHeight]); |
| 58 | |
| 59 | // Adjust height on window resize |
| 60 | useEffect(() => { |
| 61 | const handleResize = () => adjustHeight(); |
| 62 | window.addEventListener("resize", handleResize); |
| 63 | return () => window.removeEventListener("resize", handleResize); |
| 64 | }, [adjustHeight]); |
| 65 | |
| 66 | return { textareaRef, adjustHeight }; |
| 67 | } |
| 68 | |
| 69 | export function LocalGPTChat() { |
| 70 | const [value, setValue] = useState(""); |