mediahub-fe/components/editor/custom-editor.js

85 lines
2.2 KiB
JavaScript

// components/custom-editor.js
import React, { useCallback, useEffect, useRef, useState } from "react";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import Editor from "ckeditor5-custom-build";
function CustomEditor(props) {
const editorRef = useRef(null);
const [isEditorReady, setIsEditorReady] = useState(false);
const [currentContent, setCurrentContent] = useState(props.initialData || "");
// Handle editor initialization
const handleInit = useCallback((evt, editor) => {
editorRef.current = editor;
setIsEditorReady(true);
// Set initial content immediately when editor is ready
if (currentContent) {
editor.setContent(currentContent);
}
// Simple onChange handler
editor.on('change', () => {
const content = editor.getContent();
setCurrentContent(content);
if (props.onChange) {
props.onChange(content);
}
});
}, [currentContent, props.onChange]);
// Watch for changes in initialData prop
useEffect(() => {
if (props.initialData !== currentContent) {
setCurrentContent(props.initialData || "");
// Update editor content if editor is ready
if (editorRef.current && isEditorReady) {
editorRef.current.setContent(props.initialData || "");
}
}
}, [props.initialData, currentContent, isEditorReady]);
// Handle initial data when editor becomes ready
useEffect(() => {
if (isEditorReady && currentContent && editorRef.current) {
editorRef.current.setContent(currentContent);
}
}, [isEditorReady, currentContent]);
return (
<CKEditor
editor={Editor}
data={props.initialData}
onChange={(event, editor) => {
const data = editor.getData();
// console.log({ event, editor, data });
props.onChange(data);
}}
config={{
toolbar: [
"heading",
"fontsize",
"bold",
"italic",
"link",
"numberedList",
"bulletedList",
"undo",
"redo",
"alignment",
"outdent",
"indent",
"blockQuote",
"insertTable",
"codeBlock",
"sourceEditing",
],
}}
/>
);
}
export default CustomEditor;