mirror of https://github.com/theNewDynamic/gohugo-theme-ananke.git

Patrick Kollitsch
103 mins ago ce82e903e4e451102a99a452ac75bfb7a6fc8cfb
feat(images): process responsive header resources
8 files modified
8 files added
166 ■■■■■ changed files
config/_default/params.toml 1 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/FeaturedImageStyle.html 35 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/GetFeaturedImage.html 3 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/GetFeaturedImageResource.html 18 ●●●●● patch | view | raw | blame | history
layouts/_partials/page-header.html 29 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-header.html 4 ●●●●● patch | view | raw | blame | history
tests/catalog.yaml 2 ●●●●● patch | view | raw | blame | history
tests/e2e/responsive-header.spec.ts 55 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/assets/images/responsive-header.png patch | view | raw | blame | history
tests/fixtures/site/content/_index.md 1 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/asset-header.md 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/bundled-header/cover.png patch | view | raw | blame | history
tests/fixtures/site/content/bundled-header/index.md 5 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/posts/_index.md 1 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/static-header.md 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/static/images/static-header.png patch | view | raw | blame | history
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)
layouts/_partials/func/FeaturedImageStyle.html
New file
@@ -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) }}
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 }}
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 }}
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 }}">
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" .}}
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:
tests/e2e/responsive-header.spec.ts
New file
@@ -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);
});
tests/fixtures/site/assets/images/responsive-header.png
tests/fixtures/site/content/_index.md
@@ -1,4 +1,5 @@
---
featured_image: images/responsive-header.png
title: "Ananke Test Fixture"
---
tests/fixtures/site/content/asset-header.md
New file
@@ -0,0 +1,6 @@
---
title: Asset header
featured_image: images/responsive-header.png
---
A header from assets.
tests/fixtures/site/content/bundled-header/cover.png
tests/fixtures/site/content/bundled-header/index.md
New file
@@ -0,0 +1,5 @@
---
title: Bundled header
---
A header from a page bundle.
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."
---
tests/fixtures/site/content/static-header.md
New file
@@ -0,0 +1,6 @@
---
title: Static header
featured_image: /images/static-header.png
---
A static URL remains unchanged.
tests/fixtures/site/static/images/static-header.png