Merge branch 'main' into issue/142-creacin-de-planes-de-estudio-y-de-asignaturas-con-

This commit is contained in:
2026-02-27 12:26:16 -06:00
7 changed files with 718 additions and 334 deletions

View File

@@ -14,6 +14,7 @@ import {
MessageSquarePlus,
Archive,
RotateCcw,
Loader2,
} from 'lucide-react'
import { useState, useEffect, useRef, useMemo } from 'react'
@@ -27,9 +28,9 @@ import { ScrollArea } from '@/components/ui/scroll-area'
import { Textarea } from '@/components/ui/textarea'
import {
useAIPlanChat,
useChatHistory,
useConversationByPlan,
useUpdateConversationStatus,
useUpdateConversationTitle,
} from '@/data'
import { usePlan } from '@/data/hooks/usePlans'
@@ -66,7 +67,25 @@ interface SelectedField {
label: string
value: string
}
interface EstructuraDefinicion {
properties?: {
[key: string]: {
title: string
description?: string
}
}
}
interface ChatMessageJSON {
user: 'user' | 'assistant'
message?: string
prompt?: string
refusal?: boolean
recommendations?: Array<{
campo_afectado: string
texto_mejora: string
aplicada: boolean
}>
}
export const Route = createFileRoute('/planes/$planId/_detalle/iaplan')({
component: RouteComponent,
})
@@ -76,19 +95,14 @@ function RouteComponent() {
const { data } = usePlan(planId)
const routerState = useRouterState()
const [openIA, setOpenIA] = useState(false)
const [conversacionId, setConversacionId] = useState<string | null>(null)
const { mutateAsync: sendChat, isLoading } = useAIPlanChat()
const { mutateAsync: sendChat, isPending: isLoading } = useAIPlanChat()
const { mutate: updateStatusMutation } = useUpdateConversationStatus()
const [activeChatId, setActiveChatId] = useState<string | undefined>(
undefined,
)
const { data: historyMessages, isLoading: isLoadingHistory } =
useChatHistory(activeChatId)
const { data: lastConversation, isLoading: isLoadingConv } =
useConversationByPlan(planId)
// archivos
const [selectedArchivoIds, setSelectedArchivoIds] = useState<Array<string>>(
[],
)
@@ -104,76 +118,167 @@ function RouteComponent() {
const [pendingSuggestion, setPendingSuggestion] = useState<any>(null)
const queryClient = useQueryClient()
const scrollRef = useRef<HTMLDivElement>(null)
const [showArchived, setShowArchived] = useState(false)
const [editingChatId, setEditingChatId] = useState<string | null>(null)
const editableRef = useRef<HTMLSpanElement>(null)
const { mutate: updateTitleMutation } = useUpdateConversationTitle()
const [isSending, setIsSending] = useState(false)
const [optimisticMessage, setOptimisticMessage] = useState<string | null>(
null,
)
const [filterQuery, setFilterQuery] = useState('')
const availableFields = useMemo(() => {
const definicion = data?.estructuras_plan
?.definicion as EstructuraDefinicion
useEffect(() => {
// 1. Si no hay ID o está cargando el historial, no hacemos nada
if (!activeChatId || isLoadingHistory) return
// Encadenamiento opcional para evitar errores si data es null
if (!definicion.properties) return []
const messagesFromApi = historyMessages?.items || historyMessages
return Object.entries(definicion.properties).map(([key, value]) => ({
key,
label: value.title,
value: String(value.description || ''),
}))
}, [data])
if (Array.isArray(messagesFromApi)) {
const flattened = messagesFromApi.map((msg) => {
let content = msg.content
let suggestions: Array<any> = []
const filteredFields = useMemo(() => {
return availableFields.filter(
(field) =>
field.label.toLowerCase().includes(filterQuery.toLowerCase()) &&
!selectedFields.some((s) => s.key === field.key), // No mostrar ya seleccionados
)
}, [availableFields, filterQuery, selectedFields])
if (typeof content === 'object' && content !== null) {
suggestions = Object.entries(content)
.filter(([key]) => key !== 'ai-message')
.map(([key, value]) => ({
key,
label: key.replace(/_/g, ' '),
newValue: value as string,
}))
const activeChatData = useMemo(() => {
return lastConversation?.find((chat: any) => chat.id === activeChatId)
}, [lastConversation, activeChatId])
content = content['ai-message'] || JSON.stringify(content)
}
// Si el content es un string que parece JSON (caso común en respuestas RAW)
else if (typeof content === 'string' && content.startsWith('{')) {
try {
const parsed = JSON.parse(content)
suggestions = Object.entries(parsed)
.filter(([key]) => key !== 'ai-message')
.map(([key, value]) => ({
key,
label: key.replace(/_/g, ' '),
newValue: value as string,
}))
content = parsed['ai-message'] || content
} catch (e) {
/* no es json */
}
}
const chatMessages = useMemo(() => {
// 1. Si no hay ID o no hay data del chat, retornamos vacío
if (!activeChatId || !activeChatData) return []
const json = (activeChatData.conversacion_json ||
[]) as unknown as Array<ChatMessageJSON>
// 2. Verificamos que 'json' sea realmente un array antes de mapear
if (!Array.isArray(json)) return []
return json.map((msg, index: number) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!msg?.user) {
return {
...msg,
content,
suggestions,
type: suggestions.length > 0 ? 'improvement-card' : 'text',
id: `err-${index}`,
role: 'assistant',
content: '',
suggestions: [],
}
})
}
// Solo actualizamos si no estamos esperando la respuesta de un POST
// para evitar saltos visuales
if (!isLoading) {
setMessages(flattened.reverse())
const isAssistant = msg.user === 'assistant'
return {
id: `${activeChatId}-${index}`,
role: isAssistant ? 'assistant' : 'user',
content: isAssistant ? msg.message || '' : msg.prompt || '', // Agregamos fallback a string vacío
isRefusal: isAssistant && msg.refusal === true,
suggestions:
isAssistant && msg.recommendations
? msg.recommendations.map((rec) => {
const fieldConfig = availableFields.find(
(f) => f.key === rec.campo_afectado,
)
return {
key: rec.campo_afectado,
label: fieldConfig
? fieldConfig.label
: rec.campo_afectado.replace(/_/g, ' '),
newValue: rec.texto_mejora,
applied: rec.aplicada,
}
})
: [],
}
})
}, [activeChatData, activeChatId, availableFields])
const scrollToBottom = () => {
if (scrollRef.current) {
// Buscamos el viewport interno del ScrollArea de Radix
const scrollContainer = scrollRef.current.querySelector(
'[data-radix-scroll-area-viewport]',
)
if (scrollContainer) {
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
behavior: 'smooth',
})
}
}
}, [historyMessages, activeChatId, isLoadingHistory, isLoading])
}
const { activeChats, archivedChats } = useMemo(() => {
const allChats = lastConversation || []
return {
activeChats: allChats.filter((chat: any) => chat.estado === 'ACTIVA'),
archivedChats: allChats.filter(
(chat: any) => chat.estado === 'ARCHIVADA',
),
}
}, [lastConversation])
useEffect(() => {
// Si no hay un chat seleccionado manualmente y la API nos devuelve chats existentes
const isCreationMode = messages.length === 1 && messages[0].id === 'welcome'
if (
!activeChatId &&
lastConversation &&
lastConversation.length > 0 &&
!isCreationMode
) {
setActiveChatId(lastConversation[0].id)
scrollToBottom()
}, [chatMessages, isLoading])
useEffect(() => {
// Verificamos cuáles campos de la lista "selectedFields" ya no están presentes en el texto del input
const camposActualizados = selectedFields.filter((field) =>
input.includes(field.label),
)
// Solo actualizamos el estado si hubo un cambio real (para evitar bucles infinitos)
if (camposActualizados.length !== selectedFields.length) {
setSelectedFields(camposActualizados)
}
}, [lastConversation, activeChatId])
}, [input, selectedFields])
useEffect(() => {
if (isLoadingConv || !lastConversation) return
const isChatStillActive = activeChats.some(
(chat) => chat.id === activeChatId,
)
const isCreationMode = messages.length === 1 && messages[0].id === 'welcome'
// Caso A: El chat actual ya no es válido (fue archivado o borrado)
if (activeChatId && !isChatStillActive && !isCreationMode) {
setActiveChatId(undefined)
setMessages([])
return // Salimos para evitar ejecuciones extra en este render
}
// Caso B: No hay chat seleccionado y hay chats disponibles (Auto-selección al cargar)
if (!activeChatId && activeChats.length > 0 && !isCreationMode) {
setActiveChatId(activeChats[0].id)
}
// Caso C: Si la lista de chats está vacía y no estamos creando uno, limpiar por si acaso
if (activeChats.length === 0 && activeChatId && !isCreationMode) {
setActiveChatId(undefined)
}
}, [activeChats, activeChatId, isLoadingConv, messages.length])
useEffect(() => {
const state = routerState.location.state as any
if (!state?.campo_edit || availableFields.length === 0) return
const field = availableFields.find(
(f) =>
f.value === state.campo_edit.label || f.key === state.campo_edit.clave,
)
if (!field) return
setSelectedFields([field])
setInput((prev) =>
injectFieldsIntoInput(prev || 'Mejora este campo:', [field]),
)
}, [availableFields])
const createNewChat = () => {
setActiveChatId(undefined) // Al ser undefined, el próximo handleSend creará uno nuevo
@@ -202,6 +307,9 @@ function RouteComponent() {
if (activeChatId === id) {
setActiveChatId(undefined)
setMessages([])
setOptimisticMessage(null)
setInput('')
setSelectedFields([])
}
},
},
@@ -214,8 +322,6 @@ function RouteComponent() {
{ id, estado: 'ACTIVA' },
{
onSuccess: () => {
// Al invalidar la query, React Query traerá la lista fresca
// y el chat se moverá solo de "archivados" a "activos"
queryClient.invalidateQueries({
queryKey: ['conversation-by-plan', planId],
})
@@ -224,49 +330,28 @@ function RouteComponent() {
)
}
// 1. Transformar datos de la API para el menú de selección
const availableFields = useMemo(() => {
if (!data?.estructuras_plan?.definicion?.properties) return []
return Object.entries(data.estructuras_plan.definicion.properties).map(
([key, value]) => ({
key,
label: value.title,
value: String(value.description || ''),
}),
)
}, [data])
// 2. Manejar el estado inicial si viene de "Datos Generales"
useEffect(() => {
const state = routerState.location.state as any
if (!state?.campo_edit || availableFields.length === 0) return
const field = availableFields.find(
(f) =>
f.value === state.campo_edit.label || f.key === state.campo_edit.clave,
)
if (!field) return
setSelectedFields([field])
setInput((prev) =>
injectFieldsIntoInput(prev || 'Mejora este campo:', [field]),
)
}, [availableFields])
// 3. Lógica para el disparador ":"
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value
const cursorPosition = e.target.selectionStart // Dónde está escribiendo el usuario
setInput(val)
// Solo abrir si termina en ":"
setShowSuggestions(val.endsWith(':'))
// Busca un ":" seguido de letras justo antes del cursor
const textBeforeCursor = val.slice(0, cursorPosition)
const match = textBeforeCursor.match(/:(\w*)$/)
if (match) {
setShowSuggestions(true)
setFilterQuery(match[1]) // Esto es lo que se usa para el filtrado
} else {
setShowSuggestions(false)
setFilterQuery('')
}
}
const injectFieldsIntoInput = (
input: string,
fields: Array<SelectedField>,
) => {
// Quita cualquier bloque previo de campos
const cleaned = input.replace(/\n?\[Campos:[^\]]*]/g, '').trim()
if (fields.length === 0) return cleaned
@@ -277,60 +362,42 @@ function RouteComponent() {
}
const toggleField = (field: SelectedField) => {
let isAdding = false
// 1. Lo agregamos a la lista de "SelectedFields" (para que la IA sepa qué procesar)
setSelectedFields((prev) => {
const isSelected = prev.find((f) => f.key === field.key)
if (isSelected) {
return prev.filter((f) => f.key !== field.key)
} else {
isAdding = true
return [...prev, field]
}
return isSelected ? prev : [...prev, field]
})
// 2. Insertamos el nombre del campo en el texto exactamente donde estaba el ":"
setInput((prev) => {
// 1. Eliminamos TODOS los ":" que existan en el texto actual
// 2. Quitamos espacios en blanco extra al final
const cleanPrev = prev.replace(/:/g, '').trim()
// 3. Si el input resultante está vacío, solo ponemos la frase
if (cleanPrev === '') {
return `${field.label} `
}
// 4. Si ya había algo, lo concatenamos con un espacio
// Usamos un espacio simple al final para que el usuario pueda seguir escribiendo
return `${cleanPrev} ${field.label} `
// Reemplaza el último ":" y cualquier texto de filtro por el label del campo
const nuevoTexto = prev.replace(/:(\w*)$/, field.label)
return nuevoTexto + ' ' // Añadimos un espacio para que el usuario siga escribiendo
})
// 3. Limpiamos estados de búsqueda
setShowSuggestions(false)
setFilterQuery('')
}
const buildPrompt = (userInput: string, fields: Array<SelectedField>) => {
// Si no hay campos, enviamos el texto tal cual
if (fields.length === 0) return userInput
return `Instrucción del usuario: ${userInput}`
return ` ${userInput}`
}
const handleSend = async (promptOverride?: string) => {
const rawText = promptOverride || input
if (!rawText.trim() && selectedFields.length === 0) return
if (isSending || (!rawText.trim() && selectedFields.length === 0)) return
const currentFields = [...selectedFields]
const finalPrompt = buildPrompt(rawText, currentFields)
const userMsg = {
id: Date.now().toString(),
role: 'user',
content: rawText,
}
setMessages((prev) => [...prev, userMsg])
setIsSending(true)
setOptimisticMessage(rawText)
setInput('')
// setSelectedFields([])
setSelectedArchivoIds([])
setSelectedRepositorioIds([])
setUploadedFiles([])
try {
const payload: any = {
planId: planId,
@@ -346,58 +413,19 @@ function RouteComponent() {
if (response.conversacionId && response.conversacionId !== activeChatId) {
setActiveChatId(response.conversacionId)
// Esto obliga a 'useConversationByPlan' a buscar en la DB el nuevo chat creado
queryClient.invalidateQueries({
queryKey: ['conversation-by-plan', planId],
})
}
// --- NUEVA LÓGICA DE PARSEO ---
let aiText = 'Sin respuesta del asistente'
let suggestions: Array<any> = []
if (response.raw) {
try {
const rawData = JSON.parse(response.raw)
// Extraemos el mensaje conversacional
aiText = rawData['ai-message'] || 'Cambios aplicados con éxito.'
// Filtramos todo lo que no sea el mensaje para crear las sugerencias
suggestions = Object.entries(rawData)
.filter(([key]) => key !== 'ai-message')
.map(([key, value]) => ({
key,
label: key.replace(/_/g, ' '),
newValue: value as string,
}))
} catch (e) {
console.error('Error parseando el campo raw:', e)
aiText = response.raw // Fallback si no es JSON
}
}
setMessages((prev) => [
...prev,
{
id: Date.now().toString(),
role: 'assistant',
content: aiText,
type: suggestions.length > 0 ? 'improvement-card' : 'text',
suggestions: suggestions,
},
])
await queryClient.invalidateQueries({
queryKey: ['conversation-by-plan', planId],
})
setOptimisticMessage(null)
} catch (error) {
console.error('Error en el chat:', error)
setMessages((prev) => [
...prev,
{
id: 'error',
role: 'assistant',
content: 'Lo siento, hubo un error al procesar tu solicitud.',
},
])
// Aquí sí podrías usar un toast o un mensaje de error temporal
} finally {
// 5. CRÍTICO: Detener el estado de carga SIEMPRE
setIsSending(false)
setOptimisticMessage(null)
}
}
@@ -409,15 +437,9 @@ function RouteComponent() {
)
}, [selectedArchivoIds, selectedRepositorioIds, uploadedFiles])
const { activeChats, archivedChats } = useMemo(() => {
const allChats = lastConversation || []
return {
activeChats: allChats.filter((chat: any) => chat.estado === 'ACTIVA'),
archivedChats: allChats.filter(
(chat: any) => chat.estado === 'ARCHIVADA',
),
}
}, [lastConversation])
const removeSelectedField = (fieldKey: string) => {
setSelectedFields((prev) => prev.filter((f) => f.key !== fieldKey))
}
return (
<div className="flex h-[calc(100vh-160px)] max-h-[calc(100vh-160px)] w-full gap-6 overflow-hidden p-4">
@@ -454,7 +476,6 @@ function RouteComponent() {
<ScrollArea className="flex-1">
<div className="space-y-1">
{!showArchived ? (
// --- LISTA DE CHATS ACTIVOS ---
activeChats.map((chat) => (
<div
key={chat.id}
@@ -466,21 +487,77 @@ function RouteComponent() {
}`}
>
<FileText size={16} className="shrink-0 opacity-40" />
{/* Usamos el primer mensaje o un título por defecto */}
<span className="truncate pr-8">
{chat.title || `Chat ${chat.creado_en.split('T')[0]}`}
</span>
<button
onClick={(e) => archiveChat(e, chat.id)}
className="absolute right-2 p-1 opacity-0 transition-opacity group-hover:opacity-100 hover:text-amber-600"
title="Archivar"
<span
ref={editingChatId === chat.id ? editableRef : null}
contentEditable={editingChatId === chat.id}
suppressContentEditableWarning={true}
className={`truncate pr-14 transition-all outline-none ${
editingChatId === chat.id
? 'min-w-[50px] cursor-text rounded bg-white px-1 ring-1 ring-teal-500'
: 'cursor-pointer'
}`}
onDoubleClick={(e) => {
e.stopPropagation()
setEditingChatId(chat.id)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
const newTitle = e.currentTarget.textContent || ''
updateTitleMutation(
{ id: chat.id, nombre: newTitle },
{
onSuccess: () => setEditingChatId(null),
},
)
}
if (e.key === 'Escape') {
setEditingChatId(null)
e.currentTarget.textContent = chat.nombre || ''
}
}}
onBlur={(e) => {
if (editingChatId === chat.id) {
const newTitle = e.currentTarget.textContent || ''
if (newTitle !== chat.nombre) {
updateTitleMutation({ id: chat.id, nombre: newTitle })
}
setEditingChatId(null)
}
}}
onClick={(e) => {
if (editingChatId === chat.id) e.stopPropagation()
}}
>
<Archive size={14} />
</button>
{chat.nombre || `Chat ${chat.creado_en.split('T')[0]}`}
</span>
{/* ACCIONES */}
<div className="absolute right-2 flex items-center gap-1 opacity-0 group-hover:opacity-100">
<button
onClick={(e) => {
e.stopPropagation()
setEditingChatId(chat.id)
// Pequeño timeout para asegurar que el DOM se actualice antes de enfocar
setTimeout(() => editableRef.current?.focus(), 50)
}}
className="p-1 text-slate-400 hover:text-teal-600"
>
<Send size={12} className="rotate-45" />
</button>
<button
onClick={(e) => archiveChat(e, chat.id)}
className="p-1 text-slate-400 hover:text-amber-600"
>
<Archive size={14} />
</button>
</div>
</div>
))
) : (
// --- LISTA DE CHATS ARCHIVADOS ---
/* ... Resto del código de archivados (sin cambios) ... */
<div className="animate-in fade-in slide-in-from-left-2">
<p className="mb-2 px-2 text-[10px] font-bold text-slate-400 uppercase">
Archivados
@@ -492,25 +569,17 @@ function RouteComponent() {
>
<Archive size={14} className="shrink-0 opacity-30" />
<span className="truncate pr-8">
{chat.title ||
{chat.nombre ||
`Archivado ${chat.creado_en.split('T')[0]}`}
</span>
<button
onClick={(e) => unarchiveChat(e, chat.id)}
className="absolute right-2 p-1 opacity-0 group-hover:opacity-100 hover:text-teal-600"
title="Desarchivar"
>
<RotateCcw size={14} />
</button>
</div>
))}
{archivedChats.length === 0 && (
<div className="px-2 py-4 text-center">
<p className="text-xs text-slate-400 italic">
No hay archivados
</p>
</div>
)}
</div>
)}
</div>
@@ -543,46 +612,98 @@ function RouteComponent() {
<div className="relative min-h-0 flex-1">
<ScrollArea ref={scrollRef} className="h-full w-full">
<div className="mx-auto max-w-3xl space-y-6 p-6">
{messages.map((msg) => (
<div
key={msg.id}
className={`flex max-w-[85%] flex-col ${msg.role === 'user' ? 'ml-auto items-end' : 'items-start'}`}
>
<div
className={`rounded-2xl p-3 text-sm whitespace-pre-wrap shadow-sm ${
msg.role === 'user'
? 'rounded-tr-none bg-teal-600 text-white'
: 'rounded-tl-none border bg-white text-slate-700'
}`}
>
{/* Contenido de texto normal */}
{msg.content}
{!activeChatId &&
chatMessages.length === 0 &&
!optimisticMessage ? (
<div className="flex h-[400px] flex-col items-center justify-center text-center opacity-40">
<MessageSquarePlus
size={48}
className="mb-4 text-slate-300"
/>
<h3 className="text-lg font-medium text-slate-900">
No hay un chat seleccionado
</h3>
<p className="text-sm text-slate-500">
Selecciona un chat del historial o crea uno nuevo para
empezar.
</p>
</div>
) : (
<>
{chatMessages.map((msg: any) => (
<div
key={msg.id}
className={`flex max-w-[85%] flex-col ${
msg.role === 'user'
? 'ml-auto items-end'
: 'items-start'
}`}
>
<div
className={`relative rounded-2xl p-3 text-sm whitespace-pre-wrap shadow-sm transition-all duration-300 ${
msg.role === 'user'
? 'rounded-tr-none bg-teal-600 text-white'
: `rounded-tl-none border bg-white text-slate-700 ${
// --- LÓGICA DE REFUSAL ---
msg.isRefusal
? 'border-red-200 bg-red-50/50 ring-1 ring-red-100'
: 'border-slate-100'
}`
}`}
>
{/* Icono opcional de advertencia si es refusal */}
{msg.isRefusal && (
<div className="mb-1 flex items-center gap-1 text-[10px] font-bold text-red-500 uppercase">
<span>Aviso del Asistente</span>
</div>
)}
{/* Si el mensaje tiene sugerencias (ImprovementCard) */}
{msg.suggestions && msg.suggestions.length > 0 && (
<div className="mt-4">
<ImprovementCard
suggestions={msg.suggestions}
planId={planId} // Del useParams()
currentDatos={data?.datos} // De tu query usePlan(planId)
onApply={(key, val) => {
// Esto es opcional, si quieres hacer algo más en la UI del chat
console.log(
'Evento onApply disparado desde el chat',
)
}}
/>
{msg.content}
{!msg.isRefusal &&
msg.suggestions &&
msg.suggestions.length > 0 && (
<div className="mt-4">
<ImprovementCard
suggestions={msg.suggestions}
planId={planId}
currentDatos={data?.datos}
activeChatId={activeChatId}
onApplySuccess={(key) =>
removeSelectedField(key)
}
/>
</div>
)}
</div>
)}
</div>
</div>
))}
{isLoading && (
<div className="flex gap-2 p-4">
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400" />
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400 [animation-delay:0.2s]" />
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400 [animation-delay:0.4s]" />
</div>
</div>
))}
{optimisticMessage && (
<div className="animate-in fade-in slide-in-from-right-2 ml-auto flex max-w-[85%] flex-col items-end">
<div className="rounded-2xl rounded-tr-none bg-teal-600/70 p-3 text-sm whitespace-pre-wrap text-white shadow-sm">
{optimisticMessage}
</div>
</div>
)}
{isSending && (
<div className="animate-in fade-in slide-in-from-left-2 flex flex-col items-start duration-300">
<div className="rounded-2xl rounded-tl-none border border-slate-200 bg-white p-4 shadow-sm">
<div className="flex items-center gap-2">
<div className="flex gap-1">
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-teal-500 [animation-delay:-0.3s]" />
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-teal-500 [animation-delay:-0.15s]" />
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-teal-500" />
</div>
<span className="text-[10px] font-medium tracking-tight text-slate-400 uppercase">
Esperando respuesta...
</span>
</div>
</div>
</div>
)}
</>
)}
</div>
</ScrollArea>
@@ -613,25 +734,35 @@ function RouteComponent() {
<div className="relative mx-auto max-w-4xl">
{/* MENÚ DE SUGERENCIAS FLOTANTE */}
{showSuggestions && (
<div className="animate-in slide-in-from-bottom-2 absolute bottom-full z-50 mb-2 w-72 overflow-hidden rounded-xl border bg-white shadow-2xl">
<div className="border-b bg-slate-50 px-3 py-2 text-[10px] font-bold tracking-wider text-slate-500 uppercase">
Seleccionar campo para IA
<div className="animate-in slide-in-from-bottom-2 absolute bottom-full mb-2 w-full rounded-xl border bg-white shadow-2xl">
<div className="border-b bg-slate-50 px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">
Resultados para "{filterQuery}"
</div>
<div className="max-h-64 overflow-y-auto p-1">
{availableFields.map((field) => (
<button
key={field.key}
onClick={() => toggleField(field)}
className="group flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-teal-50"
>
<span className="text-slate-700 group-hover:text-teal-700">
{field.label}
</span>
{selectedFields.find((f) => f.key === field.key) && (
<Check size={14} className="text-teal-600" />
)}
</button>
))}
{filteredFields.length > 0 ? (
filteredFields.map((field, index) => (
<button
key={field.key}
onClick={() => toggleField(field)}
className={`flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors ${
index === 0
? 'bg-teal-50 text-teal-700 ring-1 ring-teal-200 ring-inset'
: 'hover:bg-slate-50'
}`}
>
<span>{field.label}</span>
{index === 0 && (
<span className="font-mono text-[10px] opacity-50">
TAB
</span>
)}
</button>
))
) : (
<div className="p-3 text-center text-xs text-slate-400">
No hay coincidencias
</div>
)}
</div>
</div>
)}
@@ -663,6 +794,35 @@ function RouteComponent() {
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={(e) => {
if (showSuggestions) {
if (e.key === 'Tab' || e.key === 'Enter') {
if (filteredFields.length > 0) {
e.preventDefault()
toggleField(filteredFields[0])
}
}
if (e.key === 'Escape') {
e.preventDefault()
setShowSuggestions(false)
setFilterQuery('')
}
} else {
// Si el usuario borra y el input está vacío, eliminar el último campo
if (
e.key === 'Backspace' &&
input === '' &&
selectedFields.length > 0
) {
setSelectedFields((prev) => prev.slice(0, -1))
}
}
if (e.key === 'Enter' && !e.shiftKey && !showSuggestions) {
e.preventDefault()
if (!isSending) handleSend()
}
}}
placeholder={
selectedFields.length > 0
? 'Escribe instrucciones adicionales...'
@@ -673,12 +833,16 @@ function RouteComponent() {
<Button
onClick={() => handleSend()}
disabled={
(!input.trim() && selectedFields.length === 0) || isLoading
isSending || (!input.trim() && selectedFields.length === 0)
}
size="icon"
className="mb-1 h-9 w-9 shrink-0 bg-teal-600 hover:bg-teal-700"
>
<Send size={16} className="text-white" />
{isSending ? (
<Loader2 className="animate-spin" size={16} />
) : (
<Send size={16} />
)}
</Button>
</div>
</div>