From e6743da250c2b7174e2ab1ad205661f1127dac48 Mon Sep 17 00:00:00 2001
From: Eric Bremner <ebremner@uwaterloo.ca>
Date: Mon, 29 Nov 2021 19:59:25 +0000
Subject: [PATCH] ISTWCMS-5204: updating the display of images to only include
 those images stlyes used for an image

---
 uw_cfg_common.module | 63 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 63 insertions(+)

diff --git a/uw_cfg_common.module b/uw_cfg_common.module
index f1970ee9..d243a0ba 100644
--- a/uw_cfg_common.module
+++ b/uw_cfg_common.module
@@ -722,6 +722,69 @@ function uw_cfg_common_form_menu_link_content_menu_link_content_form_alter(array
   unset($form['menu_parent']['#options']['main:uw_base_profile.front_page']);
 }
 
+/**
+ * Implements template_preprocess_responsive_images().
+ */
+function uw_cfg_common_preprocess_responsive_image(&$variables) {
+
+  // Get the current path.
+  $current_path = \Drupal::service('path.current')->getPath();
+
+  // Explode the current path so we can check where we are.
+  $current_path_parts = explode('/', $current_path);
+
+  // If the current path has a node, we need to alter
+  // the image styles.
+  if ($current_path_parts[1] == 'node') {
+
+    // Get the media library parameters, we will use this
+    // if we are on a media library page/modal.
+    $media_lib_parameters = \Drupal::request()->query->get('media_library_opener_parameters');
+
+    // If we are on a contact image, remove all styles
+    // but those for portraits.
+    if (
+      $media_lib_parameters['bundle'] == 'uw_ct_contact' ||
+      end($current_path_parts) == 'uw_ct_contact'
+    ) {
+
+      // Get the styles used for portraits.
+      $uw_styles = \Drupal::service('uw_cfg_common.uw_service')->getCropImageStyles('portrait');
+    }
+    else {
+
+      // Get the styles used for responsive.
+      $uw_styles = \Drupal::service('uw_cfg_common.uw_service')->getCropImageStyles('portrait');
+    }
+
+    // Step through each of the sources and see if we are.
+    // to use it.
+    foreach ($variables['sources'] as $index => $source) {
+
+      // Get the srcset.
+      $srcset = $source->storage()['srcset']->render();
+
+      // Break into parts so that we can check for image styles.
+      $srcset_parts = explode('/', $srcset);
+
+      // Step through each of the srcset parts.
+      foreach ($srcset_parts as $sp) {
+
+        // Ensure that we are on an image style.
+        if (strpos($sp, 'uw_is') !== FALSE) {
+
+          // If not in the list of image styles, remove
+          // it from the sources.
+          if (!in_array($sp, $uw_styles)) {
+            unset($variables['sources'][$index]);
+          }
+        }
+      }
+    }
+  }
+}
+
+
 /**
  * Implements hook_form_alter().
  *
-- 
GitLab