feat: textarea with adaptive height

This commit is contained in:
leedom
2023-04-07 12:17:37 +08:00
parent a8a8becf96
commit 3656c8458f
5 changed files with 28 additions and 108 deletions

View File

@@ -41,6 +41,8 @@ import chatStyle from "./chat.module.scss";
import { Input, Modal, showModal, showToast } from "./ui-lib";
import calcTextareaHeight from "../calcTextareaHeight";
const Markdown = dynamic(
async () => memo((await import("./markdown")).Markdown),
{
@@ -331,6 +333,10 @@ function useScrollToBottom() {
export function Chat(props: {
showSideBar?: () => void;
sideBarShowing?: boolean;
autoSize: {
minRows: number;
maxRows?: number;
};
}) {
type RenderMessage = Message & { preview?: boolean };
@@ -347,6 +353,7 @@ export function Chat(props: {
const { submitKey, shouldSubmit } = useSubmitHandler();
const { scrollRef, setAutoScroll } = useScrollToBottom();
const [hitBottom, setHitBottom] = useState(false);
const [textareaStyle, setTextareaStyle] = useState({});
const onChatBodyScroll = (e: HTMLElement) => {
const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
@@ -380,6 +387,16 @@ export function Chat(props: {
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
};
// textarea has an adaptive height
const resizeTextarea = () => {
const dom = inputRef.current;
if (!dom) return;
const { minRows, maxRows } = props.autoSize;
setTimeout(() => {
setTextareaStyle(calcTextareaHeight(dom, minRows, maxRows));
}, 50);
};
// only search prompts when user input is short
const SEARCH_TEXT_LIMIT = 30;
const onInput = (text: string) => {
@@ -504,6 +521,11 @@ export function Chat(props: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Textarea Adaptive height
useEffect(() => {
resizeTextarea();
});
return (
<div className={styles.chat} key={session.id}>
<div className={styles["window-header"]}>
@@ -659,8 +681,8 @@ export function Chat(props: {
<textarea
ref={inputRef}
className={styles["chat-input"]}
style={textareaStyle}
placeholder={Locale.Chat.Input(submitKey)}
rows={2}
onInput={(e) => onInput(e.currentTarget.value)}
value={userInput}
onKeyDown={onInputKeyDown}