feat: enhance chat UI and functionality with new scrollbar and animation features

- Added custom scrollbar styles for sources display to improve aesthetics and usability.
- Introduced animations for reasoning steps to enhance user experience during chat interactions.
- Refactored chat page to group thinking messages, improving message handling and display.
- Updated sources display component for better favicon handling and user interaction.
This commit is contained in:
Evandro Fonseca Junior committed 2025-11-27 16:57:50 -03:00
1 parent e5f062040c
commit f2e8a1b933
6 files changed
+453 -189

No files matched your search

+99 -66
View File
@@ -9,6 +9,7 @@ import { MessageSquare, Settings, Server, Moon, Sun, PanelLeftClose, PanelLeftOp
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ChatInput } from "@/components/chat/chat-input"; import { ChatInput } from "@/components/chat/chat-input";
import { ChatMessage } from "@/components/chat/chat-message"; import { ChatMessage } from "@/components/chat/chat-message";
import { ReasoningChain } from "@/components/chat/reasoning-chain";
import { SidebarList } from "@/components/chat/sidebar-list"; import { SidebarList } from "@/components/chat/sidebar-list";
import { useChat } from "@/hooks/use-chat"; import { useChat } from "@/hooks/use-chat";
@@ -122,8 +123,7 @@ export default function ChatPage() {
// Initialize with default format prompt // Initialize with default format prompt
const [systemPrompt, setSystemPrompt] = useState(defaultFormatPrompt || "Você é um assistente útil e prestativo."); const [systemPrompt, setSystemPrompt] = useState(defaultFormatPrompt || "Você é um assistente útil e prestativo.");
const [isChatsSidebarCollapsed, setIsChatsSidebarCollapsed] = useState(true); // Iniciar colapsada const [isChatsSidebarCollapsed, setIsChatsSidebarCollapsed] = useState(true); // Iniciar colapsada
const [thinkingStep, setThinkingStep] = useState<ThinkingStep | null>(null); // Removido: thinkingStep e processSteps - agora usando mensagens thinking agrupadas
const [processSteps, setProcessSteps] = useState<ProcessStep[]>([]);
const [error, setError] = useState<string | Error | null>(null); const [error, setError] = useState<string | Error | null>(null);
const chatsSidebarRef = useRef<ImperativePanelHandle>(null); const chatsSidebarRef = useRef<ImperativePanelHandle>(null);
@@ -266,10 +266,7 @@ export default function ChatPage() {
// Adicionar mensagem de processo: Pré-processamento // Adicionar mensagem de processo: Pré-processamento
addThinkingMessage('preprocessing', 'Pré-processamento', 'running'); addThinkingMessage('preprocessing', 'Pré-processamento', 'running');
// Resetar e inicializar steps do processo (para compatibilidade com componentes antigos) // Removido: setProcessSteps - agora usando mensagens thinking agrupadas
setProcessSteps([
{ id: 'preprocessing', label: 'Pré-processamento', status: 'running', timestamp: Date.now() },
]);
// Limpar erros anteriores // Limpar erros anteriores
setError(null); setError(null);
@@ -305,11 +302,7 @@ export default function ChatPage() {
duration: Date.now() - preprocessingStart, duration: Date.now() - preprocessingStart,
}); });
setProcessSteps(prev => prev.map(s => // Removido: setProcessSteps - agora usando mensagens thinking agrupadas
s.id === 'preprocessing'
? { ...s, status: 'error' as const, error: errorMessage }
: s
));
// Definir erro global // Definir erro global
setError(error); setError(error);
@@ -369,14 +362,12 @@ export default function ChatPage() {
// Passo 1: Decomposição // Passo 1: Decomposição
chatLog.info('Step 1: Decomposition'); chatLog.info('Step 1: Decomposition');
setThinkingStep('planning');
const searchPlan = await deepResearch.decompose(content, selectedModel); const searchPlan = await deepResearch.decompose(content, selectedModel);
chatLog.info(`Search Plan: ${JSON.stringify(searchPlan)}`); chatLog.info(`Search Plan: ${JSON.stringify(searchPlan)}`);
if (searchPlan && searchPlan.length > 0) { if (searchPlan && searchPlan.length > 0) {
// Passo 2: Executar buscas com fallback progressivo // Passo 2: Executar buscas com fallback progressivo
chatLog.info(`\nStep 2: Executing ${searchPlan.length} searches with progressive fallback`); chatLog.info(`\nStep 2: Executing ${searchPlan.length} searches with progressive fallback`);
setThinkingStep('searching');
// Atualizar progresso: decomposição concluída // Atualizar progresso: decomposição concluída
updateThinkingMessage('web-research', { updateThinkingMessage('web-research', {
@@ -567,13 +558,11 @@ export default function ChatPage() {
} else { } else {
// Fallback para busca simples // Fallback para busca simples
chatLog.info('Decomposition returned empty, falling back to simple search'); chatLog.info('Decomposition returned empty, falling back to simple search');
setThinkingStep('searching');
const simpleQuery = await generateQuery(content, selectedModel); const simpleQuery = await generateQuery(content, selectedModel);
chatLog.info(`Simple query generated: "${simpleQuery}"`); chatLog.info(`Simple query generated: "${simpleQuery}"`);
if (simpleQuery && simpleQuery !== 'NO_SEARCH') { if (simpleQuery && simpleQuery !== 'NO_SEARCH') {
const results = await webSearch.smartSearchRag(simpleQuery, settings.webSearch.maxResults); const results = await webSearch.smartSearchRag(simpleQuery, settings.webSearch.maxResults);
chatLog.info(`Simple search results: ${results.length}`); chatLog.info(`Simple search results: ${results.length}`);
setThinkingStep('reading');
if (results.length > 0) { if (results.length > 0) {
deepResearch.addToKnowledgeBase(simpleQuery, results); deepResearch.addToKnowledgeBase(simpleQuery, results);
knowledgeBaseContext = deepResearch.getCuratedContext(); knowledgeBaseContext = deepResearch.getCuratedContext();
@@ -617,16 +606,7 @@ export default function ChatPage() {
}; };
// ========== LÓGICA DE DEEP RESEARCH (Knowledge Base Aggregation) ========== // ========== LÓGICA DE DEEP RESEARCH (Knowledge Base Aggregation) ==========
// Iniciar indicador de pensamento // Removido: setThinkingStep e setProcessSteps - agora usando mensagens thinking agrupadas
setThinkingStep('analyzing');
// Adicionar step de pesquisa web se necessário
if (webSearch.isEnabled && preprocessed.shouldSearch) {
setProcessSteps(prev => [
...prev,
{ id: 'web-research', label: 'Pesquisa Web', status: 'running', timestamp: Date.now() },
]);
}
const researchStart = Date.now(); const researchStart = Date.now();
// Executar pesquisa web // Executar pesquisa web
@@ -635,24 +615,9 @@ export default function ChatPage() {
preprocessed preprocessed
); );
// Atualizar step de pesquisa web
if (webSearch.isEnabled && preprocessed.shouldSearch) {
setProcessSteps(prev => prev.map(s =>
s.id === 'web-research'
? { ...s, status: 'completed' as const, duration: Date.now() - researchStart }
: s
));
}
// Passo 5: Formular resposta // Passo 5: Formular resposta
chatLog.info('\nStep 5: Formulating Response'); chatLog.info('\nStep 5: Formulating Response');
setThinkingStep('formulating'); // Removido: setThinkingStep e setProcessSteps - agora usando mensagens thinking agrupadas
// Adicionar step de geração de resposta
setProcessSteps(prev => [
...prev,
{ id: 'response-generation', label: 'Geração de Resposta', status: 'running', timestamp: Date.now() },
]);
// ========== MONTAR SYSTEM PROMPT COM CONTEXTO TEMPORAL E VALIDAÇÃO ========== // ========== MONTAR SYSTEM PROMPT COM CONTEXTO TEMPORAL E VALIDAÇÃO ==========
// Usar timezone do sistema do usuário (não fixo) // Usar timezone do sistema do usuário (não fixo)
@@ -793,12 +758,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
duration: Date.now() - responseStart, duration: Date.now() - responseStart,
}); });
// Atualizar step de geração de resposta quando streaming completar (para compatibilidade) // Removido: setProcessSteps - agora usando mensagens thinking agrupadas
setProcessSteps(prev => prev.map(s =>
s.id === 'response-generation'
? { ...s, status: 'completed' as const, duration: Date.now() - responseStart }
: s
));
chatLog.info('✅ Response generation complete'); chatLog.info('✅ Response generation complete');
chatLog.info('========== QUERY COMPLETE ==========\n'); chatLog.info('========== QUERY COMPLETE ==========\n');
@@ -831,8 +791,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
}); });
} }
// Marcar como completo quando começar a streamar // Removido: setThinkingStep - agora usando mensagens thinking agrupadas
setTimeout(() => setThinkingStep('complete'), 100);
}; };
const handleSelectSession = async (id: string) => { const handleSelectSession = async (id: string) => {
@@ -1102,24 +1061,98 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
</div> </div>
) : ( ) : (
<div className="flex flex-col gap-4 sm:gap-6"> <div className="flex flex-col gap-4 sm:gap-6">
{messages.map((msg, i) => { {(() => {
const isLastMessage = i === messages.length - (isLoading ? 1 : 0); // Ajuste simples // Agrupar mensagens thinking consecutivas
// Streaming logica mantida simples const groupedMessages: Array<{
const isAssistantStreaming = i === messages.length - 1 && msg.role === 'assistant' && isLoading; type: 'thinking-group' | 'regular';
messages?: Message[];
thinkingSteps?: ThinkingMessageMetadata[];
searchQueries?: string[];
index?: number;
message?: Message;
isStreaming?: boolean;
}> = [];
return ( let currentThinkingGroup: ThinkingMessageMetadata[] = [];
<div key={i} className="animate-in fade-in slide-in-from-bottom-4 duration-500"> let currentSearchQueries: string[] = [];
<ChatMessage message={msg} isStreaming={isAssistantStreaming} />
</div> for (let i = 0; i < messages.length; i++) {
); const msg = messages[i];
})} const isThinkingMessage = msg.metadata &&
typeof msg.metadata === 'object' &&
{isLoading && ( 'type' in msg.metadata &&
<div className="px-4 py-2 text-sm text-muted-foreground animate-pulse flex items-center gap-2"> msg.metadata.type === 'thinking';
<div className="w-2 h-2 bg-primary/50 rounded-full animate-bounce" />
<span>Pensando...</span> if (isThinkingMessage) {
</div> const thinkingMeta = msg.metadata as ThinkingMessageMetadata;
)} currentThinkingGroup.push(thinkingMeta);
// Extrair queries de busca dos detalhes
if (thinkingMeta.details && thinkingMeta.stepType === 'web-research') {
const queryMatch = thinkingMeta.details.match(/Buscando consulta \d+\/\d+: "([^"]+)"/);
if (queryMatch && queryMatch[1]) {
if (!currentSearchQueries.includes(queryMatch[1])) {
currentSearchQueries.push(queryMatch[1]);
}
}
}
} else {
// Se havia um grupo thinking, adicionar antes desta mensagem
if (currentThinkingGroup.length > 0) {
groupedMessages.push({
type: 'thinking-group',
thinkingSteps: [...currentThinkingGroup],
searchQueries: [...currentSearchQueries],
});
currentThinkingGroup = [];
currentSearchQueries = [];
}
// Adicionar mensagem regular
const isLastMessage = i === messages.length - (isLoading ? 1 : 0);
const isAssistantStreaming = i === messages.length - 1 && msg.role === 'assistant' && isLoading;
groupedMessages.push({
type: 'regular',
message: msg,
index: i,
isStreaming: isAssistantStreaming,
});
}
}
// Adicionar grupo thinking final se houver
if (currentThinkingGroup.length > 0) {
groupedMessages.push({
type: 'thinking-group',
thinkingSteps: currentThinkingGroup,
searchQueries: currentSearchQueries,
});
}
return groupedMessages.map((group, idx) => {
if (group.type === 'thinking-group' && group.thinkingSteps) {
return (
<div key={`thinking-${idx}`} className="animate-in fade-in slide-in-from-bottom-4 duration-500">
<ReasoningChain
steps={group.thinkingSteps}
searchQueries={group.searchQueries}
/>
</div>
);
} else if (group.type === 'regular' && group.message) {
return (
<div key={group.index || idx} className="animate-in fade-in slide-in-from-bottom-4 duration-500">
<ChatMessage
message={group.message}
isStreaming={group.isStreaming}
/>
</div>
);
}
return null;
});
})()}
</div> </div>
)} )}
+59 -1
View File
@@ -296,4 +296,62 @@
.sidebar-chat-list { .sidebar-chat-list {
scrollbar-width: thin; scrollbar-width: thin;
scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent; scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent;
} }
/* Minimalista scrollbar para sources */
.sources-scrollbar {
scrollbar-width: thin;
scrollbar-color: hsl(var(--muted-foreground) / 0.2) transparent;
}
.sources-scrollbar::-webkit-scrollbar {
height: 4px;
}
.sources-scrollbar::-webkit-scrollbar-track {
background: transparent;
border-radius: 2px;
}
.sources-scrollbar::-webkit-scrollbar-thumb {
background: hsl(var(--muted-foreground) / 0.2);
border-radius: 2px;
transition: background 0.2s ease;
}
.sources-scrollbar::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.35);
}
/* Ocultar scrollbar quando não há overflow */
.sources-scrollbar:not(:hover)::-webkit-scrollbar-thumb {
background: transparent;
}
/* Reasoning Chain animations */
@keyframes reasoning-fade-in {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.reasoning-step {
animation: reasoning-fade-in 0.3s ease-out forwards;
opacity: 0;
}
/* Staggered reveal para steps */
.reasoning-step:nth-child(1) { animation-delay: 0ms; }
.reasoning-step:nth-child(2) { animation-delay: 100ms; }
.reasoning-step:nth-child(3) { animation-delay: 200ms; }
.reasoning-step:nth-child(4) { animation-delay: 300ms; }
.reasoning-step:nth-child(5) { animation-delay: 400ms; }
.reasoning-step:nth-child(6) { animation-delay: 500ms; }
.reasoning-step:nth-child(7) { animation-delay: 600ms; }
.reasoning-step:nth-child(8) { animation-delay: 700ms; }
.reasoning-step:nth-child(n+9) { animation-delay: 800ms; }
+26 -64
View File
@@ -27,65 +27,27 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
const [isExpanded, setIsExpanded] = useState(false); const [isExpanded, setIsExpanded] = useState(false);
const [copiedIndex, setCopiedIndex] = useState<number | null>(null); const [copiedIndex, setCopiedIndex] = useState<number | null>(null);
const getStepConfig = () => {
switch (metadata.stepType) {
case 'preprocessing':
return {
icon: Brain,
textColor: "text-blue-600 dark:text-blue-400",
bgColor: "bg-blue-50 dark:bg-blue-900/20",
};
case 'web-research':
return {
icon: Globe,
textColor: "text-green-600 dark:text-green-400",
bgColor: "bg-green-50 dark:bg-green-900/20",
};
case 'sources-found':
return {
icon: Package,
textColor: "text-purple-600 dark:text-purple-400",
bgColor: "bg-purple-50 dark:bg-purple-900/20",
};
case 'processing':
return {
icon: Brain,
textColor: "text-indigo-600 dark:text-indigo-400",
bgColor: "bg-indigo-50 dark:bg-indigo-900/20",
};
case 'response-generation':
return {
icon: Loader2,
textColor: "text-orange-600 dark:text-orange-400",
bgColor: "bg-orange-50 dark:bg-orange-900/20",
};
case 'fallback':
return {
icon: AlertCircle,
textColor: "text-yellow-600 dark:text-yellow-400",
bgColor: "bg-yellow-50 dark:bg-yellow-900/20",
};
case 'error':
return {
icon: XCircle,
textColor: "text-red-600 dark:text-red-400",
bgColor: "bg-red-50 dark:bg-red-900/20",
};
default:
return {
icon: Search,
textColor: "text-muted-foreground",
bgColor: "bg-muted/30",
};
}
};
const getStepIcon = () => { const getStepIcon = () => {
const config = getStepConfig();
const Icon = config.icon;
const isSpinning = metadata.stepType === 'response-generation' && metadata.status === 'running'; const isSpinning = metadata.stepType === 'response-generation' && metadata.status === 'running';
return <Icon className={cn("w-4 h-4", config.textColor, isSpinning && "animate-spin")} />; switch (metadata.stepType) {
case 'preprocessing':
return <Brain className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
case 'web-research':
return <Globe className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
case 'sources-found':
return <Package className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
case 'processing':
return <Brain className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
case 'response-generation':
return <Loader2 className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
case 'fallback':
return <AlertCircle className="w-4 h-4 text-muted-foreground/80" />;
case 'error':
return <XCircle className="w-4 h-4 text-destructive/80" />;
default:
return <Search className="w-4 h-4 text-muted-foreground/80" />;
}
}; };
const copyToClipboard = async (url: string, index: number) => { const copyToClipboard = async (url: string, index: number) => {
@@ -98,17 +60,17 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
} }
}; };
const config = getStepConfig();
return ( return (
<div className="mb-4 ml-10 animate-in fade-in slide-in-from-bottom-2 duration-300"> <div className="mb-4 ml-10 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div className={cn( <div className="flex items-center gap-3 p-2 transition-all w-fit max-w-full">
"flex items-center gap-3 p-2 rounded-lg transition-all w-fit max-w-full",
config.bgColor
)}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{getStepIcon()} {getStepIcon()}
<span className={cn("text-sm font-medium", config.textColor)}> <span className={cn(
"text-sm font-medium",
metadata.status === 'error'
? "text-destructive/80"
: "text-muted-foreground/80"
)}>
{metadata.label} {metadata.label}
</span> </span>
</div> </div>
@@ -135,7 +97,7 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
{metadata.progress !== undefined && metadata.progress < 100 && ( {metadata.progress !== undefined && metadata.progress < 100 && (
<div className="ml-1 mt-1 w-32 h-1 bg-muted/50 rounded-full overflow-hidden"> <div className="ml-1 mt-1 w-32 h-1 bg-muted/50 rounded-full overflow-hidden">
<div <div
className={cn("h-full transition-all duration-300", config.textColor.replace('text-', 'bg-'))} className="h-full bg-primary/50 transition-all duration-300"
style={{ width: `${metadata.progress}%` }} style={{ width: `${metadata.progress}%` }}
/> />
</div> </div>
+134
View File
@@ -0,0 +1,134 @@
'use client';
import {
Loader2,
CheckCircle2,
Circle,
Search,
Globe,
Brain,
Package,
BookOpen
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ThinkingMessageMetadata } from '@/hooks/use-chat';
import { SourcesCompact } from './sources-compact';
interface ReasoningChainProps {
steps: ThinkingMessageMetadata[];
searchQueries?: string[];
className?: string;
}
export function ReasoningChain({ steps, searchQueries = [], className }: ReasoningChainProps) {
const hasActiveStep = steps.some(step => step.status === 'running');
const allSources = steps
.flatMap(step => step.sources || [])
.filter((source, index, self) =>
index === self.findIndex(s => s.url === source.url)
);
const getStepIcon = (step: ThinkingMessageMetadata) => {
const isRunning = step.status === 'running';
const isCompleted = step.status === 'completed';
const isError = step.status === 'error';
if (isError) {
return null; // Não mostrar ícone para erros, apenas texto
}
if (isCompleted) {
return <CheckCircle2 className="w-3.5 h-3.5 text-muted-foreground/60" />;
}
if (isRunning) {
return <Loader2 className="w-3.5 h-3.5 text-muted-foreground/60 animate-spin" />;
}
// Ícone baseado no tipo de step
switch (step.stepType) {
case 'preprocessing':
return <Brain className="w-3.5 h-3.5 text-muted-foreground/60" />;
case 'web-research':
return <Search className="w-3.5 h-3.5 text-muted-foreground/60" />;
case 'sources-found':
return <Globe className="w-3.5 h-3.5 text-muted-foreground/60" />;
case 'processing':
return <Brain className="w-3.5 h-3.5 text-muted-foreground/60" />;
case 'response-generation':
return <Loader2 className="w-3.5 h-3.5 text-muted-foreground/60 animate-spin" />;
default:
return <Search className="w-3.5 h-3.5 text-muted-foreground/60" />;
}
};
return (
<div className={cn("mb-6 space-y-3", className)}>
{/* Header: "Working..." com spinner sutil */}
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Circle className="w-2 h-2 fill-current animate-pulse" />
<span>Working...</span>
</div>
{/* Lista vertical de steps - texto simples */}
<div className="space-y-1.5 pl-6">
{steps.map((step, index) => {
const isRunning = step.status === 'running';
const isCompleted = step.status === 'completed';
const isError = step.status === 'error';
return (
<div
key={`${step.stepType}-${step.timestamp}`}
className={cn(
"reasoning-step flex items-center gap-2 text-sm",
isError
? "text-destructive/80"
: isCompleted
? "text-muted-foreground/60"
: "text-muted-foreground/80"
)}
style={{ animationDelay: `${index * 100}ms` }}
>
{getStepIcon(step)}
<span>{step.label}</span>
{step.details && (
<span className="text-xs text-muted-foreground/50 ml-1">
{step.details}
</span>
)}
</div>
);
})}
</div>
{/* Pills de busca - cápsulas sutis */}
{searchQueries.length > 0 && (
<div className="flex flex-wrap gap-2 pl-6">
<span className="text-xs text-muted-foreground/60">Searching:</span>
{searchQueries.map((query, index) => (
<span
key={index}
className="text-xs font-mono px-2 py-1 bg-white/5 dark:bg-white/5 border border-white/10 dark:border-white/10 rounded-full text-muted-foreground/70"
>
{query}
</span>
))}
</div>
)}
{/* Fontes em revisão */}
{allSources.length > 0 && (
<div className="pl-6">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs text-muted-foreground/60">
Reviewing sources - {allSources.length}
</span>
</div>
<SourcesCompact sources={allSources} />
</div>
)}
</div>
);
}
+78
View File
@@ -0,0 +1,78 @@
'use client';
import { ExternalLink } from 'lucide-react';
import { cn } from '@/lib/utils';
interface Source {
url: string;
title?: string;
}
interface SourcesCompactProps {
sources: Source[];
className?: string;
}
export function SourcesCompact({ sources, className }: SourcesCompactProps) {
const getFaviconUrl = (url: string): string => {
try {
const domain = new URL(url).hostname;
return `https://www.google.com/s2/favicons?domain=${domain}&sz=16`;
} catch {
return '';
}
};
const getDomain = (url: string): string => {
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0];
}
};
if (!sources || sources.length === 0) {
return null;
}
return (
<div className={cn("flex gap-3 overflow-x-auto py-2 sources-scrollbar", className)}>
{sources.map((source, idx) => {
const faviconUrl = getFaviconUrl(source.url);
const domain = getDomain(source.url);
return (
<a
key={idx}
href={source.url}
target="_blank"
rel="noopener noreferrer"
className="group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted/30 hover:bg-muted/50 border border-transparent hover:border-muted transition-all flex-shrink-0"
>
{faviconUrl ? (
<img
src={faviconUrl}
alt=""
className="w-4 h-4 rounded flex-shrink-0"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<ExternalLink className="w-4 h-4 text-muted-foreground/60 flex-shrink-0" />
)}
<div className="min-w-0">
<div className="text-xs font-medium truncate max-w-[140px] text-foreground/90">
{source.title || domain}
</div>
<div className="text-[10px] text-muted-foreground truncate">
{domain}
</div>
</div>
</a>
);
})}
</div>
);
}
+57 -58
View File
@@ -27,90 +27,89 @@ export function SourcesDisplay({ sources, className }: SourcesDisplayProps) {
} }
}; };
// Memoizar URLs de favicon para evitar recálculos const getFaviconUrl = (url: string): string => {
const faviconUrls = useMemo(() => { try {
return sources.map(source => { const domain = new URL(url).hostname;
try { return `https://www.google.com/s2/favicons?domain=${domain}&sz=16`;
const domain = new URL(source.url).hostname; } catch {
return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`; return '';
} catch { }
return null; };
}
}); const getDomain = (url: string): string => {
}, [sources]); try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0];
}
};
return ( return (
<div className={cn("px-6 py-4 border-t border-muted bg-muted/20", className)}> <div className={cn("px-6 py-4 border-t border-muted/50", className)}>
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<Globe className="w-4 h-4 text-muted-foreground" /> <Globe className="w-4 h-4 text-muted-foreground/60" />
<p className="text-xs font-medium text-muted-foreground"> <p className="text-xs font-medium text-muted-foreground/80">
Fontes consultadas ({sources.length}): Fontes consultadas ({sources.length}):
</p> </p>
</div> </div>
<div className="flex flex-wrap gap-2 overflow-x-auto pb-2 scrollbar-thin scrollbar-thumb-muted scrollbar-track-transparent"> <div className="flex gap-3 overflow-x-auto py-2 sources-scrollbar">
{sources.map((source, idx) => { {sources.map((source, idx) => {
const faviconUrl = faviconUrls[idx]; const faviconUrl = getFaviconUrl(source.url);
const domain = getDomain(source.url);
const isCopied = copiedIndex === idx; const isCopied = copiedIndex === idx;
return ( return (
<div <a
key={idx} key={idx}
className="group flex-shrink-0 flex items-center gap-2 px-3 py-2 rounded-md bg-background hover:bg-muted/80 transition-all duration-200 border border-muted hover:border-primary/50 shadow-sm hover:shadow-md" href={source.url}
target="_blank"
rel="noopener noreferrer"
className="group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted/30 hover:bg-muted/50 border border-transparent hover:border-muted transition-all flex-shrink-0"
onClick={(e) => {
// Permitir que o botão de copiar funcione sem navegar
if ((e.target as HTMLElement).closest('button')) {
e.preventDefault();
}
}}
> >
{/* Favicon */}
{faviconUrl ? ( {faviconUrl ? (
<img <img
src={faviconUrl} src={faviconUrl}
alt="" alt=""
className="w-4 h-4 flex-shrink-0 rounded-sm" className="w-4 h-4 rounded flex-shrink-0"
onError={(e) => { onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none'; (e.target as HTMLImageElement).style.display = 'none';
}} }}
/> />
) : ( ) : (
<Globe className="w-4 h-4 flex-shrink-0 text-muted-foreground" /> <Globe className="w-4 h-4 text-muted-foreground/60 flex-shrink-0" />
)} )}
<div className="min-w-0">
{/* Title and URL */} <div className="text-xs font-medium truncate max-w-[140px] text-foreground/90">
<div className="flex-1 min-w-0 max-w-[200px] md:max-w-[300px]"> {source.title || domain}
<div className="text-xs font-medium text-foreground truncate" title={source.title || source.url}>
{source.title || `Fonte ${idx + 1}`}
</div> </div>
<div className="text-[10px] text-muted-foreground truncate" title={source.url}> <div className="text-[10px] text-muted-foreground truncate">
{source.url.replace(/^https?:\/\//, '').replace(/^www\./, '')} {domain}
</div> </div>
</div> </div>
<button
{/* Actions */} onClick={(e) => {
<div className="flex items-center gap-1"> e.preventDefault();
{/* Copy Button */} e.stopPropagation();
<button copyToClipboard(source.url, idx);
onClick={() => copyToClipboard(source.url, idx)} }}
className="p-1 rounded hover:bg-muted transition-colors" className="ml-1 p-1 rounded hover:bg-muted/50 transition-colors opacity-0 group-hover:opacity-100"
title="Copiar URL" title="Copiar URL"
aria-label="Copiar URL" aria-label="Copiar URL"
> >
{isCopied ? ( {isCopied ? (
<Check className="w-3 h-3 text-green-600 dark:text-green-400" /> <Check className="w-3 h-3 text-green-600 dark:text-green-400" />
) : ( ) : (
<Copy className="w-3 h-3 text-muted-foreground" /> <Copy className="w-3 h-3 text-muted-foreground" />
)} )}
</button> </button>
</a>
{/* External Link Button */}
<a
href={source.url}
target="_blank"
rel="noopener noreferrer"
className="p-1 rounded hover:bg-muted transition-colors"
title="Abrir em nova aba"
aria-label="Abrir em nova aba"
>
<ExternalLink className="w-3 h-3 text-muted-foreground" />
</a>
</div>
</div>
); );
})} })}
</div> </div>