| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/file` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* When the `core/file` block is rendering, check if we need to enqueue the `wp-block-file-view` script. |
| 10 |
* |
| 11 |
* @since 5.8.0 |
| 12 |
* |
| 13 |
* @param array $attributes The block attributes. |
| 14 |
* @param string $content The block content. |
| 15 |
* @param WP_Block $block The parsed block. |
| 16 |
* |
| 17 |
* @return string Returns the block content. |
| 18 |
*/ |
| 19 |
function gutenberg_render_block_core_file( $attributes, $content ) { |
| 20 |
// If it's interactive, enqueue the script module and add the directives. |
| 21 |
if ( ! empty( $attributes['displayPreview'] ) ) { |
| 22 |
$suffix = wp_scripts_get_suffix(); |
| 23 |
if ( defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN ) { |
| 24 |
$module_url = gutenberg_url( '/build/interactivity/file.min.js' ); |
| 25 |
} |
| 26 |
|
| 27 |
wp_register_script_module( |
| 28 |
'@wordpress/block-library/file', |
| 29 |
isset( $module_url ) ? $module_url : includes_url( "blocks/file/view{$suffix}.js" ), |
| 30 |
array( '@wordpress/interactivity' ), |
| 31 |
defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : get_bloginfo( 'version' ) |
| 32 |
); |
| 33 |
wp_enqueue_script_module( '@wordpress/block-library/file' ); |
| 34 |
|
| 35 |
$processor = new WP_HTML_Tag_Processor( $content ); |
| 36 |
$processor->next_tag(); |
| 37 |
$processor->set_attribute( 'data-wp-interactive', 'core/file' ); |
| 38 |
$processor->next_tag( 'object' ); |
| 39 |
$processor->set_attribute( 'data-wp-bind--hidden', '!state.hasPdfPreview' ); |
| 40 |
$processor->set_attribute( 'hidden', true ); |
| 41 |
|
| 42 |
$filename = $processor->get_attribute( 'aria-label' ); |
| 43 |
$has_filename = ! empty( $filename ) && 'PDF embed' !== $filename; |
| 44 |
$label = $has_filename ? sprintf( |
| 45 |
/* translators: %s: filename. */ |
| 46 |
__( 'Embed of %s.' ), |
| 47 |
$filename |
| 48 |
) : __( 'PDF embed' ); |
| 49 |
|
| 50 |
// Update object's aria-label attribute if present in block HTML. |
| 51 |
// Match an aria-label attribute from an object tag. |
| 52 |
$processor->set_attribute( 'aria-label', $label ); |
| 53 |
|
| 54 |
return $processor->get_updated_html(); |
| 55 |
} |
| 56 |
|
| 57 |
return $content; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Registers the `core/file` block on server. |
| 62 |
* |
| 63 |
* @since 5.8.0 |
| 64 |
*/ |
| 65 |
function gutenberg_register_block_core_file() { |
| 66 |
register_block_type_from_metadata( |
| 67 |
__DIR__ . '/file', |
| 68 |
array( |
| 69 |
'render_callback' => 'gutenberg_render_block_core_file', |
| 70 |
) |
| 71 |
); |
| 72 |
} |
| 73 |
add_action( 'init', 'gutenberg_register_block_core_file', 20 ); |
| 74 |
|