AI Resource Pro / website / lib / hooks / useImageGenerationDialog.ts
| 1 | import { useState, useCallback } from 'react'; |
| 2 | import { toast } from '@/components/ui/use-toast'; |
| 3 | |
| 4 | /** |
| 5 | * Default generation options (Gemini Imagen) |
| 6 | */ |
| 7 | export interface GenerationDefaults { |
| 8 | aspectRatio: string; |
| 9 | imageSize: string; |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * Props for the useImageGenerationDialog hook |
| 14 | */ |
| 15 | interface UseImageGenerationDialogProps { |
| 16 | contentSource: string; |
| 17 | generationApiEndpoint: string; |
| 18 | generationDefaults: GenerationDefaults; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * Return type for the hook |
| 23 | */ |
| 24 | interface UseImageGenerationDialogReturn { |
| 25 | generateImageDialogOpen: boolean; |
| 26 | setGenerateImageDialogOpen: React.Dispatch<React.SetStateAction<boolean>>; |
| 27 | dialogStep: 'selectPrompt' | 'configureOptions'; |
| 28 | loadingPrompts: boolean; |
| 29 | availablePrompts: string[]; |
| 30 | dialogSelectedPrompt: string; |
| 31 | isGeneratingImage: boolean; |
| 32 | generationError: string | null; |
| 33 | generationSuccess: boolean; |
| 34 | generatedImageUrl: string | null; |
| 35 | openDialog: () => void; |
| 36 | handleDialogPromptSelect: (prompt: string) => void; |
| 37 | handleGoToOptions: () => void; |
| 38 | handleGoBackToPromptSelect: () => void; |
| 39 | triggerImageGeneration: (options: { prompt: string; aspectRatio: string; imageSize: string }) => Promise<void>; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Simplified hook for image generation using Gemini Imagen API |
| 44 | * No polling needed - synchronous API call |
| 45 | */ |
| 46 | export function useImageGenerationDialog({ |
| 47 | contentSource, |
| 48 | generationApiEndpoint, |
| 49 | generationDefaults, |
| 50 | }: UseImageGenerationDialogProps): UseImageGenerationDialogReturn { |
| 51 | // Dialog state |
| 52 | const [generateImageDialogOpen, setGenerateImageDialogOpen] = useState(false); |
| 53 | const [dialogStep, setDialogStep] = useState<'selectPrompt' | 'configureOptions'>('selectPrompt'); |
| 54 | const [availablePrompts, setAvailablePrompts] = useState<string[]>([]); |
| 55 | const [dialogSelectedPrompt, setDialogSelectedPrompt] = useState<string>(''); |
| 56 | const [loadingPrompts, setLoadingPrompts] = useState(false); |
| 57 | |
| 58 | // Generation state |
| 59 | const [isGeneratingImage, setIsGeneratingImage] = useState(false); |
| 60 | const [generationError, setGenerationError] = useState<string | null>(null); |
| 61 | const [generationSuccess, setGenerationSuccess] = useState<boolean>(false); |
| 62 | const [generatedImageUrl, setGeneratedImageUrl] = useState<string | null>(null); |
| 63 | |
| 64 | // Dialog flow handlers |
| 65 | const handleDialogPromptSelect = (prompt: string) => { |
| 66 | setDialogSelectedPrompt(prompt); |
| 67 | }; |
| 68 | |
| 69 | const handleGoToOptions = () => { |
| 70 | if (dialogSelectedPrompt) { |
| 71 | setDialogStep('configureOptions'); |
| 72 | setGenerationError(null); |
| 73 | } else { |
| 74 | toast({ title: "Error", description: "Please select a prompt first.", variant: "destructive" }); |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | const handleGoBackToPromptSelect = () => { |
| 79 | setDialogStep('selectPrompt'); |
| 80 | setIsGeneratingImage(false); |
| 81 | setGenerationError(null); |
| 82 | setGenerationSuccess(false); |
| 83 | setGeneratedImageUrl(null); |
| 84 | }; |
| 85 | |
| 86 | // Fetch prompts from API |
| 87 | const fetchPrompts = useCallback(async () => { |
| 88 | setLoadingPrompts(true); |
| 89 | setGenerationError(null); |
| 90 | setAvailablePrompts([]); |
| 91 | setDialogSelectedPrompt(''); |
| 92 | |
| 93 | const sourceText = contentSource || "Generate creative image prompts"; |
| 94 | |
| 95 | try { |
| 96 | console.log("[useImageGenerationDialog] Fetching prompts for content:", sourceText.substring(0, 100) + "..."); |
| 97 | |
| 98 | const response = await fetch('/api/admin/generate-prompts', { |
| 99 | method: 'POST', |
| 100 | headers: { 'Content-Type': 'application/json' }, |
| 101 | body: JSON.stringify({ content: sourceText }) |
| 102 | }); |
| 103 | |
| 104 | const data = await response.json(); |
| 105 | |
| 106 | if (!response.ok) { |
| 107 | throw new Error(data.error || `API Error: ${response.statusText}`); |
| 108 | } |
| 109 | |
| 110 | if (!data.prompts || !Array.isArray(data.prompts) || data.prompts.length === 0) { |
| 111 | console.warn('[useImageGenerationDialog] API returned no valid prompts.'); |
| 112 | setAvailablePrompts([]); |
| 113 | } else { |
| 114 | console.log("[useImageGenerationDialog] Received prompts:", data.prompts); |
| 115 | setAvailablePrompts(data.prompts); |
| 116 | if (data.prompts.length > 0) { |
| 117 | setDialogSelectedPrompt(data.prompts[0]); |
| 118 | } |
| 119 | } |
| 120 | } catch (error) { |
| 121 | const errorMessage = error instanceof Error ? error.message : "Failed to fetch prompts."; |
| 122 | console.error("[useImageGenerationDialog] Error fetching prompts:", errorMessage); |
| 123 | setGenerationError(errorMessage); |
| 124 | toast({ title: 'Error Fetching Prompts', description: `${errorMessage}. You can still type your own prompt.`, variant: 'destructive' }); |
| 125 | setAvailablePrompts([]); |
| 126 | } finally { |
| 127 | setLoadingPrompts(false); |
| 128 | } |
| 129 | }, [contentSource]); |
| 130 | |
| 131 | // Open dialog and fetch prompts |
| 132 | const openDialog = useCallback(() => { |
| 133 | setDialogStep('selectPrompt'); |
| 134 | setAvailablePrompts([]); |
| 135 | setDialogSelectedPrompt(''); |
| 136 | setGenerationError(null); |
| 137 | setGenerationSuccess(false); |
| 138 | setGeneratedImageUrl(null); |
| 139 | setIsGeneratingImage(false); |
| 140 | |
| 141 | fetchPrompts(); |
| 142 | setGenerateImageDialogOpen(true); |
| 143 | }, [fetchPrompts]); |
| 144 | |
| 145 | // Trigger image generation - synchronous API call (Gemini Imagen) |
| 146 | const triggerImageGeneration = useCallback(async (options: { prompt: string; aspectRatio: string; imageSize: string }) => { |
| 147 | setIsGeneratingImage(true); |
| 148 | setGenerationError(null); |
| 149 | setGenerationSuccess(false); |
| 150 | setGeneratedImageUrl(null); |
| 151 | |
| 152 | console.log("[useImageGenerationDialog] Generating image with Gemini Imagen:", options); |
| 153 | |
| 154 | try { |
| 155 | const response = await fetch(generationApiEndpoint, { |
| 156 | method: 'POST', |
| 157 | headers: { 'Content-Type': 'application/json' }, |
| 158 | body: JSON.stringify({ |
| 159 | prompt: options.prompt, |
| 160 | aspectRatio: options.aspectRatio, |
| 161 | imageSize: options.imageSize, |
| 162 | }) |
| 163 | }); |
| 164 | |
| 165 | const data = await response.json(); |
| 166 | |
| 167 | if (!response.ok || data.error) { |
| 168 | throw new Error(data.error || data.details || `API Error: ${response.statusText}`); |
| 169 | } |
| 170 | |
| 171 | if (!data.imageUrl) { |
| 172 | throw new Error('Generation API response missing imageUrl.'); |
| 173 | } |
| 174 | |
| 175 | console.log("[useImageGenerationDialog] Generation successful, imageUrl:", data.imageUrl); |
| 176 | |
| 177 | setGeneratedImageUrl(data.imageUrl); |
| 178 | setGenerationSuccess(true); |
| 179 | |
| 180 | toast({ |
| 181 | title: "Generation Complete!", |
| 182 | description: "Image generated successfully.", |
| 183 | className: "bg-green-500/10 text-green-700 dark:text-green-400 border-green-500/50" |
| 184 | }); |
| 185 | |
| 186 | } catch (error) { |
| 187 | const errorMessage = error instanceof Error ? error.message : "Unknown generation error."; |
| 188 | console.error("[useImageGenerationDialog] Generation error:", errorMessage); |
| 189 | setGenerationError(errorMessage); |
| 190 | toast({ title: 'Generation Error', description: errorMessage, variant: 'destructive' }); |
| 191 | } finally { |
| 192 | setIsGeneratingImage(false); |
| 193 | } |
| 194 | }, [generationApiEndpoint]); |
| 195 | |
| 196 | return { |
| 197 | generateImageDialogOpen, |
| 198 | setGenerateImageDialogOpen, |
| 199 | dialogStep, |
| 200 | loadingPrompts, |
| 201 | availablePrompts, |
| 202 | dialogSelectedPrompt, |
| 203 | isGeneratingImage, |
| 204 | generationError, |
| 205 | generationSuccess, |
| 206 | generatedImageUrl, |
| 207 | openDialog, |
| 208 | handleDialogPromptSelect, |
| 209 | handleGoToOptions, |
| 210 | handleGoBackToPromptSelect, |
| 211 | triggerImageGeneration, |
| 212 | }; |
| 213 | } |