Wire up the Filtered Image block end-to-end

This commit is contained in:
Keith Solomon
2026-08-05 16:48:03 -05:00
parent c2a0ae2d8c
commit d21d3c9ac2
5 changed files with 285 additions and 3 deletions
+77
View File
@@ -0,0 +1,77 @@
/**
* Block registration entry point.
*
* @package ImageFilters
*/
import { registerBlockType } from '@wordpress/blocks';
import { addFilter } from '@wordpress/hooks';
import './styles/style.scss';
import './styles/editor.scss';
import metadata from './block.json';
import edit from './edit';
import save from './save';
import { PRESETS, DEFAULT_PRESET, isValidPresetSlug } from './presets';
import { FilterPanel } from './inspector';
registerBlockType( metadata.name, {
...metadata,
edit,
save,
} );
/**
* Add the filter panel to the Image block's inspector when the active
* block is the Filtered Image block. We use the editor.BlockEdit filter
* so we don't have to re-implement the entire MediaPlaceholder UX.
*
* @param {Function} BlockEdit
* @return {Function}
*/
function withFilterPanel( BlockEdit ) {
return ( props ) => {
if ( props.name !== 'ksolo/image-filter' ) {
return <BlockEdit { ...props } />;
}
return (
<>
<BlockEdit { ...props } />
<FilterPanel
attributes={ props.attributes }
setAttributes={ props.setAttributes }
/>
</>
);
};
}
addFilter( 'editor.BlockEdit', 'image-filters/with-filter-panel', withFilterPanel );
/**
* Normalise the filter attribute on save. If the saved slug is unknown
* (e.g. the post was edited by hand), fall back to DEFAULT_PRESET so the
* block still renders without errors.
*/
function ensureValidFilter( settings, name ) {
if ( name !== 'ksolo/image-filter' ) {
return settings;
}
const originalSave = settings.save;
settings.save = ( props ) => {
if ( ! isValidPresetSlug( props.attributes.filter ) ) {
props.attributes.filter = DEFAULT_PRESET;
}
return originalSave( props );
};
return settings;
}
addFilter(
'blocks.registerBlockType',
'image-filters/ensure-valid-filter',
ensureValidFilter
);
// Re-export PRESETS so the consuming downstream code (e.g. a future
// design-tool integration) can grab them from this module.
export { PRESETS };