import React, { useState, useEffect, useRef } from 'react'; import { NodeViewWrapper, NodeViewContent, NodeViewProps } from '@tiptap/react'; import { Copy, Check, Download, Pencil, ChevronDown, ChevronUp, Settings } from 'lucide-react'; export const CodeBlockComponent: React.FC = (props) => { const [copied, setCopied] = useState(false); const { node: { attrs: { language: defaultLanguage, filename: defaultFilename, showLineNumbers, wrapText } }, updateAttributes, extension } = props; const [detectedLang, setDetectedLang] = useState(defaultLanguage || 'text'); const [isEditingName, setIsEditingName] = useState(false); const [filename, setFilename] = useState(defaultFilename || ''); const inputRef = useRef(null); const [isManualExpanded, setIsManualExpanded] = useState(false); const contentRef = useRef(null); const [contentHeight, setContentHeight] = useState('300px'); // Default max height for collapsed state const handleCopy = () => { const text = props.node.textContent; navigator.clipboard.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); }); }; const detectLanguage = (content: string): string => { const c = content.trim(); if (c.startsWith('npm ') || c.startsWith('yarn ') || c.startsWith('pnpm ') || c.startsWith('npx ') || c.startsWith('git ')) return 'bash'; if (c.includes('@echo off') || c.startsWith('::') || c.startsWith('REM ') || c.includes('set "PROYECTO=')) return 'batch'; if ((c.includes('def ') && c.includes(':')) || c.includes('import pandas') || c.includes('print(')) return 'python'; if (c.includes('public class') || c.includes('System.out.println') || c.includes('public static void')) return 'java'; if (c.includes('import React') || c.includes('export const') || c.includes('interface ')) return 'typescript'; if (c.includes('function ') || c.includes('const ') || c.includes('let ') || c.includes('console.log')) return 'javascript'; if (c.includes('') || c.includes('')) return 'html'; if (c.includes('{') && c.includes('}') && c.includes(':') && c.includes(';')) return 'css'; return 'text'; }; useEffect(() => { const content = props.node.textContent; const lang = detectLanguage(content); if (lang !== detectedLang && lang !== 'text') { setDetectedLang(lang); updateAttributes({ language: lang }); } else if (lang === 'text' && defaultLanguage && defaultLanguage !== 'text') { setDetectedLang(defaultLanguage); } const measureHeight = () => { if (contentRef.current) { const currentMaxHeight = contentRef.current.style.maxHeight; contentRef.current.style.maxHeight = 'none'; setContentHeight(contentRef.current.scrollHeight); contentRef.current.style.maxHeight = currentMaxHeight; } }; measureHeight(); window.addEventListener('resize', measureHeight); return () => window.removeEventListener('resize', measureHeight); }, [props.node.textContent, showLineNumbers, wrapText]); useEffect(() => { if (isEditingName && inputRef.current) { inputRef.current.focus(); } }, [isEditingName]); const handleDownload = () => { const text = props.node.textContent; let downloadName = filename; if (!downloadName) { const extensionMap: Record = { 'bash': 'sh', 'batch': 'bat', 'python': 'py', 'java': 'java', 'typescript': 'ts', 'javascript': 'js', 'html': 'html', 'css': 'css', 'text': 'txt' }; const ext = extensionMap[detectedLang] || 'txt'; downloadName = `code.${ext}`; } const blob = new Blob([text], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = downloadName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; const handleNameSubmit = () => { setIsEditingName(false); updateAttributes({ filename }); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { handleNameSubmit(); } }; const handleOpenSettings = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); if (props.editor.isEditable) { const event = new CustomEvent('block-triple-click', { detail: { type: 'code', pos: props.getPos() }, bubbles: true }); props.editor.view.dom.dispatchEvent(event); } }; const toggleExpand = () => { setIsManualExpanded(!isManualExpanded); }; const isCollapsed = props.node.attrs.collapsible && !isManualExpanded; const lineCount = props.node.textContent.split('\n').length; return (
{isEditingName ? ( setFilename(e.target.value)} onBlur={handleNameSubmit} onKeyDown={handleKeyDown} className="ml-3 text-xs font-medium text-zinc-200 bg-white/10 rounded px-1.5 py-0.5 outline-none border border-white/20 w-32 font-mono" placeholder="nombre.ext" /> ) : ( {filename || detectedLang} )}
{props.editor.isEditable && ( <> )} {props.node.attrs.collapsible && ( )}
{copied && (
Copiado!
)}
{showLineNumbers && !wrapText && (
{Array.from({ length: lineCount }).map((_, i) => (
{i + 1}
))}
)}
                    
                
); };