Skip to content

A platform for community discussion. Free, open, simple.

FIX: fix unexpected scaling in lightbox when missing height/width. (#35616)

small-lovely-cat7d6790e641a3
diff --git a/frontend/discourse/app/lib/lightbox.js b/frontend/discourse/app/lib/lightbox.js
index 84cb8f06042..55faa80d8ba 100644
--- a/frontend/discourse/app/lib/lightbox.js
+++ b/frontend/discourse/app/lib/lightbox.js
@@ -240,6 +240,35 @@ export default async function lightbox(elem, siteSettings) {
return data;
});
+ const itemsToPreload = items.filter((item) => {
+ const { largeSrc, targetWidth, targetHeight } = item.dataset;
+ const hasImageSrc = largeSrc || item.getAttribute("href");
+ const missingDimensions = !targetWidth || !targetHeight;
+ const imgDimensions = item
+ .querySelector(".informations")
+ ?.textContent.trim()
+ .split(" ")[0];
+ const missingMetaData = !imgDimensions?.split(/x|×/).every((d) => !!d);
+
+ return hasImageSrc && missingDimensions && missingMetaData;
+ });
+
+ await Promise.all(
+ itemsToPreload.map(
+ (item) =>
+ new Promise((resolve) => {
+ const img = new Image();
+ img.src =
+ item.getAttribute("data-large-src") || item.getAttribute("href");
+ img.onload = () => {
+ item.setAttribute("data-target-width", img.naturalWidth);
+ item.setAttribute("data-target-height", img.naturalHeight);
+ resolve();
+ };
+ img.onerror = resolve;
+ })
+ )
+ );
function tapAction(pt, event) {
const pswp = lightboxEl.pswp;
if (event.target.classList.contains("pswp__img")) {
diff --git a/spec/system/lightbox_spec.rb b/spec/system/lightbox_spec.rb
index 9e924634867..8aa01f7db8f 100644
--- a/spec/system/lightbox_spec.rb
+++ b/spec/system/lightbox_spec.rb
@@ -212,4 +212,19 @@ describe "Lightbox | Photoswipe", type: :system do
expect(lightbox).to have_no_caption_details
end
end
+
+ context "when missing data attributes" do
+ it "preloads images and sets dimensions" do
+ post.update(
+ cooked:
+ "<p><a href=\"#{upload_1.url}\" class=\"lightbox\" data-download-href=\"#{upload_1.url}\">[image]</a></p>",
+ )
+
+ topic_page.visit_topic(topic)
+ lightbox_link = find("#post_1 a.lightbox")
+
+ expect(lightbox_link["data-target-width"]).to eq(upload_1.width.to_s)
+ expect(lightbox_link["data-target-height"]).to eq(upload_1.height.to_s)
+ end
+ end
end