import React, { useEffect, useState } from 'react'; import { Editor } from '@tiptap/react'; import { Bold, Italic, Code, Link as LinkIcon, Heading1, Heading2, List, ListOrdered, Quote, Pilcrow, Settings, Check, X, Eraser, Image as ImageIcon, AlignLeft, AlignCenter, AlignRight, AlignJustify, Video, Terminal, FileCode, MousePointerClick, ExternalLink, Download, Github, Send, Twitter, Linkedin, Instagram, Youtube, Facebook, Layers, MessageCircle, // Using MessageCircle as generic community/chat since Discord might be missing Globe, Mail, FileText, Minus, Paperclip } from 'lucide-react'; import { TiktokIcon } from './TiktokIcon'; import { QuoteStyleConfig, LinkStyleConfig, CodeStyleConfig } from '../services/codeStyleService'; import { uploadImageToImgBB } from '../services/imageService'; interface EditorToolbarProps { editor: Editor | null; onOpenSettings?: () => void; onSave?: () => void; defaultQuoteStyles?: QuoteStyleConfig; linkStyleConfig?: LinkStyleConfig; codeStyleConfig?: CodeStyleConfig; buttonStyleConfig?: any; minimalMode?: boolean; } export const EditorToolbar: React.FC = ({ editor, onOpenSettings, onSave, defaultQuoteStyles, linkStyleConfig, codeStyleConfig, buttonStyleConfig, minimalMode = false }) => { const [hasSelection, setHasSelection] = useState(false); const [showLinkInput, setShowLinkInput] = useState(false); const [linkUrl, setLinkUrl] = useState(''); const fileInputRef = React.useRef(null); const [isImageUploading, setIsImageUploading] = useState(false); const [isFileUploading, setIsFileUploading] = useState(false); const [uploadProgress, setUploadProgress] = useState(0); const [showVideoInput, setShowVideoInput] = useState(false); const [videoUrl, setVideoUrl] = useState(''); const [showButtonInput, setShowButtonInput] = useState(false); const [buttonText, setButtonText] = useState(''); const [buttonUrl, setButtonUrl] = useState(''); const [buttonVariant, setButtonVariant] = useState<'visit' | 'download' | 'github' | 'telegram' | 'twitter' | 'linkedin' | 'instagram' | 'youtube' | 'facebook' | 'tiktok' | 'x' | 'code' | 'layers' | 'community' | 'globe' | 'mail' | 'file'>('visit'); useEffect(() => { if (!editor) return; const updateSelection = () => { setHasSelection(!editor.state.selection.empty); }; // Initial check updateSelection(); editor.on('selectionUpdate', updateSelection); editor.on('update', updateSelection); return () => { editor.off('selectionUpdate', updateSelection); editor.off('update', updateSelection); }; }, [editor]); if (!editor) return null; const handleAction = (e: React.MouseEvent, action: () => void) => { e.preventDefault(); action(); }; const handleLink = (e: React.MouseEvent) => { e.preventDefault(); if (editor.state.selection.empty && !editor.isActive('image')) { return; } let previousUrl = ''; if (editor.isActive('image')) { previousUrl = editor.getAttributes('image').href; } else { previousUrl = editor.getAttributes('link').href; } setLinkUrl(previousUrl || ''); setShowLinkInput(!showLinkInput); }; const saveLink = () => { if (editor.isActive('image')) { if (linkUrl === '') { editor.chain().focus().updateAttributes('image', { href: null }).run(); } else { editor.chain().focus().updateAttributes('image', { href: linkUrl }).run(); } } else { if (linkUrl === '') { editor.chain().focus().extendMarkRange('link').unsetLink().run(); } else { const attributes: any = { href: linkUrl }; // Check if underline should be disabled if (linkStyleConfig && !linkStyleConfig.underlineEnabled) { attributes.class = 'no-underline-link'; } editor.chain().focus().extendMarkRange('link').setLink(attributes).run(); } } setShowLinkInput(false); setLinkUrl(''); }; const handleQuoteClick = (e: React.MouseEvent) => { e.preventDefault(); // Allow quote creation even with empty selection (it will wrap the current block) if (editor.isActive('customBlockquote')) { editor.chain().focus().unsetBlockquote().run(); } else { console.log('Creating quote with styles:', defaultQuoteStyles); // Create with default styles if available // Map QuoteStyleConfig properties to CustomBlockquote attributes const attributes = defaultQuoteStyles ? { ...defaultQuoteStyles, backgroundColor: defaultQuoteStyles.bgColor, // Map bgColor to backgroundColor // Ensure all other properties are passed correctly borderColor: defaultQuoteStyles.borderColor, borderWidth: defaultQuoteStyles.borderWidth, textColor: defaultQuoteStyles.textColor, padding: defaultQuoteStyles.padding, fontSize: defaultQuoteStyles.fontSize, borderRadius: defaultQuoteStyles.borderRadius, width: defaultQuoteStyles.width, height: defaultQuoteStyles.height, italic: defaultQuoteStyles.italic, showCopyButton: defaultQuoteStyles.showCopyButton, showDownloadButton: defaultQuoteStyles.showDownloadButton, collapsible: defaultQuoteStyles.collapsible, fontFamily: defaultQuoteStyles.fontFamily, isCodeFont: defaultQuoteStyles.isCodeFont } : {}; editor.chain().focus().wrapIn('customBlockquote', attributes).run(); } }; const handleCodeClick = (e: React.MouseEvent) => { e.preventDefault(); // Allow toggle for typing // if (editor.state.selection.empty) { // return; // } const isCodeActive = editor.isActive('code'); const currentAttributes = editor.getAttributes('code'); const wantsBackground = codeStyleConfig?.showBackground ?? true; if (isCodeActive) { const currentShowBackground = currentAttributes.showBackground ?? true; // If the current state doesn't match the preference, update it if (currentShowBackground !== wantsBackground) { editor.chain().focus().updateAttributes('code', { showBackground: wantsBackground }).run(); } else { // If it matches, toggle it off (remove mark) editor.chain().focus().unsetMark('code').run(); } } else { editor.chain().focus().setMark('code', { showBackground: wantsBackground }).run(); } (editor.commands as any).removeStoredMark('code'); }; const handleCardCodeClick = (e: React.MouseEvent) => { e.preventDefault(); // Allow toggle for typing // if (editor.state.selection.empty) { // return; // } const isCodeActive = editor.isActive('code'); const currentAttributes = editor.getAttributes('code'); if (isCodeActive) { if (currentAttributes.showBackground !== false) { // Switch to card style code editor.chain().focus().updateAttributes('code', { showBackground: false }).run(); } else { // Toggle off editor.chain().focus().unsetMark('code').run(); } } else { editor.chain().focus().setMark('code', { showBackground: false }).run(); } (editor.commands as any).removeStoredMark('code'); }; const handleClearFormatting = (e: React.MouseEvent) => { e.preventDefault(); // Solo eliminamos marcas para no romper estructura de listas o código editor.chain().focus().unsetAllMarks().run(); }; const handleImageUploadClick = () => { fileInputRef.current?.click(); }; const handleFileChange = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setIsImageUploading(true); try { const url = await uploadImageToImgBB(file); if (editor) { editor.chain().focus().setImage({ src: url }).run(); } } catch (error) { console.error('Failed to upload image:', error); alert('Error al subir la imagen. Por favor intenta de nuevo.'); } finally { setIsImageUploading(false); if (fileInputRef.current) { fileInputRef.current.value = ''; } } }; const handleVideoClick = (e: React.MouseEvent) => { e.preventDefault(); setShowVideoInput(!showVideoInput); setShowLinkInput(false); // Cierra el input de links si estaba abierto }; const saveVideo = () => { if (videoUrl && editor) { // Validamos si es YouTube y aseguramos el protocolo let finalUrl = videoUrl.trim(); const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+$/; if (youtubeRegex.test(finalUrl)) { if (!finalUrl.match(/^https?:\/\//)) { finalUrl = `https://${finalUrl}`; } } else if (!finalUrl.match(/^https?:\/\//) && !finalUrl.startsWith('data:')) { finalUrl = `https://${finalUrl}`; } editor.chain().focus().insertContent({ type: 'universalVideo', attrs: { src: finalUrl } }).run(); } setShowVideoInput(false); setVideoUrl(''); }; const handleButtonClick = (e: React.MouseEvent) => { e.preventDefault(); setShowButtonInput(!showButtonInput); setShowLinkInput(false); setShowVideoInput(false); }; const saveButton = () => { if (buttonText && buttonUrl && editor) { let finalUrl = buttonUrl.trim(); if (!finalUrl.match(/^https?:\/\//) && !finalUrl.startsWith('mailto:') && !finalUrl.startsWith('/')) { finalUrl = `https://${finalUrl}`; } (editor.commands as any).setCustomButton({ text: buttonText, url: finalUrl, variant: buttonVariant, backgroundColor: buttonStyleConfig?.backgroundColor, textColor: buttonStyleConfig?.textColor, borderRadius: buttonStyleConfig?.borderRadius, width: buttonStyleConfig?.width, height: buttonStyleConfig?.height }); } setShowButtonInput(false); setButtonText(''); setButtonUrl(''); setButtonVariant('visit'); }; const handleAlign = (alignment: 'left' | 'center' | 'right' | 'justify') => { if (!editor) return; if (editor.isActive('universalVideo')) { editor.chain().focus().updateAttributes('universalVideo', { align: alignment }).run(); } else if (editor.isActive('image')) { editor.chain().focus().updateAttributes('image', { align: alignment }).run(); } else { editor.chain().focus().setTextAlign(alignment).run(); } }; const isAlignActive = (alignment: 'left' | 'center' | 'right' | 'justify') => { if (!editor) return false; if (editor.isActive('universalVideo')) { return editor.getAttributes('universalVideo').align === alignment; } if (editor.isActive('image')) { return editor.getAttributes('image').align === alignment; } return editor.isActive({ textAlign: alignment }); }; return ( <>
handleAction(e, () => editor.chain().focus().toggleHeading({ level: 1 }).run())} isActive={editor.isActive('heading', { level: 1 })} disabled={!editor.can().toggleHeading({ level: 1 })} icon={} title="Título 1" /> handleAction(e, () => editor.chain().focus().toggleHeading({ level: 2 }).run())} isActive={editor.isActive('heading', { level: 2 })} disabled={!editor.can().toggleHeading({ level: 2 })} icon={} title="Título 2" /> handleAction(e, () => editor.chain().focus().setParagraph().run())} isActive={editor.isActive('paragraph')} disabled={!editor.can().setParagraph()} icon={} title="Párrafo" />
handleAction(e, () => editor.chain().focus().toggleBold().run())} isActive={editor.isActive('bold')} disabled={!editor.can().toggleBold()} icon={} title="Negrita" /> handleAction(e, () => editor.chain().focus().toggleItalic().run())} isActive={editor.isActive('italic')} disabled={!editor.can().toggleItalic()} icon={} title="Cursiva" /> } title="Enlace" /> } title="Código Inline" /> } title="Texto Estilo Tarjeta" /> { e.preventDefault(); editor.chain().focus().setCodeBlock({ language: 'text' // Set a default language if required or just keep it simple }).updateAttributes('codeBlock', { collapsible: codeStyleConfig?.collapsible ?? true, showLineNumbers: codeStyleConfig?.showLineNumbers ?? false, wrapText: codeStyleConfig?.wrapText ?? false }).run(); }} isActive={editor.isActive('codeBlock')} disabled={!editor.can().setCodeBlock()} icon={} title="Bloque de Código" /> } title="Limpiar Formato" />
{ e.preventDefault(); handleImageUploadClick(); }} isActive={false} icon={isImageUploading ?
: } title="Subir Imagen" /> { e.preventDefault(); const input = document.createElement('input'); input.type = 'file'; input.multiple = true; // Habilitamos selección múltiple input.onchange = async (event: any) => { const files = Array.from(event.target.files || []); if (files.length === 0) return; setIsFileUploading(true); // Procesamos los archivos uno por uno para no saturar el bot for (const file of files as File[]) { setUploadProgress(0); await new Promise((resolve, reject) => { const formData = new FormData(); formData.append('file', file); const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const percent = Math.round((e.loaded / e.total) * 100); setUploadProgress(percent); } }); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); if (data.status === 'success') { editor?.chain() .focus() .insertContent([ { type: 'customFile', attrs: { name: file.name, messageId: data.message_id || 'Subido', channelId: data.channel_id } }, { type: 'paragraph' } ]) .run(); resolve(true); } else { alert('Error en ' + file.name + ': ' + data.message); resolve(false); } } else { alert('Error de conexión al subir ' + file.name); resolve(false); } } }; xhr.open('POST', '/upload', true); xhr.send(formData); }); } setIsFileUploading(false); }; input.click(); }} isActive={false} icon={isFileUploading ? (
{uploadProgress}%
) : } title="Subir Archivo a Telegram" /> } title="Insertar Video de YouTube" /> } title="Insertar Botón de Acción" />
handleAction(e, () => handleAlign('left'))} isActive={isAlignActive('left')} icon={} title="Alinear a la izquierda" /> handleAction(e, () => handleAlign('center'))} isActive={isAlignActive('center')} icon={} title="Centrar" /> handleAction(e, () => handleAlign('right'))} isActive={isAlignActive('right')} icon={} title="Alinear a la derecha" /> handleAction(e, () => handleAlign('justify'))} isActive={isAlignActive('justify')} icon={} title="Justificar" />
handleAction(e, () => editor.chain().focus().toggleBulletList().run())} isActive={editor.isActive('bulletList')} disabled={!editor.can().toggleBulletList()} icon={} title="Lista con viñetas" /> handleAction(e, () => editor.chain().focus().toggleOrderedList().run())} isActive={editor.isActive('orderedList')} disabled={!editor.can().toggleOrderedList()} icon={} title="Lista numerada" />
} title="Cita Personalizada" /> handleAction(e, () => editor.chain().focus().setHorizontalRule().run())} isActive={false} icon={} title="Insertar Separador (---)" />
{onOpenSettings && ( <>
{ e.preventDefault(); onOpenSettings(); }} isActive={false} icon={} title="Configurar Estilo" /> )}
{ showLinkInput && (
setLinkUrl(e.target.value)} placeholder="https://ejemplo.com" className="bg-transparent border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-primary min-w-[200px]" onKeyDown={(e) => { if (e.key === 'Enter') saveLink(); if (e.key === 'Escape') setShowLinkInput(false); }} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()} />
) } {showVideoInput && (
e.stopPropagation()} > setVideoUrl(e.target.value)} placeholder="https://www.youtube.com/watch?v=..." className="bg-transparent border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-primary min-w-[250px]" onKeyDown={(e) => { if (e.key === 'Enter') saveVideo(); if (e.key === 'Escape') setShowVideoInput(false); }} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()} autoFocus />
)} {showButtonInput && (
e.stopPropagation()} > setButtonText(e.target.value)} placeholder="Texto" className="bg-transparent border border-white/10 rounded-lg px-2 py-1.5 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-primary w-full" onMouseDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()} autoFocus /> setButtonUrl(e.target.value)} placeholder="URL" className="bg-transparent border border-white/10 rounded-lg px-2 py-1.5 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-primary w-full" onMouseDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()} />
)} ); }; interface ToolbarButtonProps { onMouseDown: (e: React.MouseEvent) => void; isActive?: boolean; disabled?: boolean; icon: React.ReactNode; title: string; } const ToolbarButton: React.FC = ({ onMouseDown, isActive, disabled, icon, title }) => ( );