image-compare.php
88 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Image Compare Block. |
| 4 | * |
| 5 | * @since 8.6 |
| 6 | * |
| 7 | * @package automattic/jetpack |
| 8 | */ |
| 9 | |
| 10 | namespace Automattic\Jetpack\Extensions\ImageCompare; |
| 11 | |
| 12 | use Automattic\Jetpack\Blocks; |
| 13 | use Jetpack_Gutenberg; |
| 14 | |
| 15 | /** |
| 16 | * Registers the block for use in Gutenberg |
| 17 | * This is done via an action so that we can disable |
| 18 | * registration if we need to. |
| 19 | */ |
| 20 | function register_block() { |
| 21 | Blocks::jetpack_register_block( |
| 22 | __DIR__, |
| 23 | array( 'render_callback' => __NAMESPACE__ . '\load_assets' ) |
| 24 | ); |
| 25 | } |
| 26 | add_action( 'init', __NAMESPACE__ . '\register_block' ); |
| 27 | |
| 28 | /** |
| 29 | * Image Compare block registration/dependency declaration. |
| 30 | * |
| 31 | * @param array $attr Array containing the image-compare block attributes. |
| 32 | * @param string $content String containing the image-compare block content. |
| 33 | * |
| 34 | * @return string |
| 35 | */ |
| 36 | function load_assets( $attr, $content ) { |
| 37 | Jetpack_Gutenberg::load_assets_as_required( __DIR__ ); |
| 38 | wp_localize_script( |
| 39 | 'jetpack-block-' . sanitize_title_with_dashes( Blocks::get_block_feature( __DIR__ ) ), |
| 40 | 'imageCompareHandle', |
| 41 | array( |
| 42 | 'msg' => __( 'Slide to compare images', 'jetpack' ), |
| 43 | ) |
| 44 | ); |
| 45 | if ( Blocks::is_amp_request() ) { |
| 46 | $content = preg_replace( |
| 47 | '#<div class="juxtapose".+?</div>#s', |
| 48 | render_amp( $attr ), |
| 49 | $content |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | return $content; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Render image compare block for AMP |
| 58 | * |
| 59 | * @param array $attr Array containing the image-compare block attributes. |
| 60 | * |
| 61 | * @return string Markup for amp-image-slider. |
| 62 | */ |
| 63 | function render_amp( $attr ) { |
| 64 | $img_before = $attr['imageBefore']; |
| 65 | $img_after = $attr['imageAfter']; |
| 66 | |
| 67 | $width = ! empty( $img_before['width'] ) ? absint( $img_before['width'] ) : 0; |
| 68 | $height = ! empty( $img_before['height'] ) ? absint( $img_before['height'] ) : 0; |
| 69 | |
| 70 | // As fallback, give 1:1 aspect ratio. |
| 71 | if ( ! $width || ! $height ) { |
| 72 | $width = 1; |
| 73 | $height = 1; |
| 74 | } |
| 75 | |
| 76 | return sprintf( |
| 77 | '<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>', |
| 78 | esc_attr( $width ), |
| 79 | esc_attr( $height ), |
| 80 | absint( $img_before['id'] ), |
| 81 | esc_url( $img_before['url'] ), |
| 82 | esc_attr( $img_before['alt'] ), |
| 83 | absint( $img_after['id'] ), |
| 84 | esc_url( $img_after['url'] ), |
| 85 | esc_attr( $img_after['alt'] ) |
| 86 | ); |
| 87 | } |
| 88 |