| 1 |
/** |
| 2 |
* Open mini-inserter destination store. |
| 3 |
* Existing Fields inserts here instead of appending to the root list. |
| 4 |
*/ |
| 5 |
import { select as dataSelect } from '@wordpress/data'; |
| 6 |
import { useSyncExternalStore } from '@wordpress/element'; |
| 7 |
|
| 8 |
import { createPubsubStore } from './createPubsubStore'; |
| 9 |
import { REPEATER_BLOCK_NAME as REPEATER_BLOCK } from './repeaterBlockName'; |
| 10 |
|
| 11 |
const CLOSED = { open: false, rootClientId: undefined, clientId: undefined, isAppender: false }; |
| 12 |
|
| 13 |
const store = createPubsubStore( |
| 14 |
CLOSED, |
| 15 |
( a, b ) => |
| 16 |
a.open === b.open && |
| 17 |
a.rootClientId === b.rootClientId && |
| 18 |
a.clientId === b.clientId && |
| 19 |
a.isAppender === b.isAppender, |
| 20 |
); |
| 21 |
|
| 22 |
/** |
| 23 |
* Called when a mini inserter popover opens. |
| 24 |
* |
| 25 |
* @param {Object} destination |
| 26 |
* @param {string} [destination.rootClientId] Container to insert into (undefined = root list). |
| 27 |
* @param {string} [destination.clientId] Insert BEFORE this block (core's in-between semantics). |
| 28 |
* @param {boolean} [destination.isAppender] Append to the end of `rootClientId`. |
| 29 |
*/ |
| 30 |
export const setMiniInserterTarget = ( { rootClientId, clientId, isAppender } = {} ) => |
| 31 |
store.set( { open: true, rootClientId, clientId, isAppender: !! isAppender } ); |
| 32 |
|
| 33 |
/** Called when the mini inserter popover closes. */ |
| 34 |
export const clearMiniInserterTarget = () => store.set( CLOSED ); |
| 35 |
|
| 36 |
/** Read the destination reactively (React components). */ |
| 37 |
export const useMiniInserterTarget = () => useSyncExternalStore( store.subscribe, store.get ); |
| 38 |
|
| 39 |
/** Read the destination imperatively (DOM sync code). */ |
| 40 |
export const getMiniInserterTarget = () => store.get(); |
| 41 |
|
| 42 |
/** Re-run on destination changes (DOM sync code). Returns an unsubscribe fn. */ |
| 43 |
export const subscribeMiniInserterTarget = ( listener ) => store.subscribe( listener ); |
| 44 |
|
| 45 |
/** |
| 46 |
* False when the destination is inside a Repeater (existing fields can't be |
| 47 |
* sub-fields). Driven by destination, not a per-caller flag. |
| 48 |
*/ |
| 49 |
export const miniInserterAllowsExistingFields = () => { |
| 50 |
const { rootClientId } = store.get(); |
| 51 |
if ( ! rootClientId ) return true; |
| 52 |
const editor = dataSelect( 'core/block-editor' ); |
| 53 |
if ( editor.getBlockName( rootClientId ) === REPEATER_BLOCK ) return false; |
| 54 |
const parents = editor.getBlockParents( rootClientId ) || []; |
| 55 |
return ! parents.some( ( id ) => editor.getBlockName( id ) === REPEATER_BLOCK ); |
| 56 |
}; |
| 57 |
|