feat: use srcset/sizes for all images
This commit is contained in:
@@ -1,5 +1,34 @@
|
||||
import { asset } from "$fresh/runtime.ts";
|
||||
import * as CSS from "https://esm.sh/csstype@3.1.2";
|
||||
import { isLocalImage } from "@lib/string.ts";
|
||||
|
||||
interface ResponsiveAttributes {
|
||||
srcset: string;
|
||||
sizes: string;
|
||||
}
|
||||
|
||||
function generateResponsiveAttributes(
|
||||
imageUrl: string,
|
||||
widths: number[],
|
||||
baseApiUrl: string,
|
||||
sizes = "100vw",
|
||||
): ResponsiveAttributes {
|
||||
const srcsets: string[] = [];
|
||||
|
||||
for (const width of widths) {
|
||||
const apiUrl = `${baseApiUrl}?image=${imageUrl}&width=${width}`;
|
||||
srcsets.push(`${apiUrl} ${width}w`);
|
||||
}
|
||||
|
||||
const srcset = srcsets.join(", ");
|
||||
|
||||
return {
|
||||
srcset,
|
||||
sizes,
|
||||
};
|
||||
}
|
||||
|
||||
const widths = [320, 640, 960, 1280]; // List of widths for srcset
|
||||
|
||||
const Image = (
|
||||
props: {
|
||||
@@ -12,6 +41,12 @@ const Image = (
|
||||
style?: CSS.HtmlAttributes;
|
||||
},
|
||||
) => {
|
||||
const responsiveAttributes: ResponsiveAttributes = isLocalImage(props.src)
|
||||
? generateResponsiveAttributes(props.src, widths, "/api/images")
|
||||
: { srcset: "", sizes: "" };
|
||||
|
||||
console.log({ src: props.src, responsiveAttributes });
|
||||
|
||||
return (
|
||||
<span
|
||||
style={{
|
||||
@@ -28,6 +63,8 @@ const Image = (
|
||||
loading="lazy"
|
||||
alt={props.alt}
|
||||
style={props.style}
|
||||
srcset={responsiveAttributes.srcset}
|
||||
sizes={responsiveAttributes.sizes}
|
||||
src={asset(props.src)}
|
||||
width={props.width}
|
||||
height={props.height}
|
||||
|
||||
Reference in New Issue
Block a user