Calculate DetailImage fallback width using rem (#4441)

This commit is contained in:
DingDongSoLong4 2024-01-09 02:11:46 +02:00 committed by GitHub
parent a998497004
commit 9859ec61fb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 3 deletions

View file

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

View file

@ -15,3 +15,7 @@ export function cmToInches(cm: number) {
const inches = cm * cmInInches; const inches = cm * cmInInches;
return inches; return inches;
} }
export function remToPx(rem: number) {
return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
}