Neah/components/ui/rich-text-editor.tsx
2025-05-01 10:17:28 +02:00

159 lines
4.7 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { detectTextDirection } from '@/lib/utils/text-direction';
import DOMPurify from 'isomorphic-dompurify';
interface RichTextEditorProps {
/** Initial HTML content */
initialContent?: string;
/** Callback when content changes */
onChange?: (html: string) => void;
/** Additional CSS class names */
className?: string;
/** Editor placeholder text */
placeholder?: string;
/** Whether the editor is read-only */
readOnly?: boolean;
/** Minimum height of the editor */
minHeight?: string;
/** Initial text direction */
initialDirection?: 'ltr' | 'rtl';
}
// Before using DOMPurify, configure it to not add dir attributes automatically
// This will prevent conflicts with our explicit direction handling
DOMPurify.removeHooks('afterSanitizeAttributes');
/**
* Unified rich text editor component with proper RTL support
* Handles email composition with appropriate text direction detection
*/
const RichTextEditor = forwardRef<HTMLDivElement, RichTextEditorProps>(({
initialContent = '',
onChange,
className = '',
placeholder = 'Write your message...',
readOnly = false,
minHeight = '200px',
initialDirection
}, ref) => {
const internalEditorRef = useRef<HTMLDivElement>(null);
const [direction, setDirection] = useState<'ltr' | 'rtl'>(
initialDirection || detectTextDirection(initialContent)
);
// Forward the ref to parent components
useImperativeHandle(ref, () => internalEditorRef.current as HTMLDivElement);
// Initialize editor with clean content
useEffect(() => {
if (internalEditorRef.current) {
// Clean the initial content but preserve existing dir attributes
const cleanContent = DOMPurify.sanitize(initialContent, {
ADD_ATTR: ['dir'], // Ensure dir attributes are preserved
FORBID_ATTR: ['onerror', 'onload', 'onclick'] // Only strip dangerous attributes
});
internalEditorRef.current.innerHTML = cleanContent;
// Set initial direction
internalEditorRef.current.setAttribute('dir', direction);
// Focus editor if not read-only
if (!readOnly) {
setTimeout(() => {
internalEditorRef.current?.focus();
}, 100);
}
}
}, [initialContent, direction, readOnly]);
// Handle content changes and detect direction changes
const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
if (onChange && e.currentTarget.innerHTML !== initialContent) {
onChange(e.currentTarget.innerHTML);
}
// Re-detect direction on significant content changes
// Only do this when the content length has changed significantly
const newContent = e.currentTarget.innerText;
if (newContent.length > 5 && newContent.length % 10 === 0) {
const newDirection = detectTextDirection(newContent);
if (newDirection !== direction) {
setDirection(newDirection);
e.currentTarget.setAttribute('dir', newDirection);
}
}
};
return (
<div className="rich-text-editor-container">
<div
ref={internalEditorRef}
contentEditable={!readOnly}
className={`rich-text-editor outline-none p-3 ${className}`}
onInput={handleInput}
dir={direction}
style={{
minHeight,
cursor: readOnly ? 'default' : 'text',
}}
data-placeholder={placeholder}
suppressContentEditableWarning
/>
<style jsx>{`
.rich-text-editor {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.6;
overflow-wrap: break-word;
word-break: break-word;
white-space: pre-wrap;
}
.rich-text-editor:empty:before {
content: attr(data-placeholder);
color: #aaa;
pointer-events: none;
}
/* RTL text direction is automatically handled via dir attribute */
.rich-text-editor[dir="rtl"] {
text-align: right;
}
.rich-text-editor blockquote {
margin: 10px 0;
padding-left: 15px;
border-left: 2px solid #ddd;
color: #666;
}
/* Handle RTL blockquotes properly */
.rich-text-editor[dir="rtl"] blockquote {
padding-left: 0;
padding-right: 15px;
border-left: none;
border-right: 2px solid #ddd;
}
.rich-text-editor img {
max-width: 100%;
height: auto;
}
`}</style>
</div>
);
});
RichTextEditor.displayName = 'RichTextEditor';
export default RichTextEditor;