buster/web/src/controllers/HomePage/NewChatInput.tsx

65 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-03-04 05:25:51 +08:00
'use client';
2025-03-04 06:08:42 +08:00
import React, { useRef } from 'react';
2025-03-04 05:25:51 +08:00
import { InputTextAreaButton } from '@/components/ui/inputs/InputTextAreaButton';
2025-03-05 00:45:55 +08:00
import { useBusterNewChatContextSelector } from '@/context/Chats';
2025-03-04 05:25:51 +08:00
import { inputHasText } from '@/lib/text';
2025-03-04 06:08:42 +08:00
import { useMemoizedFn, useMount } from 'ahooks';
2025-03-04 05:25:51 +08:00
import { ChangeEvent, useMemo, useState } from 'react';
const autoResizeConfig = {
minRows: 3,
maxRows: 18
};
export const NewChatInput: React.FC<{}> = () => {
const onStartNewChat = useBusterNewChatContextSelector((state) => state.onStartNewChat);
const [inputValue, setInputValue] = useState('');
2025-03-04 05:30:56 +08:00
const [loading, setLoading] = useState(false);
2025-03-04 06:08:42 +08:00
const textAreaRef = useRef<HTMLTextAreaElement>(null);
2025-03-04 05:25:51 +08:00
const disabledSubmit = useMemo(() => {
return !inputHasText(inputValue);
}, [inputValue]);
2025-03-04 05:30:56 +08:00
const onSubmit = useMemoizedFn(async (value: string) => {
2025-03-04 05:52:25 +08:00
if (disabledSubmit) return;
try {
setLoading(true);
await onStartNewChat({ prompt: value });
} finally {
setLoading(false);
}
});
const onStop = useMemoizedFn(() => {
setLoading(false);
2025-03-04 06:08:42 +08:00
textAreaRef.current?.focus();
textAreaRef.current?.select();
2025-03-04 05:25:51 +08:00
});
const onChange = useMemoizedFn((e: ChangeEvent<HTMLTextAreaElement>) => {
setInputValue(e.target.value);
});
2025-03-04 06:08:42 +08:00
useMount(() => {
if (textAreaRef.current) {
textAreaRef.current.focus();
}
});
2025-03-04 05:25:51 +08:00
return (
<InputTextAreaButton
placeholder="Ask Buster a question..."
autoResize={autoResizeConfig}
onSubmit={onSubmit}
onChange={onChange}
2025-03-04 05:52:25 +08:00
onStop={onStop}
loading={loading}
2025-03-04 05:25:51 +08:00
disabledSubmit={disabledSubmit}
2025-03-04 05:52:25 +08:00
autoFocus
2025-03-04 06:08:42 +08:00
ref={textAreaRef}
2025-03-04 05:25:51 +08:00
/>
);
};