| 1 |
import { dispatch, select } from '@wordpress/data'; |
| 2 |
import { useGlobalsStore } from '@library/state/global'; |
| 3 |
import { addGlobalCSS, requiredCSSVars } from '@library/util/css'; |
| 4 |
|
| 5 |
export const insertBlocks = async (blocks) => { |
| 6 |
const { insertBlocks, replaceBlock } = dispatch('core/block-editor'); |
| 7 |
const { |
| 8 |
getSelectedBlock, |
| 9 |
getBlockHierarchyRootClientId, |
| 10 |
getBlockIndex, |
| 11 |
getGlobalBlockCount, |
| 12 |
} = select('core/block-editor'); |
| 13 |
|
| 14 |
const { clientId, name, attributes } = getSelectedBlock() || {}; |
| 15 |
const rootClientId = clientId ? getBlockHierarchyRootClientId(clientId) : ''; |
| 16 |
const insertPointIndex = |
| 17 |
(rootClientId ? getBlockIndex(rootClientId) : getGlobalBlockCount()) + 1; |
| 18 |
|
| 19 |
// If there are spacing vars in state, we need to add them to the dom |
| 20 |
const { missingCSSVars } = useGlobalsStore.getState(); |
| 21 |
missingCSSVars.forEach((key) => { |
| 22 |
// Add variables to the dom |
| 23 |
document?.documentElement?.style?.setProperty(key, requiredCSSVars[key]); |
| 24 |
// Editor might be nested in an iframe too |
| 25 |
document |
| 26 |
.querySelector('iframe[name="editor-canvas"]') |
| 27 |
?.contentDocument?.documentElement?.style?.setProperty( |
| 28 |
key, |
| 29 |
requiredCSSVars[key], |
| 30 |
); |
| 31 |
}); |
| 32 |
|
| 33 |
// We also need to add them to global styles too |
| 34 |
if (missingCSSVars.length) addGlobalCSS(missingCSSVars); |
| 35 |
|
| 36 |
if (name === 'core/paragraph' && attributes?.content === '') { |
| 37 |
return await replaceBlock(clientId, blocks); |
| 38 |
} |
| 39 |
return await insertBlocks(blocks, insertPointIndex); |
| 40 |
}; |
| 41 |
|