From ce82e903e4e451102a99a452ac75bfb7a6fc8cfb Mon Sep 17 00:00:00 2001
From: Patrick Kollitsch <davidsneighbourdev+gh@gmail.com>
Date: Fri, 20 Nov 2026 01:51:20 +0000
Subject: [PATCH] feat(images): process responsive header resources

---
 tests/fixtures/site/content/_index.md                   |    1 
 layouts/_partials/site-header.html                      |    4 +
 tests/catalog.yaml                                      |    2 
 layouts/_partials/func/GetFeaturedImageResource.html    |   18 +++++
 layouts/_partials/page-header.html                      |   29 +--------
 tests/fixtures/site/content/static-header.md            |    6 ++
 tests/fixtures/site/content/bundled-header/index.md     |    5 +
 layouts/_partials/func/FeaturedImageStyle.html          |   35 +++++++++++
 tests/fixtures/site/static/images/static-header.png     |    0 
 config/_default/params.toml                             |    1 
 tests/e2e/responsive-header.spec.ts                     |   55 ++++++++++++++++++
 tests/fixtures/site/content/asset-header.md             |    6 ++
 tests/fixtures/site/content/bundled-header/cover.png    |    0 
 tests/fixtures/site/assets/images/responsive-header.png |    0 
 layouts/_partials/func/GetFeaturedImage.html            |    3 +
 tests/fixtures/site/content/posts/_index.md             |    1 
 16 files changed, 137 insertions(+), 29 deletions(-)

diff --git a/config/_default/params.toml b/config/_default/params.toml
index 9c0a4e0..4ed9a74 100644
--- a/config/_default/params.toml
+++ b/config/_default/params.toml
@@ -1,4 +1,5 @@
 [ananke]
+responsive_image_widths = [480, 960, 1440, 1920] # header image widths in pixels
 show_recent_posts = true # show recent posts on the homepage
 show_categories = true # show categories terms on single pages
 copy_code = true # show a copy-to-clipboard button on code blocks (progressive enhancement)
diff --git a/layouts/_partials/func/FeaturedImageStyle.html b/layouts/_partials/func/FeaturedImageStyle.html
new file mode 100644
index 0000000..71e8e67
--- /dev/null
+++ b/layouts/_partials/func/FeaturedImageStyle.html
@@ -0,0 +1,35 @@
+{{/* Return a background style shared by home, list, and individual-page headers.
+     Static URLs and unsupported image formats retain their original URL. */}}
+{{ $url := partials.Include "func/GetFeaturedImage.html" . }}
+{{ $page := . }}
+{{ $stylesheet := "" }}
+{{ $style := printf "background-image: url('%s');" $url }}
+{{ with partials.Include "func/GetFeaturedImageResource.html" . }}
+  {{ if in (slice "jpeg" "png" "webp" "tiff" "bmp" "gif") .MediaType.SubType }}
+    {{ $image := . }}
+    {{ $widths := ($page.Param "ananke.responsive_image_widths") | default (slice 480 960 1440 1920) }}
+    {{ $candidates := slice }}
+    {{ range sort $widths }}
+      {{ if lt (int .) $image.Width }}
+        {{ $resized := $image.Resize (printf "%dx" (int .)) }}
+        {{ $candidates = $candidates | append (dict "width" (int .) "url" $resized.RelPermalink) }}
+      {{ end }}
+    {{ end }}
+    {{ $candidates = $candidates | append (dict "width" $image.Width "url" $image.RelPermalink) }}
+    {{/* Select the next sufficient width without upscaling the source. */}}
+    {{ $id := printf "ananke-header-%s" (crypto.MD5 $image.RelPermalink) }}
+    {{ $first := index $candidates 0 }}
+    {{ $style = printf "background-image: var(--%s, url('%s'));" $id $first.url }}
+    {{ $css := printf ":root { --%s: url('%s'); }" $id $first.url }}
+    {{ range $index, $candidate := $candidates }}
+      {{ if gt $index 0 }}
+        {{ $previous := index $candidates (sub $index 1) }}
+        {{ $css = printf "%s @media (min-width: %dpx) { :root { --%s: url('%s'); } }" $css (add $previous.width 1) $id $candidate.url }}
+      {{ end }}
+    {{ end }}
+    {{/* Publish a shared stylesheet for each image and width configuration. */}}
+    {{ $cssResource := resources.FromString (printf "ananke/header-%s.css" (crypto.MD5 $css)) $css }}
+    {{ $stylesheet = $cssResource.RelPermalink }}
+  {{ end }}
+{{ end }}
+{{ return (dict "style" $style "stylesheet" $stylesheet) }}
diff --git a/layouts/_partials/func/GetFeaturedImage.html b/layouts/_partials/func/GetFeaturedImage.html
index f9f0804..925cf22 100644
--- a/layouts/_partials/func/GetFeaturedImage.html
+++ b/layouts/_partials/func/GetFeaturedImage.html
@@ -54,4 +54,7 @@
 
 {{/* return either a permalink, or an empty string. Note that partials can only have a single
 return statement, so this needs to be at the end of the partial (and not in the if block) */}}
+{{ with partials.Include "func/GetFeaturedImageResource.html" . }}
+  {{ $linkToCover = .RelPermalink }}
+{{ end }}
 {{ return $linkToCover }}
diff --git a/layouts/_partials/func/GetFeaturedImageResource.html b/layouts/_partials/func/GetFeaturedImageResource.html
index 2ff28d8..4b49889 100644
--- a/layouts/_partials/func/GetFeaturedImageResource.html
+++ b/layouts/_partials/func/GetFeaturedImageResource.html
@@ -4,7 +4,7 @@
 	This partial gets the featured image resource for a given page.
 
 	If a featured_image was set in the page's front matter and it matches a page
-	resource, then that resource will be used.
+	resource, then that resource will be used. Otherwise, assets are searched.
 
 	If no featured_image was set, this will use the first matching page resource from
 	the page's images front matter array.
@@ -12,7 +12,7 @@
 	If not set, this will search page resources to find an image that contains the word
 	"cover" or "feature", and if found, returns that resource.
 
-	If no matching page resource can be found, this partial returns false.
+	If no matching page or asset resource can be found, this partial returns false.
 
 	@return Featured image resource, or false if not found.
 
@@ -20,7 +20,9 @@
 
 {{ $resource := false }}
 {{ $matches := "feature,cover" }}
+{{ $path := "" }}
 {{ with .Params.featured_image }}
+  {{ $path = . }}
   {{ with $.Resources.GetMatch . }}
     {{ $resource = . }}
   {{ end }}
@@ -28,6 +30,7 @@
   {{ with .Params.images }}
     {{ range first 1 . }}
       {{ with . }}
+        {{ $path = . }}
         {{ with $.Resources.GetMatch . }}
           {{ $resource = . }}
         {{ end }}
@@ -42,4 +45,15 @@
   {{ end }}
 {{ end }}
 
+{{ if and (not $resource) $path }}
+  {{ with resources.Get (strings.TrimPrefix "/" $path) }}
+    {{ $resource = . }}
+  {{ end }}
+{{ end }}
+{{ if $resource }}
+  {{ if ne $resource.ResourceType "image" }}
+    {{ $resource = false }}
+  {{ end }}
+{{ end }}
+
 {{ return $resource }}
diff --git a/layouts/_partials/page-header.html b/layouts/_partials/page-header.html
index 393988c..168202c 100644
--- a/layouts/_partials/page-header.html
+++ b/layouts/_partials/page-header.html
@@ -1,35 +1,12 @@
 {{ $featured_image := partials.Include "func/GetFeaturedImage.html" . }}
-{{ $featured_image_resource := partials.Include "func/GetFeaturedImageResource.html" . }}
 {{ if $featured_image }}
   {{/* Trimming the slash and adding absURL make sure the image works no matter where our site lives */}}
   {{ $featured_image_class := .Params.featured_image_class | compare.Default "cover bg-center" }}
   {{ $cover_dimming_class := .Params.cover_dimming_class | compare.Default "bg-black-60" }}
   {{ $header_section_class := .Param "header_section_class" | compare.Default "tc-l pv6 ph3 ph4-ns" }}
-  {{ $responsive_image_widths := .Site.Params.ananke.responsive_image_widths | compare.Default (slice 480 960 1440 1920) }}
-  {{ $responsive_header_id := "" }}
-  {{ $background_image := $featured_image }}
-  {{ if and $featured_image_resource (compare.Ne $featured_image_resource.MediaType.SubType "svg") }}
-    {{ $responsive_header_id = printf "featured-image-%s" (crypto.MD5 $featured_image_resource.RelPermalink) }}
-    {{ range first 1 $responsive_image_widths }}
-      {{ if compare.Le . $featured_image_resource.Width }}
-        {{ $resized_image := $featured_image_resource.Resize (printf "%dx" .) }}
-        {{ $background_image = $resized_image.RelPermalink }}
-      {{ end }}
-    {{ end }}
-  {{ end }}
-  {{ if $responsive_header_id }}
-    <style>
-      {{ range $responsive_image_widths }}
-        {{ if compare.Le . $featured_image_resource.Width }}
-          {{ $resized_image := $featured_image_resource.Resize (printf "%dx" .) }}
-          @media screen and (min-width: {{ . }}px) {
-            #{{ $responsive_header_id }} { background-image: url('{{ $resized_image.RelPermalink }}'); }
-          }
-        {{ end }}
-      {{ end }}
-    </style>
-  {{ end }}
-  <header {{ with $responsive_header_id }}id="{{ . }}" {{ end }}class="{{ $featured_image_class }}" style="background-image: url('{{ $background_image }}');">
+  {{ $background := partials.Include "func/FeaturedImageStyle.html" . }}
+  {{ with $background.stylesheet }}<link rel="stylesheet" href="{{ . }}">{{ end }}
+  <header class="{{ $featured_image_class }}" style="{{ $background.style | safe.CSS }}">
     <div class="{{ $cover_dimming_class }}">
       {{ partials.Include "site-navigation.html" . }}
       <div class="{{ $header_section_class }}">
diff --git a/layouts/_partials/site-header.html b/layouts/_partials/site-header.html
index 19ba931..40ead6a 100644
--- a/layouts/_partials/site-header.html
+++ b/layouts/_partials/site-header.html
@@ -3,7 +3,9 @@
   {{/* Trimming the slash and adding absURL make sure the image works no matter where our site lives */}}
   {{ $featured_image_class := site.Params.featured_image_class | compare.Default "cover bg-top" }}
   {{ $header_section_class := .Param "header_section_class" | compare.Default "tc-l pv4 pv6-l ph3 ph4-ns" }}
-  <header class="{{ $featured_image_class }}" style="background-image: url('{{ $featured_image }}');">
+  {{ $background := partials.Include "func/FeaturedImageStyle.html" . }}
+  {{ with $background.stylesheet }}<link rel="stylesheet" href="{{ . }}">{{ end }}
+  <header class="{{ $featured_image_class }}" style="{{ $background.style | safe.CSS }}">
     {{ $cover_dimming_class := site.Params.cover_dimming_class | compare.Default "bg-black-60" }}
     <div class="{{ $cover_dimming_class }}">
       {{ partials.Include "site-navigation.html" .}}
diff --git a/tests/catalog.yaml b/tests/catalog.yaml
index db873a9..52ba48d 100644
--- a/tests/catalog.yaml
+++ b/tests/catalog.yaml
@@ -8,6 +8,8 @@
 # humans; the gate only checks that the key is present and has a non-empty list.
 
 params:
+  ananke.responsive_image_widths:
+    tests: ["tests/e2e/responsive-header.spec.ts"]
   ananke.show_recent_posts:
     tests: ["scripts/test-hugo-quickstart.ts"]
   ananke.show_categories:
diff --git a/tests/e2e/responsive-header.spec.ts b/tests/e2e/responsive-header.spec.ts
new file mode 100644
index 0000000..141a47b
--- /dev/null
+++ b/tests/e2e/responsive-header.spec.ts
@@ -0,0 +1,55 @@
+import { expect, type Locator, test } from "@playwright/test";
+
+for (const path of ["/", "/posts/", "/asset-header/", "/bundled-header/"]) {
+  test(`responsive header selects a larger resource on ${path}`, async ({
+    page,
+  }) => {
+    await page.setViewportSize({ width: 375, height: 800 });
+    await page.goto(path);
+    const header = page.locator("header").first();
+    const small = await header.evaluate(
+      (node) => getComputedStyle(node).backgroundImage,
+    );
+    expect(await backgroundWidth(header)).toBe(480);
+    await page.setViewportSize({ width: 900, height: 800 });
+    await expect.poll(() => backgroundWidth(header)).toBe(960);
+    expect(
+      await header.evaluate((node) => getComputedStyle(node).backgroundImage),
+    ).not.toBe(small);
+  });
+}
+
+test("responsive header works without JavaScript", async ({ browser }) => {
+  const context = await browser.newContext({
+    javaScriptEnabled: false,
+    viewport: { width: 900, height: 800 },
+  });
+  const page = await context.newPage();
+  await page.goto("http://localhost:4321/asset-header/");
+  expect(await backgroundWidth(page.locator("header").first())).toBe(960);
+  await context.close();
+});
+
+async function backgroundWidth(header: Locator) {
+  return header.evaluate(async (node) => {
+    const url = getComputedStyle(node).backgroundImage.slice(5, -2);
+    const image = new Image();
+    image.src = url;
+    await image.decode();
+    return image.naturalWidth;
+  });
+}
+
+test("static image URLs remain unchanged", async ({ page }) => {
+  await page.goto("/static-header/");
+  const header = page.locator("header").first();
+  expect(
+    await header.evaluate((node) => getComputedStyle(node).backgroundImage),
+  ).toContain("/images/static-header.png");
+});
+
+test("small bundle sources are not enlarged", async ({ page }) => {
+  await page.setViewportSize({ width: 2200, height: 800 });
+  await page.goto("/bundled-header/");
+  expect(await backgroundWidth(page.locator("header").first())).toBe(1000);
+});
diff --git a/tests/fixtures/site/assets/images/responsive-header.png b/tests/fixtures/site/assets/images/responsive-header.png
new file mode 100644
index 0000000..f455f3a
--- /dev/null
+++ b/tests/fixtures/site/assets/images/responsive-header.png
Binary files differ
diff --git a/tests/fixtures/site/content/_index.md b/tests/fixtures/site/content/_index.md
index 05781f9..6287f56 100644
--- a/tests/fixtures/site/content/_index.md
+++ b/tests/fixtures/site/content/_index.md
@@ -1,4 +1,5 @@
 ---
+featured_image: images/responsive-header.png
 title: "Ananke Test Fixture"
 ---
 
diff --git a/tests/fixtures/site/content/asset-header.md b/tests/fixtures/site/content/asset-header.md
new file mode 100644
index 0000000..948ebf2
--- /dev/null
+++ b/tests/fixtures/site/content/asset-header.md
@@ -0,0 +1,6 @@
+---
+title: Asset header
+featured_image: images/responsive-header.png
+---
+
+A header from assets.
diff --git a/tests/fixtures/site/content/bundled-header/cover.png b/tests/fixtures/site/content/bundled-header/cover.png
new file mode 100644
index 0000000..2641aa4
--- /dev/null
+++ b/tests/fixtures/site/content/bundled-header/cover.png
Binary files differ
diff --git a/tests/fixtures/site/content/bundled-header/index.md b/tests/fixtures/site/content/bundled-header/index.md
new file mode 100644
index 0000000..ec0bc26
--- /dev/null
+++ b/tests/fixtures/site/content/bundled-header/index.md
@@ -0,0 +1,5 @@
+---
+title: Bundled header
+---
+
+A header from a page bundle.
diff --git a/tests/fixtures/site/content/posts/_index.md b/tests/fixtures/site/content/posts/_index.md
index f548d9d..0f62395 100644
--- a/tests/fixtures/site/content/posts/_index.md
+++ b/tests/fixtures/site/content/posts/_index.md
@@ -1,4 +1,5 @@
 ---
+featured_image: images/responsive-header.png
 title: "Posts"
 description: "All posts on the test fixture site."
 ---
diff --git a/tests/fixtures/site/content/static-header.md b/tests/fixtures/site/content/static-header.md
new file mode 100644
index 0000000..b7848b9
--- /dev/null
+++ b/tests/fixtures/site/content/static-header.md
@@ -0,0 +1,6 @@
+---
+title: Static header
+featured_image: /images/static-header.png
+---
+
+A static URL remains unchanged.
diff --git a/tests/fixtures/site/static/images/static-header.png b/tests/fixtures/site/static/images/static-header.png
new file mode 100644
index 0000000..f455f3a
--- /dev/null
+++ b/tests/fixtures/site/static/images/static-header.png
Binary files differ

--
Gitblit v1.10.0