import * as React from 'react' import {__, _x} from '@wordpress/i18n' import { useEffect, } from '@wordpress/element' import { useDispatch, useSelect, } from '@wordpress/data' import { store as editorStore, } from '@wordpress/editor' import { store as noticesStore, } from '@wordpress/notices' import { usePluginOptions, } from '../options' import { isAdmin, isElevated, canUnfilteredHtml, } from '../../data' export const useHasPermissions = (type: 'unfiltered_html' | 'admin' | 'elevated' = 'unfiltered_html') => { const hasPermissions = useSelect(select => { switch(type) { /** User has full control of plugin. */ case 'admin': return isAdmin /** User can use plugin but doesn't see settings pages. */ case 'elevated': return isElevated /** User can do unfiltered HTML. */ default: return canUnfilteredHtml // select(editorStore).canUserUseUnfilteredHTML() } }, [type]) as any as boolean return hasPermissions } const PermissionsPlugin: React.FC = () => { const hasPermissions = useHasPermissions() const {unfilteredHTMLWarn} = usePluginOptions() const content = useSelect(select => { if(!unfilteredHTMLWarn) { // Don't select any content when it's not needed to warn return '' } return select(editorStore).getEditedPostContent() }, [unfilteredHTMLWarn]) const { createWarningNotice, } = useDispatch(noticesStore) useEffect(() => { const shouldWarn = !hasPermissions && content && (content.includes('"skaBlocks":{') || content.includes('"skaBlocksAttributes":{')) if(shouldWarn) { createWarningNotice( __(`Warning: Current user does not have the unfiltered HTML capability, editing this post may cause content loss.`, 'ska-blocks'), { id: 'ska-blocks-permissions', isDismissible: false, } ) } }, [hasPermissions, content, createWarningNotice]) return null } export default { name: 'ska-blocks-permissions', render: PermissionsPlugin, }