You are here

public static function BlazyMedia::build in Blazy 7

Same name and namespace in other branches
  1. 8.2 src/BlazyMedia.php \Drupal\blazy\BlazyMedia::build()
  2. 8 src/BlazyMedia.php \Drupal\blazy\BlazyMedia::build()

Prepares the Blazy iframe as a structured array ready for ::renderer().

@todo support other Media file entities like at D8: Media Facebook, etc.

Parameters

array $element: The renderable array being modified.

1 call to BlazyMedia::build()
BlazyManager::preRender in src/BlazyManager.php
Builds the Blazy as a structured array ready for ::renderer().

File

src/BlazyMedia.php, line 25

Class

BlazyMedia
Provides extra utilities to work with Media.

Namespace

Drupal\blazy

Code

public static function build(array &$element = []) {
  $attributes =& $element['#attributes'];
  $settings =& $element['#settings'];
  $settings['player'] = empty($settings['lightbox']) && $settings['media_switch'] == 'media';
  $settings['use_image'] = !empty($settings['media_switch']);
  $iframe_attributes = [
    'data-src' => $settings['embed_url'],
    'src' => 'about:blank',
    'class' => [
      'b-lazy',
      'media__element',
    ],
    'allowfullscreen' => '',
  ];

  // Prevents broken iframe when aspect ratio is empty.
  if (empty($settings['ratio']) && $settings['width']) {
    $iframe_attributes['width'] = $settings['width'];
    $iframe_attributes['height'] = $settings['height'];
  }

  // Adds specific Youtube attributes, related to mobile apps.
  $allow = '';
  if (strpos($settings['embed_url'], 'youtu') !== FALSE) {
    $allow = $iframe_attributes['allow'] = 'autoplay; accelerometer; encrypted-media; gyroscope; picture-in-picture';
  }
  $player_attributes = [
    'class' => 'media__icon media__icon--play',
    'data-url' => $settings['autoplay_url'],
  ];
  if ($settings['use_media']) {
    $iframe = [
      '#type' => 'html_tag',
      '#tag' => 'iframe',
      '#value' => '',
      '#attributes' => $iframe_attributes,
    ];

    // No need to print iframe when media switcher is on to save bytes.
    if ($settings['player']) {
      $icon = '<span class="media__icon media__icon--close"></span>';
      $iframe = [
        '#markup' => $icon . '<span' . drupal_attributes($player_attributes) . '></span>',
      ];
    }
    $element['#iframe'] = $iframe;
    $attributes['class'][] = 'media--player';

    // Support browser native lazy loading as per 8/2019, Chrome 76+.
    // See https://web.dev/native-lazy-loading/
    $attributes['loading'] = 'lazy';
  }

  // Iframe is removed on lazyloaded, puts data at non-removable storage.
  $attributes['data-media'] = drupal_json_encode([
    'type' => $settings['type'],
    'scheme' => $settings['scheme'],
    'allow' => $allow,
  ]);
}