chatbot-template/components/chat-message.tsx

78 lines
2.4 KiB
TypeScript
Raw Normal View History

import { Message } from 'ai-connector'
2023-06-02 15:33:48 -04:00
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import { cn } from '@/lib/utils'
import { CodeBlock } from '@/components/ui/codeblock'
import { MemoizedReactMarkdown } from '@/components/markdown'
2023-06-13 16:02:07 +04:00
import { IconOpenAI, IconUser } from '@/components/ui/icons'
2023-06-13 23:58:59 +04:00
import { ChatMessageActions } from '@/components/chat-message-actions'
2023-06-07 16:17:59 +04:00
2023-05-19 12:33:56 -04:00
export interface ChatMessageProps {
2023-06-02 15:33:48 -04:00
message: Message
2023-05-19 12:33:56 -04:00
}
2023-06-07 16:17:59 +04:00
export function ChatMessage({ message, ...props }: ChatMessageProps) {
2023-05-19 12:33:56 -04:00
return (
2023-06-13 23:58:59 +04:00
<div
2023-06-14 16:04:30 +04:00
className={cn('group relative mb-4 flex items-start md:-ml-12')}
2023-06-13 23:58:59 +04:00
{...props}
>
2023-06-07 16:17:59 +04:00
<div
className={cn(
2023-06-11 23:07:38 +04:00
'flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow',
message.role === 'user'
? 'bg-background'
: 'bg-primary text-primary-foreground'
2023-06-07 16:17:59 +04:00
)}
>
2023-06-13 16:02:07 +04:00
{message.role === 'user' ? <IconUser /> : <IconOpenAI />}
2023-06-07 16:17:59 +04:00
</div>
2023-06-15 15:48:43 +04:00
<div className="ml-4 flex-1 space-y-2 overflow-hidden px-1">
2023-06-15 11:31:20 +04:00
<MemoizedReactMarkdown
2023-06-15 15:48:43 +04:00
className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0"
2023-06-15 11:31:20 +04:00
remarkPlugins={[remarkGfm, remarkMath]}
components={{
p({ children }) {
return <p className="mb-2 last:mb-0">{children}</p>
},
code({ node, inline, className, children, ...props }) {
if (children.length) {
if (children[0] == '▍') {
return (
<span className="mt-1 animate-pulse cursor-default"></span>
)
2023-06-13 23:58:59 +04:00
}
2023-05-19 12:33:56 -04:00
2023-06-15 11:31:20 +04:00
children[0] = (children[0] as string).replace('`▍`', '▍')
}
const match = /language-(\w+)/.exec(className || '')
2023-05-19 12:33:56 -04:00
2023-06-15 11:31:20 +04:00
if (inline) {
return (
2023-06-13 23:58:59 +04:00
<code className={className} {...props}>
{children}
</code>
)
}
2023-06-15 11:31:20 +04:00
return (
<CodeBlock
key={Math.random()}
language={(match && match[1]) || ''}
value={String(children).replace(/\n$/, '')}
{...props}
/>
)
}
}}
>
{message.content}
</MemoizedReactMarkdown>
2023-06-13 23:58:59 +04:00
<ChatMessageActions message={message} />
2023-06-07 16:17:59 +04:00
</div>
</div>
2023-06-02 15:33:48 -04:00
)
2023-05-19 12:33:56 -04:00
}