From 1f1987d7c2d6c19fbae0229e7b3de62fdffeb6da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Wickstr=C3=B6m?= Date: Wed, 28 Aug 2024 20:09:09 +0200 Subject: [PATCH] handle broken media --- index.css | 4 ++++ index.js | 25 ++++++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/index.css b/index.css index 6722659..c23c2f6 100644 --- a/index.css +++ b/index.css @@ -189,6 +189,10 @@ img, video { width: 100%; object-fit: contain; } +img { + font-style: italic; + color: var(--text-color-alt); +} details { border: var(--border-thickness) solid var(--text-color); diff --git a/index.js b/index.js index 62d7f78..4379fc2 100644 --- a/index.js +++ b/index.js @@ -13,6 +13,19 @@ function gridCellDimensions() { function adjustMediaPadding() { const cell = gridCellDimensions(); + function setHeightFromRatio(media, ratio) { + const rect = media.getBoundingClientRect(); + const realHeight = rect.width / ratio; + const diff = cell.height - (realHeight % cell.height); + media.style.setProperty("padding-bottom", `${diff}px`); + } + + function setFallbackHeight(media) { + const rect = media.getBoundingClientRect(); + const height = Math.round((rect.width / 2) / cell.height) * cell.height; + media.style.setProperty("height", `${height}px`); + } + function onMediaLoaded(media) { var width, height; switch (media.tagName) { @@ -26,11 +39,9 @@ function adjustMediaPadding() { break; } if (width > 0 && height > 0) { - const rect = media.getBoundingClientRect(); - const ratio = width / height; - const realHeight = rect.width / ratio; - const diff = cell.height - (realHeight % cell.height); - media.style.setProperty("padding-bottom", `${diff}px`); + setHeightFromRatio(media, width / height); + } else { + setFallbackHeight(media); } } @@ -43,7 +54,7 @@ function adjustMediaPadding() { } else { media.addEventListener("load", () => onMediaLoaded(media)); media.addEventListener("error", function() { - console.error(media); + setFallbackHeight(media); }); } break; @@ -57,7 +68,7 @@ function adjustMediaPadding() { default: media.addEventListener("loadeddata", () => onMediaLoaded(media)); media.addEventListener("error", function() { - console.error(media); + setFallbackHeight(media); }); break; }