Skip to content

An AI-powered search engine with a generative UI

feat: Add CollapsibleMessage

Yoshiki Miurae36213a3697e
diff --git a/components/answer-section.tsx b/components/answer-section.tsx
index cdfae8c0..47776404 100644
--- a/components/answer-section.tsx
+++ b/components/answer-section.tsx
@@ -1,20 +1,36 @@
'use client'
-import { Section } from './section'
import { BotMessage } from './message'
import { DefaultSkeleton } from './default-skeleton'
-import { MessageWithAvatar } from './message-with-avatar'
+import { CollapsibleMessage } from './collapsible-message'
+import { Text } from 'lucide-react'
export type AnswerSectionProps = {
content: string
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function AnswerSection({ content }: AnswerSectionProps) {
+export function AnswerSection({
+ content,
+ isOpen,
+ onOpenChange
+}: AnswerSectionProps) {
+ const header = (
+ <div className="flex items-center gap-1">
+ <Text size={16} />
+ <div>Answer</div>
+ </div>
+ )
return (
- <MessageWithAvatar role="assistant">
- <Section title="Answer">
- {content ? <BotMessage message={content} /> : <DefaultSkeleton />}
- </Section>
- </MessageWithAvatar>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
+ {content ? <BotMessage message={content} /> : <DefaultSkeleton />}
+ </CollapsibleMessage>
)
}
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index cd71124d..b12934ff 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -2,6 +2,7 @@ import { Message } from 'ai'
import RelatedQuestions from './related-questions'
import { RenderMessage } from './render-message'
import { Spinner } from './ui/spinner'
+import { useState, useEffect } from 'react'
interface ChatMessagesProps {
messages: Message[]
@@ -14,21 +15,50 @@ export function ChatMessages({
onQuerySelect,
isLoading
}: ChatMessagesProps) {
- if (!messages.length) {
- return null
- }
+ const [openStates, setOpenStates] = useState<Record<string, boolean>>({})
+ useEffect(() => {
+ const lastMessage = messages[messages.length - 1]
+ if (lastMessage?.role === 'user') {
+ setOpenStates({})
+ }
+ }, [messages])
+
+ if (!messages.length) return null
+
+ const lastUserIndex =
+ messages.length -
+ 1 -
+ [...messages].reverse().findIndex(msg => msg.role === 'user')
const showSpinner = isLoading && messages[messages.length - 1].role === 'user'
return (
<div className="relative mx-auto px-4 w-full">
- {messages.map(message => (
- <div key={message.id} className="mb-4">
- <RenderMessage message={message} />
+ {messages.map((message, index) => (
+ <div key={message.id} className="mb-4 flex flex-col gap-4">
+ <RenderMessage
+ message={message}
+ isOpen={openStates[message.id] ?? index >= lastUserIndex}
+ onOpenChange={(open: boolean) => {
+ setOpenStates(prev => ({
+ ...prev,
+ [message.id]: open
+ }))
+ }}
+ />
{!message.toolInvocations && message.annotations && (
<RelatedQuestions
annotations={message.annotations}
onQuerySelect={onQuerySelect}
+ isOpen={
+ openStates[`${message.id}-related`] ?? index >= lastUserIndex
+ }
+ onOpenChange={(open: boolean) => {
+ setOpenStates(prev => ({
+ ...prev,
+ [`${message.id}-related`]: open
+ }))
+ }}
/>
)}
</div>
diff --git a/components/collapsible-message.tsx b/components/collapsible-message.tsx
index a094236a..26397eb6 100644
--- a/components/collapsible-message.tsx
+++ b/components/collapsible-message.tsx
@@ -1,75 +1,63 @@
-'use client'
-
-import React, { useEffect, useState } from 'react'
+import { UserCircle2, Bot, ChevronDown } from 'lucide-react'
import {
Collapsible,
- CollapsibleTrigger,
- CollapsibleContent
-} from '@radix-ui/react-collapsible'
-import { Button } from './ui/button'
-import { ChevronDown } from 'lucide-react'
-import { StreamableValue, useStreamableValue } from 'ai/rsc'
-import { cn } from '@/lib/utils'
+ CollapsibleContent,
+ CollapsibleTrigger
+} from './ui/collapsible'
import { Separator } from './ui/separator'
+import { cn } from '@/lib/utils'
interface CollapsibleMessageProps {
- message: {
- id: string
- isCollapsed?: StreamableValue<boolean>
- component: React.ReactNode
- }
- isLastMessage?: boolean
+ children: React.ReactNode
+ role: 'user' | 'assistant'
+ isCollapsible?: boolean
+ isOpen?: boolean
+ header?: React.ReactNode
+ onOpenChange?: (open: boolean) => void
}
-export const CollapsibleMessage: React.FC<CollapsibleMessageProps> = ({
- message,
- isLastMessage = false
-}) => {
- const [data] = useStreamableValue(message.isCollapsed)
- const isCollapsed = data ?? false
- const [open, setOpen] = useState(isLastMessage)
-
- useEffect(() => {
- setOpen(isLastMessage)
- }, [isCollapsed, isLastMessage])
-
- // if not collapsed, return the component
- if (!isCollapsed) {
- return message.component
- }
+export function CollapsibleMessage({
+ children,
+ role,
+ isCollapsible = false,
+ isOpen = true,
+ header,
+ onOpenChange
+}: CollapsibleMessageProps) {
+ const content = <div className="py-2 flex-1">{children}</div>
return (
- <Collapsible
- open={open}
- onOpenChange={value => {
- setOpen(value)
- }}
- >
- <CollapsibleTrigger asChild>
- <div
- className={cn(
- 'w-full flex justify-end',
- !isCollapsed ? 'hidden' : ''
+ <div className="flex gap-3">
+ <div className="relative flex flex-col items-center">
+ <div className={cn('mt-[10px]', role === 'assistant' && 'pl-4')}>
+ {role === 'user' && (
+ <UserCircle2 size={20} className="text-muted-foreground" />
)}
- >
- <Button
- variant="ghost"
- size={'icon'}
- className={cn('-mt-3 rounded-full')}
+ </div>
+ </div>
+
+ {isCollapsible ? (
+ <div className="flex-1 border border-border/50 rounded-2xl p-4">
+ <Collapsible
+ open={isOpen}
+ onOpenChange={onOpenChange}
+ className="w-full"
>
- <ChevronDown
- size={14}
- className={cn(
- open ? 'rotate-180' : 'rotate-0',
- 'h-4 w-4 transition-all'
- )}
- />
- <span className="sr-only">collapse</span>
- </Button>
+ <CollapsibleTrigger className="flex items-center justify-between w-full group">
+ <div className="flex items-center justify-between w-full gap-2">
+ {header && <div className="text-sm">{header}</div>}
+ <ChevronDown className="h-4 w-4 text-muted-foreground transition-transform duration-200 group-data-[state=open]:rotate-180" />
+ </div>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="data-[state=closed]:animate-collapse-up data-[state=open]:animate-collapse-down">
+ <Separator className="my-4" />
+ {content}
+ </CollapsibleContent>
+ </Collapsible>
</div>
- </CollapsibleTrigger>
- <CollapsibleContent>{message.component}</CollapsibleContent>
- {!open && <Separator className="my-2 bg-muted" />}
- </Collapsible>
+ ) : (
+ content
+ )}
+ </div>
)
}
diff --git a/components/message-with-avatar.tsx b/components/message-with-avatar.tsx
deleted file mode 100644
index 607537d2..00000000
--- a/components/message-with-avatar.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { cn } from '@/lib/utils'
-import { UserCircle2, Bot } from 'lucide-react'
-
-interface MessageWithAvatarProps {
- children: React.ReactNode
- role: 'user' | 'assistant'
-}
-
-export function MessageWithAvatar({ children, role }: MessageWithAvatarProps) {
- return (
- <div className="flex gap-3">
- <div className="relative flex flex-col items-center">
- <div className={cn('mt-[10px]', role === 'assistant' && 'pl-4')}>
- {role === 'user' && (
- <UserCircle2 size={20} className="text-muted-foreground" />
- )}
- </div>
- </div>
- <div className="py-2 flex-1">{children}</div>
- </div>
- )
-}
diff --git a/components/related-questions.tsx b/components/related-questions.tsx
index 7bf2a6a1..2bc1aa0c 100644
--- a/components/related-questions.tsx
+++ b/components/related-questions.tsx
@@ -2,15 +2,16 @@
import React from 'react'
import { Button } from './ui/button'
-import { ArrowRight } from 'lucide-react'
-import { Section } from './section'
+import { ArrowRight, Repeat2 } from 'lucide-react'
import { Skeleton } from './ui/skeleton'
import { JSONValue } from 'ai'
-import { MessageWithAvatar } from './message-with-avatar'
+import { CollapsibleMessage } from './collapsible-message'
export interface RelatedQuestionsProps {
annotations: JSONValue[]
onQuerySelect: (query: string) => void
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
interface RelatedQuestionsAnnotation extends Record<string, JSONValue> {
@@ -23,7 +24,9 @@ interface RelatedQuestionsAnnotation extends Record<string, JSONValue> {
export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
annotations,
- onQuerySelect
+ onQuerySelect,
+ isOpen,
+ onOpenChange
}) => {
if (!annotations) {
return null
@@ -38,45 +41,60 @@ export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
a.status === 'done'
)
+ const header = (
+ <div className="flex items-center gap-1">
+ <Repeat2 size={16} />
+ <div>Related</div>
+ </div>
+ )
+
const relatedQuestions = lastRelatedQuestionsAnnotation?.relatedQuestions
if (!relatedQuestions) {
return (
- <MessageWithAvatar role="assistant">
- <Section title="Related" separator={true}>
- <Skeleton className="w-full h-6" />
- </Section>
- </MessageWithAvatar>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
+ <Skeleton className="w-full h-6" />
+ </CollapsibleMessage>
)
}
return (
- <MessageWithAvatar role="assistant">
- <Section title="Related" separator={true}>
- <div className="flex flex-wrap">
- {Array.isArray(relatedQuestions.items) ? (
- relatedQuestions.items
- ?.filter(item => item?.query !== '')
- .map((item, index) => (
- <div className="flex items-start w-full" key={index}>
- <ArrowRight className="h-4 w-4 mr-2 mt-1 flex-shrink-0 text-accent-foreground/50" />
- <Button
- variant="link"
- className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
- type="submit"
- name={'related_query'}
- value={item?.query}
- onClick={() => onQuerySelect(item?.query)}
- >
- {item?.query}
- </Button>
- </div>
- ))
- ) : (
- <div>Not an array</div>
- )}
- </div>
- </Section>
- </MessageWithAvatar>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
+ <div className="flex flex-wrap">
+ {Array.isArray(relatedQuestions.items) ? (
+ relatedQuestions.items
+ ?.filter(item => item?.query !== '')
+ .map((item, index) => (
+ <div className="flex items-start w-full" key={index}>
+ <ArrowRight className="h-4 w-4 mr-2 mt-1 flex-shrink-0 text-accent-foreground/50" />
+ <Button
+ variant="link"
+ className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
+ type="submit"
+ name={'related_query'}
+ value={item?.query}
+ onClick={() => onQuerySelect(item?.query)}
+ >
+ {item?.query}
+ </Button>
+ </div>
+ ))
+ ) : (
+ <div>Not an array</div>
+ )}
+ </div>
+ </CollapsibleMessage>
)
}
export default RelatedQuestions
diff --git a/components/render-message.tsx b/components/render-message.tsx
index dc6399ab..0550e4c8 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -5,9 +5,15 @@ import { AnswerSection } from './answer-section'
interface RenderMessageProps {
message: Message
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function RenderMessage({ message }: RenderMessageProps) {
+export function RenderMessage({
+ message,
+ isOpen,
+ onOpenChange
+}: RenderMessageProps) {
if (message.role === 'user') {
return <UserMessage message={message.content} />
}
@@ -16,11 +22,22 @@ export function RenderMessage({ message }: RenderMessageProps) {
return (
<>
{message.toolInvocations.map(tool => (
- <ToolSection key={tool.toolCallId} tool={tool} />
+ <ToolSection
+ key={tool.toolCallId}
+ tool={tool}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
))}
</>
)
}
- return <AnswerSection content={message.content} />
+ return (
+ <AnswerSection
+ content={message.content}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
+ )
}
diff --git a/components/retrieve-section.tsx b/components/retrieve-section.tsx
index 908eff65..1a9a1919 100644
--- a/components/retrieve-section.tsx
+++ b/components/retrieve-section.tsx
@@ -5,21 +5,34 @@ import { SearchResults } from '@/components/search-results'
import { SearchResults as SearchResultsType } from '@/lib/types'
import { ToolInvocation } from 'ai'
import { DefaultSkeleton } from './default-skeleton'
-import { ToolBadge } from './tool-badge'
+import { CollapsibleMessage } from './collapsible-message'
interface RetrieveSectionProps {
tool: ToolInvocation
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function RetrieveSection({ tool }: RetrieveSectionProps) {
+export function RetrieveSection({
+ tool,
+ isOpen,
+ onOpenChange
+}: RetrieveSectionProps) {
const isLoading = tool.state === 'call'
const data: SearchResultsType =
tool.state === 'result' ? tool.result : undefined
const url = tool.args.url as string | undefined
+ const header = <ToolArgsSection tool="retrieve">{url}</ToolArgsSection>
+
return (
- <div>
- <ToolArgsSection tool="retrieve">{url}</ToolArgsSection>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
{!isLoading && data ? (
<Section title="Sources">
<SearchResults results={data.results} />
@@ -27,7 +40,7 @@ export function RetrieveSection({ tool }: RetrieveSectionProps) {
) : (
<DefaultSkeleton />
)}
- </div>
+ </CollapsibleMessage>
)
}
diff --git a/components/search-section.tsx b/components/search-section.tsx
index a0e54c91..90630256 100644
--- a/components/search-section.tsx
+++ b/components/search-section.tsx
@@ -6,12 +6,19 @@ import { SearchResultsImageSection } from './search-results-image'
import { Section, ToolArgsSection } from './section'
import type { SearchResults as TypeSearchResults } from '@/lib/types'
import { ToolInvocation } from 'ai'
+import { CollapsibleMessage } from './collapsible-message'
interface SearchSectionProps {
tool: ToolInvocation
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function SearchSection({ tool }: SearchSectionProps) {
+export function SearchSection({
+ tool,
+ isOpen,
+ onOpenChange
+}: SearchSectionProps) {
const isLoading = tool.state === 'call'
const searchResults: TypeSearchResults =
tool.state === 'result' ? tool.result : undefined
@@ -21,9 +28,18 @@ export function SearchSection({ tool }: SearchSectionProps) {
? ` [${includeDomains.join(', ')}]`
: ''
+ const header = (
+ <ToolArgsSection tool="search">{`${query}${includeDomainsString}`}</ToolArgsSection>
+ )
+
return (
- <div>
- <ToolArgsSection tool="search">{`${query}${includeDomainsString}`}</ToolArgsSection>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
{searchResults &&
searchResults.images &&
searchResults.images.length > 0 && (
@@ -41,6 +57,6 @@ export function SearchSection({ tool }: SearchSectionProps) {
) : (
<DefaultSkeleton />
)}
- </div>
+ </CollapsibleMessage>
)
}
diff --git a/components/section.tsx b/components/section.tsx
index ec7ea155..02447b64 100644
--- a/components/section.tsx
+++ b/components/section.tsx
@@ -61,7 +61,7 @@ export const Section: React.FC<SectionProps> = ({
{separator && <Separator className="my-2 bg-primary/10" />}
<section
className={cn(
- ` ${size === 'sm' ? 'py-1' : size === 'lg' ? 'py-4' : 'py-2'}`,
+ ` ${size === 'sm' ? 'py-1' : size === 'lg' ? 'py-4' : 'py-1'}`,
className
)}
>
@@ -85,7 +85,7 @@ export function ToolArgsSection({
tool: string
}) {
return (
- <Section size="sm" className="pt-2 pb-0">
+ <Section size="sm" className="py-0">
<ToolBadge tool={tool}>{children}</ToolBadge>
</Section>
)
diff --git a/components/tool-section.tsx b/components/tool-section.tsx
index 59f9f3ca..da93863a 100644
--- a/components/tool-section.tsx
+++ b/components/tool-section.tsx
@@ -4,25 +4,40 @@ import { ToolInvocation } from 'ai'
import { SearchSection } from './search-section'
import { VideoSearchSection } from './video-search-section'
import RetrieveSection from './retrieve-section'
-import { MessageWithAvatar } from './message-with-avatar'
interface ToolSectionProps {
tool: ToolInvocation
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function ToolSection({ tool }: ToolSectionProps) {
- const content = (() => {
- switch (tool.toolName) {
- case 'search':
- return <SearchSection tool={tool} />
- case 'video_search':
- return <VideoSearchSection tool={tool} />
- case 'retrieve':
- return <RetrieveSection tool={tool} />
- default:
- return null
- }
- })()
-
- return <MessageWithAvatar role="assistant">{content}</MessageWithAvatar>
+export function ToolSection({ tool, isOpen, onOpenChange }: ToolSectionProps) {
+ switch (tool.toolName) {
+ case 'search':
+ return (
+ <SearchSection
+ tool={tool}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
+ )
+ case 'video_search':
+ return (
+ <VideoSearchSection
+ tool={tool}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
+ )
+ case 'retrieve':
+ return (
+ <RetrieveSection
+ tool={tool}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
+ )
+ default:
+ return null
+ }
}
diff --git a/components/user-message.tsx b/components/user-message.tsx
index c3f11492..e537b95f 100644
--- a/components/user-message.tsx
+++ b/components/user-message.tsx
@@ -1,6 +1,6 @@
import React from 'react'
import { ChatShare } from './chat-share'
-import { MessageWithAvatar } from './message-with-avatar'
+import { CollapsibleMessage } from './collapsible-message'
type UserMessageProps = {
message: string
chatId?: string
@@ -14,9 +14,9 @@ export const UserMessage: React.FC<UserMessageProps> = ({
}) => {
const enableShare = process.env.ENABLE_SHARE === 'true'
return (
- <MessageWithAvatar role="user">
+ <CollapsibleMessage role="user">
<div className="flex-1 break-words w-full">{message}</div>
{enableShare && showShare && chatId && <ChatShare chatId={chatId} />}
- </MessageWithAvatar>
+ </CollapsibleMessage>
)
}
diff --git a/components/video-search-section.tsx b/components/video-search-section.tsx
index 2b132f2c..7233e74c 100644
--- a/components/video-search-section.tsx
+++ b/components/video-search-section.tsx
@@ -5,20 +5,34 @@ import { Section, ToolArgsSection } from './section'
import type { SerperSearchResults } from '@/lib/types'
import { ToolInvocation } from 'ai'
import { VideoSearchResults } from './video-search-results'
+import { CollapsibleMessage } from './collapsible-message'
interface VideoSearchSectionProps {
tool: ToolInvocation
+ isOpen: boolean
+ onOpenChange: (open: boolean) => void
}
-export function VideoSearchSection({ tool }: VideoSearchSectionProps) {
+export function VideoSearchSection({
+ tool,
+ isOpen,
+ onOpenChange
+}: VideoSearchSectionProps) {
const isLoading = tool.state === 'call'
const searchResults: SerperSearchResults =
tool.state === 'result' ? tool.result : undefined
const query = tool.args.q as string | undefined
+ const header = <ToolArgsSection tool="video_search">{query}</ToolArgsSection>
+
return (
- <div>
- <ToolArgsSection tool="video_search">{query}</ToolArgsSection>
+ <CollapsibleMessage
+ role="assistant"
+ isCollapsible={true}
+ header={header}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ >
{!isLoading && searchResults ? (
<Section title="Videos">
<VideoSearchResults results={searchResults} />
@@ -26,6 +40,6 @@ export function VideoSearchSection({ tool }: VideoSearchSectionProps) {
) : (
<DefaultSkeleton />
)}
- </div>
+ </CollapsibleMessage>
)
}