import { useTranslation } from 'react-i18next'; import React, { useEffect, useRef, useState } from 'react'; import Quill, { Delta } from 'quill/core'; import BoldFormat from 'quill/formats/bold'; import ItalicFormat from 'quill/formats/italic'; import UnderlineFormat from 'quill/formats/underline'; import HeaderFormat from 'quill/formats/header'; import ListFormat from 'quill/formats/list'; import QuoteFormat from 'quill/formats/blockquote'; import ImageFormat from 'quill/formats/image'; import { Bold, Italic, Underline, List, ListOrdered, Undo2, Redo2, Eraser, } from '../icons/ActionIcons'; import { Quote, ImagePlus } from 'lucide-react'; import { articleImageSource, ARTICLE_IMAGE_TYPES, readArticleImage, } from './richTextImages'; import { sanitizeArticleHtml } from './richTextContent'; import { countRichText, limitRichTextChange } from './richTextLength'; import 'quill/dist/quill.core.css'; import './RichTextEditor.css'; Quill.register( { 'formats/bold': BoldFormat, 'formats/italic': ItalicFormat, 'formats/underline': UnderlineFormat, 'formats/header': HeaderFormat, 'formats/list': ListFormat, 'formats/blockquote': QuoteFormat, 'formats/image': ImageFormat, }, true, ); export default function RichTextEditor({ value = '', onChange, disabled = false, invalid = false, onBusyChange, label = '富文本正文', placeholder = '', maxLength, }) { const { t } = useTranslation(); const host = useRef(null); const picker = useRef(null); const instance = useRef(null); const selection = useRef({ index: 0, length: 0 }); const callbacks = useRef({ value, onChange, onBusyChange, disabled, label, placeholder, maxLength, }); const insertFiles = useRef(null); const lastHtml = useRef(''); const [format, setFormat] = useState({}); const [count, setCount] = useState(0); const [busy, setBusy] = useState(false); const [imageError, setImageError] = useState(''); useEffect(() => { callbacks.current = { value, onChange, onBusyChange, disabled, label, placeholder, maxLength, }; }, [value, onChange, onBusyChange, disabled, label, placeholder, maxLength]); useEffect(() => { // A separate mount node keeps Quill DOM mutations outside React's tree. const mount = document.createElement('div'); const container = host.current; container.append(mount); let active = true; let processing = false; let compositionStart = null; const quill = new Quill(mount, { readOnly: callbacks.current.disabled, placeholder: callbacks.current.placeholder, formats: [ 'bold', 'italic', 'underline', 'header', 'list', 'blockquote', 'image', ], modules: { history: { userOnly: false }, toolbar: false }, }); instance.current = quill; const root = quill.root; root.setAttribute('role', 'textbox'); root.setAttribute('aria-multiline', 'true'); root.setAttribute('aria-required', 'true'); root.setAttribute('aria-label', callbacks.current.label); const update = (change, old) => { if (compositionStart) return; const limit = callbacks.current.maxLength; if (Number.isFinite(limit) && old && change) { const bounded = old.compose( new Delta(limitRichTextChange(old, change, limit)), ); const correction = quill.getContents().diff(bounded); if (correction.length()) quill.updateContents(correction, 'silent'); } const html = sanitizeArticleHtml(quill.getSemanticHTML()); const next = !quill.getText().trim() && !root.querySelector('img') ? '' : html; lastHtml.current = next; setCount(countRichText(quill.getText())); callbacks.current.onChange?.(next); }; const updateSelection = (range) => { if (range) selection.current = { index: range.index, length: range.length }; setFormat(quill.getFormat(range || selection.current)); }; quill.setContents( quill.clipboard.convert({ html: sanitizeArticleHtml(callbacks.current.value), }), 'silent', ); lastHtml.current = callbacks.current.value; setCount(countRichText(quill.getText())); quill.history.clear(); quill.on('text-change', update); quill.on('editor-change', updateSelectionFromEditor); function updateSelectionFromEditor(name, range) { updateSelection( name === 'selection-change' ? range : quill.getSelection(), ); } const begin = () => { if (!active || processing || callbacks.current.disabled) return false; processing = true; setBusy(true); setImageError(''); callbacks.current.onBusyChange?.(true); quill.enable(false); return true; }; const finish = () => { processing = false; if (!active) return; setBusy(false); callbacks.current.onBusyChange?.(false); quill.enable(!callbacks.current.disabled); if (!callbacks.current.disabled) { const range = { ...selection.current }; quill.focus(); quill.setSelection(range, 'silent'); } }; const insert = (delta, range) => { if (!active) return; let change = new Delta() .retain(range.index) .delete(range.length) .concat(delta); if (Number.isFinite(callbacks.current.maxLength)) { change = new Delta( limitRichTextChange( quill.getContents(), change, callbacks.current.maxLength, ), ); } quill.history.cutoff(); quill.updateContents(change, 'api'); quill.history.cutoff(); selection.current = { index: change.transformPosition(range.index, false), length: 0, }; }; const readFiles = async (files) => { const sources = []; for (const file of files) { try { sources.push(await readArticleImage(file)); } catch (error) { if (active) setImageError(error.message); sources.push(''); } } return sources; }; insertFiles.current = async (files) => { if (!begin()) return; const range = { ...selection.current }; try { const sources = await readFiles(files); const delta = sources .filter(Boolean) .reduce( (result, source) => result.insert({ image: source }), new Delta(), ); if (delta.length()) insert(delta, range); } finally { finish(); } }; const paste = async (event) => { event.preventDefault(); event.stopImmediatePropagation(); if (!begin()) return; const range = quill.getSelection() || selection.current; const html = event.clipboardData?.getData('text/html') || ''; const text = event.clipboardData?.getData('text/plain') || ''; const files = Array.from(event.clipboardData?.files || []); try { let delta; if (html) { const template = document.createElement('template'); template.innerHTML = html; let fileIndex = 0; let sources; for (const img of template.content.querySelectorAll('img')) { const original = img.getAttribute('src') || ''; let source = articleImageSource(original) || articleImageSource(img.getAttribute('data-src')); if ( !source && /^(?:file:|blob:|cid:|$)/i.test(original) && files.length ) { sources ??= await readFiles(files); source = sources[fileIndex++]; } if (source) img.setAttribute('src', source); else { img.remove(); if (active) setImageError( '部分图片无法粘贴,请使用可公开访问的图片地址,或粘贴不超过 2 MB 的 JPG、PNG、WebP、GIF 图片。', ); } } delta = quill.clipboard.convert({ html: sanitizeArticleHtml(template.innerHTML), text, }); } else if (files.length) { const sources = await readFiles(files); delta = sources .filter(Boolean) .reduce( (result, source) => result.insert({ image: source }), new Delta(), ); } else delta = quill.clipboard.convert( { text }, quill.getFormat(range.index), ); if (delta.length()) insert(delta, range); } catch { if (active) setImageError('粘贴失败,请重试或使用纯文本粘贴'); } finally { finish(); } }; const imageFailed = (event) => { if (event.target.tagName === 'IMG') setImageError( '部分图片加载失败,请确认原图地址可公开访问,或下载图片后重新插入。', ); }; // Capture before Quill's default clipboard/uploader to validate every image path. root.addEventListener('paste', paste, true); root.addEventListener('error', imageFailed, true); const drop = (event) => { event.preventDefault(); event.stopImmediatePropagation(); insertFiles.current?.(Array.from(event.dataTransfer?.files || [])); }; root.addEventListener('drop', drop, true); const startComposition = () => { compositionStart = quill.getContents(); }; const endComposition = () => { queueMicrotask(() => { if (!active || !compositionStart) return; const old = compositionStart; compositionStart = null; quill.update(); update(old.diff(quill.getContents()), old); }); }; root.addEventListener('compositionstart', startComposition); root.addEventListener('compositionend', endComposition); return () => { active = false; callbacks.current.onBusyChange?.(false); quill.off('text-change', update); quill.off('editor-change', updateSelectionFromEditor); root.removeEventListener('paste', paste, true); root.removeEventListener('error', imageFailed, true); root.removeEventListener('drop', drop, true); root.removeEventListener('compositionstart', startComposition); root.removeEventListener('compositionend', endComposition); quill.enable(false); instance.current = null; insertFiles.current = null; mount.remove(); container.classList.remove('ql-container'); }; }, []); useEffect(() => { const quill = instance.current; if (!quill) return; quill.enable(!disabled && !busy); quill.root.setAttribute('aria-invalid', String(invalid)); quill.root.setAttribute('aria-label', label); // Quill renders placeholder text via CSS, keeping it outside saved HTML. quill.root.setAttribute('data-placeholder', placeholder); quill.root.setAttribute('aria-placeholder', placeholder); }, [disabled, busy, invalid, label, placeholder]); useEffect(() => { const quill = instance.current; if (!quill || value === lastHtml.current) return; quill.setContents( quill.clipboard.convert({ html: sanitizeArticleHtml(value) }), 'silent', ); quill.history.clear(); lastHtml.current = value; selection.current = { index: 0, length: 0 }; setCount(countRichText(quill.getText())); setFormat({}); }, [value]); const run = (command) => { const quill = instance.current; if (!quill || disabled || busy) return; const range = { ...selection.current }; quill.focus(); quill.setSelection(range, 'silent'); command(quill); setFormat(quill.getFormat()); }; const tools = [ ['加粗', Bold, (q) => q.format('bold', !format.bold, 'user'), format.bold], [ '斜体', Italic, (q) => q.format('italic', !format.italic, 'user'), format.italic, ], [ '下划线', Underline, (q) => q.format('underline', !format.underline, 'user'), format.underline, ], [ '项目列表', List, (q) => q.format('list', format.list === 'bullet' ? false : 'bullet', 'user'), format.list === 'bullet', ], [ '有序列表', ListOrdered, (q) => q.format('list', format.list === 'ordered' ? false : 'ordered', 'user'), format.list === 'ordered', ], [ '引用', Quote, (q) => q.format('blockquote', !format.blockquote, 'user'), format.blockquote, ], ['撤销', Undo2, (q) => q.history.undo()], ['重做', Redo2, (q) => q.history.redo()], [ '清除格式', Eraser, (q) => q.removeFormat( selection.current.index, selection.current.length || 1, 'user', ), ], ]; return (