mirror of
https://github.com/lucasrcsantana/story-generator.git
synced 2025-12-18 22:37:51 +00:00
refactor: otimiza carregamento e visualização de imagens
- Implementa lazy loading e placeholders para imagens - Adiciona pré-carregamento da próxima imagem - Otimiza URLs de imagem com parâmetros de transformação - Padroniza visualização de cards de histórias - Ajusta estilos para consistência entre páginas - Implementa cache de imagens no frontend - Atualiza queries para usar story_pages como capa
This commit is contained in:
parent
92e4546ecf
commit
8475babb2c
35
CHANGELOG.md
35
CHANGELOG.md
@ -26,16 +26,33 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|||||||
- Relacionamentos explícitos entre histórias e páginas
|
- Relacionamentos explícitos entre histórias e páginas
|
||||||
- Suporte a ordenação por número da página
|
- Suporte a ordenação por número da página
|
||||||
|
|
||||||
|
- Otimização de carregamento de imagens
|
||||||
|
- Lazy loading com placeholders
|
||||||
|
- Pré-carregamento da próxima imagem
|
||||||
|
- Cache de imagens no frontend
|
||||||
|
- Transformações de imagem no Supabase Storage
|
||||||
|
- Múltiplas resoluções de imagem
|
||||||
|
|
||||||
|
- Sistema de cache de imagens no frontend
|
||||||
|
- Implementação de imageCache.ts
|
||||||
|
- Prevenção de recarregamento desnecessário
|
||||||
|
- Melhor performance em navegação
|
||||||
|
|
||||||
### Modificado
|
### Modificado
|
||||||
|
- Otimização de imagens de capa
|
||||||
|
- Uso da primeira página como capa
|
||||||
|
- Tamanho reduzido para thumbnails
|
||||||
|
- Carregamento lazy para melhor performance
|
||||||
|
|
||||||
|
- Padronização da interface de histórias
|
||||||
|
- Consistência visual entre dashboard e lista
|
||||||
|
- Cards de história com mesmo estilo e comportamento
|
||||||
|
- Melhor experiência do usuário na navegação
|
||||||
|
|
||||||
- Atualização do schema do banco para suportar novas categorias
|
- Atualização do schema do banco para suportar novas categorias
|
||||||
- Adição de tabelas para temas, disciplinas, personagens e cenários
|
- Adição de tabelas para temas, disciplinas, personagens e cenários
|
||||||
- Relacionamentos entre histórias e categorias
|
- Relacionamentos entre histórias e categorias
|
||||||
- Índices para otimização de consultas
|
- Índices para otimização de consultas
|
||||||
- Renomeado componente StoryPage para StoryPageDemo para melhor organização
|
|
||||||
- Separado visualização de histórias demo da visualização principal
|
|
||||||
- Migração de dados das páginas para nova estrutura
|
|
||||||
- Mantida compatibilidade com interface existente
|
|
||||||
- Melhor organização e tipagem dos dados
|
|
||||||
|
|
||||||
### Técnico
|
### Técnico
|
||||||
- Implementação de logs estruturados com prefixos por contexto
|
- Implementação de logs estruturados com prefixos por contexto
|
||||||
@ -45,6 +62,14 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|||||||
- Feedback em tempo real do processo de geração
|
- Feedback em tempo real do processo de geração
|
||||||
- Queries otimizadas para nova estrutura de dados
|
- Queries otimizadas para nova estrutura de dados
|
||||||
- Melhor tratamento de estados de loading e erro
|
- Melhor tratamento de estados de loading e erro
|
||||||
|
- Implementação de componente ImageWithLoading
|
||||||
|
- Sistema de cache de imagens
|
||||||
|
- Otimização de URLs de imagem
|
||||||
|
|
||||||
|
- Refatoração de componentes para melhor reuso
|
||||||
|
- Separação de lógica de carregamento de imagens
|
||||||
|
- Componentes mais modulares e reutilizáveis
|
||||||
|
- Melhor organização do código
|
||||||
|
|
||||||
### Segurança
|
### Segurança
|
||||||
- Validação de dados de entrada na edge function
|
- Validação de dados de entrada na edge function
|
||||||
|
|||||||
17
src/lib/imageCache.ts
Normal file
17
src/lib/imageCache.ts
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
const imageCache = new Map<string, string>();
|
||||||
|
|
||||||
|
export function cacheImage(url: string): Promise<string> {
|
||||||
|
if (imageCache.has(url)) {
|
||||||
|
return Promise.resolve(imageCache.get(url)!);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
img.src = url;
|
||||||
|
img.onload = () => {
|
||||||
|
imageCache.set(url, url);
|
||||||
|
resolve(url);
|
||||||
|
};
|
||||||
|
img.onerror = reject;
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,3 +1,260 @@
|
|||||||
export function StoryPageDemo({ demo = false }: StoryPageProps): JSX.Element {
|
import React from 'react';
|
||||||
// ... resto do código permanece igual ...
|
import { ArrowLeft, ArrowRight, Mic, Volume2, Share2 } from 'lucide-react';
|
||||||
|
import { AudioRecorder } from '../../components/story/AudioRecorder';
|
||||||
|
import { StoryMetrics } from '../../components/story/StoryMetrics';
|
||||||
|
import type { StoryRecording } from '../../types/database';
|
||||||
|
|
||||||
|
const demoRecording: StoryRecording = {
|
||||||
|
id: 'demo-recording',
|
||||||
|
fluency_score: 85,
|
||||||
|
pronunciation_score: 90,
|
||||||
|
accuracy_score: 88,
|
||||||
|
comprehension_score: 92,
|
||||||
|
words_per_minute: 120,
|
||||||
|
pause_count: 3,
|
||||||
|
error_count: 2,
|
||||||
|
self_corrections: 1,
|
||||||
|
strengths: [
|
||||||
|
'Ótima pronúncia das palavras',
|
||||||
|
'Boa velocidade de leitura',
|
||||||
|
'Excelente compreensão do texto'
|
||||||
|
],
|
||||||
|
improvements: [
|
||||||
|
'Reduzir pequenas pausas entre frases',
|
||||||
|
'Praticar palavras mais complexas'
|
||||||
|
],
|
||||||
|
suggestions: 'Continue praticando a leitura em voz alta regularmente',
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
processed_at: new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
const demoStory = {
|
||||||
|
id: 'demo',
|
||||||
|
student_id: 'demo',
|
||||||
|
title: 'Uma Aventura Educacional',
|
||||||
|
content: {
|
||||||
|
pages: [
|
||||||
|
{
|
||||||
|
text: 'Bem-vindo à demonstração do Histórias Mágicas! Aqui você pode ver como funciona nossa plataforma de leitura interativa...',
|
||||||
|
image: 'https://images.unsplash.com/photo-1472162072942-cd5147eb3902?auto=format&fit=crop&q=80&w=800&h=600',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Com histórias interativas e educativas, seus alunos aprenderão de forma divertida e envolvente. Cada história é uma nova aventura!',
|
||||||
|
image: 'https://images.unsplash.com/photo-1519681393784-d120267933ba?auto=format&fit=crop&q=80&w=800&h=600',
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
status: 'published',
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
updated_at: new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
function RecordingHistoryCard({ recording }: { recording: StoryRecording }) {
|
||||||
|
const [isExpanded, setIsExpanded] = React.useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
{new Date(recording.created_at).toLocaleDateString()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsExpanded(!isExpanded)}
|
||||||
|
className="text-gray-500 hover:text-gray-700"
|
||||||
|
>
|
||||||
|
{isExpanded ? 'Menos detalhes' : 'Mais detalhes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isExpanded && (
|
||||||
|
<div>
|
||||||
|
<div className="grid grid-cols-2 gap-4 mt-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Palavras por minuto:</span>
|
||||||
|
<span className="ml-2 font-medium">{recording.words_per_minute}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Pausas:</span>
|
||||||
|
<span className="ml-2 font-medium">{recording.pause_count}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Erros:</span>
|
||||||
|
<span className="ml-2 font-medium">{recording.error_count}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Autocorreções:</span>
|
||||||
|
<span className="ml-2 font-medium">{recording.self_corrections}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
<div>
|
||||||
|
<h5 className="text-sm font-medium text-green-600 mb-1">Pontos Fortes</h5>
|
||||||
|
<ul className="list-disc list-inside text-sm text-gray-600">
|
||||||
|
{recording.strengths.map((strength, i) => (
|
||||||
|
<li key={i}>{strength}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h5 className="text-sm font-medium text-orange-600 mb-1">Pontos para Melhorar</h5>
|
||||||
|
<ul className="list-disc list-inside text-sm text-gray-600">
|
||||||
|
{recording.improvements.map((improvement, i) => (
|
||||||
|
<li key={i}>{improvement}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h5 className="text-sm font-medium text-blue-600 mb-1">Sugestões</h5>
|
||||||
|
<p className="text-sm text-gray-600">{recording.suggestions}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StoryPageDemo(): JSX.Element {
|
||||||
|
const [currentPage, setCurrentPage] = React.useState(0);
|
||||||
|
const [isPlaying, setIsPlaying] = React.useState(false);
|
||||||
|
const [recordings] = React.useState([demoRecording]);
|
||||||
|
|
||||||
|
const metricsData = {
|
||||||
|
metrics: {
|
||||||
|
fluency: demoRecording.fluency_score,
|
||||||
|
pronunciation: demoRecording.pronunciation_score,
|
||||||
|
accuracy: demoRecording.accuracy_score,
|
||||||
|
comprehension: demoRecording.comprehension_score
|
||||||
|
},
|
||||||
|
feedback: {
|
||||||
|
strengths: demoRecording.strengths,
|
||||||
|
improvements: demoRecording.improvements,
|
||||||
|
suggestions: demoRecording.suggestions
|
||||||
|
},
|
||||||
|
details: {
|
||||||
|
wordsPerMinute: demoRecording.words_per_minute,
|
||||||
|
pauseCount: demoRecording.pause_count,
|
||||||
|
errorCount: demoRecording.error_count,
|
||||||
|
selfCorrections: demoRecording.self_corrections
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleShare = () => {
|
||||||
|
alert('Funcionalidade de compartilhamento disponível apenas na versão completa!');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gradient-to-b from-purple-50 to-white py-12">
|
||||||
|
<div className="max-w-4xl mx-auto px-4">
|
||||||
|
<div className="flex justify-between items-center mb-6">
|
||||||
|
<button
|
||||||
|
onClick={() => window.history.back()}
|
||||||
|
className="flex items-center gap-2 text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
Voltar
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
onClick={handleShare}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<Share2 className="h-5 w-5" />
|
||||||
|
Compartilhar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsPlaying(!isPlaying)}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<Volume2 className="h-5 w-5" />
|
||||||
|
{isPlaying ? 'Pausar' : 'Ouvir'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Dashboard de métricas */}
|
||||||
|
{recordings.length > 0 && (
|
||||||
|
<StoryMetrics
|
||||||
|
data={metricsData}
|
||||||
|
isLoading={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Histórico de gravações */}
|
||||||
|
{recordings.length > 0 && (
|
||||||
|
<div className="mb-6">
|
||||||
|
<h3 className="text-lg font-medium mb-4">Histórico de Gravações</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{recordings.map((recording) => (
|
||||||
|
<RecordingHistoryCard
|
||||||
|
key={recording.id}
|
||||||
|
recording={recording}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
|
||||||
|
{/* Imagem da página atual */}
|
||||||
|
<div className="relative aspect-video">
|
||||||
|
<img
|
||||||
|
src={demoStory.content.pages[currentPage].image}
|
||||||
|
alt={`Página ${currentPage + 1}`}
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-6">
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900 mb-4">{demoStory.title}</h1>
|
||||||
|
|
||||||
|
{/* Texto da página atual */}
|
||||||
|
<p className="text-lg text-gray-700 mb-8">
|
||||||
|
{demoStory.content.pages[currentPage].text}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Gravador de áudio */}
|
||||||
|
<AudioRecorder
|
||||||
|
storyId={demoStory.id}
|
||||||
|
studentId={demoStory.student_id}
|
||||||
|
onAudioUploaded={() => {
|
||||||
|
alert('Gravação disponível apenas na versão completa!');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Navegação entre páginas */}
|
||||||
|
<div className="flex justify-between items-center mt-8 pt-6 border-t border-gray-200">
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage(prev => Math.max(0, prev - 1))}
|
||||||
|
disabled={currentPage === 0}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
Anterior
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
Página {currentPage + 1} de {demoStory.content.pages.length}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage(prev => Math.min(demoStory.content.pages.length - 1, prev + 1))}
|
||||||
|
disabled={currentPage === demoStory.content.pages.length - 1}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Próxima
|
||||||
|
<ArrowRight className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@ -1,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { ArrowLeft, ArrowRight, Mic, Volume2, Share2, Save, ChevronDown, ChevronUp } from 'lucide-react';
|
import { ArrowLeft, ArrowRight, Mic, Volume2, Share2, Save, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
import { supabase } from '../../lib/supabase';
|
import { supabase } from '../../lib/supabase';
|
||||||
import { AudioRecorder } from '../../components/story/AudioRecorder';
|
import { AudioRecorder } from '../../components/story/AudioRecorder';
|
||||||
@ -125,6 +125,39 @@ function RecordingHistoryCard({ recording }: { recording: StoryRecording }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ImageWithLoading({ src, alt, className }: { src: string; alt: string; className?: string }) {
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative aspect-video bg-gray-100">
|
||||||
|
{isLoading && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center">
|
||||||
|
<Loader2 className="w-8 h-8 text-purple-600 animate-spin" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt={alt}
|
||||||
|
loading="lazy"
|
||||||
|
className={`w-full h-full object-cover transition-opacity duration-300 ${
|
||||||
|
isLoading ? 'opacity-0' : 'opacity-100'
|
||||||
|
} ${className}`}
|
||||||
|
onLoad={() => setIsLoading(false)}
|
||||||
|
onError={() => {
|
||||||
|
setError(true);
|
||||||
|
setIsLoading(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{error && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-gray-100">
|
||||||
|
<p className="text-gray-500">Erro ao carregar imagem</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function StoryPage() {
|
export function StoryPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
@ -266,6 +299,14 @@ export function StoryPage() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Pré-carregar próxima imagem
|
||||||
|
useEffect(() => {
|
||||||
|
if (story?.content?.pages?.[currentPage + 1]?.image) {
|
||||||
|
const nextImage = new Image();
|
||||||
|
nextImage.src = story.content.pages[currentPage + 1].image;
|
||||||
|
}
|
||||||
|
}, [currentPage, story]);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="animate-pulse">
|
<div className="animate-pulse">
|
||||||
@ -355,13 +396,11 @@ export function StoryPage() {
|
|||||||
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
|
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
|
||||||
{/* Imagem da página atual */}
|
{/* Imagem da página atual */}
|
||||||
{story?.content?.pages?.[currentPage]?.image && (
|
{story?.content?.pages?.[currentPage]?.image && (
|
||||||
<div className="relative aspect-video">
|
<ImageWithLoading
|
||||||
<img
|
src={story.content.pages[currentPage].image}
|
||||||
src={story.content.pages[currentPage].image}
|
alt={`Página ${currentPage + 1}`}
|
||||||
alt={`Página ${currentPage + 1}`}
|
className="w-full h-full object-cover"
|
||||||
className="w-full h-full object-cover"
|
/>
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
|
|||||||
@ -23,6 +23,7 @@ export function StudentDashboardPage() {
|
|||||||
});
|
});
|
||||||
const [loading, setLoading] = React.useState(true);
|
const [loading, setLoading] = React.useState(true);
|
||||||
const [error, setError] = React.useState<string | null>(null);
|
const [error, setError] = React.useState<string | null>(null);
|
||||||
|
const [recentStories, setRecentStories] = React.useState<Story[]>([]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const fetchDashboardData = async () => {
|
const fetchDashboardData = async () => {
|
||||||
@ -64,6 +65,23 @@ export function StudentDashboardPage() {
|
|||||||
currentLevel: 3 // Exemplo
|
currentLevel: 3 // Exemplo
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Buscar histórias recentes
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('stories')
|
||||||
|
.select(`
|
||||||
|
*,
|
||||||
|
cover:story_pages!inner(
|
||||||
|
image_url
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
.eq('student_id', session.user.id)
|
||||||
|
.eq('story_pages.page_number', 1)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.limit(3);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
setRecentStories(data || []);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Erro ao carregar dashboard:', err);
|
console.error('Erro ao carregar dashboard:', err);
|
||||||
setError('Não foi possível carregar seus dados');
|
setError('Não foi possível carregar seus dados');
|
||||||
@ -197,16 +215,16 @@ export function StudentDashboardPage() {
|
|||||||
{/* Histórias Recentes */}
|
{/* Histórias Recentes */}
|
||||||
<div>
|
<div>
|
||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-center mb-6">
|
||||||
<h2 className="text-xl font-bold text-gray-900">Histórias Recentes</h2>
|
<h2 className="text-2xl font-bold text-gray-900">Histórias Recentes</h2>
|
||||||
<button
|
<button
|
||||||
onClick={() => navigate('/aluno/historias')}
|
onClick={() => navigate('/aluno/historias')}
|
||||||
className="text-purple-600 hover:text-purple-700"
|
className="flex items-center gap-2 text-purple-600 hover:text-purple-700"
|
||||||
>
|
>
|
||||||
Ver todas
|
Ver todas
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{stories.length === 0 ? (
|
{recentStories.length === 0 ? (
|
||||||
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
|
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
|
||||||
<BookOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
<BookOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||||
<h3 className="text-lg font-medium text-gray-900 mb-2">
|
<h3 className="text-lg font-medium text-gray-900 mb-2">
|
||||||
@ -225,18 +243,21 @@ export function StudentDashboardPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
{stories.map((story) => (
|
{recentStories.map((story) => (
|
||||||
<div
|
<div
|
||||||
key={story.id}
|
key={story.id}
|
||||||
className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
|
className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
|
||||||
onClick={() => navigate(`/aluno/historias/${story.id}`)}
|
onClick={() => navigate(`/aluno/historias/${story.id}`)}
|
||||||
>
|
>
|
||||||
{story.content?.pages?.[0]?.image && (
|
{story.cover && (
|
||||||
<img
|
<div className="relative aspect-video">
|
||||||
src={story.content.pages[0].image}
|
<img
|
||||||
alt={story.title}
|
src={`${story.cover.image_url}?width=400&quality=80&format=webp`}
|
||||||
className="w-full h-48 object-cover"
|
alt={story.title}
|
||||||
/>
|
className="w-full h-48 object-cover"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<h3 className="font-medium text-gray-900 mb-2">{story.title}</h3>
|
<h3 className="font-medium text-gray-900 mb-2">{story.title}</h3>
|
||||||
|
|||||||
@ -23,35 +23,22 @@ export function StudentStoriesPage() {
|
|||||||
const { data: { session } } = await supabase.auth.getSession();
|
const { data: { session } } = await supabase.auth.getSession();
|
||||||
if (!session?.user?.id) return;
|
if (!session?.user?.id) return;
|
||||||
|
|
||||||
const query = supabase
|
const { data, error } = await supabase
|
||||||
.from('stories')
|
.from('stories')
|
||||||
.select('*')
|
.select(`
|
||||||
.eq('student_id', session.user.id);
|
*,
|
||||||
|
cover:story_pages!inner(
|
||||||
|
image_url
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
.eq('student_id', session.user.id)
|
||||||
|
.eq('story_pages.page_number', 1)
|
||||||
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
if (statusFilter !== 'all') {
|
|
||||||
query.eq('status', statusFilter);
|
|
||||||
}
|
|
||||||
|
|
||||||
let { data, error } = await query;
|
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
|
setStories(data || []);
|
||||||
// Aplicar ordenação
|
|
||||||
const sortedData = (data || []).sort((a, b) => {
|
|
||||||
switch (sortBy) {
|
|
||||||
case 'oldest':
|
|
||||||
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
|
|
||||||
case 'title':
|
|
||||||
return a.title.localeCompare(b.title);
|
|
||||||
case 'performance':
|
|
||||||
return (b.performance_score || 0) - (a.performance_score || 0);
|
|
||||||
default: // recent
|
|
||||||
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setStories(sortedData);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Erro ao buscar histórias:', err);
|
console.error('Erro ao carregar histórias:', err);
|
||||||
setError('Não foi possível carregar suas histórias');
|
setError('Não foi possível carregar suas histórias');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@ -59,7 +46,7 @@ export function StudentStoriesPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
fetchStories();
|
fetchStories();
|
||||||
}, [statusFilter, sortBy]);
|
}, []);
|
||||||
|
|
||||||
const filteredStories = stories.filter(story =>
|
const filteredStories = stories.filter(story =>
|
||||||
story.title.toLowerCase().includes(searchTerm.toLowerCase())
|
story.title.toLowerCase().includes(searchTerm.toLowerCase())
|
||||||
@ -197,12 +184,15 @@ export function StudentStoriesPage() {
|
|||||||
className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
|
className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
|
||||||
onClick={() => navigate(`/aluno/historias/${story.id}`)}
|
onClick={() => navigate(`/aluno/historias/${story.id}`)}
|
||||||
>
|
>
|
||||||
{story.content?.pages?.[0]?.image && (
|
{story.cover && (
|
||||||
<img
|
<div className="relative aspect-video bg-gray-100">
|
||||||
src={story.content.pages[0].image}
|
<img
|
||||||
alt={story.title}
|
src={`${story.cover.image_url}?width=400&quality=80&format=webp`}
|
||||||
className="w-full h-48 object-cover"
|
alt={story.title}
|
||||||
/>
|
className="w-full h-48 object-cover"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<h3 className="font-medium text-gray-900 mb-2">{story.title}</h3>
|
<h3 className="font-medium text-gray-900 mb-2">{story.title}</h3>
|
||||||
|
|||||||
@ -125,7 +125,7 @@ export const router = createBrowserRouter([
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/demo',
|
path: '/demo',
|
||||||
element: <StoryPageDemo />,
|
element: <StoryPageDemo />
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/auth/callback',
|
path: '/auth/callback',
|
||||||
|
|||||||
@ -20,6 +20,15 @@ const ALLOWED_ORIGINS = [
|
|||||||
'https://historiasmagicas.netlify.app' // Produção
|
'https://historiasmagicas.netlify.app' // Produção
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Função para otimizar URL da imagem
|
||||||
|
function getOptimizedImageUrl(originalUrl: string, width = 800): string {
|
||||||
|
// Se já for uma URL do Supabase Storage, adicionar transformações
|
||||||
|
if (originalUrl.includes('storage.googleapis.com')) {
|
||||||
|
return `${originalUrl}?width=${width}&quality=80&format=webp`;
|
||||||
|
}
|
||||||
|
return originalUrl;
|
||||||
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
serve(async (req) => {
|
||||||
const origin = req.headers.get('origin') || '';
|
const origin = req.headers.get('origin') || '';
|
||||||
const corsHeaders = {
|
const corsHeaders = {
|
||||||
@ -179,9 +188,12 @@ serve(async (req) => {
|
|||||||
|
|
||||||
console.log(`[Storage] Imagem ${index + 1} salva com sucesso`)
|
console.log(`[Storage] Imagem ${index + 1} salva com sucesso`)
|
||||||
|
|
||||||
|
// Otimizar URL antes de salvar
|
||||||
|
const optimizedUrl = getOptimizedImageUrl(imageResponse.data[0].url);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
text: page.text,
|
text: page.text,
|
||||||
image: publicUrl.publicUrl,
|
image: optimizedUrl,
|
||||||
image_path: fileName
|
image_path: fileName
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user