/** * WPEditor — React wrapper around WordPress TinyMCE (wp.oldEditor / wp_editor). * * Props: * id {string} Unique editor ID (must be valid HTML id, no dots) * value {string} HTML content * onChange {function} Callback receiving HTML string on every change * height {number} Editor height in px (default 420) */ import { useEffect, useRef, useCallback } from '@wordpress/element'; /* ──────── helpers to access the WP editor API ──────── */ const getEditorAPI = () => window.wp?.oldEditor || window.wp?.editor; const WPEditor = ( { id = 'aime-tinymce', value = '', onChange, height = 420 } ) => { const containerRef = useRef( null ); const isInitialized = useRef( false ); const pendingValue = useRef( value ); // Track the most recent internal content to avoid unnecessary setContent calls const lastContent = useRef( value ); /** * Flush the TinyMCE or textarea content through the onChange callback. */ const flush = useCallback( () => { const editor = window.tinymce?.get( id ); let html; if ( editor && ! editor.isHidden() ) { html = editor.getContent(); } else { const ta = document.getElementById( id ); html = ta ? ta.value : ''; } lastContent.current = html; onChange?.( html ); }, [ id, onChange ] ); /* ──────── init / destroy ──────── */ useEffect( () => { let cancelled = false; let retryTimer = null; let attempts = 0; // ~6s of retries at 100ms — covers slow/concatenated script loads. const MAX_ATTEMPTS = 60; const doInitialize = () => { const api = getEditorAPI(); try { // Clear any stale editor registered under this id (leftover from a // prior mount or a partially-failed init) so the toolbar renders. if ( window.tinymce?.get( id ) ) { api.remove( id ); } } catch ( e ) { /* */ } try { api.initialize( id, { // Top-level false prevents WP's own autop filter from wrapping //