An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: Implement full image display mode for artifacts
Yoshiki Miura2e32422e775c
diff --git a/components/artifact/artifact-content.tsx b/components/artifact/artifact-content.tsxindex 3ed3eeb6..073e87d0 100644--- a/components/artifact/artifact-content.tsx+++ b/components/artifact/artifact-content.tsx@@ -1,9 +1,6 @@'use client'-import { SearchResults } from '@/components/search-results'-import { SearchResultsImageSection } from '@/components/search-results-image'-import { Section } from '@/components/section'-import type { SearchResults as TypeSearchResults } from '@/lib/types'+import { SearchArtifactContent } from '@/components/artifact/search-artifact-content'import type { ToolInvocation } from 'ai'export function ArtifactContent({@@ -20,30 +17,3 @@ export function ArtifactContent({return <div className="p-4">Details for this tool are not available</div>}}--function SearchArtifactContent({ tool }: { tool: ToolInvocation }) {- const searchResults: TypeSearchResults =- tool.state === 'result' ? tool.result : undefined- const query = tool.args?.query as string | undefined-- if (!searchResults?.results) {- return <div className="p-4">No search results</div>- }-- return (- <div className="p-4 space-y-6">- {searchResults.images && searchResults.images.length > 0 && (- <Section>- <SearchResultsImageSection- images={searchResults.images}- query={query}- />- </Section>- )}-- <Section title="Sources">- <SearchResults results={searchResults.results} />- </Section>- </div>- )-}diff --git a/components/artifact/search-artifact-content.tsx b/components/artifact/search-artifact-content.tsxnew file mode 100644index 00000000..cea8d31c--- /dev/null+++ b/components/artifact/search-artifact-content.tsx@@ -0,0 +1,33 @@+'use client'++import { SearchResults } from '@/components/search-results'+import { SearchResultsImageSection } from '@/components/search-results-image'+import { Section } from '@/components/section'+import type { SearchResults as TypeSearchResults } from '@/lib/types'+import type { ToolInvocation } from 'ai'++export function SearchArtifactContent({ tool }: { tool: ToolInvocation }) {+ const searchResults: TypeSearchResults =+ tool.state === 'result' ? tool.result : undefined+ const query = tool.args?.query as string | undefined++ if (!searchResults?.results) {+ return <div className="p-4">No search results</div>+ }++ return (+ <div className="p-4 space-y-2">+ {searchResults.images && searchResults.images.length > 0 && (+ <SearchResultsImageSection+ images={searchResults.images}+ query={query}+ displayMode="full"+ />+ )}++ <Section title="Sources">+ <SearchResults results={searchResults.results} />+ </Section>+ </div>+ )+}diff --git a/components/search-results-image.tsx b/components/search-results-image.tsxindex ac4c412b..fff48028 100644--- a/components/search-results-image.tsx+++ b/components/search-results-image.tsx@@ -1,15 +1,6 @@/* eslint-disable @next/next/no-img-element */'use client'-import { Card, CardContent } from '@/components/ui/card'-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger-} from '@/components/ui/dialog'import {Carousel,type CarouselApi,@@ -18,135 +9,199 @@ import {CarouselNext,CarouselPrevious} from '@/components/ui/carousel'-import { useEffect, useState } from 'react'-import { PlusCircle } from 'lucide-react'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger+} from '@/components/ui/dialog'import { SearchResultImage } from '@/lib/types'+import { PlusCircle } from 'lucide-react'+import { useEffect, useState } from 'react'interface SearchResultsImageSectionProps {images: SearchResultImage[]query?: string+ displayMode?: 'preview' | 'full'}export const SearchResultsImageSection: React.FC<SearchResultsImageSectionProps-> = ({ images, query }) => {+> = ({ images, query, displayMode = 'preview' }) => {const [api, setApi] = useState<CarouselApi>()const [current, setCurrent] = useState(0)const [count, setCount] = useState(0)const [selectedIndex, setSelectedIndex] = useState(0)+ // Calculate convertedImages first, before any hooks that might depend on it or early returns+ let convertedImages: { url: string; description: string }[] = []+ if (images && images.length > 0) {+ // Check images array before accessing its elements+ if (typeof images[0] === 'string') {+ convertedImages = (images as string[]).map(image => ({+ url: image,+ description: ''+ }))+ } else {+ convertedImages = images as { url: string; description: string }[]+ }+ }+// Update the current and count state when the carousel api is availableuseEffect(() => {if (!api) {return}+ // Set initial count from scroll snaps, current from selected snapsetCount(api.scrollSnapList().length)setCurrent(api.selectedScrollSnap() + 1)- api.on('select', () => {+ const handleSelect = () => {setCurrent(api.selectedScrollSnap() + 1)- })+ }+ api.on('select', handleSelect)++ // Cleanup listener on unmount or when api changes+ return () => {+ api.off('select', handleSelect)+ }}, [api])- // Scroll to the selected index+ // Update count based on the actual number of converted images+ // This ensures the count reflects the data, even if the carousel API is slowuseEffect(() => {- if (api) {- api.scrollTo(selectedIndex, true)+ setCount(convertedImages.length)+ }, [convertedImages.length])++ // Scroll to the selected index when it changes or api becomes available+ useEffect(() => {+ if (api && convertedImages.length > 0) {+ const actualIndex = Math.min(+ selectedIndex,+ Math.max(0, convertedImages.length - 1) // Ensure index is not negative+ )+ api.scrollTo(actualIndex, false) // Use false for instant scroll on open}- }, [api, selectedIndex])+ // Add convertedImages.length as dep: scroll might need adjustment if images load async+ }, [api, selectedIndex, convertedImages.length])- if (!images || images.length === 0) {+ // Early return AFTER all hooks if there are no images to display+ if (convertedImages.length === 0) {return <div className="text-muted-foreground">No images found</div>}- // If enabled the include_images_description is true, the images will be an array of { url: string, description: string }- // Otherwise, the images will be an array of strings- let convertedImages: { url: string; description: string }[] = []- if (typeof images[0] === 'string') {- convertedImages = (images as string[]).map(image => ({- url: image,- description: ''- }))- } else {- convertedImages = images as { url: string; description: string }[]- }-- return (- <div className="flex flex-wrap gap-2">- {convertedImages.slice(0, 4).map((image, index) => (- <Dialog key={index}>- <DialogTrigger asChild>- <div- className="w-[calc(50%-0.5rem)] md:w-[calc(25%-0.5rem)] aspect-video cursor-pointer relative"- onClick={() => setSelectedIndex(index)}- >- <Card className="flex-1 h-full">- <CardContent className="p-2 h-full w-full">- {image ? (- <img- src={image.url}- alt={`Image ${index + 1}`}- className="h-full w-full object-cover"- onError={e =>- (e.currentTarget.src = '/images/placeholder-image.png')- }- />- ) : (- <div className="w-full h-full bg-muted animate-pulse" />- )}- </CardContent>- </Card>- {index === 3 && images.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 Images</DialogTitle>- <DialogDescription className="text-sm">{query}</DialogDescription>- </DialogHeader>- <div className="py-4">- <Carousel- setApi={setApi}- className="w-full bg-muted max-h-[60vh]"+ const renderImageGrid = (+ imageSubset: { url: string; description: string }[],+ gridClasses: string,+ startIndex: number = 0+ ) => (+ <div className={gridClasses}>+ {imageSubset.map((image, index) => {+ const actualIndex = startIndex + index+ return (+ <Dialog key={actualIndex}>+ <DialogTrigger asChild>+ <div+ className="aspect-video cursor-pointer relative"+ onClick={() => setSelectedIndex(actualIndex)}>- <CarouselContent>- {convertedImages.map((img, idx) => (- <CarouselItem key={idx}>- <div className="p-1 flex items-center justify-center h-full">- <img- src={img.url}- alt={`Image ${idx + 1}`}- className="h-auto w-full object-contain max-h-[60vh]"- onError={e =>- (e.currentTarget.src =- '/images/placeholder-image.png')- }- />- </div>- </CarouselItem>- ))}- </CarouselContent>- <div className="absolute inset-8 flex items-center justify-between p-4">- <CarouselPrevious className="w-10 h-10 rounded-full shadow focus:outline-none">- <span className="sr-only">Previous</span>- </CarouselPrevious>- <CarouselNext className="w-10 h-10 rounded-full shadow focus:outline-none">- <span className="sr-only">Next</span>- </CarouselNext>+ <div className="flex-1 h-full">+ <div className="h-full w-full">+ {image ? (+ <img+ src={image.url}+ alt={`Image ${actualIndex + 1}`}+ className="h-full w-full object-cover rounded-lg shadow"+ onError={e =>+ (e.currentTarget.src =+ '/images/placeholder-image.png')+ }+ />+ ) : (+ <div className="w-full h-full bg-muted animate-pulse rounded-sm" />+ )}+ </div>+ </div>+ {displayMode === 'preview' &&+ actualIndex === 3 &&+ convertedImages.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 Images</DialogTitle>+ <DialogDescription className="text-sm">+ {query}+ </DialogDescription>+ </DialogHeader>+ <div className="py-4">+ <Carousel+ setApi={setApi}+ opts={{+ startIndex: selectedIndex,+ loop: convertedImages.length > 1+ }}+ className="w-full bg-muted max-h-[60vh]"+ >+ <CarouselContent>+ {convertedImages.map((img, idx) => (+ <CarouselItem key={idx}>+ <div className="p-1 flex items-center justify-center h-full">+ <img+ src={img.url}+ alt={`Image ${idx + 1}`}+ className="h-auto w-full object-contain max-h-[60vh]"+ onError={e =>+ (e.currentTarget.src =+ '/images/placeholder-image.png')+ }+ />+ </div>+ </CarouselItem>+ ))}+ </CarouselContent>+ {convertedImages.length > 1 && (+ <div className="absolute inset-8 flex items-center justify-between p-4">+ <CarouselPrevious className="w-10 h-10 rounded-full shadow focus:outline-none">+ <span className="sr-only">Previous</span>+ </CarouselPrevious>+ <CarouselNext className="w-10 h-10 rounded-full shadow focus:outline-none">+ <span className="sr-only">Next</span>+ </CarouselNext>+ </div>+ )}+ </Carousel>+ <div className="py-2 text-center text-sm text-muted-foreground">+ {current} of {count} images</div>- </Carousel>- <div className="py-2 text-center text-sm text-muted-foreground">- {current} of {count}</div>- </div>- </DialogContent>- </Dialog>- ))}+ </DialogContent>+ </Dialog>+ )+ })}</div>)++ if (displayMode === 'full') {+ const firstRowImages = convertedImages.slice(0, 2)+ const secondRowImages = convertedImages.slice(2, 5)++ return (+ <div className="flex flex-col gap-2">+ {renderImageGrid(firstRowImages, 'grid grid-cols-2 gap-2', 0)}+ {renderImageGrid(secondRowImages, 'grid grid-cols-3 gap-2', 2)}+ </div>+ )+ }++ // Default to preview mode+ const previewImages = convertedImages.slice(0, 4)+ return renderImageGrid(previewImages, 'grid grid-cols-2 md:grid-cols-4 gap-2')}