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

Patrick Kollitsch
7 hours ago 7e54b1c5ae101e10700f594569e537a14694c6a7
feat(navigation): add configurable submenu modes

Support split, hover, click, and toplevel modes with per-call overrides. Keep mobile navigation behind one hamburger with expanded, indented child lists, and preserve focus across layout changes.
14 files modified
10 files added
842 ■■■■■ changed files
assets/ananke/css/_styles.css 38 ●●●●● patch | view | raw | blame | history
assets/ananke/css/navigation-classes.css 21 ●●●●● patch | view | raw | blame | history
config/_default/params.toml 9 ●●●●● patch | view | raw | blame | history
i18n/en.toml 3 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/GetSubmenuMode.html 14 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/component.html 2 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/submenu.html 13 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/menu.html 51 ●●●●● patch | view | raw | blame | history
layouts/_partials/navigation/menu.html 68 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-navigation.html 4 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-scripts.html 106 ●●●●● patch | view | raw | blame | history
tests/catalog.yaml 2 ●●●●● patch | view | raw | blame | history
tests/coverage-gate.mjs 6 ●●●●● patch | view | raw | blame | history
tests/e2e/accessibility.spec.ts 4 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation-modes.spec.ts 422 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation.spec.ts 14 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/_index.md 9 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/click.md 5 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/hover.md 8 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/invalid.md 8 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/local.md 9 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/toplevel.md 8 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/hugo.toml 4 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/layouts/_partials/hooks/body-end.html 14 ●●●●● patch | view | raw | blame | history
assets/ananke/css/_styles.css
@@ -48,7 +48,8 @@
.ananke-nav-toggle[hidden],
.ananke-submenu-toggle[hidden],
.ananke-submenu[hidden] {
.ananke-submenu[hidden],
.ananke-nav-link[hidden] {
  display: none;
}
@@ -161,23 +162,12 @@
    padding: 0.5rem 0;
  }
  .ananke-nav-item > .ananke-submenu-toggle {
    min-width: 2.75rem;
    min-height: 2.75rem;
  .ananke-nav-item > .ananke-submenu-toggle,
  .ananke-submenu-overview {
    display: none;
  }
  /* A parent without a URL: the button spans the row, and its chevron
     lines up with the chevrons of the other parents. */
  .ananke-nav-item
    > .ananke-submenu-label
    + .ananke-submenu-toggle:not([hidden]) {
    flex: 1 1 auto;
    justify-content: space-between;
    padding: 0;
    padding-inline-end: 1rem;
  }
  .ananke-submenu {
  .ananke-nav-menu .ananke-submenu {
    flex-basis: 100%;
    margin: 0 0 0.5rem;
    padding: 0;
@@ -186,7 +176,14 @@
    border: 0;
  }
  .ananke-nav-item > .ananke-nav-link,
  .ananke-nav-item > .ananke-submenu-label,
  .ananke-submenu-link {
    min-height: 2.75rem;
  }
  .ananke-submenu-link {
    padding-block: 0.5rem;
    padding-inline: 0;
  }
}
@@ -227,6 +224,15 @@
    max-width: calc(100vw - 2rem);
  }
  /* Bridge the visual gap so a slow pointer can enter the dropdown. */
  [data-submenu-mode="hover"] > .ananke-has-submenu > .ananke-submenu-toggle:not([hidden]) + .ananke-submenu::before {
    content: "";
    position: absolute;
    inset-inline: 0;
    top: -0.5rem;
    height: 0.5rem;
  }
  /* Set by the script when the dropdown would leave the viewport. */
  .ananke-submenu-toggle:not([hidden]) + .ananke-submenu-flip {
    inset-inline-start: auto;
assets/ananke/css/navigation-classes.css
@@ -13,7 +13,8 @@
 * [params.ananke.navigation.classes].
 *
 * Breakpoint: below 60em (Tachyons `-l`) the menu collapses behind the menu
 * button and submenus open inline. From 60em the navigation is one row and
 * button and included child lists are always expanded and indented, without
 * submenu controls. From 60em the navigation is one row and
 * submenus open as dropdowns.
 */
@@ -22,6 +23,19 @@
  /* */
}
/* Navigation mode from ananke.navigation.submenu_mode. */
.ananke-nav-menu[data-submenu-mode="hover"] {
  /* */
}
.ananke-nav-menu[data-submenu-mode="click"] {
  /* */
}
.ananke-nav-menu[data-submenu-mode="toplevel"] {
  /* */
}
/* Set on .ananke-nav by the script while the menu panel is closed. */
.ananke-nav-collapsed {
  /* */
@@ -153,6 +167,11 @@
  /* */
}
/* First item linking to the parent page in click mode. */
.ananke-submenu-overview {
  /* */
}
/* Submenu link, or the name of an entry without a URL. */
.ananke-submenu-link {
  /* */
config/_default/params.toml
@@ -27,6 +27,15 @@
# `title` and `description`.
content = ["title", "description"]
[ananke.navigation]
# Desktop behaviour (from 60em). Below 60em, the hamburger opens a list with
# all included child levels expanded and indented, without submenu controls.
# split: parent link and a separate submenu button (default).
# hover: also open on hover with a mouse on large screens; parent stays a link.
# click: parent becomes a button; its page is the first link in the submenu.
# toplevel: render only the top-level entries, without submenus.
submenu_mode = "split"
# 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.
i18n/en.toml
@@ -59,3 +59,6 @@
[menuToggle]
other = "Menu"
[menuOverview]
other = "Overview"
layouts/_partials/func/header/GetSubmenuMode.html
New file
@@ -0,0 +1,14 @@
{{- /*
  Resolve a menu's mode: explicit partial argument > page front matter >
  cascade > site parameters > split. The page's Param method handles the
  page, cascade, and site layers.
  @param page          page    Current page.
  @param submenu_mode  string  Optional per-call override.
*/ -}}
{{- $mode := .submenu_mode | compare.Default (.page.Param "ananke.navigation.submenu_mode") | compare.Default "split" -}}
{{- if not (collections.In (collections.Slice "split" "hover" "click" "toplevel") $mode) -}}
  {{- fmt.Warnf "[ananke] Invalid ananke.navigation.submenu_mode %q; using split. Choose split, hover, click, or toplevel." $mode -}}
  {{- $mode = "split" -}}
{{- end -}}
{{- return $mode -}}
layouts/_partials/header/component.html
@@ -16,6 +16,8 @@
    - `region`          "navigation" or "content"
    - `featured_image`  the featured image URL of the page, or an empty string
    - `variant`         "site" or "page" (content region only)
    - `submenu_mode`    "split", "hover", "click", or "toplevel"
                        (navigation region only; per-call overrides are supported)
    - `classes`         navigation classes from
                        func/header/GetNavigationClasses.html (navigation
                        region only)
layouts/_partials/header/submenu.html
@@ -7,10 +7,23 @@
  @param entries  menu    The child entries.
  @param classes  map     Classes from func/header/GetNavigationClasses.html.
  @param id       string  Optional. Id of the top-level list.
  @param overview menu.Entry Optional. Parent entry to link first in click mode.
*/ -}}
{{- $page := .page }}
{{- $classes := .classes }}
<ul {{ with .id }}id="{{ . }}" class="ananke-submenu {{ $classes.submenu }}"{{ else }}class="ananke-submenu-nested list ma0 pa0"{{ end }}>
  {{- with .overview }}
  {{- if .URL }}
  {{- $label := lang.Translate "menuOverview" . | compare.Default .Name }}
  {{- with .Page }}
    {{- with .Params.linktitle }}{{- $label = . }}{{- end }}
  {{- end }}
  {{- $current := partials.Include "func/header/GetMenuCurrent.html" (dict "page" $page "entry" .) }}
  <li class="ananke-submenu-item ananke-submenu-overview">
    <a class="ananke-submenu-link {{ $classes.submenu_link }}" href="{{ .URL }}"{{ if eq $current "page" }} aria-current="page"{{ end }}>{{ $label }}</a>
  </li>
  {{- end }}
  {{- end }}
  {{- range .entries }}
  {{- $current := partials.Include "func/header/GetMenuCurrent.html" (dict "page" $page "entry" .) }}
  <li class="ananke-submenu-item">
layouts/_partials/hooks/header/menu.html
@@ -1,49 +1,2 @@
{{- /*
  Header component: the `main` menu of the site, with submenus for entries
  that have children. Renders nothing if the site has no `main` menu.
  The child lists are always in the markup, so they stay reachable without
  JavaScript. site-scripts.html adds the submenu toggle behaviour.
*/ -}}
{{- $page := .page -}}
{{- $classes := .classes -}}
{{- if $page.Site.Menus.main -}}
<ul class="ananke-nav-menu {{ $classes.menu }}">
  {{ range $index, $entry := $page.Site.Menus.main }}
  {{- $current := partials.Include "func/header/GetMenuCurrent.html" (dict "page" $page "entry" $entry) -}}
  {{- if not $entry.HasChildren }}
  <li class="ananke-nav-item {{ $classes.item }}">
    <a class="ananke-nav-link {{ $classes.link }}" href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>
      {{ .Name }}
    </a>
  </li>
  {{- else }}
  {{- /*
    A parent entry with children. The child list is always in the
    markup, so it stays reachable without JavaScript. Entries below the
    second level render as nested lists inside the submenu, without
    their own toggle.
  */}}
  {{- $submenu_id := printf "ananke-submenu-%d" $index }}
  <li class="ananke-nav-item ananke-has-submenu {{ $classes.item }}">
    {{- if .URL }}
    <a class="ananke-nav-link {{ $classes.link }}" href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>
      {{ .Name }}
    </a>
    <button type="button" class="ananke-submenu-toggle {{ $classes.submenu_toggle }}" aria-expanded="false" aria-controls="{{ $submenu_id }}" hidden>
      <span class="clip">{{ lang.Translate "submenuToggle" . | compare.Default .Name }}</span>
      {{- partials.Include "header/submenu-icon.html" }}
    </button>
    {{- else }}
    <span class="ananke-submenu-label {{ $classes.link }}">{{ .Name }}</span>
    <button type="button" class="ananke-submenu-toggle {{ $classes.submenu_toggle }}" aria-expanded="false" aria-controls="{{ $submenu_id }}"{{ with $current }} aria-current="{{ . }}"{{ end }} hidden>
      {{ .Name }}
      {{- partials.Include "header/submenu-icon.html" }}
    </button>
    {{- end }}
    {{ partials.Include "header/submenu.html" (dict "page" $page "entries" .Children "id" $submenu_id "classes" $classes) }}
  </li>
  {{- end }}
  {{ end }}
</ul>
{{- end -}}
{{- /* The header uses the same renderer as explicitly included menus. */ -}}
{{- partials.Include "navigation/menu.html" . -}}
layouts/_partials/navigation/menu.html
New file
@@ -0,0 +1,68 @@
{{- /*
  Render the main menu. Use submenu_mode to override the configured mode for
  this call. Classes and mode default to the page's navigation settings.
  Optional id identifies the list and prefixes its submenu control IDs.
  Without id, each call gets a unique ID within the current page.
  In toplevel mode, child lists and submenu controls are omitted. All other
  modes keep child links reachable without JavaScript.
*/ -}}
{{- $page := .page -}}
{{- $classes := .classes | compare.Default (partials.Include "func/header/GetNavigationClasses.html" $page) -}}
{{- $mode := partials.Include "func/header/GetSubmenuMode.html" . -}}
{{- if $page.Site.Menus.main -}}
{{- $page.Store.Add "ananke.navigation.menu-count" 1 -}}
{{- $instance := $page.Store.Get "ananke.navigation.menu-count" -}}
{{- $id := .id | compare.Default (printf "ananke-menu-%d" $instance) -}}
{{- $prefix := printf "%s-submenu" $id -}}
{{- if and (eq $instance 1) (not .id) -}}
  {{- $id = "ananke-menu" -}}
  {{- $prefix = "ananke-submenu" -}}
{{- end -}}
<ul id="{{ $id }}" class="ananke-nav-menu {{ $classes.menu }}" data-submenu-mode="{{ $mode }}">
  {{ range $index, $entry := $page.Site.Menus.main }}
  {{- $current := partials.Include "func/header/GetMenuCurrent.html" (dict "page" $page "entry" $entry) -}}
  {{- if or (eq $mode "toplevel") (not $entry.HasChildren) }}
  <li class="ananke-nav-item {{ $classes.item }}">
    {{- if .URL }}
    <a class="ananke-nav-link {{ $classes.link }}" href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>
      {{ .Name }}
    </a>
    {{- else }}
    <span class="ananke-nav-link {{ $classes.link }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>{{ .Name }}</span>
    {{- end }}
  </li>
  {{- else }}
  {{- /*
    A parent entry with children. The child list is always in the
    markup, so it stays reachable without JavaScript. Entries below the
    second level render as nested lists inside the submenu, without
    their own toggle.
  */}}
  {{- $submenu_id := printf "%s-%d" $prefix $index }}
  <li class="ananke-nav-item ananke-has-submenu {{ $classes.item }}">
    {{- if .URL }}
    <a class="ananke-nav-link {{ $classes.link }}"{{ if eq $mode "click" }} data-submenu-parent{{ end }} href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>
      {{ .Name }}
    </a>
    <button type="button" class="ananke-submenu-toggle {{ $classes.submenu_toggle }}" aria-expanded="false" aria-controls="{{ $submenu_id }}"{{ if eq $mode "click" }}{{ with $current }} aria-current="{{ . }}"{{ end }}{{ end }} hidden>
      {{- if eq $mode "click" }}
      {{ .Name }}
      {{- else }}
      <span class="clip">{{ lang.Translate "submenuToggle" . | compare.Default .Name }}</span>
      {{- end }}
      {{- partials.Include "header/submenu-icon.html" }}
    </button>
    {{- else }}
    <span class="ananke-submenu-label {{ $classes.link }}">{{ .Name }}</span>
    <button type="button" class="ananke-submenu-toggle {{ $classes.submenu_toggle }}" aria-expanded="false" aria-controls="{{ $submenu_id }}"{{ with $current }} aria-current="{{ . }}"{{ end }} hidden>
      {{ .Name }}
      {{- partials.Include "header/submenu-icon.html" }}
    </button>
    {{- end }}
    {{ partials.Include "header/submenu.html" (dict "page" $page "entries" .Children "id" $submenu_id "classes" $classes "overview" (compare.Conditional (eq $mode "click") $entry false)) }}
  </li>
  {{- end }}
  {{ end }}
</ul>
{{- end -}}
layouts/_partials/site-navigation.html
@@ -26,11 +26,13 @@
  buttons stay hidden. site-scripts.html enhances both.
*/ -}}
{{- $classes := partials.Include "func/header/GetNavigationClasses.html" . -}}
{{- $mode := partials.Include "func/header/GetSubmenuMode.html" (dict "page" .) -}}
{{- $header := collections.Dictionary
  "page" .
  "region" "navigation"
  "featured_image" (partials.Include "func/GetFeaturedImage.html" .)
  "classes" $classes
  "submenu_mode" $mode
-}}
{{- /* Normalise the layout to a list of non-empty groups. Each group is a
@@ -71,7 +73,7 @@
  {{- end -}}
{{- end -}}
<nav class="ananke-nav {{ $classes.nav }}" role="navigation">
<nav class="ananke-nav {{ $classes.nav }}" role="navigation" data-submenu-mode="{{ $mode }}">
  <div class="ananke-nav-inner {{ $classes.inner }}">
    {{- range $index, $group := $groups }}
    {{- if compare.Eq $index $panel }}
layouts/_partials/site-scripts.html
@@ -9,7 +9,7 @@
     with `[ananke] copy_code = false`.
  2. Header navigation rendered by layouts/_partials/site-navigation.html:
     the menu button that collapses the menu below the Tachyons `-l`
     breakpoint, and the submenu toggles. Only included if the site has a
     breakpoint, and the desktop submenu toggles. Only included if the site has a
     `main` menu.
  Override this partial in your own project to add or replace site scripts.
@@ -95,6 +95,10 @@
    // The toggle button of the open submenu. Only one submenu is open at a time.
    var openButton = null;
    var hoverCloseTimer = null;
    var lastNavigationFocus = null;
    var desktopMedia = window.matchMedia("(min-width: 60em)");
    var hoverMedia = window.matchMedia("(min-width: 60em) and (hover: hover) and (pointer: fine)");
    function controlled(button) {
      return document.getElementById(button.getAttribute("aria-controls"));
@@ -102,7 +106,8 @@
    function setSubmenu(button, expanded) {
      var submenu = controlled(button);
      if (!submenu) return;
      if (!submenu || !desktopMedia.matches) return;
      window.clearTimeout(hoverCloseTimer);
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
      submenu.hidden = !expanded;
      submenu.classList.remove("ananke-submenu-flip");
@@ -131,8 +136,80 @@
      nav.classList.toggle("ananke-nav-collapsed", !expanded);
    }
    // Reveal the buttons and collapse the menu and submenus once the DOM is
    // ready. Without JavaScript everything stays visible.
    function enhanceHover(button) {
      var item = button.parentNode;
      var menu = button.closest("[data-submenu-mode]");
      if (!menu || menu.dataset.submenuMode !== "hover") return;
      item.addEventListener("pointerenter", function (event) {
        if (event.pointerType !== "mouse" || !hoverMedia.matches) return;
        window.clearTimeout(hoverCloseTimer);
        if (openButton === button) return;
        // Hover must not hide a link that still has keyboard focus.
        if (openButton && controlled(openButton).contains(document.activeElement)) return;
        closeSubmenu(false);
        setSubmenu(button, true);
      });
      item.addEventListener("pointerleave", function (event) {
        if (event.pointerType !== "mouse" || !hoverMedia.matches) return;
        // Keep the dropdown open while the keyboard focus is inside it.
        hoverCloseTimer = window.setTimeout(function () {
          if (openButton === button && !item.contains(document.activeElement)) {
            closeSubmenu(false);
          }
        }, 200);
      });
    }
    hoverMedia.addEventListener("change", function () {
      if (openButton && openButton.closest("[data-submenu-mode]").dataset.submenuMode === "hover") {
        closeSubmenu(false);
      }
    });
    // Mobile has one disclosure: the hamburger. Every included child list
    // stays expanded, and parent entries keep their normal links or labels.
    function updateSubmenus() {
      var desktop = desktopMedia.matches;
      var active = document.activeElement;
      // A breakpoint can hide the focused element before this event runs.
      if (active === document.body && lastNavigationFocus) active = lastNavigationFocus;
      var focusTarget = null;
      window.clearTimeout(hoverCloseTimer);
      openButton = null;
      var buttons = document.querySelectorAll(".ananke-submenu-toggle");
      for (var i = 0; i < buttons.length; i++) {
        var button = buttons[i];
        var submenu = controlled(button);
        if (!submenu) continue;
        submenu.hidden = desktop;
        submenu.classList.remove("ananke-submenu-flip");
        button.hidden = !desktop;
        button.setAttribute("aria-expanded", "false");
        var label = button.parentNode.querySelector(".ananke-submenu-label");
        if (label) label.hidden = desktop;
        var parentLink = button.parentNode.querySelector("[data-submenu-parent]");
        if (parentLink) parentLink.hidden = desktop;
        if (desktop && submenu.contains(active)) focusTarget = button;
        if (!desktop && active === button) {
          focusTarget = parentLink || submenu.querySelector("a");
        }
      }
      var nav = active.closest(".ananke-nav");
      if (nav) {
        var menuButton = nav.querySelector(".ananke-nav-toggle");
        var panel = menuButton && controlled(menuButton);
        if (!desktop && panel && panel.contains(active) && nav.classList.contains("ananke-nav-collapsed")) {
          focusTarget = menuButton;
        } else if (desktop && active === menuButton && panel) {
          focusTarget = panel.querySelector('a:not([hidden]), button:not([hidden])');
        }
      }
      if (focusTarget) focusTarget.focus();
    }
    desktopMedia.addEventListener("change", updateSubmenus);
    // Without JavaScript, all links stay visible and controls stay hidden.
    function enhance() {
      var menuButtons = document.querySelectorAll(".ananke-nav-toggle[hidden]");
      for (var i = 0; i < menuButtons.length; i++) {
@@ -140,14 +217,10 @@
        setMenu(menuButtons[i], false);
        menuButtons[i].hidden = false;
      }
      var buttons = document.querySelectorAll(".ananke-submenu-toggle[hidden]");
      updateSubmenus();
      var buttons = document.querySelectorAll(".ananke-submenu-toggle");
      for (var j = 0; j < buttons.length; j++) {
        var submenu = controlled(buttons[j]);
        if (!submenu) continue;
        submenu.hidden = true;
        buttons[j].hidden = false;
        var label = buttons[j].parentNode.querySelector(".ananke-submenu-label");
        if (label) label.hidden = true;
        enhanceHover(buttons[j]);
      }
    }
    if (document.readyState === "loading") {
@@ -163,7 +236,7 @@
        return;
      }
      var button = event.target.closest(".ananke-submenu-toggle");
      if (button) {
      if (button && desktopMedia.matches) {
        var expand = button.getAttribute("aria-expanded") !== "true";
        if (openButton && openButton !== button) closeSubmenu(false);
        setSubmenu(button, expand);
@@ -188,14 +261,17 @@
    });
    // Close a submenu when keyboard focus leaves its menu item. Pointer users
    // get the outside-click handler instead: on small screens submenus open
    // inline, and closing one on pointer focus would move the target of the
    // click that is still in progress.
    // get the outside-click handler instead. Mobile child lists do not have
    // their own disclosure state.
    var keyboardFocus = false;
    document.addEventListener("keydown", function () {
      keyboardFocus = true;
    }, true);
    document.addEventListener("focusin", function (event) {
      lastNavigationFocus = event.target.closest(".ananke-nav") ? event.target : null;
    });
    document.addEventListener("pointerdown", function () {
      lastNavigationFocus = null;
      keyboardFocus = false;
    }, true);
    document.addEventListener("focusout", function (event) {
tests/catalog.yaml
@@ -16,6 +16,8 @@
    tests: ["scripts/test-hugo-quickstart.ts"]
  ananke.copy_code:
    tests: ["tests/e2e/copy-button.spec.ts"]
  ananke.navigation.submenu_mode:
    tests: ["tests/e2e/navigation-modes.spec.ts"]
  ananke.navigation.classes.nav:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.inner:
tests/coverage-gate.mjs
@@ -25,7 +25,11 @@
const repoRoot = resolve(here, "..");
/** Tables in config/_default/params.toml whose direct keys are gated. */
const GATED_TABLES = ["ananke", "ananke.navigation.classes"];
const GATED_TABLES = [
  "ananke",
  "ananke.navigation",
  "ananke.navigation.classes",
];
/** Direct `key = value` entries under the gated tables. */
function collectAnankeParams() {
tests/e2e/accessibility.spec.ts
@@ -82,13 +82,13 @@
  }
}
test("header with the open menu and an open submenu at 375px has no automatically detectable a11y violations", async ({
test("header with the expanded mobile menu at 375px has no automatically detectable a11y violations", async ({
  page,
}) => {
  await page.setViewportSize({ width: 375, height: 800 });
  await page.goto("/");
  await page.getByRole("button", { name: "Menu", exact: true }).click();
  await page.getByRole("button", { name: "Topics" }).click();
  await expect(page.locator(".ananke-submenu-toggle:visible")).toHaveCount(0);
  const results = await new AxeBuilder({ page })
    .include("header")
    .withTags(TAGS)
tests/e2e/navigation-modes.spec.ts
New file
@@ -0,0 +1,422 @@
import { AxeBuilder } from "@axe-core/playwright";
import { expect, test } from "@playwright/test";
const HOVER = "/navigation-modes/hover/";
const CLICK = "/navigation-modes/click/";
test("resolves site, cascade, and page modes, and rejects invalid values", async ({
  page,
}) => {
  for (const [path, mode] of [
    ["/", "split"],
    [CLICK, "click"],
    [HOVER, "hover"],
    ["/navigation-modes/toplevel/", "toplevel"],
    ["/navigation-modes/invalid/", "split"],
  ] as const) {
    await page.goto(path);
    await expect(page.locator("nav")).toHaveAttribute(
      "data-submenu-mode",
      mode,
    );
  }
});
test.describe("hover navigation", () => {
  test("opens on hover, crosses the gap, closes on leaving, and follows the parent link", async ({
    page,
  }) => {
    await page.goto(HOVER);
    const parent = page
      .locator("nav")
      .getByRole("link", { name: "Posts", exact: true });
    const submenu = page.locator("#ananke-submenu-0");
    await parent.hover();
    await expect(submenu).toBeVisible();
    const box = await submenu.boundingBox();
    if (!box) throw new Error("Submenu has no bounds");
    // Pause in the visual gap before entering the dropdown.
    await page.mouse.move(box.x + 10, box.y - 3);
    await page.waitForTimeout(300);
    await expect(submenu).toBeVisible();
    await submenu.getByRole("link").first().hover();
    await expect(submenu).toBeVisible();
    await page.mouse.move(1, 1);
    await expect(submenu).toBeHidden();
    await parent.click();
    await expect(page).toHaveURL(/\/posts\/$/);
  });
  test("keeps only one dropdown open and respects Escape while the pointer stays", async ({
    page,
  }) => {
    await page.goto(HOVER);
    await page
      .locator("nav")
      .getByRole("link", { name: "Posts", exact: true })
      .hover();
    await page
      .locator("nav")
      .getByRole("button", { name: "Topics", exact: true })
      .hover();
    await expect(page.locator("#ananke-submenu-0")).toBeHidden();
    await expect(page.locator("#ananke-submenu-1")).toBeVisible();
    await page.keyboard.press("Escape");
    await expect(page.locator("#ananke-submenu-1")).toBeHidden();
    await page.mouse.move(1, 1);
    await page
      .locator("nav")
      .getByRole("button", { name: "Topics", exact: true })
      .hover();
    await expect(page.locator("#ananke-submenu-1")).toBeVisible();
  });
  test("supports keyboard toggling and preserves keyboard focus when the pointer leaves", async ({
    page,
  }) => {
    await page.goto(HOVER);
    const button = page.getByRole("button", { name: "Posts submenu" });
    await button.focus();
    await page.keyboard.press("Enter");
    await page.keyboard.press("Tab");
    await expect(page.locator("#ananke-submenu-0 a").first()).toBeFocused();
    await button.hover();
    await page.mouse.move(1, 1);
    await page.waitForTimeout(300);
    await expect(page.locator("#ananke-submenu-0")).toBeVisible();
    await page.getByRole("button", { name: "Topics", exact: true }).hover();
    await expect(page.locator("#ananke-submenu-0")).toBeVisible();
    await expect(page.locator("#ananke-submenu-1")).toBeHidden();
    await page.keyboard.press("Escape");
    await expect(button).toBeFocused();
    await expect(page.locator("#ananke-submenu-0")).toBeHidden();
  });
});
test.describe("click navigation", () => {
  test("turns the parent into one button and puts its overview first", async ({
    page,
  }) => {
    await page.goto(CLICK);
    const button = page
      .locator("nav")
      .getByRole("button", { name: "Posts", exact: true });
    await expect(page.locator("[data-submenu-parent]")).toBeHidden();
    await button.hover();
    await expect(page.locator("#ananke-submenu-0")).toBeHidden();
    await button.click();
    await expect(page).toHaveURL(new RegExp(CLICK));
    const first = page.locator("#ananke-submenu-0 a").first();
    await expect(first).toHaveText("Overview");
    await expect(first).toHaveAttribute("href", "/posts/");
    await first.click();
    await expect(page).toHaveURL(/\/posts\/$/);
  });
  test("supports Enter, Space, Escape, and parents without a page", async ({
    page,
  }) => {
    await page.goto(CLICK);
    const button = page
      .locator("nav")
      .getByRole("button", { name: "Posts", exact: true });
    await button.focus();
    await page.keyboard.press("Enter");
    await page.keyboard.press("Tab");
    await expect(page.locator("#ananke-submenu-0 a").first()).toBeFocused();
    await page.keyboard.press("Escape");
    await expect(button).toBeFocused();
    await page.keyboard.press("Space");
    await expect(page.locator("#ananke-submenu-0")).toBeVisible();
    await page
      .locator("nav")
      .getByRole("button", { name: "Topics", exact: true })
      .click();
    await expect(page.locator("#ananke-submenu-0")).toBeHidden();
    await expect(
      page.locator("#ananke-submenu-1 .ananke-submenu-overview"),
    ).toHaveCount(0);
  });
});
for (const [path, name] of [
  [HOVER, "Posts submenu"],
  [CLICK, "Posts"],
] as const) {
  test(`has no detected accessibility violations with ${name} open`, async ({
    page,
  }) => {
    await page.goto(path);
    await page
      .locator("nav")
      .getByRole("button", { name, exact: true })
      .click();
    const results = await new AxeBuilder({ page })
      .include("nav")
      .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"])
      .analyze();
    expect(results.violations).toEqual([]);
  });
  test(`shows expanded child lists after one tap on ${path}`, async ({
    browser,
    baseURL,
  }) => {
    const context = await browser.newContext({
      baseURL: baseURL ?? "http://localhost:4321",
      hasTouch: true,
      isMobile: true,
      viewport: { width: 375, height: 800 },
    });
    const page = await context.newPage();
    await page.goto(path);
    await page.locator(".ananke-nav-toggle").tap();
    await expect(page.locator("#ananke-submenu-0")).toBeVisible();
    await expect(page.locator("#ananke-submenu-1")).toBeVisible();
    await expect(page.locator(".ananke-submenu-toggle:visible")).toHaveCount(0);
    await page
      .locator("nav")
      .getByRole("link", { name: "Posts", exact: true })
      .tap();
    await expect(page).toHaveURL(/\/posts\/$/);
    await context.close();
  });
  test(`keeps parents and children reachable without JavaScript on ${path}`, async ({
    browser,
    baseURL,
  }) => {
    const context = await browser.newContext({
      javaScriptEnabled: false,
      baseURL: baseURL ?? "http://localhost:4321",
    });
    const page = await context.newPage();
    await page.goto(path);
    await expect(
      page.locator("nav").getByRole("link", { name: "Posts", exact: true }),
    ).toBeVisible();
    await expect(page.locator("#ananke-submenu-0 a").last()).toBeVisible();
    await expect(page.locator("nav button:visible")).toHaveCount(0);
    await context.close();
  });
}
test.describe("local menu modes", () => {
  const path = "/navigation-modes/local/";
  test("overrides the page per call and defaults to the page when omitted", async ({
    page,
  }) => {
    await page.goto(path);
    await expect(page.locator("header .ananke-nav-menu")).toHaveAttribute(
      "data-submenu-mode",
      "hover",
    );
    for (const mode of ["split", "hover", "click", "toplevel"]) {
      await expect(page.locator(`#fixture-${mode}`)).toHaveAttribute(
        "data-submenu-mode",
        mode,
      );
    }
    await expect(
      page
        .getByRole("navigation", { name: "Inherited mode", exact: true })
        .locator("ul")
        .first(),
    ).toHaveAttribute("data-submenu-mode", "hover");
    await expect(
      page
        .getByRole("navigation", { name: "Invalid local mode", exact: true })
        .locator("ul")
        .first(),
    ).toHaveAttribute("data-submenu-mode", "split");
  });
  test("uses each instance's mode and unique control targets", async ({
    page,
  }) => {
    await page.goto(path);
    const split = page.locator("#fixture-split");
    const hover = page.locator("#fixture-hover");
    const click = page.locator("#fixture-click");
    await split.getByRole("link", { name: "Posts", exact: true }).hover();
    await expect(split.locator(".ananke-submenu").first()).toBeHidden();
    await hover.getByRole("link", { name: "Posts", exact: true }).hover();
    await expect(hover.locator(".ananke-submenu").first()).toBeVisible();
    await click.getByRole("button", { name: "Posts", exact: true }).hover();
    await expect(click.locator(".ananke-submenu").first()).toBeHidden();
    await click.getByRole("button", { name: "Posts", exact: true }).click();
    await expect(click.locator(".ananke-submenu").first()).toBeVisible();
    await expect(hover.locator(".ananke-submenu").first()).toBeHidden();
    await expect(click.locator(".ananke-submenu a").first()).toHaveText(
      "Overview",
    );
    const ids = await page
      .locator("[id]")
      .evaluateAll((els) => els.map((el) => el.id));
    expect(new Set(ids).size).toBe(ids.length);
    const controls = await page
      .locator(".ananke-submenu-toggle")
      .evaluateAll((els) =>
        els.map((el) => {
          const target = document.getElementById(
            el.getAttribute("aria-controls") || "",
          );
          return !!target && target.parentElement === el.parentElement;
        }),
      );
    expect(controls.every(Boolean)).toBe(true);
  });
  test("renders only the top level, including plain labels without a target", async ({
    page,
  }) => {
    await page.goto(path);
    const menu = page.locator("#fixture-toplevel");
    await expect(menu.locator(":scope > li")).toHaveCount(3);
    await expect(menu.locator("ul, button")).toHaveCount(0);
    await expect(
      menu.getByRole("link", { name: "Posts", exact: true }),
    ).toHaveAttribute("href", "/posts/");
    await expect(menu.getByText("Topics", { exact: true })).toBeVisible();
    await expect(
      menu.getByRole("link", { name: "Topics", exact: true }),
    ).toHaveCount(0);
    await expect(menu.getByText("Hello World", { exact: true })).toHaveCount(0);
  });
  test("retains the same top-level-only output without JavaScript", async ({
    browser,
    baseURL,
  }) => {
    const context = await browser.newContext({
      javaScriptEnabled: false,
      baseURL: baseURL ?? "http://localhost:4321",
    });
    const page = await context.newPage();
    await page.goto(path);
    const menu = page.locator("#fixture-toplevel");
    await expect(menu.locator(":scope > li")).toHaveCount(3);
    await expect(menu.locator("ul, button")).toHaveCount(0);
    await expect(
      menu.getByRole("link", { name: "Posts", exact: true }),
    ).toBeVisible();
    await expect(
      page
        .locator("#fixture-click")
        .getByRole("link", { name: "Posts", exact: true }),
    ).toBeVisible();
    await expect(
      page.locator("#fixture-click .ananke-submenu").first(),
    ).toBeVisible();
    await context.close();
  });
  test("has no detected accessibility violations with mixed modes", async ({
    page,
  }) => {
    await page.goto(path);
    await page
      .locator("#fixture-click")
      .getByRole("button", { name: "Posts", exact: true })
      .click();
    const results = await new AxeBuilder({ page })
      .include("nav")
      .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"])
      .analyze();
    expect(results.violations).toEqual([]);
  });
});
test.describe("mobile navigation uses one hamburger in every mode", () => {
  for (const [mode, path] of [
    ["split", "/"],
    ["hover", HOVER],
    ["click", CLICK],
    ["toplevel", "/navigation-modes/toplevel/"],
  ] as const) {
    for (const width of [375, 959]) {
      test(`${mode} shows an expanded, indented list at ${width}px`, async ({
        page,
      }) => {
        await page.setViewportSize({ width, height: 900 });
        await page.goto(path);
        const nav = page.locator("header nav");
        const hamburger = nav.locator(".ananke-nav-toggle");
        const panel = nav.locator(".ananke-nav-panel");
        await expect(hamburger).toBeVisible();
        await expect(panel).toBeHidden();
        await hamburger.click();
        await expect(panel).toBeVisible();
        await expect(panel.getByRole("button")).toHaveCount(0);
        const parent = panel.getByRole("link", { name: "Posts", exact: true });
        await expect(parent).toBeVisible();
        await expect(
          panel.locator("span").getByText("Topics", { exact: true }),
        ).toBeVisible();
        if (mode === "toplevel") {
          await expect(panel.locator("ul ul")).toHaveCount(0);
        } else {
          const child = panel.getByRole("link", {
            name: "Hello World",
            exact: true,
          });
          const tags = panel.getByRole("link", { name: "Tags", exact: true });
          const alpha = panel.getByRole("link", { name: "Alpha", exact: true });
          await expect(child).toBeVisible();
          await expect(alpha).toBeVisible();
          expect((await child.boundingBox())?.x).toBeGreaterThan(
            (await parent.boundingBox())?.x ?? 0,
          );
          expect((await alpha.boundingBox())?.x).toBeGreaterThan(
            (await tags.boundingBox())?.x ?? 0,
          );
          await parent.hover();
          await page.mouse.move(1, 1);
          await expect(child).toBeVisible();
          await expect(alpha).toBeVisible();
          await alpha.focus();
          await page.keyboard.press("Escape");
          await expect(panel).toBeHidden();
          await expect(hamburger).toBeFocused();
          await hamburger.click();
          await expect(child).toBeVisible();
        }
        await parent.click();
        await expect(page).toHaveURL(/\/posts\/$/);
      });
    }
  }
  for (const [path, label] of [
    ["/", "Posts submenu"],
    [HOVER, "Posts submenu"],
    [CLICK, "Posts"],
  ] as const) {
    test(`resets submenu state and keeps focus visible when resizing ${path}`, async ({
      page,
    }) => {
      await page.goto(path);
      const nav = page.locator("header nav");
      const button = nav.getByRole("button", { name: label, exact: true });
      const submenu = nav.locator(".ananke-submenu").first();
      await button.focus();
      await page.keyboard.press("Enter");
      await submenu.getByRole("link").last().focus();
      await page.setViewportSize({ width: 375, height: 900 });
      const hamburger = nav.locator(".ananke-nav-toggle");
      await expect(hamburger).toBeFocused();
      await hamburger.click();
      await expect(submenu).toBeVisible();
      await expect(nav.locator(".ananke-submenu-toggle:visible")).toHaveCount(
        0,
      );
      await submenu.getByRole("link").last().focus();
      await page.setViewportSize({ width: 1280, height: 900 });
      await expect(submenu).toBeHidden();
      await expect(button).toBeFocused();
      await page.keyboard.press("Enter");
      await expect(submenu).toBeVisible();
    });
  }
});
tests/e2e/navigation.spec.ts
@@ -201,7 +201,7 @@
        [postsToggle(page), postsSubmenu(page)],
        [topicsToggle(page), topicsSubmenu(page)],
      ] as const) {
        await toggle.click();
        if (width >= 960) await toggle.click();
        await expect(submenu).toBeVisible();
        const box = await submenu.boundingBox();
        expect(box).not.toBeNull();
@@ -248,8 +248,10 @@
    await expect(menuButton(page)).toHaveAttribute("aria-expanded", "true");
    await expect(panel(page)).toBeVisible();
    await expect(nav(page).getByRole("link", { name: "About" })).toBeVisible();
    // Submenus open inline inside the panel.
    await topicsToggle(page).click();
    // All child levels are already visible inside the panel.
    await expect(
      nav(page).locator(".ananke-submenu-toggle:visible"),
    ).toHaveCount(0);
    await expect(
      topicsSubmenu(page).getByRole("link", { name: "Categories" }),
    ).toBeVisible();
@@ -269,13 +271,13 @@
    await expect(menuButton(page)).toBeFocused();
  });
  test("gives touch targets of at least 44px to submenu buttons", async ({
  test("gives touch targets of at least 44px to navigation links", async ({
    page,
  }) => {
    await page.goto("/");
    await menuButton(page).click();
    for (const toggle of [postsToggle(page), topicsToggle(page)]) {
      const box = await toggle.boundingBox();
    for (const link of await panel(page).getByRole("link").all()) {
      const box = await link.boundingBox();
      expect(box?.height ?? 0).toBeGreaterThanOrEqual(44);
    }
  });
tests/fixtures/site/content/navigation-modes/_index.md
New file
@@ -0,0 +1,9 @@
---
title: Navigation modes
cascade:
  ananke:
    navigation:
      submenu_mode: click
---
This section selects click navigation through cascade.
tests/fixtures/site/content/navigation-modes/click.md
New file
@@ -0,0 +1,5 @@
---
title: Click navigation
---
This page inherits click navigation from its section.
tests/fixtures/site/content/navigation-modes/hover.md
New file
@@ -0,0 +1,8 @@
---
title: Hover navigation
ananke:
  navigation:
    submenu_mode: hover
---
This page overrides the cascade with hover navigation.
tests/fixtures/site/content/navigation-modes/invalid.md
New file
@@ -0,0 +1,8 @@
---
title: Invalid navigation mode
ananke:
  navigation:
    submenu_mode: unknown
---
This page falls back to split navigation with a build warning.
tests/fixtures/site/content/navigation-modes/local.md
New file
@@ -0,0 +1,9 @@
---
title: Local menu modes
fixture_menu_instances: true
ananke:
  navigation:
    submenu_mode: hover
---
The header uses the page mode. Additional menu calls override it independently.
tests/fixtures/site/content/navigation-modes/toplevel.md
New file
@@ -0,0 +1,8 @@
---
title: Top-level navigation
ananke:
  navigation:
    submenu_mode: toplevel
---
Only the top-level main menu entries are rendered.
tests/fixtures/site/hugo.toml
@@ -21,6 +21,10 @@
[params.ananke.header]
navigation = [["logo"], ["search"], ["languages", "menu", "social"]]
# Explicit site value; navigation-modes fixtures override it via cascade and front matter.
[params.ananke.navigation]
submenu_mode = "split"
# 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/body-end.html
New file
@@ -0,0 +1,14 @@
{{- if .Params.fixture_menu_instances }}
{{- $page := . }}
{{- range slice "split" "hover" "click" "toplevel" }}
<nav aria-label="Local {{ . }}" class="ananke-nav pv3 ph3 bg-black">
  {{ partials.Include "navigation/menu.html" (dict "page" $page "submenu_mode" . "id" (printf "fixture-%s" .)) }}
</nav>
{{- end }}
<nav aria-label="Inherited mode" class="ananke-nav pv3 ph3 bg-black">
  {{ partials.Include "navigation/menu.html" (dict "page" .) }}
</nav>
<nav aria-label="Invalid local mode" class="ananke-nav pv3 ph3 bg-black">
  {{ partials.Include "navigation/menu.html" (dict "page" . "submenu_mode" "invalid") }}
</nav>
{{- end }}