Skip to content

An AI-powered search engine with a generative UI

feat: Add video search artifact and refactor video components

Yoshiki Miura674d90209b03
diff --git a/components/artifact/artifact-content.tsx b/components/artifact/artifact-content.tsx
index 3871afce..14a4396a 100644
--- a/components/artifact/artifact-content.tsx
+++ b/components/artifact/artifact-content.tsx
@@ -2,6 +2,7 @@
import { RetrieveArtifactContent } from '@/components/artifact/retrieve-artifact-content'
import { SearchArtifactContent } from '@/components/artifact/search-artifact-content'
+import { VideoSearchArtifactContent } from '@/components/artifact/video-search-artifact-content'
import type { ToolInvocation } from 'ai'
export function ArtifactContent({
@@ -16,6 +17,8 @@ export function ArtifactContent({
return <SearchArtifactContent tool={artifact} />
case 'retrieve':
return <RetrieveArtifactContent tool={artifact} />
+ case 'videoSearch':
+ return <VideoSearchArtifactContent tool={artifact} />
default:
return <div className="p-4">Details for this tool are not available</div>
}
diff --git a/components/artifact/video-search-artifact-content.tsx b/components/artifact/video-search-artifact-content.tsx
new file mode 100644
index 00000000..7889597a
--- /dev/null
+++ b/components/artifact/video-search-artifact-content.tsx
@@ -0,0 +1,46 @@
+'use client'
+
+import { ToolArgsSection } from '@/components/section'
+import { VideoResultGrid } from '@/components/video-result-grid'
+import {
+ type SerperSearchResultItem,
+ type SerperSearchResults
+} from '@/lib/types'
+import type { ToolInvocation } from 'ai'
+
+export function VideoSearchArtifactContent({ tool }: { tool: ToolInvocation }) {
+ const videoResults: SerperSearchResults | undefined =
+ tool.state === 'result' ? tool.result : undefined
+ const query = tool.args?.query as string | undefined
+
+ const videos = (videoResults?.videos || []).filter(
+ (video: SerperSearchResultItem) => {
+ try {
+ return new URL(video.link).pathname === '/watch'
+ } catch (e) {
+ console.error('Invalid video URL:', video.link)
+ return false
+ }
+ }
+ )
+
+ if (videos.length === 0) {
+ return (
+ <div className="p-4 space-y-4">
+ <ToolArgsSection tool="videoSearch">{query}</ToolArgsSection>
+ <p className="text-muted-foreground">No video results</p>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-4 p-4">
+ <ToolArgsSection tool="videoSearch">{query}</ToolArgsSection>
+ <VideoResultGrid
+ videos={videos}
+ query={query || ''}
+ displayMode="artifact"
+ />
+ </div>
+ )
+}
diff --git a/components/section.tsx b/components/section.tsx
index 736a375c..973a412e 100644
--- a/components/section.tsx
+++ b/components/section.tsx
@@ -44,6 +44,7 @@ export const Section: React.FC<SectionProps> = ({
break
case 'Videos':
icon = <Film size={iconSize} className={iconClassName} />
+ type = 'badge'
break
case 'Sources':
icon = <Newspaper size={iconSize} className={iconClassName} />
diff --git a/components/tool-badge.tsx b/components/tool-badge.tsx
index 59684026..3a094428 100644
--- a/components/tool-badge.tsx
+++ b/components/tool-badge.tsx
@@ -1,5 +1,5 @@
+import { Film, Link, Search } from 'lucide-react'
import React from 'react'
-import { Link, Search, Video } from 'lucide-react'
import { Badge } from './ui/badge'
type ToolBadgeProps = {
@@ -16,7 +16,7 @@ export const ToolBadge: React.FC<ToolBadgeProps> = ({
const icon: Record<string, React.ReactNode> = {
search: <Search size={14} />,
retrieve: <Link size={14} />,
- video_search: <Video size={14} />
+ videoSearch: <Film size={14} />
}
return (
diff --git a/components/tool-section.tsx b/components/tool-section.tsx
index 0bbb35a6..771b4c28 100644
--- a/components/tool-section.tsx
+++ b/components/tool-section.tsx
@@ -63,7 +63,7 @@ export function ToolSection({
onOpenChange={onOpenChange}
/>
)
- case 'video_search':
+ case 'videoSearch':
return (
<VideoSearchSection
tool={tool}
diff --git a/components/video-carousel-dialog.tsx b/components/video-carousel-dialog.tsx
new file mode 100644
index 00000000..2c7f6871
--- /dev/null
+++ b/components/video-carousel-dialog.tsx
@@ -0,0 +1,123 @@
+'use client'
+
+import {
+ Carousel,
+ type CarouselApi,
+ CarouselContent,
+ CarouselItem,
+ CarouselNext,
+ CarouselPrevious
+} from '@/components/ui/carousel'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog'
+import { SerperSearchResultItem } from '@/lib/types'
+import { useEffect, useRef, useState } from 'react'
+
+interface VideoCarouselDialogProps {
+ children: React.ReactNode
+ videos: SerperSearchResultItem[]
+ query: string
+ initialIndex?: number // Add initialIndex prop
+}
+
+export function VideoCarouselDialog({
+ children,
+ videos,
+ query,
+ initialIndex = 0 // Default to 0
+}: VideoCarouselDialogProps) {
+ const [api, setApi] = useState<CarouselApi>()
+ const [current, setCurrent] = useState(initialIndex + 1) // Initialize with initialIndex
+ const [count, setCount] = useState(0)
+ const videoRefs = useRef<(HTMLIFrameElement | null)[]>([])
+
+ // Update the current and count state when the carousel api is available
+ useEffect(() => {
+ if (api) {
+ setCount(api.scrollSnapList().length)
+ // Initialize current based on initialIndex
+ setCurrent(api.selectedScrollSnap() + 1)
+
+ api.on('select', () => {
+ const newCurrent = api.selectedScrollSnap() + 1
+ if (current !== undefined && videoRefs.current[current - 1]) {
+ const prevVideo = videoRefs.current[current - 1]
+ prevVideo?.contentWindow?.postMessage(
+ '{"event":"command","func":"pauseVideo","args":""}',
+ '*'
+ )
+ }
+ setCurrent(newCurrent)
+ })
+ }
+ }, [api, current]) // Keep dependency on current to stop previous video
+
+ // Scroll to the initial index when the dialog opens and API is ready
+ useEffect(() => {
+ if (api) {
+ api.scrollTo(initialIndex, false) // Scroll instantly
+ }
+ }, [api, initialIndex])
+
+ return (
+ <Dialog>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="sm:max-w-3xl max-h-[80vh] overflow-auto">
+ <DialogHeader>
+ <DialogTitle>Search Videos</DialogTitle>
+ <DialogDescription className="text-sm">{query}</DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <Carousel
+ setApi={setApi}
+ className="w-full bg-muted max-h-[60vh]"
+ opts={{
+ startIndex: initialIndex // Set initial slide
+ }}
+ >
+ <CarouselContent>
+ {videos.map((video, idx) => {
+ const videoId = video.link.split('v=')[1]
+ return (
+ <CarouselItem key={idx}>
+ <div className="p-1 flex items-center justify-center h-full">
+ <iframe
+ ref={el => {
+ videoRefs.current[idx] = el
+ }}
+ src={`https://www.youtube.com/embed/${videoId}?enablejsapi=1`}
+ className="w-full aspect-video"
+ title={video.title}
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
+ allowFullScreen
+ />
+ </div>
+ </CarouselItem>
+ )
+ })}
+ </CarouselContent>
+ <div className="absolute inset-8 flex items-center justify-between p-4 pointer-events-none">
+ <CarouselPrevious className="w-10 h-10 rounded-full shadow focus:outline-none pointer-events-auto">
+ <span className="sr-only">Previous</span>
+ </CarouselPrevious>
+ <CarouselNext className="w-10 h-10 rounded-full shadow focus:outline-none pointer-events-auto">
+ <span className="sr-only">Next</span>
+ </CarouselNext>
+ </div>
+ </Carousel>
+ <div className="py-2">
+ <div className="text-center text-sm text-muted-foreground">
+ {current} of {count}
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/video-result-grid.tsx b/components/video-result-grid.tsx
new file mode 100644
index 00000000..0170ef27
--- /dev/null
+++ b/components/video-result-grid.tsx
@@ -0,0 +1,107 @@
+'use client'
+
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
+import { Card, CardContent } from '@/components/ui/card'
+import { SerperSearchResultItem } from '@/lib/types'
+import { PlusCircle } from 'lucide-react'
+import Image from 'next/image'
+import { VideoCarouselDialog } from './video-carousel-dialog'
+
+interface VideoResultGridProps {
+ videos: SerperSearchResultItem[]
+ query: string
+ displayMode: 'chat' | 'artifact'
+}
+
+export function VideoResultGrid({
+ videos,
+ query,
+ displayMode
+}: VideoResultGridProps) {
+ const containerClasses =
+ displayMode === 'chat'
+ ? 'flex flex-wrap'
+ : 'grid grid-cols-1 sm:grid-cols-2 gap-4'
+
+ const itemsToMap = displayMode === 'chat' ? videos.slice(0, 4) : videos
+
+ return (
+ <div className={containerClasses}>
+ {itemsToMap.map((video, index) => {
+ const baseUrl = video.imageUrl ? video.imageUrl.split('?')[0] : ''
+ const showOverlay =
+ displayMode === 'chat' && index === 3 && videos.length > 4
+ const cardClasses = displayMode === 'chat' ? 'w-1/2 md:w-1/4 p-1' : ''
+
+ return (
+ <VideoCarouselDialog
+ key={video.link || index}
+ videos={videos} // Pass all filtered videos for the dialog
+ query={query}
+ initialIndex={index}
+ >
+ <div className={`relative cursor-pointer ${cardClasses}`}>
+ <Card className="flex-1 min-h-40 overflow-hidden rounded-lg border hover:shadow-sm transition-shadow duration-200">
+ <CardContent className="p-0">
+ {' '}
+ {/* Adjusted padding */}
+ {baseUrl && (
+ <div className="relative w-full aspect-video bg-muted">
+ <Image
+ src={baseUrl}
+ alt={`Thumbnail for ${video.title}`}
+ fill
+ sizes={
+ displayMode === 'chat'
+ ? '(max-width: 768px) 50vw, 25vw'
+ : '(max-width: 639px) 300px, 250px'
+ } // Different sizes per mode
+ className="object-cover"
+ priority={index < 4}
+ onError={e => {
+ const target = e.target as HTMLImageElement
+ target.src = '/images/placeholder-image.png'
+ }}
+ />
+ </div>
+ )}
+ <div className="p-2">
+ {' '}
+ {/* Inner padding for text */}
+ <p className="text-xs line-clamp-2 mb-1 font-semibold">
+ {video.title}
+ </p>
+ <div className="flex items-center space-x-2">
+ <Avatar className="h-4 w-4">
+ <AvatarImage
+ src={`https://www.google.com/s2/favicons?domain=${
+ new URL(video.link).hostname
+ }`}
+ alt={video.channel || video.source}
+ />
+ <AvatarFallback>
+ {new URL(video.link).hostname[0]}
+ </AvatarFallback>
+ </Avatar>
+ <div className="text-xs text-muted-foreground opacity-60 truncate">
+ {/* Display channel or source if available */}
+ {video.channel ||
+ video.source ||
+ new URL(video.link).hostname}
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ {showOverlay && (
+ <div className="absolute inset-0 bg-black/30 rounded-md flex items-center justify-center text-white/80 text-sm">
+ <PlusCircle size={24} />
+ </div>
+ )}
+ </div>
+ </VideoCarouselDialog>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/components/video-search-results.tsx b/components/video-search-results.tsx
index 819838ef..14293c53 100644
--- a/components/video-search-results.tsx
+++ b/components/video-search-results.tsx
@@ -1,171 +1,28 @@
/* eslint-disable @next/next/no-img-element */
'use client'
-import { useEffect, useRef, useState } from 'react'
-import { AvatarImage, Avatar, AvatarFallback } from '@/components/ui/avatar'
-import { CardContent, Card } from '@/components/ui/card'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger
-} from '@/components/ui/dialog'
-import {
- Carousel,
- type CarouselApi,
- CarouselContent,
- CarouselItem,
- CarouselNext,
- CarouselPrevious
-} from '@/components/ui/carousel'
import { SerperSearchResultItem, SerperSearchResults } from '@/lib/types'
-import { PlusCircle } from 'lucide-react'
+import { VideoResultGrid } from './video-result-grid'
export interface VideoSearchResultsProps {
results: SerperSearchResults
}
export function VideoSearchResults({ results }: VideoSearchResultsProps) {
- const [api, setApi] = useState<CarouselApi>()
- const [current, setCurrent] = useState(1)
- const [count, setCount] = useState(0)
- const [selectedIndex, setSelectedIndex] = useState(0)
- const videoRefs = useRef<(HTMLIFrameElement | null)[]>([])
-
- // filter out the videos that path is not /watch
const videos = results.videos.filter((video: SerperSearchResultItem) => {
- return new URL(video.link).pathname === '/watch'
- })
-
- // Update the current and count state when the carousel api is available
- useEffect(() => {
- if (api) {
- setCount(api.scrollSnapList().length)
- setCurrent(api.selectedScrollSnap() + 1)
-
- api.on('select', () => {
- const newCurrent = api.selectedScrollSnap() + 1
- if (newCurrent !== current && videoRefs.current[current - 1]) {
- const prevVideo = videoRefs.current[current - 1]
- prevVideo?.contentWindow?.postMessage(
- '{"event":"command","func":"pauseVideo","args":""}',
- '*'
- )
- }
- setCurrent(newCurrent)
- })
+ try {
+ return new URL(video.link).pathname === '/watch'
+ } catch (e) {
+ console.error('Invalid video URL:', video.link)
+ return false
}
- }, [api, current])
+ })
- // Scroll to the selected index
- useEffect(() => {
- if (api) {
- api.scrollTo(selectedIndex, true)
- }
- }, [api, selectedIndex])
+ const query = results.searchParameters?.q || ''
- if (!results.videos || results.videos.length === 0) {
+ if (!videos || videos.length === 0) {
return <div className="text-muted-foreground">No videos found</div>
}
- return (
- <div className="flex flex-wrap">
- {videos.slice(0, 4).map((result: SerperSearchResultItem, index: any) => (
- <Dialog key={index}>
- <DialogTrigger asChild>
- <div
- className="w-1/2 md:w-1/4 p-1 cursor-pointer relative"
- onClick={() => setSelectedIndex(index)}
- >
- <Card className="flex-1 min-h-40 ">
- <CardContent className="p-2">
- <img
- src={result.imageUrl}
- alt={result.title}
- className="w-full aspect-video mb-2"
- onError={e =>
- (e.currentTarget.src = '/images/placeholder-image.png')
- }
- />
- <p className="text-xs line-clamp-2">{result.title}</p>
- <div className="mt-2 flex items-center space-x-2">
- <Avatar className="h-4 w-4">
- <AvatarImage
- src={`https://www.google.com/s2/favicons?domain=${
- new URL(result.link).hostname
- }`}
- alt={result.channel}
- />
- <AvatarFallback>
- {new URL(result.link).hostname[0]}
- </AvatarFallback>
- </Avatar>
- <div className="text-xs opacity-60 truncate">
- {new URL(result.link).hostname}
- </div>
- </div>
- </CardContent>
- </Card>
- {index === 3 && results.videos.length > 4 && (
- <div className="absolute inset-0 bg-black/30 rounded-md flex items-center justify-center text-white/80 text-sm">
- <PlusCircle size={24} />
- </div>
- )}
- </div>
- </DialogTrigger>
- <DialogContent className="sm:max-w-3xl max-h-[80vh] overflow-auto">
- <DialogHeader>
- <DialogTitle>Search Videos</DialogTitle>
- <DialogDescription className="text-sm">
- {results.searchParameters.q}
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <Carousel
- setApi={setApi}
- className="w-full bg-muted max-h-[60vh]"
- >
- <CarouselContent>
- {videos.map((video, idx) => {
- const videoId = video.link.split('v=')[1]
- return (
- <CarouselItem key={idx}>
- <div className="p-1 flex items-center justify-center h-full">
- <iframe
- ref={el => {
- videoRefs.current[idx] = el
- }}
- src={`https://www.youtube.com/embed/${videoId}?enablejsapi=1`}
- className="w-full aspect-video"
- title={video.title}
- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
- allowFullScreen
- />
- </div>
- </CarouselItem>
- )
- })}
- </CarouselContent>
- <div className="absolute inset-8 flex items-center justify-between p-4 pointer-events-none">
- <CarouselPrevious className="w-10 h-10 rounded-full shadow focus:outline-none pointer-events-auto">
- <span className="sr-only">Previous</span>
- </CarouselPrevious>
- <CarouselNext className="w-10 h-10 rounded-full shadow focus:outline-none pointer-events-auto">
- <span className="sr-only">Next</span>
- </CarouselNext>
- </div>
- </Carousel>
- <div className="py-2">
- <div className="text-center text-sm text-muted-foreground">
- {current} of {count}
- </div>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- ))}
- </div>
- )
+ return <VideoResultGrid videos={videos} query={query} displayMode="chat" />
}
diff --git a/components/video-search-section.tsx b/components/video-search-section.tsx
index de128f56..e19481d0 100644
--- a/components/video-search-section.tsx
+++ b/components/video-search-section.tsx
@@ -1,6 +1,9 @@
'use client'
+import { useArtifact } from '@/components/artifact/artifact-context'
+import { CHAT_ID } from '@/lib/constants'
import type { SerperSearchResults } from '@/lib/types'
+import { useChat } from '@ai-sdk/react'
import { ToolInvocation } from 'ai'
import { CollapsibleMessage } from './collapsible-message'
import { DefaultSkeleton } from './default-skeleton'
@@ -18,12 +21,29 @@ export function VideoSearchSection({
isOpen,
onOpenChange
}: VideoSearchSectionProps) {
- const isLoading = tool.state === 'call'
- const searchResults: SerperSearchResults =
+ const { status } = useChat({
+ id: CHAT_ID
+ })
+ const isLoading = status === 'submitted' || status === 'streaming'
+
+ const isToolLoading = tool.state === 'call'
+ const videoResults: SerperSearchResults =
tool.state === 'result' ? tool.result : undefined
- const query = tool.args.q as string | undefined
+ const query = tool.args?.query as string | undefined
- const header = <ToolArgsSection tool="video_search">{query}</ToolArgsSection>
+ const { open } = useArtifact()
+ const header = (
+ <button
+ type="button"
+ onClick={() => open(tool)}
+ className="flex items-center justify-between w-full text-left rounded-md p-1 -ml-1"
+ title="Open details"
+ >
+ <ToolArgsSection tool="videoSearch" number={videoResults?.videos?.length}>
+ {query}
+ </ToolArgsSection>
+ </button>
+ )
return (
<CollapsibleMessage
@@ -34,9 +54,9 @@ export function VideoSearchSection({
onOpenChange={onOpenChange}
showIcon={false}
>
- {!isLoading && searchResults ? (
+ {!isLoading && videoResults ? (
<Section title="Videos">
- <VideoSearchResults results={searchResults} />
+ <VideoSearchResults results={videoResults} />
</Section>
) : (
<DefaultSkeleton />
diff --git a/next.config.mjs b/next.config.mjs
index 4678774e..b7cfb42d 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -1,4 +1,16 @@
/** @type {import('next').NextConfig} */
-const nextConfig = {};
+const nextConfig = {
+ images: {
+ remotePatterns: [
+ {
+ protocol: 'https',
+ hostname: 'i.ytimg.com',
+ port: '',
+ pathname: '/vi/**'
+ }
+ // Add other domains here if needed in the future
+ ]
+ }
+}
-export default nextConfig;
+export default nextConfig