render.php
80 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Image Compare block render implementation. |
| 4 | * |
| 5 | * Loaded lazily from image-compare.php only when the block is rendered, to keep |
| 6 | * the render body out of the eager front-end PHP/opcache footprint. |
| 7 | * |
| 8 | * @package automattic/jetpack |
| 9 | */ |
| 10 | |
| 11 | namespace Automattic\Jetpack\Extensions\ImageCompare; |
| 12 | |
| 13 | use Automattic\Jetpack\Blocks; |
| 14 | use Jetpack_Gutenberg; |
| 15 | |
| 16 | if ( ! defined( 'ABSPATH' ) ) { |
| 17 | exit( 0 ); |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Dynamic rendering of the block. |
| 22 | * |
| 23 | * @param array $attr Array containing the image-compare block attributes. |
| 24 | * @param string $content String containing the image-compare block content. |
| 25 | * |
| 26 | * @return string |
| 27 | */ |
| 28 | function render_implementation( $attr, $content ) { |
| 29 | Jetpack_Gutenberg::load_assets_as_required( __DIR__ ); |
| 30 | wp_localize_script( |
| 31 | 'jetpack-block-' . sanitize_title_with_dashes( Blocks::get_block_feature( __DIR__ ) ), |
| 32 | 'imageCompareHandle', |
| 33 | array( |
| 34 | 'msg' => __( 'Slide to compare images', 'jetpack' ), |
| 35 | ) |
| 36 | ); |
| 37 | if ( Blocks::is_amp_request() ) { |
| 38 | $content = preg_replace( |
| 39 | '#<div class="juxtapose".+?</div>#s', |
| 40 | render_amp( $attr ), |
| 41 | $content |
| 42 | ); |
| 43 | } |
| 44 | |
| 45 | return $content; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Render image compare block for AMP |
| 50 | * |
| 51 | * @param array $attr Array containing the image-compare block attributes. |
| 52 | * |
| 53 | * @return string Markup for amp-image-slider. |
| 54 | */ |
| 55 | function render_amp( $attr ) { |
| 56 | $img_before = $attr['imageBefore']; |
| 57 | $img_after = $attr['imageAfter']; |
| 58 | |
| 59 | $width = ! empty( $img_before['width'] ) ? absint( $img_before['width'] ) : 0; |
| 60 | $height = ! empty( $img_before['height'] ) ? absint( $img_before['height'] ) : 0; |
| 61 | |
| 62 | // As fallback, give 1:1 aspect ratio. |
| 63 | if ( ! $width || ! $height ) { |
| 64 | $width = 1; |
| 65 | $height = 1; |
| 66 | } |
| 67 | |
| 68 | return sprintf( |
| 69 | '<amp-image-slider layout="responsive" width="%1$s" height="%2$s"> <amp-img id="%3$d" src="%4$s" alt="%5$s" layout="fill"></amp-img> <amp-img id="%6$d" src="%7$s" alt="%8$s" layout="fill"></amp-img></amp-image-slider>', |
| 70 | esc_attr( $width ), |
| 71 | esc_attr( $height ), |
| 72 | absint( $img_before['id'] ?? 0 ), |
| 73 | esc_url( $img_before['url'] ?? '' ), |
| 74 | esc_attr( $img_before['alt'] ?? '' ), |
| 75 | absint( $img_after['id'] ?? 0 ), |
| 76 | esc_url( $img_after['url'] ?? '' ), |
| 77 | esc_attr( $img_after['alt'] ?? '' ) |
| 78 | ); |
| 79 | } |
| 80 |