admin管理员组文章数量:1327488
I have been trying to extend some custom blocks I coded along with core blocks to support custom CSS.
This is how tried to extend the block attributes
const {assign} = lodash;
const {__} = wp.i18n;
const {hasBlockSupport} = wp.blocks;
const {PanelBody} = wpponents;
const {createHigherOrderComponent} = wppose;
const {InspectorControls} = wp.blockEditor || wp.editor;
const {Fragment} = wp.element;
const {addFilter} = wp.hooks;
/**
* Internal dependencies.
*/
import './style.scss';
import CSSEditor from './editor.js';
import './inject-css.js';
const addAttribute = (settings) => {
console.log(settings);
if (hasBlockSupport(settings, 'customClassName', true)) {
settings.attributes = assign(settings.attributes, {
hasCustomCSS: {
type: 'boolean',
default: false
},
customCSS: {
type: 'string',
default: null
}
});
}
return settings;
};
const withInspectorControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const hasCustomClassName = hasBlockSupport(props.name, 'customClassName', true);
if (hasCustomClassName && props.isSelected) {
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody
title={__('Additional CSS')}
initialOpen={false}>
<CSSEditor
clientId={props.clientId}
setAttributes={props.setAttributes}
attributes={props.attributes}
/>
</PanelBody>
</InspectorControls>
</Fragment>
);
}
return <BlockEdit {...props} />;
};
}, 'withInspectorControl');
addFilter('blocks.registerBlockType', 'attire-blocks/custom-css', addAttribute);
addFilter('editor.BlockEdit', 'attire-blocks/with-inspector-controls', withInspectorControls);
The thing is, custom attributes I introduced (hasCustomCSS
and customCSS
) are applied to core blocks are not applied to blocks I made! Also, see the console.log(settings);
. This only prints core blocks, mine are not shown.
EDIT: This is how I am applying the attributes:
add_action('wp_head', array($this, 'apply_custom_css'));
public function apply_custom_css()
{
if (function_exists('has_blocks') && has_blocks(get_the_ID())) {
global $post;
if (!is_object($post)) {
return;
}
$blocks = $this->parse_blocks($post->post_content);
if (!is_array($blocks) || empty($blocks)) {
return;
}
$style = "\n" . '<style type="text/css" media="all" id="atbs-ccss">' . "\n";
$style .= $this->get_block_custom_css($blocks);
$style .= "\n" . '</style>' . "\n";
echo $style;
}
}
public function get_block_custom_css($inner_blocks)
{
$style = '';
foreach ($inner_blocks as $block) {
if (isset($block['attrs'])) {
if (isset($block['attrs']['hasCustomCSS']) && isset($block['attrs']['customCSS'])) {
$style .= $block['attrs']['customCSS'];
}
}
if ('core/block' === $block['blockName'] && !empty($block['attrs']['ref'])) {
$reusable_block = get_post($block['attrs']['ref']);
if (!$reusable_block || 'wp_block' !== $reusable_block->post_type) {
return;
}
if ('publish' !== $reusable_block->post_status || !empty($reusable_block->post_password)) {
return;
}
$blocks = $this->parse_blocks($reusable_block->post_content);
$style .= $this->get_block_custom_css($blocks);
}
if (isset($block['innerBlocks']) && !empty($block['innerBlocks']) && is_array($block['innerBlocks'])) {
$style .= $this->get_block_custom_css($block['innerBlocks']);
}
}
return $style;
}
Edit 2 : the CSSEditor component
const CSSEditor = ({attributes, setAttributes, clientId}) => {
useEffect(() => {
if (attributes.customCSS) {
customCSSRef.current = (attributes.customCSS).replace(/.atbs-ccss-[a-zA-Z0-9_-]*/g, 'wrapper');
} else {
customCSSRef.current = 'wrapper {\n}\n';
}
editorRef.current = wp.CodeMirror(document.getElementById('atbs-css-editor'), {
value: customCSSRef.current,
autoCloseBrackets: true,
continueComments: true,
lineNumbers: true,
lineWrapping: true,
matchBrackets: true,
lint: true,
gutters: ['CodeMirror-lint-markers'],
styleActiveLine: true,
styleActiveSelected: true,
extraKeys: {
'Ctrl-Space': 'autocomplete',
'Alt-F': 'findPersistent',
'Cmd-F': 'findPersistent'
}
});
editorRef.current.on('change', () => {
const regex = new RegExp('wrapper', 'g');
customCSSRef.current = editorRef.current.getValue().replace(regex, `.${classArRef.current}`);
if (('wrapper {\n}\n').replace(/\s+/g, '') === customCSSRef.current.replace(/\s+/g, '')) {
return setAttributes({customCSS: null});
}
setAttributes({customCSS: customCSSRef.current});
});
}, []);
useEffect(() => {
let classes = getClassName();
setAttributes({
hasCustomCSS: true,
className: classes
});
}, [attributes]);
const getClassName = () => {
let classes;
const uniqueId = clientId.substr(0, 8);
if (null !== customCSSRef.current && ('wrapper {\n}\n').replace(/\s+/g, '') === customCSSRef.current.replace(/\s+/g, '')) {
return attributes.className;
}
if (attributes.className) {
classes = attributes.className;
if (!classes.includes('atbs-ccss-')) {
classes = classes.split(' ');
classes.push(`atbs-ccss-${uniqueId}`);
classes = classes.join(' ');
}
classArRef.current = classes.split(' ');
classArRef.current = classArRef.current.find(i => i.includes('atbs-ccss'));
} else {
classes = `atbs-ccss-${uniqueId}`;
classArRef.current = classes;
}
return classes;
};
const editorRef = useRef(null);
const customCSSRef = useRef(null);
const classArRef = useRef(null);
return (
<Fragment>
<p>{__('Add your custom CSS.')}</p>
<div id="atbs-css-editor" className="atbs-css-editor"/>
<p>{__('Use')} <code>wrapper</code> {__('to target block wrapper.')}</p>
<p>{__('')}</p>
<p>{__('Example:')}</p>
<pre className="atbs-css-editor-help">
{'wrapper {\n background: #000;\n}\n\nwrapper img {\n border-radius: 100%;\n}'}
</pre>
<p>{__('You can also use other CSS syntax here, such as media queries.')}</p>
</Fragment>
);
};
本文标签: Can39t extend my custom gutenberg block
版权声明:本文标题:Can't extend my custom gutenberg block 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742198957a2431601.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论