Skip to content

Instantly share code, notes, and snippets.

@troychaplin
Last active September 7, 2023 14:41
Show Gist options
  • Save troychaplin/19221f942ebf4532bf3037f700d437fa to your computer and use it in GitHub Desktop.
Save troychaplin/19221f942ebf4532bf3037f700d437fa to your computer and use it in GitHub Desktop.
Block Formats
import domReady from '@wordpress/dom-ready'
import { compose, ifCondition } from '@wordpress/compose'
import { withSelect } from '@wordpress/data'
import { BlockControls } from '@wordpress/block-editor'
import { ToolbarButton } from '@wordpress/components'
import { formatBold, formatItalic } from '@wordpress/icons'
// Array of format types to unregister
// Check formats in browser console --> wp.data.select( 'core/rich-text' ).getFormatTypes();
const formatTypesToUnregister = [
'core/annotation',
'core/code',
'core/bold',
'core/footnote',
'core/image',
'core/italic',
'core/keyboard',
'core/language',
// 'core/link',
'core/subscript',
'core/superscript',
// 'core/strikethrough',
'core/text-color',
'core/underline',
// 'core/unknown',
]
// Arrays of allowed format types on blocks
const boldFormatTypes = ['core/paragraph']
const italicFormatTypes = ['core/paragraph']
domReady(() => {
// Loop through array of formats to unregister
formatTypesToUnregister.forEach((formatType) => {
wp.richText.unregisterFormatType(formatType)
})
const BoldButton = (props) => {
return (
<BlockControls>
<ToolbarButton
icon={formatBold}
title="Bold"
onClick={() => {
props.onChange(
wp.richText.toggleFormat(props.value, {
type: 'core/bold',
}),
)
}}
isActive={props.isActive}
/>
</BlockControls>
)
}
const ItalicButton = (props) => {
return (
<BlockControls>
<ToolbarButton
icon={formatItalic}
title="Italic"
onClick={() => {
props.onChange(
wp.richText.toggleFormat(props.value, {
type: 'core/italic',
}),
)
}}
isActive={props.isActive}
/>
</BlockControls>
)
}
const ConditionalBoldButton = compose(
withSelect((select) => {
return {
selectedBlock: select('core/block-editor').getSelectedBlock(),
}
}),
ifCondition((props) => {
return props.selectedBlock && boldFormatTypes.includes(props.selectedBlock.name)
}),
)(BoldButton)
const ConditionalItalicButton = compose(
withSelect((select) => {
return {
selectedBlock: select('core/block-editor').getSelectedBlock(),
}
}),
ifCondition((props) => {
return props.selectedBlock && italicFormatTypes.includes(props.selectedBlock.name)
}),
)(ItalicButton)
// Then they are re-registered conditionally (on specific blocks)
wp.richText.registerFormatType('core/bold', {
title: 'Bold',
tagName: 'strong',
className: 'myprefix-text-bold',
edit: ConditionalBoldButton,
})
wp.richText.registerFormatType('core/italic', {
title: 'Italic',
tagName: 'em',
className: 'myprefix-text-italic',
edit: ConditionalItalicButton,
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment