Skip to content

Commit

Permalink
Use an Image component in the blog list to support optimized images
Browse files Browse the repository at this point in the history
  • Loading branch information
fwextensions committed Sep 23, 2024
1 parent 18c381d commit 824503b
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions src/components/BlogListItem.astro
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
import { Image } from "astro:assets";
import type { CollectionEntry } from "astro:content";
import { base, dateFromSlug, getBlogImage, formatShortMDY } from "@/utils";
import defaultThumbnail from "../assets/blog/default-thumbnail.png";
Expand All @@ -7,6 +8,10 @@ interface Props {
post: CollectionEntry<"blog">;
}
// the thumbnail item is set to 14rem square, and the font size is 21px, so
// double that to support a max 2X image
const ThumbnailWidth = 14 * 21 * 2;
const {
post: {
slug,
Expand All @@ -20,16 +25,21 @@ const {
}
} = Astro.props;
const imageData = await getBlogImage(image);
const backgroundImageURL = imageData?.src ?? defaultThumbnail.src;
const backgroundImage = imageData || defaultThumbnail;
const postURL = base("/blog/" + slug);
const dateString = formatShortMDY(date);
---

<li>
<div class="thumbnail"
style={`background-image: url(${backgroundImageURL})`}
title={image_alt}
/>
<a href={postURL}>
<Image class="thumbnail"
src={backgroundImage}
alt={image_alt}
widths={[ThumbnailWidth]}
sizes=`${ThumbnailWidth}px`
inferSize
/>
</a>
<div class="info">
<time datetime={date?.toISOString()}>{dateString}</time>
<h3><a href={postURL}>{title}</a></h3>
Expand All @@ -46,10 +56,10 @@ const dateString = formatShortMDY(date);
gap: var(--pico-block-spacing-horizontal);
}

div.thumbnail {
img.thumbnail {
aspect-ratio: 1;
background-size: cover;
background-position: center;
object-fit: cover;
object-position: center;
width: 14rem;
height: 14rem;
}
Expand Down

0 comments on commit 824503b

Please sign in to comment.