Нема описа

image-compare.php 2.3KB

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