You are here

public static function BlazyBreakpoint::attributes in Blazy 7

Provides re-usable breakpoint data-attributes for IMG or DIV element.

$settings['breakpoints'] must contain: xs, sm, md, lg breakpoints with the expected keys: width, image_style.

Overrides BlazyBreakpointInterface::attributes

File

src/BlazyBreakpoint.php, line 23

Class

BlazyBreakpoint
Implements BlazyBreakpointInterface.

Namespace

Drupal\blazy

Code

public static function attributes(array &$attributes, array &$settings, $item = NULL) {

  // Only provide multi-serving image URLs if breakpoints are provided.
  if (empty($settings['breakpoints'])) {
    return;
  }
  $srcset = $json = [];

  // https://css-tricks.com/sometimes-sizes-is-quite-important/
  // For older iOS devices that don't support w descriptors in srcset, the
  // first source item in the list will be used.
  $settings['breakpoints'] = array_reverse($settings['breakpoints']);
  foreach ($settings['breakpoints'] as $key => $breakpoint) {
    $url = image_style_url($breakpoint['image_style'], $settings['uri']);

    // Supports multi-breakpoint aspect ratio with irregular sizes.
    // Yet, only provide individual dimensions if not already set.
    // See Drupal\blazy\BlazyFormatter::setImageDimensions().
    if (!empty($settings['_breakpoint_ratio']) && empty($settings['blazy_data']['dimensions'])) {
      $dimensions = Blazy::transformDimensions($breakpoint['image_style'], $item);
      if ($width = self::widthFromDescriptors($breakpoint['width'])) {
        $json[$width] = round($dimensions['height'] / $dimensions['width'] * 100, 2);
      }
    }
    $settings['breakpoints'][$key]['url'] = $url;

    // Recheck library if multi-styled BG is still supported anyway.
    // Confirmed: still working with GridStack multi-image-style per item.
    if ($settings['background']) {
      $attributes['data-src-' . $key] = $url;
    }
    else {
      $width = trim($breakpoint['width']);
      $width = is_numeric($width) ? $width . 'w' : $width;
      $srcset[] = $url . ' ' . $width;
    }
  }
  if ($srcset) {
    $settings['srcset'] = implode(', ', $srcset);
    $attributes['srcset'] = '';
    $attributes['data-srcset'] = $settings['srcset'];
    $attributes['sizes'] = '100w';
    if (!empty($settings['sizes'])) {
      $attributes['sizes'] = trim($settings['sizes']);
      unset($attributes['height'], $attributes['width']);
    }
  }
  if ($json) {
    $settings['blazy_data']['dimensions'] = $json;
  }
}