| 1 |
import { createBlock } from '@wordpress/blocks'; |
| 2 |
import { ToolbarButton } from '@wordpress/components'; |
| 3 |
import { useDispatch } from '@wordpress/data'; |
| 4 |
import { render } from '@wordpress/element'; |
| 5 |
import { __ } from '@wordpress/i18n'; |
| 6 |
import { registerPlugin } from '@wordpress/plugins'; |
| 7 |
|
| 8 |
import getIcon from '../../utils/get-icon'; |
| 9 |
|
| 10 |
const { GHOSTKIT } = window; |
| 11 |
|
| 12 |
/** |
| 13 |
* Add templates button to Gutenberg toolbar |
| 14 |
*/ |
| 15 |
function ToolbarTemplates() { |
| 16 |
const { insertBlocks } = useDispatch('core/block-editor'); |
| 17 |
|
| 18 |
if (!GHOSTKIT.allowTemplates) { |
| 19 |
return null; |
| 20 |
} |
| 21 |
|
| 22 |
function LibraryButton() { |
| 23 |
return ( |
| 24 |
<ToolbarButton |
| 25 |
className="components-button components-icon-button" |
| 26 |
aria-label={__('Add Template', 'ghostkit')} |
| 27 |
onClick={() => { |
| 28 |
insertBlocks( |
| 29 |
createBlock('ghostkit/grid', { |
| 30 |
isTemplatesModalOnly: true, |
| 31 |
}) |
| 32 |
); |
| 33 |
}} |
| 34 |
> |
| 35 |
{getIcon('plugin-templates')} |
| 36 |
{__('Templates Library', 'ghostkit')} |
| 37 |
</ToolbarButton> |
| 38 |
); |
| 39 |
} |
| 40 |
|
| 41 |
const checkElement = async (selector) => { |
| 42 |
while (document.querySelector(selector) === null) { |
| 43 |
await new Promise((resolve) => |
| 44 |
window.requestAnimationFrame(resolve) |
| 45 |
); |
| 46 |
} |
| 47 |
return document.querySelector(selector); |
| 48 |
}; |
| 49 |
|
| 50 |
checkElement('.edit-post-header-toolbar').then(($toolbar) => { |
| 51 |
if (!$toolbar.querySelector('.ghostkit-toolbar-templates')) { |
| 52 |
const $toolbarPlace = document.createElement('div'); |
| 53 |
$toolbarPlace.classList.add('ghostkit-toolbar-templates'); |
| 54 |
|
| 55 |
$toolbar.appendChild($toolbarPlace); |
| 56 |
|
| 57 |
render(<LibraryButton />, $toolbarPlace); |
| 58 |
} |
| 59 |
}); |
| 60 |
|
| 61 |
return null; |
| 62 |
} |
| 63 |
|
| 64 |
registerPlugin('gkt-toolbar-templates', { |
| 65 |
render: ToolbarTemplates, |
| 66 |
}); |
| 67 |
|