An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: filter out broken search images
Yoshiki Miura007df5a00abd
diff --git a/components/search-results-image.tsx b/components/search-results-image.tsxindex f8d3fad2..cd6d7ee7 100644--- a/components/search-results-image.tsx+++ b/components/search-results-image.tsx@@ -1,7 +1,7 @@/* eslint-disable @next/next/no-img-element */'use client'-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { PlusCircle } from 'lucide-react'@@ -30,6 +30,8 @@ interface SearchResultsImageSectionProps {displayMode?: 'preview' | 'full'}+type NormalizedImage = { url: string; description: string }+export const SearchResultsImageSection: React.FC<SearchResultsImageSectionProps> = ({ images, query, displayMode = 'preview' }) => {@@ -37,20 +39,89 @@ export const SearchResultsImageSection: React.FC<const [current, setCurrent] = useState(0)const [count, setCount] = useState(0)const [selectedIndex, setSelectedIndex] = useState(0)+ const [filteredImages, setFilteredImages] = useState<NormalizedImage[]>([])+ const [isCheckingImages, setIsCheckingImages] = useState(true)++ const convertedImages = useMemo(() => {+ if (!images || images.length === 0) {+ return [] as NormalizedImage[]+ }- // 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 elementsif (typeof images[0] === 'string') {- convertedImages = (images as string[]).map(image => ({+ return (images as string[]).map(image => ({url: image,description: ''}))- } else {- convertedImages = images as { url: string; description: string }[]}- }++ return images as NormalizedImage[]+ }, [images])++ useEffect(() => {+ let isMounted = true++ if (typeof window === 'undefined') {+ setFilteredImages(convertedImages)+ setIsCheckingImages(false)+ return+ }++ if (convertedImages.length === 0) {+ setFilteredImages([])+ setIsCheckingImages(false)+ return+ }++ setIsCheckingImages(true)+ setFilteredImages([])++ const preloadResults: (NormalizedImage | null)[] = Array(+ convertedImages.length+ ).fill(null)+ let completedChecks = 0++ const markComplete = () => {+ completedChecks += 1+ if (!isMounted) {+ return+ }+ if (completedChecks === convertedImages.length) {+ setFilteredImages(preloadResults.filter(Boolean) as NormalizedImage[])+ setIsCheckingImages(false)+ }+ }++ convertedImages.forEach((image, index) => {+ if (!image?.url) {+ markComplete()+ return+ }++ const preloader = new window.Image()+ preloader.onload = () => {+ if (!isMounted) {+ return+ }+ preloadResults[index] = image+ markComplete()+ }+ preloader.onerror = markComplete+ preloader.src = image.url+ })++ return () => {+ isMounted = false+ }+ }, [convertedImages])++ useEffect(() => {+ setSelectedIndex(prevIndex => {+ if (filteredImages.length === 0) {+ return 0+ }+ return Math.min(prevIndex, filteredImages.length - 1)+ })+ }, [filteredImages.length])// Update the current and count state when the carousel api is availableuseEffect(() => {@@ -76,31 +147,46 @@ export const SearchResultsImageSection: React.FC<// Update count based on the actual number of converted images// This ensures the count reflects the data, even if the carousel API is slowuseEffect(() => {- setCount(convertedImages.length)- }, [convertedImages.length])+ setCount(filteredImages.length)+ }, [filteredImages.length])++ useEffect(() => {+ if (filteredImages.length === 0) {+ setCurrent(0)+ }+ }, [filteredImages.length])// Scroll to the selected index when it changes or api becomes availableuseEffect(() => {- if (api && convertedImages.length > 0) {+ if (api && filteredImages.length > 0) {const actualIndex = Math.min(selectedIndex,- Math.max(0, convertedImages.length - 1) // Ensure index is not negative+ Math.max(0, filteredImages.length - 1) // Ensure index is not negative)api.scrollTo(actualIndex, false) // Use false for instant scroll on open}// Add convertedImages.length as dep: scroll might need adjustment if images load async- }, [api, selectedIndex, convertedImages.length])+ }, [api, selectedIndex, filteredImages.length])// Early return AFTER all hooks if there are no images to display- if (convertedImages.length === 0) {+ if (!isCheckingImages && filteredImages.length === 0) {return <div className="text-muted-foreground">No images found</div>}+ const handleImageError = (indexToRemove: number) => {+ setFilteredImages(prevImages =>+ prevImages.filter((_, imageIndex) => imageIndex !== indexToRemove)+ )+ }++ const baseImages = isCheckingImages ? convertedImages : filteredImages+const renderImageGrid = (- imageSubset: { url: string; description: string }[],+ imageSubset: NormalizedImage[],gridClasses: string,startIndex: number = 0,- isFullMode: boolean = false // Add flag to indicate full mode for corner rounding+ isFullMode: boolean = false, // Add flag to indicate full mode for corner rounding+ isLoading: boolean = false) => (<div className={gridClasses}>{imageSubset.map((image, index) => {@@ -120,6 +206,19 @@ export const SearchResultsImageSection: React.FC<cornerClasses = 'rounded-lg' // Default for preview mode}+ if (isLoading || !image?.url) {+ return (+ <div+ key={`placeholder-${startIndex}-${index}`}+ className="aspect-video"+ >+ <div+ className={`h-full w-full bg-muted animate-pulse shadow-sm ${cornerClasses}`}+ />+ </div>+ )+ }+return (<Dialog key={actualIndex}><DialogTrigger asChild>@@ -129,16 +228,13 @@ export const SearchResultsImageSection: React.FC<><div className="flex-1 h-full"><div className="h-full w-full">- {image ? (+ {image?.url ? (<imgsrc={image.url}alt={`Image ${actualIndex + 1}`}// Apply specific or default roundingclassName={`h-full w-full object-cover shadow-sm ${cornerClasses}`}- onError={e =>- (e.currentTarget.src =- '/images/placeholder-image.png')- }+ onError={() => handleImageError(actualIndex)}/>) : (<div className="w-full h-full bg-muted animate-pulse rounded-sm" />@@ -147,7 +243,8 @@ export const SearchResultsImageSection: React.FC<</div>{displayMode === 'preview' &&actualIndex === 3 &&- convertedImages.length > 4 && (+ !isLoading &&+ filteredImages.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>@@ -166,28 +263,25 @@ export const SearchResultsImageSection: React.FC<setApi={setApi}opts={{startIndex: selectedIndex,- loop: convertedImages.length > 1+ loop: filteredImages.length > 1}}className="w-full bg-muted max-h-[60vh]"><CarouselContent>- {convertedImages.map((img, idx) => (- <CarouselItem key={idx}>+ {filteredImages.map((img, idx) => (+ <CarouselItem key={`${img.url}-${idx}`}><div className="p-1 flex items-center justify-center h-full"><imgsrc={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')- }+ onError={() => handleImageError(idx)}/></div></CarouselItem>))}</CarouselContent>- {convertedImages.length > 1 && (+ {filteredImages.length > 1 && (<div className="absolute inset-8 flex items-center justify-between p-4"><CarouselPrevious className="w-10 h-10 rounded-full shadow-sm focus:outline-hidden"><span className="sr-only">Previous</span>@@ -211,8 +305,8 @@ export const SearchResultsImageSection: React.FC<if (displayMode === 'full') {// Original 2 rows: 2 images + 3 images- const firstRowImages = convertedImages.slice(0, 2)- const secondRowImages = convertedImages.slice(2, 5)+ const firstRowImages = baseImages.slice(0, 2)+ const secondRowImages = baseImages.slice(2, 5)// Render two rows, passing isFullMode=true to apply specific roundingreturn (@@ -221,26 +315,29 @@ export const SearchResultsImageSection: React.FC<firstRowImages,'grid grid-cols-2 gap-2',0,- true // Pass true for isFullMode+ true, // Pass true for isFullMode+ isCheckingImages)}{secondRowImages.length > 0 && // Only render second row if images existrenderImageGrid(secondRowImages,'grid grid-cols-3 gap-2',2,- true // Pass true for isFullMode+ true, // Pass true for isFullMode+ isCheckingImages)}</div>)}// Default to preview mode (2x2 or 4 wide grid)- const previewImages = convertedImages.slice(0, 4)+ const previewImages = baseImages.slice(0, 4)// Preview mode uses default rounding (rounded-lg), so isFullMode=falsereturn renderImageGrid(previewImages,'grid grid-cols-2 md:grid-cols-4 gap-2',0,- false+ false,+ isCheckingImages)}