Primeiro Commit
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { ChatHeader } from "@/components/ChatHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
@@ -13,56 +13,133 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { imageGenerationService, IMAGE_SIZE_OPTIONS, ImageSize } from "@/services/imageGeneration";
|
||||
|
||||
interface GeneratedImage {
|
||||
id: string;
|
||||
url: string;
|
||||
prompt: string;
|
||||
size: string;
|
||||
timestamp: string;
|
||||
size: ImageSize;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export const ImageView = () => {
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [selectedSize, setSelectedSize] = useState("1024x1024");
|
||||
const [selectedSize, setSelectedSize] = useState<ImageSize>("1024x1024");
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [images, setImages] = useState<GeneratedImage[]>([
|
||||
{
|
||||
id: "1",
|
||||
url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=512&h=512&fit=crop",
|
||||
prompt: "Paisagem futurista com cidades voadoras",
|
||||
size: "1024x1024",
|
||||
timestamp: "Há 2 horas",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
url: "https://images.unsplash.com/photo-1634017839464-5c339ebe3cb4?w=512&h=512&fit=crop",
|
||||
prompt: "Robô humanoide em estilo cyberpunk",
|
||||
size: "1024x1536",
|
||||
timestamp: "Há 5 horas",
|
||||
},
|
||||
]);
|
||||
const [images, setImages] = useState<GeneratedImage[]>([]);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Carrega histórico do localStorage ao montar o componente
|
||||
useEffect(() => {
|
||||
const savedImages = localStorage.getItem('imageHistory');
|
||||
if (savedImages) {
|
||||
try {
|
||||
const parsedImages = JSON.parse(savedImages);
|
||||
// Converte strings de data de volta para Date objects
|
||||
const imagesWithDates = parsedImages.map((img: any) => ({
|
||||
...img,
|
||||
timestamp: new Date(img.timestamp),
|
||||
}));
|
||||
setImages(imagesWithDates);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar histórico de imagens:', error);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
// Valida a descrição antes de enviar
|
||||
const validation = imageGenerationService.validateDescription(prompt);
|
||||
if (!validation.valid) {
|
||||
toast({
|
||||
title: "Descrição inválida",
|
||||
description: validation.error,
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const handleGenerate = () => {
|
||||
setIsGenerating(true);
|
||||
// Simulate image generation
|
||||
setTimeout(() => {
|
||||
const newImage: GeneratedImage = {
|
||||
id: Date.now().toString(),
|
||||
url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=512&h=512&fit=crop",
|
||||
prompt: prompt,
|
||||
|
||||
try {
|
||||
// Chama o serviço de geração de imagem
|
||||
const response = await imageGenerationService.generateImage({
|
||||
description: prompt,
|
||||
size: selectedSize,
|
||||
timestamp: "Agora",
|
||||
};
|
||||
setImages([newImage, ...images]);
|
||||
});
|
||||
|
||||
// Verifica se a geração foi bem-sucedida
|
||||
if (response.success) {
|
||||
// Log da URL da imagem para debug
|
||||
console.log('URL da imagem gerada:', response.image_url);
|
||||
|
||||
const newImage: GeneratedImage = {
|
||||
id: response.image_generation_id,
|
||||
url: response.image_url,
|
||||
prompt: response.message,
|
||||
size: selectedSize,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const newHistory = [newImage, ...images].slice(0, 20); // Mantém apenas as últimas 20 imagens
|
||||
setImages(newHistory);
|
||||
localStorage.setItem('imageHistory', JSON.stringify(newHistory));
|
||||
|
||||
toast({
|
||||
title: "Imagem gerada com sucesso",
|
||||
description: `Tamanho: ${IMAGE_SIZE_OPTIONS[selectedSize].label}`,
|
||||
});
|
||||
|
||||
// Limpa o campo de descrição após sucesso
|
||||
setPrompt("");
|
||||
} else {
|
||||
throw new Error('Erro ao gerar imagem');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro na geração de imagem:', error);
|
||||
|
||||
toast({
|
||||
title: "Erro na geração",
|
||||
description: error.message || "Não foi possível gerar a imagem. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
setPrompt("");
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = (id: string) => {
|
||||
setImages(images.filter((img) => img.id !== id));
|
||||
const newHistory = images.filter((img) => img.id !== id);
|
||||
setImages(newHistory);
|
||||
localStorage.setItem('imageHistory', JSON.stringify(newHistory));
|
||||
|
||||
toast({
|
||||
title: "Imagem removida",
|
||||
description: "A imagem foi removida do histórico.",
|
||||
});
|
||||
};
|
||||
|
||||
const handleDownload = async (image: GeneratedImage) => {
|
||||
try {
|
||||
await imageGenerationService.downloadImage(
|
||||
image.url,
|
||||
`${image.prompt.substring(0, 30)}_${image.size}.png`
|
||||
);
|
||||
|
||||
toast({
|
||||
title: "Download iniciado",
|
||||
description: "A imagem está sendo baixada.",
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Erro no download",
|
||||
description: "Não foi possível baixar a imagem.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const filteredImages = images.filter((img) =>
|
||||
@@ -107,14 +184,14 @@ export const ImageView = () => {
|
||||
<label className="text-sm font-medium text-foreground">
|
||||
Tamanho
|
||||
</label>
|
||||
<Select value={selectedSize} onValueChange={setSelectedSize}>
|
||||
<Select value={selectedSize} onValueChange={(value) => setSelectedSize(value as ImageSize)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="glass-effect bg-popover border-border z-50">
|
||||
<SelectItem value="1024x1024">1024x1024 (Quadrado)</SelectItem>
|
||||
<SelectItem value="1024x1536">1024x1536 (Retrato)</SelectItem>
|
||||
<SelectItem value="1536x1024">1536x1024 (Paisagem)</SelectItem>
|
||||
<SelectItem value="1024x1792">1024x1792 (Retrato)</SelectItem>
|
||||
<SelectItem value="1792x1024">1792x1024 (Paisagem)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -153,9 +230,10 @@ export const ImageView = () => {
|
||||
{!isGenerating && images.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-4">Última Geração</h3>
|
||||
<ImageCard
|
||||
image={images[0]}
|
||||
<ImageCard
|
||||
image={images[0]}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -178,10 +256,11 @@ export const ImageView = () => {
|
||||
{filteredImages.length > 0 ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredImages.map((image) => (
|
||||
<ImageCard
|
||||
key={image.id}
|
||||
<ImageCard
|
||||
key={image.id}
|
||||
image={image}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -205,29 +284,93 @@ export const ImageView = () => {
|
||||
interface ImageCardProps {
|
||||
image: GeneratedImage;
|
||||
onDelete: (id: string) => void;
|
||||
onDownload: (image: GeneratedImage) => void;
|
||||
}
|
||||
|
||||
const ImageCard = ({ image, onDelete }: ImageCardProps) => {
|
||||
const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [imageLoading, setImageLoading] = useState(true);
|
||||
|
||||
// Calcula tempo relativo
|
||||
const getRelativeTime = (timestamp: Date) => {
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - new Date(timestamp).getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
const hours = Math.floor(diff / 3600000);
|
||||
const days = Math.floor(diff / 86400000);
|
||||
|
||||
if (minutes < 1) return 'Agora';
|
||||
if (minutes < 60) return `Há ${minutes} ${minutes === 1 ? 'minuto' : 'minutos'}`;
|
||||
if (hours < 24) return `Há ${hours} ${hours === 1 ? 'hora' : 'horas'}`;
|
||||
return `Há ${days} ${days === 1 ? 'dia' : 'dias'}`;
|
||||
};
|
||||
|
||||
const handleImageError = () => {
|
||||
console.warn('Erro CORS ao carregar imagem:', image.url);
|
||||
setImageError(true);
|
||||
setImageLoading(false);
|
||||
};
|
||||
|
||||
const handleImageLoad = () => {
|
||||
console.log('Imagem carregada com sucesso:', image.url);
|
||||
setImageLoading(false);
|
||||
setImageError(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="group glass-effect rounded-xl overflow-hidden animate-fade-in">
|
||||
<div className="relative aspect-square">
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.prompt}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
{imageLoading && !imageError && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-muted">
|
||||
<div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{imageError ? (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center bg-muted text-muted-foreground p-4">
|
||||
<Sparkles className="w-12 h-12 mb-2 opacity-50" />
|
||||
<p className="text-sm text-center font-medium mb-1">Erro ao carregar</p>
|
||||
<p className="text-xs text-center mb-2">A imagem foi gerada, mas não pode ser exibida aqui</p>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<a
|
||||
href={image.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-center bg-primary text-primary-foreground px-3 py-2 rounded-md hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
Abrir imagem em nova aba
|
||||
</a>
|
||||
<button
|
||||
onClick={() => navigator.clipboard.writeText(image.url)}
|
||||
className="text-xs text-center bg-secondary text-secondary-foreground px-3 py-1 rounded-md hover:bg-secondary/80 transition-colors"
|
||||
>
|
||||
Copiar URL
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.prompt}
|
||||
className="w-full h-full object-cover"
|
||||
onError={handleImageError}
|
||||
onLoad={handleImageLoad}
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
)}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/0 to-black/0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div className="absolute bottom-0 left-0 right-0 p-4 space-y-2">
|
||||
<p className="text-sm text-white line-clamp-2">{image.prompt}</p>
|
||||
<div className="flex items-center justify-between text-xs text-white/70">
|
||||
<span>{image.size}</span>
|
||||
<span>{image.timestamp}</span>
|
||||
<span>{IMAGE_SIZE_OPTIONS[image.size].label}</span>
|
||||
<span>{getRelativeTime(image.timestamp)}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="flex-1 gap-1"
|
||||
onClick={() => onDownload(image)}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
Baixar
|
||||
|
||||
Reference in New Issue
Block a user