setup basic components

This commit is contained in:
bluemoehre
2026-06-30 23:02:06 +02:00
parent 98649496bd
commit 7121715af9
43 changed files with 6523 additions and 63 deletions
+142
View File
@@ -0,0 +1,142 @@
'use client'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import type { UIMessage } from 'ai'
import { ArrowDownIcon, DownloadIcon } from 'lucide-react'
import type { ComponentProps } from 'react'
import { useCallback } from 'react'
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom'
export type ConversationProps = ComponentProps<typeof StickToBottom>
export const Conversation = ({ className, ...props }: ConversationProps) => (
<StickToBottom
className={cn('relative flex-1 overflow-y-hidden', className)}
initial="smooth"
resize="smooth"
role="log"
{...props}
/>
)
export type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>
export const ConversationContent = ({ className, ...props }: ConversationContentProps) => (
<StickToBottom.Content className={cn('flex flex-col gap-8 p-4', className)} {...props} />
)
export type ConversationEmptyStateProps = ComponentProps<'div'> & {
title?: string
description?: string
icon?: React.ReactNode
}
export const ConversationEmptyState = ({
className,
title = 'No messages yet',
description = 'Start a conversation to see messages here',
icon,
children,
...props
}: ConversationEmptyStateProps) => (
<div
className={cn('flex size-full flex-col items-center justify-center gap-3 p-8 text-center', className)}
{...props}
>
{children ?? (
<>
{icon && <div className="text-muted-foreground">{icon}</div>}
<div className="space-y-1">
<h3 className="text-sm font-medium">{title}</h3>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
</div>
</>
)}
</div>
)
export type ConversationScrollButtonProps = ComponentProps<typeof Button>
export const ConversationScrollButton = ({ className, ...props }: ConversationScrollButtonProps) => {
const { isAtBottom, scrollToBottom } = useStickToBottomContext()
const handleScrollToBottom = useCallback(() => {
scrollToBottom()
}, [scrollToBottom])
return (
!isAtBottom && (
<Button
className={cn(
'absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted',
className
)}
onClick={handleScrollToBottom}
size="icon"
type="button"
variant="outline"
{...props}
>
<ArrowDownIcon className="size-4" />
</Button>
)
)
}
const getMessageText = (message: UIMessage): string =>
message.parts
.filter((part) => part.type === 'text')
.map((part) => part.text)
.join('')
export type ConversationDownloadProps = Omit<ComponentProps<typeof Button>, 'onClick'> & {
messages: UIMessage[]
filename?: string
formatMessage?: (message: UIMessage, index: number) => string
}
const defaultFormatMessage = (message: UIMessage): string => {
const roleLabel = message.role.charAt(0).toUpperCase() + message.role.slice(1)
return `**${roleLabel}:** ${getMessageText(message)}`
}
export const messagesToMarkdown = (
messages: UIMessage[],
formatMessage: (message: UIMessage, index: number) => string = defaultFormatMessage
): string => messages.map((msg, i) => formatMessage(msg, i)).join('\n\n')
export const ConversationDownload = ({
messages,
filename = 'conversation.md',
formatMessage = defaultFormatMessage,
className,
children,
...props
}: ConversationDownloadProps) => {
const handleDownload = useCallback(() => {
const markdown = messagesToMarkdown(messages, formatMessage)
const blob = new Blob([markdown], { type: 'text/markdown' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.append(link)
link.click()
link.remove()
URL.revokeObjectURL(url)
}, [messages, filename, formatMessage])
return (
<Button
className={cn('absolute top-4 right-4 rounded-full dark:bg-background dark:hover:bg-muted', className)}
onClick={handleDownload}
size="icon"
type="button"
variant="outline"
{...props}
>
{children ?? <DownloadIcon className="size-4" />}
</Button>
)
}
+280
View File
@@ -0,0 +1,280 @@
'use client'
import { Button } from '@/components/ui/button'
import { ButtonGroup, ButtonGroupText } from '@/components/ui/button-group'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
import { cjk } from '@streamdown/cjk'
import { code } from '@streamdown/code'
import { math } from '@streamdown/math'
import { mermaid } from '@streamdown/mermaid'
import type { UIMessage } from 'ai'
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
import type { ComponentProps, HTMLAttributes, ReactElement } from 'react'
import { createContext, memo, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { Streamdown } from 'streamdown'
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
from: UIMessage['role']
}
export const Message = ({ className, from, ...props }: MessageProps) => (
<div
className={cn(
'group flex w-full max-w-[95%] flex-col gap-2',
from === 'user' ? 'is-user ml-auto justify-end' : 'is-assistant',
className
)}
{...props}
/>
)
export type MessageContentProps = HTMLAttributes<HTMLDivElement>
export const MessageContent = ({ children, className, ...props }: MessageContentProps) => (
<div
className={cn(
'is-user:dark flex w-fit max-w-full min-w-0 flex-col gap-2 overflow-hidden text-sm',
'group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground',
'group-[.is-assistant]:text-foreground',
className
)}
{...props}
>
{children}
</div>
)
export type MessageActionsProps = ComponentProps<'div'>
export const MessageActions = ({ className, children, ...props }: MessageActionsProps) => (
<div className={cn('flex items-center gap-1', className)} {...props}>
{children}
</div>
)
export type MessageActionProps = ComponentProps<typeof Button> & {
tooltip?: string
label?: string
}
export const MessageAction = ({
tooltip,
children,
label,
variant = 'ghost',
size = 'icon-sm',
...props
}: MessageActionProps) => {
const button = (
<Button size={size} type="button" variant={variant} {...props}>
{children}
<span className="sr-only">{label || tooltip}</span>
</Button>
)
if (tooltip) {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>{button}</TooltipTrigger>
<TooltipContent>
<p>{tooltip}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
return button
}
interface MessageBranchContextType {
currentBranch: number
totalBranches: number
goToPrevious: () => void
goToNext: () => void
branches: ReactElement[]
setBranches: (branches: ReactElement[]) => void
}
const MessageBranchContext = createContext<MessageBranchContextType | null>(null)
const useMessageBranch = () => {
const context = useContext(MessageBranchContext)
if (!context) {
throw new Error('MessageBranch components must be used within MessageBranch')
}
return context
}
export type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {
defaultBranch?: number
onBranchChange?: (branchIndex: number) => void
}
export const MessageBranch = ({ defaultBranch = 0, onBranchChange, className, ...props }: MessageBranchProps) => {
const [currentBranch, setCurrentBranch] = useState(defaultBranch)
const [branches, setBranches] = useState<ReactElement[]>([])
const handleBranchChange = useCallback(
(newBranch: number) => {
setCurrentBranch(newBranch)
onBranchChange?.(newBranch)
},
[onBranchChange]
)
const goToPrevious = useCallback(() => {
const newBranch = currentBranch > 0 ? currentBranch - 1 : branches.length - 1
handleBranchChange(newBranch)
}, [currentBranch, branches.length, handleBranchChange])
const goToNext = useCallback(() => {
const newBranch = currentBranch < branches.length - 1 ? currentBranch + 1 : 0
handleBranchChange(newBranch)
}, [currentBranch, branches.length, handleBranchChange])
const contextValue = useMemo<MessageBranchContextType>(
() => ({
branches,
currentBranch,
goToNext,
goToPrevious,
setBranches,
totalBranches: branches.length,
}),
[branches, currentBranch, goToNext, goToPrevious]
)
return (
<MessageBranchContext.Provider value={contextValue}>
<div className={cn('grid w-full gap-2 [&>div]:pb-0', className)} {...props} />
</MessageBranchContext.Provider>
)
}
export type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>
export const MessageBranchContent = ({ children, ...props }: MessageBranchContentProps) => {
const { currentBranch, setBranches, branches } = useMessageBranch()
const childrenArray = useMemo(() => (Array.isArray(children) ? children : [children]), [children])
// Use useEffect to update branches when they change
useEffect(() => {
if (branches.length !== childrenArray.length) {
setBranches(childrenArray)
}
}, [childrenArray, branches, setBranches])
return childrenArray.map((branch, index) => (
<div
className={cn('grid gap-2 overflow-hidden [&>div]:pb-0', index === currentBranch ? 'block' : 'hidden')}
key={branch.key}
{...props}
>
{branch}
</div>
))
}
export type MessageBranchSelectorProps = ComponentProps<typeof ButtonGroup>
export const MessageBranchSelector = ({ className, ...props }: MessageBranchSelectorProps) => {
const { totalBranches } = useMessageBranch()
// Don't render if there's only one branch
if (totalBranches <= 1) {
return null
}
return (
<ButtonGroup
className={cn('[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md', className)}
orientation="horizontal"
{...props}
/>
)
}
export type MessageBranchPreviousProps = ComponentProps<typeof Button>
export const MessageBranchPrevious = ({ children, ...props }: MessageBranchPreviousProps) => {
const { goToPrevious, totalBranches } = useMessageBranch()
return (
<Button
aria-label="Previous branch"
disabled={totalBranches <= 1}
onClick={goToPrevious}
size="icon-sm"
type="button"
variant="ghost"
{...props}
>
{children ?? <ChevronLeftIcon size={14} />}
</Button>
)
}
export type MessageBranchNextProps = ComponentProps<typeof Button>
export const MessageBranchNext = ({ children, ...props }: MessageBranchNextProps) => {
const { goToNext, totalBranches } = useMessageBranch()
return (
<Button
aria-label="Next branch"
disabled={totalBranches <= 1}
onClick={goToNext}
size="icon-sm"
type="button"
variant="ghost"
{...props}
>
{children ?? <ChevronRightIcon size={14} />}
</Button>
)
}
export type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>
export const MessageBranchPage = ({ className, ...props }: MessageBranchPageProps) => {
const { currentBranch, totalBranches } = useMessageBranch()
return (
<ButtonGroupText
className={cn('border-none bg-transparent text-muted-foreground shadow-none', className)}
{...props}
>
{currentBranch + 1} of {totalBranches}
</ButtonGroupText>
)
}
export type MessageResponseProps = ComponentProps<typeof Streamdown>
const streamdownPlugins = { cjk, code, math, mermaid }
export const MessageResponse = memo(
({ className, ...props }: MessageResponseProps) => (
<Streamdown
className={cn('size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0', className)}
plugins={streamdownPlugins}
{...props}
/>
),
(prevProps, nextProps) => prevProps.children === nextProps.children && nextProps.isAnimating === prevProps.isAnimating
)
MessageResponse.displayName = 'MessageResponse'
export type MessageToolbarProps = ComponentProps<'div'>
export const MessageToolbar = ({ className, children, ...props }: MessageToolbarProps) => (
<div className={cn('mt-4 flex w-full items-center justify-between gap-4', className)} {...props}>
{children}
</div>
)
+62
View File
@@ -0,0 +1,62 @@
'use client'
import { cn } from '@/lib/utils'
import type { MotionProps } from 'motion/react'
import { motion } from 'motion/react'
import type { CSSProperties, ElementType, JSX } from 'react'
import { memo, useMemo } from 'react'
type MotionHTMLProps = MotionProps & Record<string, unknown>
// Cache motion components at module level to avoid creating during render
const motionComponentCache = new Map<keyof JSX.IntrinsicElements, React.ComponentType<MotionHTMLProps>>()
const getMotionComponent = (element: keyof JSX.IntrinsicElements) => {
let component = motionComponentCache.get(element)
if (!component) {
component = motion.create(element)
motionComponentCache.set(element, component)
}
return component
}
export interface TextShimmerProps {
children: string
as?: ElementType
className?: string
duration?: number
spread?: number
}
const ShimmerComponent = ({ children, as: Component = 'p', className, duration = 2, spread = 2 }: TextShimmerProps) => {
const MotionComponent = getMotionComponent(Component as keyof JSX.IntrinsicElements)
const dynamicSpread = useMemo(() => (children?.length ?? 0) * spread, [children, spread])
return (
<MotionComponent
animate={{ backgroundPosition: '0% center' }}
className={cn(
'relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent',
'[background-repeat:no-repeat,padding-box] [--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))]',
className
)}
initial={{ backgroundPosition: '100% center' }}
style={
{
'--spread': `${dynamicSpread}px`,
'backgroundImage': 'var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))',
} as CSSProperties
}
transition={{
duration,
ease: 'linear',
repeat: Number.POSITIVE_INFINITY,
}}
>
{children}
</MotionComponent>
)
}
export const Shimmer = memo(ShimmerComponent)