forked from vercel/ai-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.tsx
88 lines (77 loc) · 2.49 KB
/
chat.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use client'
import type { AI } from '@/lib/chat/actions'
import { cn } from '@/lib/utils'
import { ChatList } from '@/components/chat-list'
import { ChatPanel } from '@/components/chat-panel'
import { EmptyScreen } from '@/components/empty-screen'
import { useLocalStorage } from '@/lib/hooks/use-local-storage'
import { useEffect, useState } from 'react'
import { useUIState, useAIState } from 'ai/rsc'
import { Message, Session } from '@/lib/types'
import { usePathname, useRouter } from 'next/navigation'
import { useScrollAnchor } from '@/lib/hooks/use-scroll-anchor'
import { toast } from 'sonner'
export interface ChatProps extends React.ComponentProps<'div'> {
initialMessages?: Message[]
id?: string
session?: Session
missingKeys: string[]
}
export function Chat({ id, className, session, missingKeys }: ChatProps) {
const router = useRouter()
const path = usePathname()
const [input, setInput] = useState('')
const [messages] = useUIState()
const [aiState] = useAIState<typeof AI>()
const [_, setNewChatId] = useLocalStorage('newChatId', id)
useEffect(() => {
if (session?.user) {
if (!path.includes('chat') && messages.length === 1) {
window.history.replaceState({}, '', `/chat/${id}`)
}
}
}, [id, path, session?.user, messages])
useEffect(() => {
const messagesLength = aiState.messages?.length
if (messagesLength === 2) {
router.refresh()
} else if (messagesLength === 3 && aiState.messages[2].role === 'tool') {
router.refresh()
}
}, [aiState.messages, router])
useEffect(() => {
setNewChatId(id)
})
useEffect(() => {
missingKeys.map(key => {
toast.error(`Missing ${key} environment variable!`)
})
}, [missingKeys])
const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } =
useScrollAnchor()
return (
<div
className="group w-full overflow-auto pl-0 peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]"
ref={scrollRef}
>
<div
className={cn('pb-[200px] pt-4 md:pt-10', className)}
ref={messagesRef}
>
{messages.length ? (
<ChatList messages={messages} isShared={false} session={session} />
) : (
<EmptyScreen />
)}
<div className="w-full h-px" ref={visibilityRef} />
</div>
<ChatPanel
id={id}
input={input}
setInput={setInput}
isAtBottom={isAtBottom}
scrollToBottom={scrollToBottom}
/>
</div>
)
}