Skip to content

Commit

Permalink
Calculate DetailImage fallback width using rem (#4441)
Browse files Browse the repository at this point in the history
  • Loading branch information
DingDongSoLong4 authored Jan 9, 2024
1 parent a998497 commit 9859ec6
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
7 changes: 4 additions & 3 deletions ui/v2.5/src/components/Shared/DetailImage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useLayoutEffect, useRef } from "react";
import { remToPx } from "src/utils/units";

const DEFAULT_WIDTH = "200";
const DEFAULT_WIDTH = Math.round(remToPx(30));

// Props used by the <img> element
type IDetailImageProps = JSX.IntrinsicElements["img"];
Expand All @@ -17,7 +18,7 @@ export const DetailImage = (props: IDetailImageProps) => {
// If the naturalWidth is zero, it means the image either hasn't loaded yet
// or we're on Firefox and it is an SVG w/o an intrinsic size.
// So set the width to our fallback width.
img.setAttribute("width", DEFAULT_WIDTH);
img.setAttribute("width", String(DEFAULT_WIDTH));
} else {
// If we have a `naturalWidth`, this could either be the actual intrinsic width
// of the image, or the image is an SVG w/o an intrinsic size and we're on Chrome or Safari,
Expand All @@ -26,7 +27,7 @@ export const DetailImage = (props: IDetailImageProps) => {
// so we need to clone the image to disconnect it from the DOM, and then get the `naturalWidth` of the clone,
// in order to always return the same `naturalWidth` for a given src.
const i = img.cloneNode() as HTMLImageElement;
img.setAttribute("width", (i.naturalWidth || DEFAULT_WIDTH).toString());
img.setAttribute("width", String(i.naturalWidth || DEFAULT_WIDTH));
}
}

Expand Down
4 changes: 4 additions & 0 deletions ui/v2.5/src/utils/units.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ export function cmToInches(cm: number) {
const inches = cm * cmInInches;
return inches;
}

export function remToPx(rem: number) {
return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
}

0 comments on commit 9859ec6

Please sign in to comment.