page-assist/src/hooks/useDynamicTextareaSize.tsx
zhaoweijie e640b1254d refactor(components): 重构 playground组件
- 移除 Data、Scene 和 IodRelevant 组件中的 Drawer
- 优化 Data、Scene 和 IodRelevant 组件的结构
- 添加 Header 组件用于展示标题和关闭按钮
- 使用 Main 组件替代原来的 ShowCard 组件
- 调整样式和布局,提高组件的可复用性和可维护性
2025-08-23 17:03:14 +08:00

41 lines
1.6 KiB
TypeScript

// copied from https://gist.github.com/KristofferEriksson/87ea5b8195339577151a236a9e9b46ff
/**
* Custom hook for dynamically resizing a textarea to fit its content.
* @param {React.RefObject<HTMLTextAreaElement>} textareaRef - Reference to the textarea element.
* @param {string} textContent - Current text content of the textarea.
* @param {number} maxHeight - Optional: maxHeight of the textarea in pixels.
*/
import { useEffect } from "react";
const useDynamicTextareaSize = (
textareaRef: React.RefObject<HTMLTextAreaElement>,
textContent: string,
// optional maximum height after which textarea becomes scrollable
maxHeight?: number
): void => {
useEffect(() => {
const currentTextarea = textareaRef.current;
if (currentTextarea) {
// Temporarily collapse the textarea to calculate the required height
currentTextarea.style.height = "0px";
const contentHeight = currentTextarea.scrollHeight;
if (maxHeight) {
// Set max-height and adjust overflow behavior if maxHeight is provided
currentTextarea.style.maxHeight = `${maxHeight}px`;
currentTextarea.style.overflowY = contentHeight > maxHeight ? "scroll" : "hidden";
currentTextarea.style.height = `${Math.min(contentHeight, maxHeight) < 60 ? 60 : Math.min(contentHeight, maxHeight)}px`;
currentTextarea.style.fontWeight = "normal";
currentTextarea.style.color = "#374151";
} else {
// Adjust height without max height constraint
currentTextarea.style.height = `${contentHeight}px`;
}
}
}, [textareaRef, textContent, maxHeight]);
};
export default useDynamicTextareaSize;