// components/fixed-editor.js import React, { useRef, useEffect } from "react"; import { Editor } from "@tinymce/tinymce-react"; function FixedEditor(props) { const editorRef = useRef(null); const contentRef = useRef(props.initialData || ''); const onChangeRef = useRef(props.onChange); // Update refs when props change useEffect(() => { onChangeRef.current = props.onChange; }, [props.onChange]); useEffect(() => { if (props.initialData !== undefined && editorRef.current) { contentRef.current = props.initialData; editorRef.current.setContent(props.initialData); } }, [props.initialData]); const handleInit = (evt, editor) => { editorRef.current = editor; // Set initial content if (props.initialData) { editor.setContent(props.initialData); contentRef.current = props.initialData; } // Create a debounced onChange handler let timeoutId = null; const debouncedOnChange = (content) => { if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { if (onChangeRef.current && content !== contentRef.current) { contentRef.current = content; onChangeRef.current(content); } }, 100); }; // Handle all content changes editor.on('change keyup input paste', (e) => { const content = editor.getContent(); debouncedOnChange(content); }); // Handle undo/redo editor.on('Undo Redo', (e) => { setTimeout(() => { const content = editor.getContent(); debouncedOnChange(content); }, 0); }); // Prevent cursor jumping by handling focus events editor.on('focus', (e) => { // Save current selection editor.lastSelection = editor.selection.getBookmark(); }); editor.on('blur', (e) => { // Restore selection if available if (editor.lastSelection) { try { editor.selection.moveToBookmark(editor.lastSelection); } catch (error) { // Ignore bookmark errors } } }); // Handle key events to prevent jumping editor.on('keydown', (e) => { // Save selection before any key operation editor.lastSelection = editor.selection.getBookmark(); }); editor.on('keyup', (e) => { // Restore selection after key operation if (editor.lastSelection) { try { editor.selection.moveToBookmark(editor.lastSelection); } catch (error) { // Ignore bookmark errors } } }); }; return ( ); } export default FixedEditor;