import { ChangeEvent, Fragment, KeyboardEvent, useEffect, useRef } from 'react' import { Button, Textarea } from '@janhq/uikit' import { useAtom, useAtomValue } from 'jotai' import { twMerge } from 'tailwind-merge' import LogoMark from '@/containers/Brand/Logo/Mark' import ModelStart from '@/containers/Loader/ModelStart' import { currentPromptAtom } from '@/containers/Providers/Jotai' import { MainViewState } from '@/constants/screens' import { useActiveModel } from '@/hooks/useActiveModel' import { useGetDownloadedModels } from '@/hooks/useGetDownloadedModels' import { useMainViewState } from '@/hooks/useMainViewState' import useSendChatMessage from '@/hooks/useSendChatMessage' import ChatBody from '@/screens/Chat/ChatBody' import ThreadList from '@/screens/Chat/ThreadList' import Sidebar, { showRightSideBarAtom } from './Sidebar' import { activeThreadAtom, getActiveThreadIdAtom, waitingToSendMessage, } from '@/helpers/atoms/Thread.atom' import { activeThreadStateAtom } from '@/helpers/atoms/Thread.atom' const ChatScreen = () => { const activeThread = useAtomValue(activeThreadAtom) const { downloadedModels } = useGetDownloadedModels() const { activeModel, stateModel } = useActiveModel() const { setMainViewState } = useMainViewState() const [currentPrompt, setCurrentPrompt] = useAtom(currentPromptAtom) const activeThreadState = useAtomValue(activeThreadStateAtom) const { sendChatMessage, queuedMessage } = useSendChatMessage() const isWaitingForResponse = activeThreadState?.waitingForResponse ?? false const disabled = currentPrompt.trim().length === 0 || isWaitingForResponse const activeThreadId = useAtomValue(getActiveThreadIdAtom) const [isWaitingToSend, setIsWaitingToSend] = useAtom(waitingToSendMessage) const showing = useAtomValue(showRightSideBarAtom) const textareaRef = useRef(null) const modelRef = useRef(activeModel) useEffect(() => { modelRef.current = activeModel }, [activeModel]) const onPromptChange = (e: React.ChangeEvent) => { setCurrentPrompt(e.target.value) } useEffect(() => { if (isWaitingToSend && activeThreadId) { setIsWaitingToSend(false) sendChatMessage() } // eslint-disable-next-line react-hooks/exhaustive-deps }, [waitingToSendMessage, activeThreadId]) useEffect(() => { if (textareaRef.current !== null) { const scrollHeight = textareaRef.current.scrollHeight if (currentPrompt.length === 0) { textareaRef.current.style.height = '40px' } else { textareaRef.current.style.height = `${ scrollHeight < 40 ? 40 : scrollHeight }px` } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentPrompt]) const onKeyDown = async (e: React.KeyboardEvent) => { if (e.key === 'Enter') { if (!e.shiftKey) { e.preventDefault() sendChatMessage() } } } return (
{activeThread ? (
) : (
{downloadedModels.length === 0 && (

Welcome!

You need to download your first model

)}
)} {queuedMessage && (
Message queued. It can be sent once the model has started
)}