| 1 |
<?php |
| 2 |
|
| 3 |
namespace SureCart\BlockLibrary; |
| 4 |
|
| 5 |
/** |
| 6 |
* Provide anchor support for blocks. |
| 7 |
*/ |
| 8 |
class BlockAnchorSupportService { |
| 9 |
/** |
| 10 |
* Register anchor support |
| 11 |
* |
| 12 |
* @param WP_Block_Type $block_type Block Type. |
| 13 |
* |
| 14 |
* @return void |
| 15 |
*/ |
| 16 |
public function registerAnchorSupport( $block_type ) { |
| 17 |
$has_anchor_support = block_has_support( $block_type, 'anchor', false ); |
| 18 |
|
| 19 |
if ( $has_anchor_support ) { |
| 20 |
if ( ! $block_type->attributes ) { |
| 21 |
$block_type->attributes = array(); |
| 22 |
} |
| 23 |
|
| 24 |
if ( ! array_key_exists( 'anchor', $block_type->attributes ) ) { |
| 25 |
$block_type->attributes['anchor'] = array( |
| 26 |
'type' => 'string', |
| 27 |
); |
| 28 |
} |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Add the anchor to the output. |
| 34 |
* |
| 35 |
* @param WP_Block_Type $block_type Block Type. |
| 36 |
* @param array $block_attributes Block attributes. |
| 37 |
* |
| 38 |
* @return array Block CSS classes and inline styles. |
| 39 |
*/ |
| 40 |
public function applyAnchorSupport( $block_type, $block_attributes ) { |
| 41 |
// exclude kadence blocks. |
| 42 |
if ( isset( $block_attributes['kbVersion'] ) ) { |
| 43 |
return $block_attributes; |
| 44 |
} |
| 45 |
|
| 46 |
$has_anchor_support = block_has_support( $block_type, 'anchor', false ); |
| 47 |
$attributes = array(); |
| 48 |
if ( $has_anchor_support ) { |
| 49 |
$has_anchor = array_key_exists( 'anchor', $block_attributes ); |
| 50 |
|
| 51 |
if ( $has_anchor ) { |
| 52 |
$attributes['id'] = $block_attributes['anchor']; |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
return $attributes; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Register block support. |
| 61 |
* |
| 62 |
* @return void |
| 63 |
*/ |
| 64 |
public function bootstrap() { |
| 65 |
\WP_Block_Supports::get_instance()->register( |
| 66 |
'anchor', |
| 67 |
array( |
| 68 |
'register_attribute' => [ $this, 'registerAnchorSupport' ], |
| 69 |
'apply' => [ $this, 'applyAnchorSupport' ], |
| 70 |
) |
| 71 |
); |
| 72 |
} |
| 73 |
} |
| 74 |
|