'use client'; import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { IconX, IconClock, IconEdit, IconCheck } from '@tabler/icons-react'; import { Button } from '@kandev/ui'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { cn } from '@/lib/utils'; import { Textarea } from '@kandev/ui/textarea'; export type QueuedMessageIndicatorHandle = { startEdit: () => void; }; type QueuedMessageIndicatorProps = { content: string; onCancel: () => void; onUpdate: (content: string) => Promise; isVisible: boolean; onEditComplete?: () => void; }; export const QueuedMessageIndicator = forwardRef( function QueuedMessageIndicator( { content, onCancel, onUpdate, isVisible, onEditComplete }, ref ) { const [isEditing, setIsEditing] = useState(false); const [editValue, setEditValue] = useState(content); const [isSaving, setIsSaving] = useState(false); const textareaRef = useRef(null); // Update edit value when content changes from outside (WebSocket updates) useEffect(() => { if (!isEditing) { setEditValue(content); } }, [content, isEditing]); // Auto-focus textarea when entering edit mode useEffect(() => { if (isEditing && textareaRef.current) { textareaRef.current.focus(); // Place cursor at end textareaRef.current.setSelectionRange( textareaRef.current.value.length, textareaRef.current.value.length ); } }, [isEditing]); const startEdit = useCallback(() => { setEditValue(content); setIsEditing(true); }, [content]); const handleSave = useCallback(async () => { const trimmed = editValue.trim(); if (!trimmed || trimmed === content) { setIsEditing(false); onEditComplete?.(); return; } setIsSaving(true); try { await onUpdate(trimmed); setIsEditing(false); onEditComplete?.(); } catch (error) { console.error('Failed to update queued message:', error); } finally { setIsSaving(false); } }, [editValue, content, onUpdate, onEditComplete]); const handleCancel = useCallback(() => { setEditValue(content); setIsEditing(false); onEditComplete?.(); }, [content, onEditComplete]); const handleKeyDown = useCallback( (event: React.KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); handleCancel(); } else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { event.preventDefault(); handleSave(); } }, [handleCancel, handleSave] ); useImperativeHandle(ref, () => ({ startEdit, }), [startEdit]); if (!isVisible) return null; // Truncate content for display (not in edit mode) const displayContent = content.length > 80 ? content.substring(0, 80) + '...' : content; return (
{isEditing ? (