From 8c40fdd5b2a55913c0e0b382dbc68fde33189913 Mon Sep 17 00:00:00 2001 From: Srijit S Madhavan Date: Wed, 22 Jan 2025 15:57:10 +0530 Subject: [PATCH] fix: support fallback for media src (#1490) * fix: add temporary backup url for github permanent url image availability delay * fix: added seperate function to trigger on load for img and video to remove title * chores: added comment * chores: requested changes * chore: adjust text --------- Co-authored-by: Silvester --- .../src/helpers/render-html-string.js | 42 +++++++++++++++---- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/elements/storytelling/src/helpers/render-html-string.js b/elements/storytelling/src/helpers/render-html-string.js index ccc84b505..eff0a7272 100644 --- a/elements/storytelling/src/helpers/render-html-string.js +++ b/elements/storytelling/src/helpers/render-html-string.js @@ -184,20 +184,48 @@ function processNode(node, initDispatchFunc) { const lightboxElements = []; const images = node.querySelectorAll("img"); - // Loop over each image - images.forEach((img) => { + const videos = node.querySelectorAll("video"); + + // Loop over each image/video + [...images, ...videos].forEach((media) => { // Check if the image is already inside a link (to avoid double wrapping) - const mode = img.getAttribute("mode"); + const mode = media.getAttribute("mode"); - if (img.parentNode.tagName !== "A" && mode !== "hero") { - img.style.cursor = "zoom-in"; - img.addEventListener("click", () => { + if (media.parentNode.tagName !== "A" && mode !== "hero") { + media.style.cursor = "zoom-in"; + media.addEventListener("click", () => { lightboxGallery.open(); }); + // Handle media loading error by switching to backup URL if available + media.onerror = () => { + if ( + document.body.contains(media) && + media.getAttribute("data-fallback-src") + ) { + media.src = media.getAttribute("data-fallback-src"); + media.removeAttribute("data-fallback-src"); + } else { + media.src = "https://placehold.co/600x400?text=Media+not+found"; + } + }; + + // Function to clear the backup URL title attribute after successful load + const loadFunc = () => { + if ( + document.body.contains(media) && + media.getAttribute("data-fallback-src") + ) { + media.removeAttribute("data-fallback-src"); + } + }; + + media.onload = loadFunc; + media.onloadeddata = loadFunc; + lightboxElements.push({ type: "image", - href: img.src, + href: media.src, }); } });