"use client"; import React, { useRef } from 'react'; import { Bold, Italic, List, Link as LinkIcon } from 'lucide-react'; interface RichTextEditorProps { value: string; onChange: (value: string) => void; placeholder?: string; maxLength?: number; } export default function RichTextEditor({ value, onChange, placeholder = "Saisissez votre texte...", maxLength = 1000 }: RichTextEditorProps) { const textareaRef = useRef(null); const insertMarkdown = (before: string, after: string = '') => { const textarea = textareaRef.current; if (!textarea) return; const start = textarea.selectionStart; const end = textarea.selectionEnd; const selectedText = value.substring(start, end); const newText = value.substring(0, start) + before + selectedText + after + value.substring(end); onChange(newText); // Restaurer la sélection après le rendu setTimeout(() => { textarea.focus(); const newCursorPos = start + before.length + selectedText.length; textarea.setSelectionRange(newCursorPos, newCursorPos); }, 0); }; const handleBold = () => insertMarkdown('**', '**'); const handleItalic = () => insertMarkdown('*', '*'); const handleList = () => { const textarea = textareaRef.current; if (!textarea) return; const start = textarea.selectionStart; const lineStart = value.lastIndexOf('\n', start - 1) + 1; const newText = value.substring(0, lineStart) + '• ' + value.substring(lineStart); onChange(newText); }; const handleLink = () => { const url = prompt('Entrez l\'URL du lien :'); if (url) { insertMarkdown('[', `](${url})`); } }; // Fonction pour prévisualiser le markdown en HTML simple const renderPreview = (text: string) => { let html = text; // Gras html = html.replace(/\*\*(.*?)\*\*/g, '$1'); // Italique html = html.replace(/\*(.*?)\*/g, '$1'); // Liens html = html.replace(/\[(.*?)\]\((.*?)\)/g, '$1'); // Listes - d'abord identifier les blocs de listes const lines = html.split('\n'); let inList = false; const processedLines: string[] = []; lines.forEach((line) => { if (line.trim().startsWith('• ')) { if (!inList) { processedLines.push(''); inList = false; } processedLines.push(line); } }); if (inList) { processedLines.push(''); } html = processedLines.join('\n'); // Retours à la ligne (sauf dans les listes) html = html.replace(/\n(?![^\n]*<\/?(ul|li))/g, '
'); return html; }; return (
{/* Barre d'outils */}
{value.length}/{maxLength} caractères
{/* Zone de texte */}