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

Patrick Kollitsch
12 hours ago aa7f234ec3736d192eb4ac777bfd63f77c9ade79
feat(layouts): make the header layout configurable

Add params.ananke.header with two lists:

- navigation: groups of components in the navigation bar. Groups are
spread over the width of the bar, so layouts like
"logo - search - menu" or "menu, search - logo" need only config.
- content: components below the navigation bar, from top to bottom.

Each name renders the hook partial hooks/header/<name>.html, so a site
adds its own component (for example a search form) by creating that
partial. Pages can override both lists in their front matter. A name
without a hook partial prints a warning.

Each navigation group gets a role for the collapsed layout below 60em:
the group with `menu` is the collapsible panel (the menu button sits
directly before it), the group with `logo` shares the first row with
the button, and every other group is a slot with its own row. Add the
`group` key to [ananke.navigation.classes] for the non-panel groups.

The configurable groups replace the unreleased `navigation-start` and
`navigation-end` hooks: a search box is now a component in its own
group, or in a `header/<name>-before` or `-after` hook.
1 files deleted
11 files modified
3 files added
355 ■■■■■ changed files
assets/ananke/css/_styles.css 15 ●●●●● patch | view | raw | blame | history
assets/ananke/css/navigation-classes.css 26 ●●●●● patch | view | raw | blame | history
config/_default/params.toml 23 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/GetNavigationClasses.html 1 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/component.html 6 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/content.html 13 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-navigation.html 82 ●●●●● patch | view | raw | blame | history
tests/catalog.yaml 2 ●●●●● patch | view | raw | blame | history
tests/e2e/accessibility.spec.ts 1 ●●●●● patch | view | raw | blame | history
tests/e2e/header.spec.ts 151 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation.spec.ts 2 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/header-layout/_index.md 12 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/hugo.toml 6 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/layouts/_partials/hooks/header/search.html 10 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/layouts/_partials/hooks/navigation-start.html 5 ●●●●● patch | view | raw | blame | history
assets/ananke/css/_styles.css
@@ -109,11 +109,12 @@
  text-underline-offset: 0.25em;
}
/* Small and medium screens: brand and menu button in one row, an optional
   slot (search) below, then the menu panel as a stacked list. */
/* Small and medium screens: the lead group (brand) and the menu button in one
   row, every slot group (for example search) in its own row below, then the
   menu panel as a stacked list. */
@media not all and (min-width: 60em) {
  /* A long site title wraps instead of pushing the menu button down. */
  .ananke-nav-brand {
  .ananke-nav-lead {
    flex: 1 1 0%;
    min-width: 0;
  }
@@ -196,13 +197,19 @@
    display: none;
  }
  /* The slot shrinks before the row wraps. */
  /* A slot group (for example search) shrinks before the row wraps. */
  .ananke-nav-slot {
    flex: 1 1 10rem;
    max-width: 28rem;
    margin-inline: 1.5rem;
  }
  /* Items in a slot group fill it, like a single search form. */
  .ananke-nav-slot > * {
    flex: 1 1 auto;
    min-width: 0;
  }
  .ananke-submenu-toggle {
    vertical-align: baseline;
  }
assets/ananke/css/navigation-classes.css
@@ -27,7 +27,8 @@
  /* */
}
/* Row inside <nav> that holds brand, slot, menu button, and panel. */
/* Row inside <nav> that holds the groups of [ananke.header] navigation and
   the menu button. */
.ananke-nav-inner {
  /* */
}
@@ -37,7 +38,19 @@
  /* */
}
/* Wrapper of the `navigation-start` hook, for example a search box. */
/* Every group of [ananke.header] navigation. */
.ananke-nav-group {
  /* */
}
/* The group with the `logo` component (or the first other group). Shares the
   first row with the menu button below the -l breakpoint. */
.ananke-nav-lead {
  /* */
}
/* Every other group that is not the lead or the panel, for example a search
   box. Gets its own row below the -l breakpoint. */
.ananke-nav-slot {
  /* */
}
@@ -64,8 +77,8 @@
  /* */
}
/* Collapsible panel with languages, main menu, social links, and the
   `navigation-end` hook. */
/* Collapsible panel: the group with the `menu` component (by default with
   languages, main menu, and social links). Also has .ananke-nav-group. */
.ananke-nav-panel {
  /* */
}
@@ -153,8 +166,3 @@
.ananke-submenu-nested {
  /* */
}
/* Wrapper of the `navigation-end` hook, at the end of the panel. */
.ananke-nav-end {
  /* */
}
config/_default/params.toml
@@ -6,6 +6,26 @@
[ananke.home]
content_alignment = "center" # options: left, center, right
[ananke.header]
# Layout of the navigation bar. Each entry is a group of components. Groups are
# spread over the width of the bar: the first group at the start, the last group
# at the end, and any other groups in between. A group is a list of component
# names, or a single component name. Every component name `<name>` renders the
# hook partial `layouts/_partials/hooks/header/<name>.html`. The theme ships
# `logo`, `languages`, `menu`, and `social`. Add your own (for example `search`)
# by creating the matching hook partial in your site.
#
# Below 60em, the group with `menu` collapses behind the menu button, the group
# with `logo` shares the first row with that button, and every other group gets
# its own row. Keep `logo` and `menu` in different groups.
navigation = [
  ["logo"],
  ["languages", "menu", "social"],
]
# Components below the navigation bar, from top to bottom. The theme ships
# `title` and `description`.
content = ["title", "description"]
# Tachyons classes for the header navigation (layouts/_partials/site-navigation.html).
# An empty value uses the theme default shown in the comment. A value replaces the
# default classes of that element; its `ananke-nav-*` hook class always stays.
@@ -14,7 +34,8 @@
inner = "" # row inside <nav>: "flex flex-wrap items-center justify-between center"
brand = "" # site title or logo link: "f3 fw2 hover-white white-90 dib no-underline"
toggle = "" # menu button below the -l breakpoint: "f5 white-90 hover-white"
panel = "" # collapsible panel with menu, languages, and social links: "flex-l items-center"
group = "" # every group of [ananke.header] navigation except the panel: "flex-l items-center"
panel = "" # collapsible group, the one with the `menu` component: "flex-l items-center"
menu = "" # main menu <ul>: "pl0 mr3" ("pr0 ml3" for right-to-left)
item = "" # main menu <li>: "list f5 f4-ns fw4 dib pr3" ("pl3" for right-to-left)
link = "" # main menu link: "hover-white white-90 no-underline"
layouts/_partials/func/header/GetNavigationClasses.html
@@ -11,6 +11,7 @@
  "inner" "flex flex-wrap items-center justify-between center"
  "brand" "f3 fw2 hover-white white-90 dib no-underline"
  "toggle" "f5 white-90 hover-white"
  "group" "flex-l items-center"
  "panel" "flex-l items-center"
  "menu" (compare.Conditional $rtl "pr0 ml3" "pl0 mr3")
  "item" (printf "list f5 f4-ns fw4 dib %s" (compare.Conditional $rtl "pl3" "pr3"))
layouts/_partials/header/component.html
@@ -20,11 +20,17 @@
                        func/header/GetNavigationClasses.html (navigation
                        region only)
  If `header/<name>` has no partial, the theme prints a warning, because the
  name in `params.ananke.header` is probably misspelt.
  @param name     string  Component name.
  @param context  map     Header context dictionary (see above).
*/ -}}
{{- $name := .name -}}
{{- $context := .context -}}
{{- if not (templates.Exists (fmt.Printf "_partials/hooks/header/%s.html" $name)) -}}
  {{- fmt.Warnidf "ananke-header-component" "[ananke] Header component %q has no hook partial. Create layouts/_partials/hooks/header/%s.html or remove it from params.ananke.header." $name $name -}}
{{- end -}}
{{- partials.Include "hook.html" (collections.Dictionary "hook" (fmt.Printf "header/%s-before" $name) "context" $context) -}}
{{- partials.Include "hook.html" (collections.Dictionary "hook" (fmt.Printf "header/%s" $name) "context" $context) -}}
{{- partials.Include "hook.html" (collections.Dictionary "hook" (fmt.Printf "header/%s-after" $name) "context" $context) -}}
layouts/_partials/header/content.html
@@ -1,6 +1,9 @@
{{- /*
  Header content below the navigation bar: the title and the description of
  the page. Every part is rendered through the header hooks (see
  Header content below the navigation bar.
  The components and their order come from `ananke.header.content` (page front
  matter or site parameters). The default is the title and the description of
  the page. Every component is rendered through the header hooks (see
  `header/component.html`).
  @param page            page    The current page.
@@ -8,5 +11,7 @@
  @param featured_image  string  Featured image URL, or an empty string.
*/ -}}
{{- $header := collections.Merge . (collections.Dictionary "region" "content") -}}
{{ partials.Include "header/component.html" (collections.Dictionary "name" "title" "context" $header) }}
{{ partials.Include "header/component.html" (collections.Dictionary "name" "description" "context" $header) }}
{{- $components := .page.Param "ananke.header.content" | compare.Default (collections.Slice "title" "description") -}}
{{- range $components }}
{{ partials.Include "header/component.html" (collections.Dictionary "name" . "context" $header) }}
{{- end }}
layouts/_partials/site-navigation.html
@@ -1,16 +1,24 @@
{{- /*
  Site header navigation.
  The brand link, languages, menu, and social links are header components:
  each one renders through the header hooks (see `header/component.html`).
  The layout comes from `ananke.header.navigation` (page front matter or site
  parameters): a list of groups, and each group is a list of component names
  (or one component name). Every component renders through the header hooks
  (see `header/component.html`). Each group gets one role:
    - panel (`ananke-nav-panel`): the first group with the `menu` component.
      Below the Tachyons `-l` breakpoint it collapses behind the menu button,
      which is rendered directly before it.
    - lead (`ananke-nav-lead`): the first group with the `logo` component, or
      else the first other group. Below `-l` it shares the first row with the
      menu button.
    - slot (`ananke-nav-slot`): every other group, for example a search box.
      Below `-l` it gets its own row; from `-l` it can grow.
  Every element has a stable `ananke-nav-*` or `ananke-submenu*` hook class
  for custom CSS. The Tachyons classes next to it are defaults; replace them
  per element with `[params.ananke.navigation.classes]`. Collapsing (below the
  Tachyons `-l` breakpoint) and the dropdown position are in _styles.css.
  Hooks: `navigation-start` renders after the brand link (for example a search
  box), `navigation-end` renders at the end of the collapsible panel.
  per element with `[params.ananke.navigation.classes]`. Collapsing and the
  dropdown position are in _styles.css.
  Without JavaScript, the menu and all submenus are visible and the toggle
  buttons stay hidden. site-scripts.html enhances both.
@@ -22,25 +30,63 @@
  "featured_image" (partials.Include "func/GetFeaturedImage.html" .)
  "classes" $classes
-}}
{{- /* Normalise the layout to a list of non-empty groups. Each group is a
       dictionary, because Hugo cannot append a slice to a slice of slices. */ -}}
{{- $layout := .Param "ananke.header.navigation" | compare.Default (collections.Slice
  (collections.Slice "logo")
  (collections.Slice "languages" "menu" "social")
) -}}
{{- $groups := collections.Slice -}}
{{- range $layout -}}
  {{- $group := . -}}
  {{- if not (reflect.IsSlice $group) -}}
    {{- $group = collections.Slice $group -}}
  {{- end -}}
  {{- with $group -}}
    {{- $groups = $groups | collections.Append (collections.Dictionary "components" .) -}}
  {{- end -}}
{{- end -}}
{{- /* Find the panel group and the lead group (see above). */ -}}
{{- $panel := -1 -}}
{{- range $index, $group := $groups -}}
  {{- if and (compare.Lt $panel 0) (collections.In $group.components "menu") -}}
    {{- $panel = $index -}}
  {{- end -}}
{{- end -}}
{{- $lead := -1 -}}
{{- range $index, $group := $groups -}}
  {{- if and (compare.Lt $lead 0) (compare.Ne $index $panel) (collections.In $group.components "logo") -}}
    {{- $lead = $index -}}
  {{- end -}}
{{- end -}}
{{- if compare.Lt $lead 0 -}}
  {{- range $index, $group := $groups -}}
    {{- if and (compare.Lt $lead 0) (compare.Ne $index $panel) -}}
      {{- $lead = $index -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
<nav class="ananke-nav {{ $classes.nav }}" role="navigation">
  <div class="ananke-nav-inner {{ $classes.inner }}">
    {{ partials.Include "header/component.html" (collections.Dictionary "name" "logo" "context" $header) }}
    {{- with partials.Include "hook.html" (dict "hook" "navigation-start" "context" .) | strings.TrimSpace }}
    <div class="ananke-nav-slot">{{ . | safeHTML }}</div>
    {{- end }}
    {{- if .Site.Menus.main }}
    {{- range $index, $group := $groups }}
    {{- if compare.Eq $index $panel }}
    {{- if $.Site.Menus.main }}
    <button type="button" class="ananke-nav-toggle {{ $classes.toggle }}" aria-expanded="false" aria-controls="ananke-nav-panel" hidden>
      {{- partials.Include "header/menu-toggle-icon.html" -}}
      <span class="ananke-nav-toggle-label">{{ lang.Translate "menuToggle" }}</span>
    </button>
    {{- end }}
    <div id="ananke-nav-panel" class="ananke-nav-panel {{ $classes.panel }}">
      {{ partials.Include "header/component.html" (collections.Dictionary "name" "languages" "context" $header) }}
      {{ partials.Include "header/component.html" (collections.Dictionary "name" "menu" "context" $header) }}
      {{ partials.Include "header/component.html" (collections.Dictionary "name" "social" "context" $header) }}
      {{- with partials.Include "hook.html" (dict "hook" "navigation-end" "context" .) | strings.TrimSpace }}
      <div class="ananke-nav-end">{{ . | safeHTML }}</div>
    <div id="ananke-nav-panel" class="ananke-nav-group ananke-nav-panel {{ $classes.panel }}">
    {{- else }}
    <div class="ananke-nav-group {{ compare.Conditional (compare.Eq $index $lead) "ananke-nav-lead" "ananke-nav-slot" }} {{ $classes.group }}">
    {{- end }}
      {{- range $group.components }}
      {{ partials.Include "header/component.html" (collections.Dictionary "name" . "context" $header) }}
      {{- end }}
    </div>
    {{- end }}
  </div>
</nav>
tests/catalog.yaml
@@ -22,6 +22,8 @@
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.toggle:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.group:
    tests: ["tests/e2e/header.spec.ts"]
  ananke.navigation.classes.panel:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.menu:
tests/e2e/accessibility.spec.ts
@@ -13,6 +13,7 @@
  "section list": "/posts/",
  "single page": "/posts/hello/",
  "standalone page": "/about/",
  "custom header layout": "/header-layout/",
  "taxonomy terms": "/tags/",
  "taxonomy term": "/tags/alpha/",
  "404": "/404.html",
tests/e2e/header.spec.ts
New file
@@ -0,0 +1,151 @@
import { expect, type Page, test } from "@playwright/test";
/**
 * Header layout and header hooks.
 *
 * The fixture site sets `params.ananke.header.navigation` to
 * [["logo"], ["search"], ["languages", "menu", "social"]], with a custom
 * `search` component (tests/fixtures/site/layouts/_partials/hooks/header/search.html).
 * The `/header-layout/` section changes the layout in its front matter to
 * [["menu", "search"], "logo"] and puts `search` between the description and
 * the title.
 */
const DEFAULT_PAGE = "/";
const CUSTOM_PAGE = "/header-layout/";
const groups = (page: Page) =>
  page.locator(".ananke-nav-inner > .ananke-nav-group");
const menuButton = (page: Page) => page.locator(".ananke-nav-toggle");
/** Tag names of the direct children of the navigation row. */
const rowChildren = (page: Page) =>
  page
    .locator(".ananke-nav-inner")
    .evaluate((el) =>
      Array.from(el.children).map(
        (child) => `${child.tagName.toLowerCase()}.${child.classList[0]}`,
      ),
    );
test.describe("configured header layout", () => {
  test("renders the groups in the configured order with their roles", async ({
    page,
  }) => {
    await page.goto(DEFAULT_PAGE);
    expect(await rowChildren(page)).toEqual([
      "div.ananke-nav-group",
      "div.ananke-nav-group",
      "button.ananke-nav-toggle",
      "div.ananke-nav-group",
    ]);
    await expect(groups(page).nth(0)).toHaveClass(/\bananke-nav-lead\b/);
    await expect(groups(page).nth(0).locator(".ananke-nav-brand")).toHaveCount(
      1,
    );
    await expect(groups(page).nth(1)).toHaveClass(/\bananke-nav-slot\b/);
    await expect(groups(page).nth(1).getByRole("search")).toHaveCount(1);
    await expect(groups(page).nth(2)).toHaveId("ananke-nav-panel");
    await expect(
      groups(page).nth(2).locator(".ananke-nav-menu > li"),
    ).toHaveCount(3);
    await expect(groups(page).nth(2).locator(".ananke-socials")).toHaveCount(1);
  });
  test("renders the title in the header content", async ({ page }) => {
    await page.goto("/posts/");
    await expect(page.locator("header h1")).toHaveText("Posts");
  });
});
test.describe("header layout from front matter", () => {
  test("renders the groups and components in the configured order", async ({
    page,
  }) => {
    await page.goto(CUSTOM_PAGE);
    // The menu button stays directly before the panel it controls.
    expect(await rowChildren(page)).toEqual([
      "button.ananke-nav-toggle",
      "div.ananke-nav-group",
      "div.ananke-nav-group",
    ]);
    const panel = groups(page).nth(0);
    await expect(panel).toHaveId("ananke-nav-panel");
    const order = await panel.evaluate((el) =>
      Array.from(el.children).map((child) => child.tagName.toLowerCase()),
    );
    expect(order).toEqual(["ul", "form"]);
    await expect(groups(page).nth(1)).toHaveClass(/\bananke-nav-lead\b/);
    await expect(groups(page).nth(1).locator(".ananke-nav-brand")).toHaveCount(
      1,
    );
  });
  test("renders the content components in the configured order", async ({
    page,
  }) => {
    await page.goto(CUSTOM_PAGE);
    const tags = await page
      .locator("header :is(h1, h2, form.fixture-search)")
      .evaluateAll((elements) =>
        elements
          .filter((el) => !el.closest("nav"))
          .map((el) => el.tagName.toLowerCase()),
      );
    expect(tags).toEqual(["h2", "form", "h1"]);
  });
});
test.describe("responsive header", () => {
  test("puts the groups in one row on large screens", async ({ page }) => {
    await page.setViewportSize({ width: 1280, height: 800 });
    await page.goto(DEFAULT_PAGE);
    await expect(menuButton(page)).toBeHidden();
    const boxes = await Promise.all(
      [0, 1, 2].map((index) => groups(page).nth(index).boundingBox()),
    );
    for (let index = 1; index < boxes.length; index++) {
      const previous = boxes[index - 1];
      const current = boxes[index];
      expect(previous && current).toBeTruthy();
      expect(current?.x ?? 0).toBeGreaterThanOrEqual(
        (previous?.x ?? 0) + (previous?.width ?? 0),
      );
    }
  });
  for (const path of [DEFAULT_PAGE, CUSTOM_PAGE]) {
    test(`shows the lead group next to the menu button on small screens (${path})`, async ({
      page,
    }) => {
      await page.setViewportSize({ width: 360, height: 740 });
      await page.goto(path);
      const lead = page.locator(".ananke-nav-lead");
      await expect(lead).toBeVisible();
      await expect(menuButton(page)).toBeVisible();
      await expect(page.locator("#ananke-nav-panel")).toBeHidden();
      const leadBox = await lead.boundingBox();
      const buttonBox = await menuButton(page).boundingBox();
      // Same row: the vertical ranges overlap.
      expect(buttonBox?.y ?? 0).toBeLessThan(
        (leadBox?.y ?? 0) + (leadBox?.height ?? 0),
      );
      expect(leadBox?.x ?? 0).toBeLessThan(buttonBox?.x ?? 0);
      const overflow = await page.evaluate(
        () =>
          document.documentElement.scrollWidth >
          document.documentElement.clientWidth,
      );
      expect(overflow).toBe(false);
    });
  }
  test("gives a slot group its own row on small screens", async ({ page }) => {
    await page.setViewportSize({ width: 360, height: 740 });
    await page.goto(DEFAULT_PAGE);
    const lead = await page.locator(".ananke-nav-lead").boundingBox();
    const slot = await page.locator(".ananke-nav-slot").boundingBox();
    expect(slot?.y ?? 0).toBeGreaterThanOrEqual(
      (lead?.y ?? 0) + (lead?.height ?? 0),
    );
  });
});
tests/e2e/navigation.spec.ts
@@ -302,7 +302,7 @@
    await expect(page.locator(".ananke-nav-brand")).toHaveClass(/\bf3\b/);
  });
  test("renders the navigation-start hook in the slot", async ({ page }) => {
  test("renders a custom component in its own slot group", async ({ page }) => {
    await page.goto("/");
    await expect(
      page.locator(".ananke-nav-slot").getByRole("search"),
tests/fixtures/site/content/header-layout/_index.md
New file
@@ -0,0 +1,12 @@
---
title: "Header layout"
description: "A section with a custom header layout."
ananke:
  header:
    navigation:
      - ["menu", "search"]
      - "logo"
    content: ["description", "search", "title"]
---
A section that changes the header layout in its front matter. Used by the header E2E tests.
tests/fixtures/site/hugo.toml
@@ -15,6 +15,12 @@
show_categories = true
copy_code = true
# Header layout with a custom `search` component in its own group
# (tests/e2e/header.spec.ts, tests/e2e/navigation.spec.ts). The component is
# tests/fixtures/site/layouts/_partials/hooks/header/search.html.
[params.ananke.header]
navigation = [["logo"], ["search"], ["languages", "menu", "social"]]
# Replace the default classes of one navigation element (tests/e2e/navigation.spec.ts).
[params.ananke.navigation.classes]
toggle = "f5 white-90 hover-white fixture-menu-button"
tests/fixtures/site/layouts/_partials/hooks/header/search.html
New file
@@ -0,0 +1,10 @@
{{- /*
  Test fixture: a custom `search` header component (tests/e2e/header.spec.ts,
  tests/e2e/navigation.spec.ts). The id includes the region, because the
  /header-layout/ page renders the component in both regions.
*/ -}}
{{- $id := printf "fixture-search-input-%s" .region -}}
<form class="fixture-search" role="search" action="{{ "posts/" | relURL }}">
  <label class="clip" for="{{ $id }}">Search</label>
  <input id="{{ $id }}" class="input-reset w-100 f6 pv2 ph3 br2 ba b--white-30 bg-white-10 white" type="search" name="q" placeholder="Search">
</form>
tests/fixtures/site/layouts/_partials/hooks/navigation-start.html
File was deleted