| 1 |
/** |
| 2 |
* Keep the inserter open on PB form CPTs (field palette, not dismissible). |
| 3 |
* Re-opens on any close; CSS hides the "+" toggle (Layer 8d). |
| 4 |
* Prefers `core/editor`, falls back to `core/edit-post` (pre-WP 6.5). |
| 5 |
*/ |
| 6 |
|
| 7 |
import { useEffect } from '@wordpress/element'; |
| 8 |
import { useSelect, select as dataSelect, dispatch as dataDispatch } from '@wordpress/data'; |
| 9 |
import { registerPlugin } from '@wordpress/plugins'; |
| 10 |
|
| 11 |
const PB_CPTS = [ 'wppb-rf-cpt', 'wppb-epf-cpt' ]; |
| 12 |
|
| 13 |
// Canonical first, deprecated proxy second. |
| 14 |
const INSERTER_STORES = [ 'core/editor', 'core/edit-post' ]; |
| 15 |
|
| 16 |
// Open the inserter via whichever store owns the action. Returns true once a |
| 17 |
// dispatch target accepts the call. |
| 18 |
const openInserter = () => { |
| 19 |
for ( const store of INSERTER_STORES ) { |
| 20 |
const sel = dataSelect( store ); |
| 21 |
const dis = dataDispatch( store ); |
| 22 |
if ( |
| 23 |
sel && typeof sel.isInserterOpened === 'function' && |
| 24 |
dis && typeof dis.setIsInserterOpened === 'function' |
| 25 |
) { |
| 26 |
dis.setIsInserterOpened( true ); |
| 27 |
return true; |
| 28 |
} |
| 29 |
} |
| 30 |
return false; |
| 31 |
}; |
| 32 |
|
| 33 |
const ForceOpenInserter = () => { |
| 34 |
const postType = useSelect( |
| 35 |
( select ) => select( 'core/editor' ).getCurrentPostType(), |
| 36 |
[] |
| 37 |
); |
| 38 |
const isOurPostType = PB_CPTS.includes( postType ); |
| 39 |
|
| 40 |
// Subscribe to the inserter open-state on whichever store exposes the |
| 41 |
// selector. Returning a boolean keeps the effect dep stable so it only |
| 42 |
// re-runs on a genuine open↔closed change. Default to `true` when no store |
| 43 |
// exposes the selector so we never thrash trying to open something we can't |
| 44 |
// read. |
| 45 |
const isInserterOpen = useSelect( ( select ) => { |
| 46 |
for ( const store of INSERTER_STORES ) { |
| 47 |
const sel = select( store ); |
| 48 |
if ( sel && typeof sel.isInserterOpened === 'function' ) { |
| 49 |
return !! sel.isInserterOpened(); |
| 50 |
} |
| 51 |
} |
| 52 |
return true; |
| 53 |
}, [] ); |
| 54 |
|
| 55 |
useEffect( () => { |
| 56 |
if ( ! isOurPostType ) return; |
| 57 |
// Covers the initial open (inserter closed by default on load) and |
| 58 |
// every subsequent close attempt — re-opening on a false state is what |
| 59 |
// makes it un-closable. Re-opening to `true` flips the selector, |
| 60 |
// re-runs this effect with isInserterOpen === true, and no-ops; no loop. |
| 61 |
if ( isInserterOpen === false ) { |
| 62 |
openInserter(); |
| 63 |
} |
| 64 |
}, [ isOurPostType, isInserterOpen ] ); |
| 65 |
|
| 66 |
return null; |
| 67 |
}; |
| 68 |
|
| 69 |
registerPlugin( 'wppb-fb-force-open-inserter', { render: ForceOpenInserter } ); |
| 70 |
|