feat: enhance chat functionality with markdown support and default prompts

- Added support for rendering markdown in chat messages using ReactMarkdown with custom renderers.
- Integrated a default format prompt for the chat system, improving user experience by initializing with a predefined prompt.
- Updated the prompt generator to handle model selection more robustly, including loading states and fallback options for model selection.
- Enhanced UI components for better accessibility and user feedback during prompt generation.
This commit is contained in:
Evandro Fonseca Junior committed 2025-11-19 00:34:57 -03:00
1 parent b2a06ed994
commit 032722e21b
11 files changed
+1167 -24

No files matched your search

+15 -4
View File
@@ -3,13 +3,15 @@ import remarkGfm from 'remark-gfm';
import { cn } from "@/lib/utils";
import { Message } from "@/hooks/use-chat";
import { Bot, User } from "lucide-react";
import { markdownRenderers } from "./markdown-renderers";
import { MessageActions } from "./message-actions";
export function ChatMessage({ message }: { message: Message }) {
const isUser = message.role === 'user';
return (
<div className={cn(
"flex w-full gap-4 p-6",
"group flex w-full gap-4 p-6 relative",
isUser ? "bg-background" : "bg-muted/30"
)}>
<div className="flex-shrink-0 mt-1">
@@ -20,14 +22,23 @@ export function ChatMessage({ message }: { message: Message }) {
{isUser ? <User className="w-5 h-5" /> : <Bot className="w-5 h-5" />}
</div>
</div>
<div className="flex-1 overflow-hidden">
<div className="flex-1 overflow-hidden min-w-0">
<div className="prose dark:prose-invert max-w-none break-words">
<ReactMarkdown remarkPlugins={[remarkGfm]}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={markdownRenderers}
>
{message.content}
</ReactMarkdown>
</div>
</div>
{/* Actions Toolbar - Absolute positioned or flex end */}
{!isUser && (
<div className="absolute top-4 right-4">
<MessageActions content={message.content} role={message.role} />
</div>
)}
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { Check, Copy } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
interface CodeBlockProps {
language: string;
children: string;
}
export function CodeBlock({ language, children }: CodeBlockProps) {
const [copied, setCopied] = useState(false);
const handleCopy = () => {
navigator.clipboard.writeText(children);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="my-4 rounded-lg border bg-muted/50 overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-muted/80 border-b">
<span className="text-xs font-medium text-muted-foreground uppercase">
{language || "text"}
</span>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 hover:bg-background/50"
onClick={handleCopy}
title="Copiar código"
>
{copied ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5 text-muted-foreground" />
)}
</Button>
</div>
<div className="p-4 overflow-x-auto">
<code className="text-sm font-mono whitespace-pre">{children}</code>
</div>
</div>
);
}
+138
View File
@@ -0,0 +1,138 @@
import { Components } from "react-markdown";
import { CodeBlock } from "./code-block";
import { cn } from "@/lib/utils";
export const markdownRenderers: Components = {
h1: ({ className, ...props }) => (
<h1
className={cn(
"mt-2 scroll-m-20 text-2xl font-bold tracking-tight first:mt-0",
className
)}
{...props}
/>
),
h2: ({ className, ...props }) => (
<h2
className={cn(
"mt-6 scroll-m-20 border-b pb-2 text-xl font-semibold tracking-tight first:mt-0",
className
)}
{...props}
/>
),
h3: ({ className, ...props }) => (
<h3
className={cn(
"mt-4 scroll-m-20 text-lg font-semibold tracking-tight",
className
)}
{...props}
/>
),
h4: ({ className, ...props }) => (
<h4
className={cn(
"mt-4 scroll-m-20 text-base font-semibold tracking-tight",
className
)}
{...props}
/>
),
p: ({ className, ...props }) => (
<p
className={cn("leading-7 [&:not(:first-child)]:mt-4", className)}
{...props}
/>
),
ul: ({ className, ...props }) => (
<ul className={cn("my-4 ml-6 list-disc [&>li]:mt-2", className)} {...props} />
),
ol: ({ className, ...props }) => (
<ol className={cn("my-4 ml-6 list-decimal [&>li]:mt-2", className)} {...props} />
),
li: ({ className, ...props }) => (
<li className={cn("mt-2", className)} {...props} />
),
blockquote: ({ className, ...props }) => (
<blockquote
className={cn(
"mt-4 border-l-2 border-primary pl-6 italic text-muted-foreground",
className
)}
{...props}
/>
),
img: ({ className, alt, ...props }) => (
// eslint-disable-next-line @next/next/no-img-element
<img
className={cn("rounded-md border bg-muted", className)}
alt={alt}
{...props}
/>
),
hr: ({ ...props }) => <hr className="my-4 md:my-6" {...props} />,
table: ({ className, ...props }) => (
<div className="my-4 w-full overflow-y-auto">
<table className={cn("w-full", className)} {...props} />
</div>
),
tr: ({ className, ...props }) => (
<tr
className={cn("m-0 border-t p-0 even:bg-muted", className)}
{...props}
/>
),
th: ({ className, ...props }) => (
<th
className={cn(
"border px-4 py-2 text-left font-bold [&[align=center]]:text-center [&[align=right]]:text-right",
className
)}
{...props}
/>
),
td: ({ className, ...props }) => (
<td
className={cn(
"border px-4 py-2 text-left [&[align=center]]:text-center [&[align=right]]:text-right",
className
)}
{...props}
/>
),
pre: ({ children }) => <>{children}</>,
code: ({ className, children, ...props }) => {
const match = /language-(\w+)/.exec(className || "");
const isInline = !match;
if (isInline) {
return (
<code
className={cn(
"relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",
className
)}
{...props}
>
{children}
</code>
);
}
return (
<CodeBlock language={match[1]}>
{String(children).replace(/\n$/, "")}
</CodeBlock>
);
},
a: ({ className, ...props }) => (
<a
className={cn("font-medium underline underline-offset-4 text-primary hover:text-primary/80", className)}
target="_blank"
rel="noopener noreferrer"
{...props}
/>
),
};
+81
View File
@@ -0,0 +1,81 @@
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Copy, FileJson, FileText, MoreHorizontal } from "lucide-react";
import { useState } from "react";
interface MessageActionsProps {
content: string;
role: string;
}
export function MessageActions({ content, role }: MessageActionsProps) {
const [copied, setCopied] = useState(false);
const handleCopy = (text: string) => {
navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const copyMarkdown = () => handleCopy(content);
const copyText = () => {
// Simple strip markdown (can be improved with a library if needed)
const text = content
.replace(/#{1,6}\s/g, '') // Headers
.replace(/(\*\*|__)(.*?)\1/g, '$2') // Bold
.replace(/(\*|_)(.*?)\1/g, '$2') // Italic
.replace(/`{3}[\s\S]*?`{3}/g, '$&') // Keep code blocks but maybe strip fences? For now keep raw
.replace(/`(.+?)`/g, '$1') // Inline code
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)') // Links
.replace(/>\s/g, ''); // Blockquotes
handleCopy(text);
};
const copyJson = () => {
const json = JSON.stringify({ role, content }, null, 2);
handleCopy(json);
};
return (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={copyMarkdown}
title="Copiar Markdown"
>
{copied ? (
<span className="text-green-500 text-xs font-bold">✓</span>
) : (
<Copy className="h-3.5 w-3.5 text-muted-foreground" />
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-6 w-6">
<MoreHorizontal className="h-3.5 w-3.5 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={copyText}>
<FileText className="mr-2 h-4 w-4" />
<span>Copiar Texto Puro</span>
</DropdownMenuItem>
<DropdownMenuItem onClick={copyJson}>
<FileJson className="mr-2 h-4 w-4" />
<span>Copiar JSON</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
}
+67 -18
View File
@@ -15,28 +15,46 @@ interface PromptGeneratorDialogProps {
export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: PromptGeneratorDialogProps) {
const [open, setOpen] = useState(false);
const [goal, setGoal] = useState("");
const [selectedModel, setSelectedModel] = useState(defaultModel);
const [selectedModel, setSelectedModel] = useState(defaultModel || "");
const { generatePrompt, isGenerating } = usePromptGenerator();
const { models } = useLocalModels();
const { models, loading } = useLocalModels();
// Set default model when dialog opens or defaultModel changes
useEffect(() => {
if (defaultModel) {
if (defaultModel && defaultModel.trim()) {
setSelectedModel(defaultModel);
}
}, [defaultModel]);
// Try to set specific default if available, otherwise fallback
// Try to set specific default if available and no model is selected
useEffect(() => {
if (loading || models.length === 0) return;
// Se já tem um modelo selecionado e válido, não alterar
if (selectedModel && models.some(m => m.name === selectedModel)) return;
// Primeiro, tenta usar o defaultModel se for válido
if (defaultModel && defaultModel.trim() && models.some(m => m.name === defaultModel)) {
setSelectedModel(defaultModel);
return;
}
// Fallback para modelo preferido
const preferredModel = "llama3.2-abliterate:3b";
const hasPreferred = models.some(m => m.name === preferredModel);
if (hasPreferred && !selectedModel) {
if (hasPreferred && !selectedModel.trim()) {
setSelectedModel(preferredModel);
return;
}
}, [models, selectedModel]);
// Se nenhum modelo está selecionado, seleciona o primeiro disponível
if (!selectedModel.trim() && models.length > 0) {
setSelectedModel(models[0].name);
}
}, [models, loading, defaultModel, selectedModel]);
const handleGenerate = async () => {
if (!goal.trim() || !selectedModel) return;
if (!goal.trim() || !selectedModel.trim()) return;
try {
const prompt = await generatePrompt(goal, selectedModel);
@@ -44,10 +62,16 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
setOpen(false);
setGoal("");
} catch (error) {
// Error handling usually done in hook or global toast
console.error("Erro ao gerar prompt:", error);
// TODO: Implementar toast de erro quando disponível
}
};
const handleCancel = () => {
setOpen(false);
setGoal("");
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
@@ -65,15 +89,31 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
<div className="space-y-4 py-4">
<div className="space-y-2">
<label className="text-sm font-medium">Modelo para Geração</label>
<Select value={selectedModel} onValueChange={setSelectedModel}>
<SelectTrigger>
<SelectValue placeholder="Selecione um modelo..." />
<label htmlFor="model-select" className="text-sm font-medium">
Modelo para Geração
</label>
<Select
value={selectedModel || undefined}
onValueChange={setSelectedModel}
disabled={loading || models.length === 0}
>
<SelectTrigger id="model-select">
<SelectValue placeholder={
loading
? "Carregando modelos..."
: models.length === 0
? "Nenhum modelo disponível"
: "Selecione um modelo..."
} />
</SelectTrigger>
<SelectContent>
{models.map(m => (
<SelectItem key={m.name} value={m.name}>{m.name}</SelectItem>
))}
{models.length === 0 ? (
<SelectItem value="" disabled>Nenhum modelo disponível</SelectItem>
) : (
models.map(m => (
<SelectItem key={m.name} value={m.name}>{m.name}</SelectItem>
))
)}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
@@ -82,19 +122,28 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Seu Objetivo</label>
<label htmlFor="goal-textarea" className="text-sm font-medium">
Seu Objetivo
</label>
<Textarea
id="goal-textarea"
value={goal}
onChange={(e) => setGoal(e.target.value)}
placeholder="Ex: Quero um assistente especialista em Python que explique conceitos complexos de forma simples..."
className="min-h-[150px]"
disabled={isGenerating}
/>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setOpen(false)}>Cancelar</Button>
<Button onClick={handleGenerate} disabled={isGenerating || !goal.trim() || !selectedModel}>
<Button variant="ghost" onClick={handleCancel} disabled={isGenerating}>
Cancelar
</Button>
<Button
onClick={handleGenerate}
disabled={isGenerating || !goal.trim() || !selectedModel.trim() || models.length === 0}
>
{isGenerating ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />