/
anv
/
hackathon
Обзор
Документация
Войти
/
anv
/
hackathon
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/App.tsx
234 строки
9 KB
ANV
added mf plugin
29 мар 2025, 00:24
29 мар 2025, 00:24
595fac5
Код
Авторство
О чём код?
/* eslint-disable camelcase */ import {AsideHeader} from '@gravity-ui/navigation'; import {CommentPlus, SquareDashedText} from '@gravity-ui/icons'; import {useEffect, useState} from 'react'; import {Wrapper} from './components/Wrapper/Wrapper'; import {PromptForm} from './components/PromptForm/PromptForm'; // eslint-disable-next-line @typescript-eslint/no-redeclare import {Alert, Text, Theme} from '@gravity-ui/uikit'; import {getCookie, setCookie} from './utils/utils'; import {getChats} from './requests/getChats'; import {getChatById} from './requests/getChatById'; import {postMessages} from './requests/postMessages'; import {postChats} from './requests/postChats'; import {Message, RawChat, RawMessages} from './components/types'; import styles from './App.module.scss'; import {USER_ID} from './components/constants'; const App = () => { const [theme, setTheme] = useState<Theme>('dark'); const [chatMessages, setChatMessages] = useState<RawMessages | null>(null); const [chatsList, setChatsList] = useState<RawChat[]>([]); const [currentChat, setCurrentChat] = useState<string | null>(null); const [isChatFetching, setIsChatFetching] = useState(false); const [isChatsFetching, setIsChatsFetching] = useState(false); const [isMessagesFetching, setIsMessagesFetching] = useState(false); const [typedText, setTypedText] = useState(''); const fullText = 'Привет! Я ButtonBuddy, твой Buddy в создании интерфейсов, погенерируем :)?'; const [isShowAlert, setIsShowAlert] = useState(false); const [alertMessage, setAlertMessage] = useState(''); const showAlert = (message: string) => { setIsShowAlert(true); setAlertMessage(message); setTimeout(() => { setIsShowAlert(false); }, 3000); }; useEffect(() => { let index = 0; const interval = setInterval(() => { setTypedText((prev) => prev + fullText[index]); index += 1; if (index === fullText.length) { clearInterval(interval); } }, 40); return () => clearInterval(interval); }, []); useEffect(() => { (async function () { try { const userId = getCookie('user_id'); if (userId) { setIsChatsFetching(true); const resp = await getChats({user_id: userId}); if (resp.status === 'error') { showAlert('Ошибка при получении списка чатов'); } setChatsList(resp.chats); setIsChatsFetching(false); } else { setCookie('user_id', USER_ID, 7); } } catch (e) { console.error(e); } })(); }, []); useEffect(() => { (async function () { try { const userId = getCookie('user_id'); if (currentChat && userId) { setIsChatFetching(true); const resp = await getChatById({user_id: userId, chat_id: currentChat}); if (resp.status === 'error') { showAlert('Ошибка при получении данныч чата'); } const {id, preview_text, messages} = resp; setChatMessages({id, preview_text, messages}); setIsChatFetching(false); } else { } } catch (e) { console.error(e); } })(); }, [currentChat]); const addChat = async (newMessage: Message, repoUrl: string) => { const userId = getCookie('user_id'); if (userId) { setIsChatsFetching(true); const resp = await postChats({ user_id: userId, text: newMessage.content, repo_url: repoUrl, }); if (resp.status === 'error') { showAlert('Ошибка при создании чата'); } const resp2 = await getChats({user_id: userId}); if (resp2.status === 'error') { setAlertMessage('Ошибка при получении списка чатов'); } setChatsList(resp2.chats); setCurrentChat(resp.id); setIsChatsFetching(false); return resp.id; } }; const handleMessage = async (newMessage: Message, repoUrl: string, chatId?: string) => { const newChatId = chatId || (await addChat(newMessage, repoUrl)); if (newChatId) { setIsMessagesFetching(true); if (chatMessages?.preview_text) { setChatMessages({ id: chatMessages?.id ?? 'temp', preview_text: chatMessages?.preview_text, messages: [...(chatMessages?.messages ?? []), newMessage], }); } const resp = await postMessages({chat_id: newChatId, text: newMessage.content}); if (resp.status === 'error') { setAlertMessage('Ошибка при отправке сообщения'); } setIsMessagesFetching(false); const userId = getCookie('user_id'); if (userId) { const resp = await getChatById({user_id: userId, chat_id: newChatId}); if (resp.status === 'error') { setAlertMessage('Ошибка при получении данных чата'); } const {id, preview_text, messages} = resp; setChatMessages({id, preview_text, messages}); } } }; return ( <div className={styles.wrapper}> <AsideHeader className={styles.asideContent} headerDecoration subheaderItems={[ { item: { id: 'CommentPlus', title: 'Новый чат', icon: CommentPlus, onItemClick: () => { setCurrentChat(null); }, iconSize: 24, }, }, ]} logo={{ text: 'ButtonBuddy', textSize: 22, iconSize: 0, onClick: () => { setCurrentChat(null); }, }} compact={false} hideCollapseButton menuItems={chatsList?.map((chat) => ({ id: chat.id, title: chat.preview_text || 'New Chat', icon: SquareDashedText, iconSize: 20, onItemClick: () => setCurrentChat(chat.id), afterMoreButton: true, }))} renderContent={() => currentChat === null ? ( <Wrapper theme={theme} setTheme={setTheme}> <Text variant="header-1">{typedText}</Text> {isShowAlert && ( <Alert theme="danger" title={alertMessage} className={styles.alert} /> )} <PromptForm isChatFetching={isChatFetching} isChatsFetching={isChatsFetching} isMessagesFetching={isMessagesFetching} theme={theme} chatTitle="New Chat" messages={[]} onSendMessage={(message, repoUrl) => { handleMessage(message, repoUrl); }} /> </Wrapper> ) : ( <Wrapper theme={theme} setTheme={setTheme}> {isShowAlert && ( <Alert theme="danger" title={alertMessage} className={styles.alert} /> )} <PromptForm isChatFetching={isChatFetching} isChatsFetching={isChatsFetching} isMessagesFetching={isMessagesFetching} theme={theme} messages={chatMessages?.messages || []} onSendMessage={(message, repoUrl) => handleMessage(message, repoUrl, currentChat) } /> </Wrapper> ) } /> </div> ); }; export default App;