| 1 |
/** |
| 2 |
* Stamp `wppb-fb-block-editor` on admin + canvas iframe bodies for scoped chrome CSS. |
| 3 |
* Iframe mounts late / reloads — re-stamp on mutations and iframe load. |
| 4 |
*/ |
| 5 |
|
| 6 |
import { registerPlugin } from '@wordpress/plugins'; |
| 7 |
import { useSelect } from '@wordpress/data'; |
| 8 |
import { useEffect } from '@wordpress/element'; |
| 9 |
|
| 10 |
const PB_CPTS = [ 'wppb-rf-cpt', 'wppb-epf-cpt' ]; |
| 11 |
const BODY_CLASS = 'wppb-fb-block-editor'; |
| 12 |
|
| 13 |
/** The block-canvas document: the iframe's contentDocument, else null. */ |
| 14 |
function findCanvasDoc() { |
| 15 |
const iframe = document.querySelector( 'iframe[name="editor-canvas"]' ); |
| 16 |
if ( iframe && iframe.contentDocument ) return iframe.contentDocument; |
| 17 |
return null; |
| 18 |
} |
| 19 |
|
| 20 |
function stamp() { |
| 21 |
if ( document.body ) document.body.classList.add( BODY_CLASS ); |
| 22 |
const canvasDoc = findCanvasDoc(); |
| 23 |
if ( canvasDoc && canvasDoc.body ) canvasDoc.body.classList.add( BODY_CLASS ); |
| 24 |
} |
| 25 |
|
| 26 |
const EditorBodyClass = () => { |
| 27 |
const isOurPostType = useSelect( |
| 28 |
( select ) => PB_CPTS.includes( select( 'core/editor' ).getCurrentPostType() ), |
| 29 |
[] |
| 30 |
); |
| 31 |
|
| 32 |
useEffect( () => { |
| 33 |
if ( ! isOurPostType ) return undefined; |
| 34 |
|
| 35 |
let frame = null; |
| 36 |
const scheduleStamp = () => { |
| 37 |
if ( frame ) return; |
| 38 |
frame = requestAnimationFrame( () => { |
| 39 |
frame = null; |
| 40 |
stamp(); |
| 41 |
} ); |
| 42 |
}; |
| 43 |
|
| 44 |
stamp(); // immediate (the iframe may already be present) |
| 45 |
|
| 46 |
const observer = new MutationObserver( scheduleStamp ); |
| 47 |
observer.observe( document.body, { childList: true, subtree: true } ); |
| 48 |
|
| 49 |
const iframe = document.querySelector( 'iframe[name="editor-canvas"]' ); |
| 50 |
if ( iframe ) iframe.addEventListener( 'load', scheduleStamp ); |
| 51 |
|
| 52 |
return () => { |
| 53 |
observer.disconnect(); |
| 54 |
if ( frame ) cancelAnimationFrame( frame ); |
| 55 |
if ( iframe ) iframe.removeEventListener( 'load', scheduleStamp ); |
| 56 |
}; |
| 57 |
}, [ isOurPostType ] ); |
| 58 |
|
| 59 |
return null; |
| 60 |
}; |
| 61 |
|
| 62 |
registerPlugin( 'wppb-fb-editor-body-class', { render: EditorBodyClass } ); |
| 63 |
|