responsive_image.module 12.5 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Responsive image display formatter for image fields.
6 7
 */

8
use Drupal\responsive_image\Entity\ResponsiveImageMapping;
9 10 11 12 13
use \Drupal\Core\Template\Attribute;

/**
 * Implements hook_help().
 */
14
function responsive_image_help($path, $arg) {
15 16
  $output = '';
  switch ($path) {
17
    case 'admin/help#responsive_image':
18
      $output .= '<h3>' . t('About') . '</h3>';
19
      $output .= '<p>' . t('The Responsive Image module provides an image formatter and breakpoint mappings to output responsive images using the HTML5 picture tag. For more information, see the <a href="!responsive_image">online documentation for the Responsive Image module</a>.', array( '!responsive_image' => 'https://drupal.org/documentation/modules/responsive_image')) . '</p>';
20 21
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
22 23 24 25
      $output .= '<dt>' . t('Defining responsive image mappings') . '</dt>';
      $output .= '<dd>' . t('By creating responsive image mappings you define the image styles that are being used to output images at certain breakpoints. On the <a href="!responsive_image_mapping">Responsive image mappings</a> page, click <em>Add responsive image mapping</em> to create a new mapping. First chose a label and a breakpoint group and click Save. After that you can choose the image styles that will be used for each breakpoint. Image styles can be defined on the <a href="!image_styles">Image styles page</a> that is provided by the <a href="!image_help">Image module</a>. Breakpoints are defined in the configuration files of the theme. See the <a href="!breakpoint_help">help page of the Breakpoint module</a> for more information.', array('!responsive_image_mapping' => \Drupal::url('responsive_image.mapping_page'), '!image_styles' => \Drupal::url('image.style_list'),'!image_help' => \Drupal::url('help.page', array('name' => 'image')), '!breakpoint_help' => \Drupal::url('help.page', array('name' => 'breakpoint')))) . '</dd>';
      $output .= '<dt>' . t('Using responsive image mappings in Image fields') . '</dt>';
      $output .= '<dd>' . t('After defining responsive image mappings, you can use them in the display settings for your Image fields, so that the site displays responsive images using the HTML5 picture tag. Open the Manage display page for the entity type (content type, taxonomy vocabulary, etc.) that the Image field is attached to. Choose the format <em>Responsive image</em>, click the Edit icon, and select one of the responsive image mappings that you have created. For general information on how to manage fields and their display see the <a href="!field_ui">help page of the Field UI module</a>. For information about entities see the <a href="!entity_help">help page of the Entity module</a>.', array('!field_ui' => \Drupal::url('help.page', array('name' => 'field_ui')),'!entity_help' => \Drupal::url('help.page', array('name' => 'entity')))) . '</dd>';
26
      $output .= '</dl>';
27
      break;
28 29
    case 'admin/config/media/responsive-image-mapping':
      $output .= '<p>' . t('A responsive image mapping associates an image style with each breakpoint defined by your theme.') . '</p>';
30 31 32 33 34 35 36 37 38
      break;

  }
  return $output;
}

/**
 * Implements hook_permission().
 */
39
function responsive_image_permission() {
40
  return array(
41 42
    'administer responsive image' => array(
      'title' => t('Administer responsive images'),
43 44 45 46
    ),
  );
}

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/**
 * Implements hook_menu().
 */
function responsive_image_menu() {
  $items = array();

  $items['admin/config/media/responsive-image-mapping'] = array(
    'title' => 'Responsive image mappings',
    'description' => 'Manage responsive image mappings',
    'weight' => 10,
    'route_name' => 'responsive_image.mapping_page',
  );
  $items['admin/config/media/responsive-image-mapping/%responsive_image_mapping'] = array(
    'title' => 'Edit responsive image mapping',
    'route_name' => 'responsive_image.mapping_page_edit',
  );
  $items['admin/config/media/responsive-image-mapping/%responsive_image_mapping/duplicate'] = array(
    'title' => 'Duplicate responsive image mapping',
    'route_name' => 'responsive_image.mapping_page_duplicate',
  );

  return $items;
}

71
/**
72
 * Load one responsive image by its identifier.
73 74
 *
 * @param int $id
75
 *   The id of the responsive image mapping to load.
76
 *
77
 * @return \Drupal\responsive_image\ResponsiveImageMappingInterface
78
 *   The entity object, or NULL if there is no entity with the given id.
79 80 81 82 83 84
 *
 * @todo Needed for menu_callback
 *
 * @see http://drupal.org/node/1798214
 *
 */
85 86
function responsive_image_mapping_load($id) {
  return entity_load('responsive_image_mapping', $id);
87 88 89 90 91
}

/**
 * Implements hook_theme().
 */
92
function responsive_image_theme() {
93
  return array(
94
    'responsive_image' => array(
95 96
      'variables' => array(
        'style_name' => NULL,
97
        'uri' => NULL,
98 99 100 101 102 103 104 105
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
        'breakpoints' => array(),
      ),
    ),
106
    'responsive_image_formatter' => array(
107 108 109 110 111 112 113
      'variables' => array(
        'item' => NULL,
        'path' => NULL,
        'image_style' => NULL,
        'breakpoints' => array(),
      ),
    ),
114
    'responsive_image_source' => array(
115 116 117
      'variables' => array(
        'src' => NULL,
        'srcset' => NULL,
118
        'dimensions' => NULL,
119 120 121 122 123 124 125
        'media' => NULL,
      ),
    ),
  );
}

/**
126
 * Returns HTML for a responsive image field formatter.
127 128 129
 *
 * @param array $variables
 *   An associative array containing:
130
 *   - item: An ImageItem object.
131 132 133 134 135 136
 *   - image_style: An optional image style.
 *   - path: An optional array containing the link 'path' and link 'options'.
 *   - breakpoints: An array containing breakpoints.
 *
 * @ingroup themeable
 */
137
function theme_responsive_image_formatter($variables) {
138
  $item = $variables['item'];
139
  if (!isset($variables['breakpoints']) || empty($variables['breakpoints'])) {
140 141
    $image_formatter = array(
      '#theme' => 'image_formatter',
142
      '#item' => $item,
143 144 145 146
      '#image_style' => $variables['image_style'],
      '#path' => $variables['path'],
    );
    return drupal_render($image_formatter);
147 148
  }

149 150
  $responsive_image = array(
    '#theme' => 'responsive_image',
151 152
    '#width' => $item->width,
    '#height' => $item->height,
153 154 155
    '#style_name' => $variables['image_style'],
    '#breakpoints' => $variables['breakpoints'],
  );
156
  if (isset($item->uri)) {
157
    $responsive_image['#uri'] = $item->uri;
158
  }
159
  elseif ($entity = $item->entity) {
160 161
    $responsive_image['#uri'] = $entity->getFileUri();
    $responsive_image['#entity'] = $entity;
162
  }
163
  $responsive_image['#alt'] = $item->alt;
164
  if (drupal_strlen($item->title) != 0) {
165
    $responsive_image['#title'] = $item->title;
166
  }
167
  // @todo Add support for route names.
168 169 170 171
  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    $options['html'] = TRUE;
172
    return l($responsive_image, $path, $options);
173
  }
174

175
  return drupal_render($responsive_image);
176 177 178
}

/**
179
 * Returns HTML for a responsive image.
180 181 182 183 184 185 186 187
 *
 * @param $variables
 *   An associative array containing:
 *   - uri: Either the path of the image file (relative to base_path()) or a
 *     full URL.
 *   - width: The width of the image (if known).
 *   - height: The height of the image (if known).
 *   - alt: The alternative text for text-based browsers.
188 189
 *   - title: The title text is displayed when the image is hovered in some
 *     popular browsers.
190
 *   - style_name: The name of the style to be used as a fallback image.
191 192 193 194
 *   - breakpoints: An array containing breakpoints.
 *
 * @ingroup themeable
 */
195
function theme_responsive_image($variables) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  // Make sure that width and height are proper values
  // If they exists we'll output them
  // @see http://www.w3.org/community/respimg/2012/06/18/florians-compromise/
  if (isset($variables['width']) && empty($variables['width'])) {
    unset($variables['width']);
    unset($variables['height']);
  }
  elseif (isset($variables['height']) && empty($variables['height'])) {
    unset($variables['width']);
    unset($variables['height']);
  }

  $sources = array();
  $output = array();

  // Fallback image, output as source with media query.
  $sources[] = array(
213
    'src' => entity_load('image_style', $variables['style_name'])->buildUrl($variables['uri']),
214
    'dimensions' => responsive_image_get_image_dimensions($variables),
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  );

  // All breakpoints and multipliers.
  foreach ($variables['breakpoints'] as $breakpoint_name => $multipliers) {
    $breakpoint = breakpoint_load($breakpoint_name);
    if ($breakpoint) {
      $new_sources = array();
      foreach ($multipliers as $multiplier => $image_style) {
        $new_source = $variables;
        $new_source['style_name'] = $image_style;
        $new_source['#multiplier'] = $multiplier;
        $new_sources[] = $new_source;
      }

      // Only one image, use src.
      if (count($new_sources) == 1) {
        $sources[] = array(
232
          'src' => entity_load('image_style', $new_sources[0]['style_name'])->buildUrl($new_sources[0]['uri']),
233
          'dimensions' => responsive_image_get_image_dimensions($new_sources[0]),
234 235 236 237
          'media' => $breakpoint->mediaQuery,
        );
      }
      else {
238
        // Multiple images, use srcset.
239 240
        $srcset = array();
        foreach ($new_sources as $new_source) {
241
          $srcset[] = entity_load('image_style', $new_source['style_name'])->buildUrl($new_source['uri']) . ' ' . $new_source['#multiplier'];
242 243 244
        }
        $sources[] = array(
          'srcset' => implode(', ', $srcset),
245
          'dimensions' => responsive_image_get_image_dimensions($new_sources[0]),
246 247 248 249 250 251 252
          'media' => $breakpoint->mediaQuery,
        );
      }
    }
  }

  if (!empty($sources)) {
253
    $output[] = '<picture>';
254

255
    // Add source tags to the output.
256
    foreach ($sources as $source) {
257 258
      $responsive_image_source = array(
        '#theme' => 'responsive_image_source',
259 260 261 262
        '#src' => $source['src'],
        '#dimensions' => $source['dimensions'],
      );
      if (isset($source['media'])) {
263
        $responsive_image_source['#media'] = $source['media'];
264 265
      }
      if (isset($source['srcset'])) {
266
        $responsive_image_source['#srcset'] = $source['srcset'];
267
      }
268
      $output[] = drupal_render($responsive_image_source);
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    }

    $output[] = '</picture>';
    return implode("\n", $output);
  }
}

/**
 * Returns HTML for a source tag.
 *
 * @param type $variables
 *   An associative array containing:
 *   - media: The media query to use.
 *   - srcset: The srcset containing the the path of the image file or a full
 *     URL and optionally multipliers.
 *   - src: Either the path of the image file (relative to base_path()) or a
 *     full URL.
 *   - dimensions: The width and height of the image (if known).
 *
 * @ingroup themeable
 */
290
function theme_responsive_image_source($variables) {
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  $output = array();
  if (isset($variables['media']) && !empty($variables['media'])) {
    if (!isset($variables['srcset'])) {
      $output[] = '<!-- <source media="' . $variables['media'] . '" src="' . $variables['src'] . '" ' . new Attribute($variables['dimensions']) . ' /> -->';
      $output[] = '<source media="' . $variables['media'] . '" src="' . $variables['src'] . '" ' . new Attribute($variables['dimensions']) . '/>';
    }
    elseif (!isset($variables['src'])) {
      $output[] = '<!-- <source media="' . $variables['media'] . '" srcset="' . $variables['srcset'] . '" ' . new Attribute($variables['dimensions']) . ' /> -->';
      $output[] = '<source media="' . $variables['media'] . '" srcset="' . $variables['srcset'] . '" ' . new Attribute($variables['dimensions']) . ' />';
    }
  }
  else {
    $output[] = '<!-- <source src="' . $variables['src'] . '" ' . new Attribute($variables['dimensions']) . ' /> -->';
    $output[] = '<source src="' . $variables['src'] . '" ' . new Attribute($variables['dimensions']) . '/>';
  }
  return implode("\n", $output);
}

/**
 * Determines the dimensions of an image.
 *
 * @param $variables
 *   An associative array containing:
 *   - style_name: The name of the style to be used to alter the original image.
 *   - width: The width of the source image (if known).
 *   - height: The height of the source image (if known).
 *
 * @return array
 *   Dimensions to be modified - an array with components width and height, in
 *   pixels.
 */
322
function responsive_image_get_image_dimensions($variables) {
323 324 325 326 327 328
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

329
  entity_load('image_style', $variables['style_name'])->transformDimensions($dimensions);
330 331 332

  return $dimensions;
}