-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.tsx
72 lines (68 loc) · 1.9 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
'use client'
import { useChat, type Message } from 'ai/react'
import { cn } from '@/lib/utils'
import { ChatList } from '@/components/chat-list'
import { ChatPanel } from '@/components/chat-panel'
import { EmptyScreen } from '@/components/empty-screen'
import { ChatScrollAnchor } from '@/components/chat-scroll-anchor'
import { useLocalStorage } from '@/lib/hooks/use-local-storage'
import { useState } from 'react'
import { toast } from 'react-hot-toast'
import { usePathname, useRouter } from 'next/navigation'
const IS_PREVIEW = process.env.VERCEL_ENV === 'preview'
export interface ChatProps extends React.ComponentProps<'div'> {
initialMessages?: Message[]
id?: string
}
export function Chat({ id, initialMessages, className }: ChatProps) {
const router = useRouter()
const path = usePathname()
const [previewToken, setPreviewToken] = useLocalStorage<string | null>(
'ai-token',
null
)
const { messages, append, reload, stop, isLoading, input, setInput } =
useChat({
initialMessages,
id,
body: {
id,
previewToken
},
onResponse(response) {
if (response.status === 401) {
toast.error(response.statusText)
}
},
onFinish() {
if (!path.includes('chat')) {
router.push(`/chat/${id}`, { scroll: false })
router.refresh()
}
}
})
return (
<>
<div className={cn('pb-[200px] pt-4 md:pt-10', className)}>
{messages.length ? (
<>
<ChatList messages={messages} />
<ChatScrollAnchor trackVisibility={isLoading} />
</>
) : (
<EmptyScreen setInput={setInput} />
)}
</div>
<ChatPanel
id={id}
isLoading={isLoading}
stop={stop}
append={append}
reload={reload}
messages={messages}
input={input}
setInput={setInput}
/>
</>
)
}