chatbot-template/components/chat.tsx

74 lines
2 KiB
TypeScript
Raw Normal View History

'use client'
import { cn } from '@/lib/utils'
import { ChatList } from '@/components/chat-list'
import { ChatPanel } from '@/components/chat-panel'
import { EmptyScreen } from '@/components/empty-screen'
2023-06-15 15:27:41 +04:00
import { ChatScrollAnchor } from '@/components/chat-scroll-anchor'
2023-06-16 16:30:15 -04:00
import { useLocalStorage } from '@/lib/hooks/use-local-storage'
2024-03-14 20:00:52 +03:00
import { useEffect, useState } from 'react'
import { useUIState, useAIState } from 'ai/rsc'
import { Session } from '@/lib/types'
2023-10-04 22:27:23 +01:00
import { usePathname, useRouter } from 'next/navigation'
2024-03-14 20:00:52 +03:00
import { Message } from '@/lib/chat/actions'
import { toast } from 'sonner'
export interface ChatProps extends React.ComponentProps<'div'> {
initialMessages?: Message[]
id?: string
2024-03-14 20:00:52 +03:00
session?: Session
missingKeys: string[]
}
2024-03-14 20:00:52 +03:00
export function Chat({ id, className, session, missingKeys }: ChatProps) {
2023-10-04 22:27:23 +01:00
const router = useRouter()
const path = usePathname()
2024-03-14 20:00:52 +03:00
const [input, setInput] = useState('')
const [messages] = useUIState()
const [aiState] = useAIState()
const isLoading = true
const [_, setNewChatId] = useLocalStorage('newChatId', id)
useEffect(() => {
if (session?.user) {
if (!path.includes('chat') && messages.length === 1) {
window.history.replaceState({}, '', `/chat/${id}`)
2023-06-15 11:31:03 +04:00
}
2024-03-14 20:00:52 +03:00
}
}, [id, path, session?.user, messages])
useEffect(() => {
const messagesLength = aiState.messages?.length
if (messagesLength === 2) {
router.refresh()
}
}, [aiState.messages, router])
useEffect(() => {
setNewChatId(id)
})
useEffect(() => {
missingKeys.map(key => {
toast.error(`Missing ${key} environment variable!`)
})
2024-03-14 20:00:52 +03:00
}, [missingKeys])
return (
<>
<div className={cn('pb-[200px] pt-4 md:pt-10', className)}>
{messages.length ? (
2023-06-15 15:27:41 +04:00
<>
<ChatList messages={messages} />
<ChatScrollAnchor trackVisibility={isLoading} />
</>
) : (
<EmptyScreen setInput={setInput} />
)}
</div>
2024-03-14 20:00:52 +03:00
<ChatPanel id={id} input={input} setInput={setInput} />
</>
)
}