Skip to content

Commit

Permalink
[not verified] Allow visibility settings on blocks with server side r…
Browse files Browse the repository at this point in the history
…endered previews
  • Loading branch information
mreishus committed Aug 25, 2021
1 parent cbab677 commit eb65643
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,9 @@ import { unescape } from './util';
/* eslint-disable react/react-in-jsx-scope */

const blockHasVisibilitySettings = name => {
// When I put extra attributes on these blocks, they
// refuse to render with a message "Error loading block: Invalid parameter(s): attributes"
// However, most blocks don't do this. Why is this?
const disallowed = new Set( [
'core/archives',
'core/latest-comments',
'core/latest-posts',
'core/legacy-widget', // These already have legacy visibility settings, avoid 2 levels of controls
'core/widget-area',
'core/widget-area', // This is the entire outer area; I don't think the editor lets you visit here
] );
return ! disallowed.has( name );
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,37 @@ public static function setup_block_controls() {
wp_set_script_translations( 'widget-visibility-editor', 'jetpack' );
}

/**
* Add the 'conditions' attribute, where visibility rules are stored, to some blocks.
*
* We normally add the block attributes in the browser's javascript env only,
* but these blocks use a ServerSideRender dynamic preview, so the php env needs
* to know about the new attribute, too.
*/
public static function add_block_attributes_filter() {
$blocks_to_add_visibility_conditions = array(
// These use <ServerSideRender>.
'core/calendar',
'core/latest-comments',
'core/rss',
'core/archives',
'core/tag-cloud',
'core/page-list',
'core/latest-posts',
);

$filter_metadata_registration = function ( $settings, $metadata ) use ( $blocks_to_add_visibility_conditions ) {
if ( in_array( $metadata['name'], $blocks_to_add_visibility_conditions, true ) && ! empty( $settings['attributes'] ) ) {
$settings['attributes']['conditions'] = array(
'type' => 'object',
);
}
return $settings;
};

add_filter( 'block_type_metadata_settings', $filter_metadata_registration, 10, 2 );
}

/**
* Prepare the interface for editing widgets - loading css, javascript & data
*/
Expand Down Expand Up @@ -1167,3 +1198,10 @@ static function migrate_post_type_rules() {
}

add_action( 'init', array( 'Jetpack_Widget_Conditions', 'init' ) );

// Add the 'conditions' attribute to server side rendered blocks
// 'init' happens too late to hook on block registration.
global $pagenow;
if ( is_customize_preview() || 'widgets.php' === $pagenow || ( false !== strpos( $_SERVER['REQUEST_URI'], '/wp-json/wp/v2/block-renderer' ) ) ) {
Jetpack_Widget_Conditions::add_block_attributes_filter();
}

0 comments on commit eb65643

Please sign in to comment.