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

Patrick Kollitsch
8 hours ago 804d93a7a98f2fead5e905801c6fc1f42596a27c
feat(header): rework header and navigation

Add configurable header components, hooks, submenu modes, and mobile navigation. Preserve legacy overrides with migration warnings and honour page-level navigation classes.
44 files modified
30 files added
2592 ■■■■■ changed files
CONTRIBUTING.md 2 ●●●●● patch | view | raw | blame | history
assets/ananke/css/_styles.css 234 ●●●●● patch | view | raw | blame | history
assets/ananke/css/navigation-classes.css 187 ●●●●● patch | view | raw | blame | history
config/_default/params.toml 46 ●●●●● patch | view | raw | blame | history
i18n/bg.toml 3 ●●●●● patch | view | raw | blame | history
i18n/ca.toml 3 ●●●●● patch | view | raw | blame | history
i18n/cs.toml 3 ●●●●● patch | view | raw | blame | history
i18n/cy.toml 3 ●●●●● patch | view | raw | blame | history
i18n/de.toml 3 ●●●●● patch | view | raw | blame | history
i18n/en.toml 9 ●●●●● patch | view | raw | blame | history
i18n/es.toml 3 ●●●●● patch | view | raw | blame | history
i18n/fi.toml 3 ●●●●● patch | view | raw | blame | history
i18n/fr.toml 3 ●●●●● patch | view | raw | blame | history
i18n/he.toml 3 ●●●●● patch | view | raw | blame | history
i18n/hi.toml 3 ●●●●● patch | view | raw | blame | history
i18n/hu.toml 3 ●●●●● patch | view | raw | blame | history
i18n/id.toml 3 ●●●●● patch | view | raw | blame | history
i18n/it.toml 3 ●●●●● patch | view | raw | blame | history
i18n/ja.toml 3 ●●●●● patch | view | raw | blame | history
i18n/nl.toml 3 ●●●●● patch | view | raw | blame | history
i18n/no.toml 3 ●●●●● patch | view | raw | blame | history
i18n/oc.toml 3 ●●●●● patch | view | raw | blame | history
i18n/pl.toml 3 ●●●●● patch | view | raw | blame | history
i18n/pt.toml 3 ●●●●● patch | view | raw | blame | history
i18n/ru.toml 3 ●●●●● patch | view | raw | blame | history
i18n/sv.toml 3 ●●●●● patch | view | raw | blame | history
i18n/tr.toml 3 ●●●●● patch | view | raw | blame | history
i18n/uk.toml 3 ●●●●● patch | view | raw | blame | history
i18n/zh-tw.toml 3 ●●●●● patch | view | raw | blame | history
i18n/zh.toml 3 ●●●●● patch | view | raw | blame | history
layouts/404.html 5 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/debug-cli.html 39 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/GetMenuCurrent.html 15 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/GetNavigationClasses.html 28 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/GetSubmenuMode.html 14 ●●●●● patch | view | raw | blame | history
layouts/_partials/func/header/IncludeChecked.html 30 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/component.html 38 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/content.html 17 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/menu-toggle-icon.html 2 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/submenu-icon.html 2 ●●●●● patch | view | raw | blame | history
layouts/_partials/header/submenu.html 40 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/description.html 23 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/languages.html 5 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/logo.html 12 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/menu.html 2 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/social.html 5 ●●●●● patch | view | raw | blame | history
layouts/_partials/hooks/header/title.html 15 ●●●●● patch | view | raw | blame | history
layouts/_partials/navigation/menu.html 68 ●●●●● patch | view | raw | blame | history
layouts/_partials/page-header.html 15 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-header.html 27 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-navigation.html 116 ●●●●● patch | view | raw | blame | history
layouts/_partials/site-scripts.html 216 ●●●●● patch | view | raw | blame | history
layouts/baseof.html 3 ●●●●● patch | view | raw | blame | history
layouts/page/single.html 5 ●●●●● patch | view | raw | blame | history
layouts/single.html 3 ●●●●● patch | view | raw | blame | history
scripts/test-hugo-quickstart.ts 100 ●●●●● patch | view | raw | blame | history
tests/catalog.yaml 26 ●●●●● patch | view | raw | blame | history
tests/coverage-gate.mjs 27 ●●●●● patch | view | raw | blame | history
tests/e2e/accessibility.spec.ts 50 ●●●●● patch | view | raw | blame | history
tests/e2e/header.spec.ts 151 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation-modes.spec.ts 441 ●●●●● patch | view | raw | blame | history
tests/e2e/navigation.spec.ts 351 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/featured.md 7 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/header-layout/_index.md 12 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/content/navigation-modes/_index.md 11 ●●●●● 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 10 ●●●●● 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/content/posts/hello.md 4 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/hugo.toml 50 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/layouts/_partials/hooks/body-end.html 14 ●●●●● patch | view | raw | blame | history
tests/fixtures/site/layouts/_partials/hooks/header/search.html 10 ●●●●● patch | view | raw | blame | history
CONTRIBUTING.md
@@ -27,7 +27,7 @@
The project follows a structured release workflow based on conventional commits, staging branches, and automated versioning.
For details, see [Branch Strategy](#branch-strategy).
For details, see [Branch Strategy](#branch-strategy). Publish a stable theme release from `main` before publishing the matching documentation. The documentation production build resolves the latest stable theme without changing its checked-in dependency files; preview builds can select an unreleased ref. Follow the [release and publication order](https://ananke-documentation.netlify.app/help/development/#release-and-publication-order), and confirm the resolved theme version in the documentation build log.
## Before you start
assets/ananke/css/_styles.css
@@ -17,3 +17,237 @@
.nested-links a {
  overflow-wrap: break-word;
}
/* ------------------------------------------------------------------ *
 * Header navigation (see layouts/_partials/site-navigation.html)
 *
 * Colours, type, and spacing come from Tachyons classes in the template;
 * sites replace them with [params.ananke.navigation.classes]. This file only
 * holds behaviour: the collapsed panel below the Tachyons `-l` breakpoint and
 * the dropdown position above it. Without JavaScript the toggle buttons stay
 * hidden and every list stays visible.
 * ------------------------------------------------------------------ */
.ananke-nav-toggle,
.ananke-submenu-toggle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.375em;
  margin: 0;
  padding: 0 0.25rem;
  min-width: 24px;
  min-height: 24px;
  font: inherit;
  vertical-align: middle;
  background: transparent;
  border: 0;
  border-radius: 0.25rem;
  cursor: pointer;
}
.ananke-nav-toggle[hidden],
.ananke-submenu-toggle[hidden],
.ananke-submenu[hidden],
.ananke-nav-link[hidden] {
  display: none;
}
.ananke-nav-toggle:focus-visible,
.ananke-submenu-toggle:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 2px;
}
.ananke-nav-slot {
  min-width: 0;
}
.ananke-submenu-icon,
.ananke-nav-toggle-icon {
  flex: none;
}
.ananke-submenu-icon,
.ananke-nav-toggle-line {
  transition:
    transform 0.2s cubic-bezier(0.16, 1, 0.3, 1),
    opacity 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.ananke-submenu-toggle[aria-expanded="true"] .ananke-submenu-icon {
  transform: rotate(180deg);
}
/* The hamburger lines turn into a cross while the menu is open. */
.ananke-nav-toggle-line {
  transform-box: fill-box;
  transform-origin: center;
}
.ananke-nav-toggle[aria-expanded="true"] .ananke-nav-toggle-line:nth-child(1) {
  transform: translateY(5px) rotate(45deg);
}
.ananke-nav-toggle[aria-expanded="true"] .ananke-nav-toggle-line:nth-child(2) {
  opacity: 0;
}
.ananke-nav-toggle[aria-expanded="true"] .ananke-nav-toggle-line:nth-child(3) {
  transform: translateY(-5px) rotate(-45deg);
}
.ananke-submenu {
  text-align: start;
}
.ananke-submenu-nested {
  padding-inline-start: 1rem;
}
.ananke-submenu a[aria-current="page"] {
  text-decoration: underline;
  text-underline-offset: 0.25em;
}
/* 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-lead {
    flex: 1 1 0%;
    min-width: 0;
  }
  .ananke-nav-toggle {
    order: 1;
    min-height: 2.75rem;
    padding: 0 0.5rem;
  }
  .ananke-nav-slot {
    order: 2;
    flex-basis: 100%;
    margin-top: 1rem;
  }
  .ananke-nav-panel {
    order: 3;
    flex-basis: 100%;
    margin-top: 0.75rem;
    padding-top: 0.5rem;
    border-top: 1px solid rgba(255, 255, 255, 0.2);
  }
  .ananke-nav-collapsed .ananke-nav-panel {
    display: none;
  }
  .ananke-nav-menu {
    margin: 0;
    padding: 0;
  }
  .ananke-nav-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 0;
  }
  .ananke-nav-item > .ananke-nav-link,
  .ananke-nav-item > .ananke-submenu-label {
    flex: 1 1 auto;
    padding: 0.5rem 0;
  }
  .ananke-nav-item > .ananke-submenu-toggle,
  .ananke-submenu-overview {
    display: none;
  }
  .ananke-nav-menu .ananke-submenu {
    flex-basis: 100%;
    margin: 0 0 0.5rem;
    padding: 0;
    padding-inline-start: 1rem;
    background-color: transparent;
    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;
  }
}
/* Large screens: one row, submenus as compact dropdowns. */
@media screen and (min-width: 60em) {
  .ananke-nav-toggle {
    display: none;
  }
  /* 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;
  }
  .ananke-has-submenu {
    position: relative;
  }
  .ananke-submenu-toggle:not([hidden]) + .ananke-submenu {
    position: absolute;
    top: calc(100% + 0.5rem);
    inset-inline-start: 0;
    z-index: 10;
    min-width: 11rem;
    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;
    inset-inline-end: 0;
  }
}
/* Without JavaScript, align an item with a nested list to the top. */
.ananke-has-submenu:has(> .ananke-submenu-toggle[hidden]) {
  vertical-align: top;
}
@media (prefers-reduced-motion: reduce) {
  .ananke-submenu-icon,
  .ananke-nav-toggle-line {
    transition: none;
  }
}
assets/ananke/css/navigation-classes.css
New file
@@ -0,0 +1,187 @@
/*
 * Header navigation: hook classes
 *
 * Every class and state that layouts/_partials/site-navigation.html renders,
 * with empty rules. Ananke does not load this file. To style the navigation,
 * copy it to `assets/ananke/css/navigation.css` in your site, fill in the rules
 * you need, delete the rest, and add it to your configuration:
 *
 *   [params.ananke]
 *   custom_css = ["navigation.css"]
 *
 * To change colours, type, or spacing with Tachyons classes instead, use
 * [params.ananke.navigation.classes].
 *
 * Breakpoint: below 60em (Tachyons `-l`) the menu collapses behind the menu
 * 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.
 */
/* <nav> element. */
.ananke-nav {
  /* */
}
/* 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 {
  /* */
}
/* Row inside <nav> that holds the groups of [ananke.header] navigation and
   the menu button. */
.ananke-nav-inner {
  /* */
}
/* Site title or logo link. */
.ananke-nav-brand {
  /* */
}
/* 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 {
  /* */
}
/* Menu button below the -l breakpoint. Only visible with JavaScript. */
.ananke-nav-toggle {
  /* */
}
.ananke-nav-toggle[aria-expanded="true"] {
  /* */
}
.ananke-nav-toggle-icon {
  /* */
}
/* The three lines of the menu icon. */
.ananke-nav-toggle-line {
  /* */
}
.ananke-nav-toggle-label {
  /* */
}
/* 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 {
  /* */
}
/* Main menu <ul>. */
.ananke-nav-menu {
  /* */
}
/* Main menu <li>. */
.ananke-nav-item {
  /* */
}
/* Main menu <li> with a submenu. */
.ananke-has-submenu {
  /* */
}
/* Main menu link. */
.ananke-nav-link {
  /* */
}
/* Link to the current page. */
.ananke-nav-link[aria-current="page"] {
  /* */
}
/* Link to a section or parent of the current page. */
.ananke-nav-link[aria-current="true"] {
  /* */
}
/* Name of a parent entry without a URL, shown when JavaScript is off. */
.ananke-submenu-label {
  /* */
}
/* Button that opens a submenu. Only visible with JavaScript. */
.ananke-submenu-toggle {
  /* */
}
.ananke-submenu-toggle[aria-expanded="true"] {
  /* */
}
/* Parent entry without a URL that contains the current page. */
.ananke-submenu-toggle[aria-current="true"] {
  /* */
}
/* Chevron inside the submenu button. */
.ananke-submenu-icon {
  /* */
}
/* Submenu <ul> (second level). */
.ananke-submenu {
  /* */
}
/* Set by the script when the dropdown aligns to the other edge to stay in
   the viewport. */
.ananke-submenu-flip {
  /* */
}
/* Submenu <li>. */
.ananke-submenu-item {
  /* */
}
/* 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 {
  /* */
}
.ananke-submenu-link[aria-current="page"] {
  /* */
}
/* Third and deeper levels: nested <ul> inside a submenu item. */
.ananke-submenu-nested {
  /* */
}
config/_default/params.toml
@@ -7,6 +7,52 @@
[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"]
[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.
[ananke.navigation.classes]
nav = "" # <nav>: "pv3 ph3 ph4-ns"
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"
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"
submenu_toggle = "" # submenu button: "hover-white white-90"
submenu = "" # submenu <ul>: "list ma0 pv2 ph0 br2 ba b--white-20" plus background_color_class
submenu_link = "" # submenu link: "db pv2 ph3 f5 white-90 hover-white hover-bg-white-10 no-underline"
[ananke.social]
icon_path = "ananke/socials/%s.svg"
i18n/bg.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} страница"
[menuToggle]
other = "Меню"
i18n/ca.toml
@@ -44,3 +44,6 @@
[wordCount]
one = "Una paraula"
other = "{{ .Count }} paraules"
[menuToggle]
other = "Menú"
i18n/cs.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} stránka"
[menuToggle]
other = "Menu"
i18n/cy.toml
@@ -67,3 +67,6 @@
[footerText]
other = "Hawlfraint © {{ .Year }} {{ .Site.Title }}. Cedwir pob hawl."
[menuToggle]
other = "Dewislen"
i18n/de.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} Seite"
[menuToggle]
other = "Menü"
i18n/en.toml
@@ -53,3 +53,12 @@
[pageTitle]
other = "{{ .Name }} page"
[submenuToggle]
other = "{{ .Name }} submenu"
[menuToggle]
other = "Menu"
[menuOverview]
other = "Overview"
i18n/es.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} pagina"
[menuToggle]
other = "Menú"
i18n/fi.toml
@@ -44,3 +44,6 @@
[pageTitle]
other = "{{ .Name }} sivu"
[menuToggle]
other = "Valikko"
i18n/fr.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} page"
[menuToggle]
other = "Menu"
i18n/he.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "עמוד {{ .Name }}"
[menuToggle]
other = "תפריט"
i18n/hi.toml
@@ -33,3 +33,6 @@
[taxonomyPageList]
other = "नीचे आपको ऐसे पेज मिलेंगे जो वर्गीकरण शब्द का उपयोग करते हैं “{{ .Title }}”"
[menuToggle]
other = "मेनू"
i18n/hu.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} oldal"
[menuToggle]
other = "Menü"
i18n/id.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} halaman"
[menuToggle]
other = "Menu"
i18n/it.toml
@@ -39,3 +39,6 @@
[pageTitle]
other = "{{ .Name }} pagina"
[menuToggle]
other = "Menu"
i18n/ja.toml
@@ -44,3 +44,6 @@
[pageTitle]
other = "{{ .Name }} ページ"
[menuToggle]
other = "メニュー"
i18n/nl.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} pagina"
[menuToggle]
other = "Menu"
i18n/no.toml
@@ -39,3 +39,6 @@
[pageTitle]
other = "{{ .Name }} side"
[menuToggle]
other = "Meny"
i18n/oc.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "pagina {{ .Name }}"
[menuToggle]
other = "Menú"
i18n/pl.toml
@@ -47,3 +47,6 @@
[pageTitle]
other = "{{ .Name }} strona"
[menuToggle]
other = "Menu"
i18n/pt.toml
@@ -39,3 +39,6 @@
[pageTitle]
other = "{{ .Name }} página"
[menuToggle]
other = "Menu"
i18n/ru.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} страница"
[menuToggle]
other = "Меню"
i18n/sv.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} sida"
[menuToggle]
other = "Meny"
i18n/tr.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} sayfa"
[menuToggle]
other = "Menü"
i18n/uk.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} сторінки"
[menuToggle]
other = "Меню"
i18n/zh-tw.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} 頁"
[menuToggle]
other = "選單"
i18n/zh.toml
@@ -36,3 +36,6 @@
[pageTitle]
other = "{{ .Name }} 页"
[menuToggle]
other = "菜单"
layouts/404.html
@@ -1,4 +1,7 @@
{{ define "header" }}{{ partials.Include "page-header.html" . }}{{ end }}
{{ define "header" }}
  {{/* @deprecated 2.21.0 remove in 3.0.0: include page-header.html directly (see #1120) */ -}}
  {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "page-header.html" "page" .) }}
{{ end }}
{{ define "main" }}
    <article class="center cf pv5 measure-wide-l">
      <h1>
layouts/_partials/func/debug-cli.html
@@ -14,6 +14,20 @@
*/}}
{{/*
Parameters:
@param message   string  The message.
@param severity  string  debug, info, warning, error, or deprecated.
@param id        string  Optional. Log id. With an id, the message is logged
                         with fmt.Warnidf or fmt.Erroridf, so a site can
                         suppress it with `ignoreLogs = ['<id>']`.
The `deprecated` severity is for deprecation notices. It is always printed,
whatever the verbosity is, in the warning colour with the label DEPR. Hugo
prints an identical message only once per build.
*/}}
{{/*
| Primary | `#AA99FF` | `170, 153, 255` |
| Ananke  | `#FF80BF` | `255, 128, 191` |
| Comment | `#708CA9` | `112, 140, 169` |
@@ -39,6 +53,8 @@
  {{- $severity = "error" -}}
{{- else if compare.Eq $severity "infos" -}}
  {{- $severity = "info" -}}
{{- else if or (compare.Eq $severity "deprecation") (compare.Eq $severity "depr") -}}
  {{- $severity = "deprecated" -}}
{{- end -}}
{{- $verbosity := $config.verbosity | compare.Default "error" -}}
@@ -54,7 +70,9 @@
{{- end -}}
{{- $shouldOutput := false -}}
{{- if compare.Eq $verbosity "debug" -}}
{{- if compare.Eq $severity "deprecated" -}}
  {{- $shouldOutput = true -}}
{{- else if compare.Eq $verbosity "debug" -}}
  {{- $shouldOutput = true -}}
{{- else if and (compare.Eq $verbosity "info") (not (compare.Eq $severity "debug")) -}}
  {{- $shouldOutput = true -}}
@@ -76,12 +94,27 @@
{{- else if compare.Eq $severity "debug" -}}
  {{- $colourLevel = $colourComment -}}
  {{- $severityLabel = "DEBG" -}}
{{- else if compare.Eq $severity "deprecated" -}}
  {{- $colourLevel = $colourWarning -}}
  {{- $severityLabel = "DEPR" -}}
{{- end -}}
{{/* Deprecation notices show the whole message in the warning colour. */}}
{{- $colourMessage := compare.Conditional (compare.Eq $severity "deprecated") $colourWarning $colourComment -}}
{{- if $shouldOutput -}}
  {{- $line := fmt.Printf "%s%s%s/%s%s %s%s%s" $colourAnanke $namespace $colourComment $colourLevel $severityLabel $colourMessage .message $colourReset -}}
  {{- if compare.Eq $severity "error" -}}
    {{- fmt.Errorf (fmt.Printf "%s%s%s/%s%s %s%s%s" $colourAnanke $namespace $colourComment $colourLevel $severityLabel $colourComment .message $colourReset) -}}
    {{- with .id -}}
      {{- fmt.Erroridf . "%s" $line -}}
  {{- else -}}
    {{- fmt.Warnf (fmt.Printf "%s%s%s/%s%s %s%s%s" $colourAnanke $namespace $colourComment $colourLevel $severityLabel $colourComment .message $colourReset) -}}
      {{- fmt.Errorf "%s" $line -}}
    {{- end -}}
  {{- else -}}
    {{- with .id -}}
      {{- fmt.Warnidf . "%s" $line -}}
    {{- else -}}
      {{- fmt.Warnf "%s" $line -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
layouts/_partials/func/header/GetMenuCurrent.html
New file
@@ -0,0 +1,15 @@
{{- /*
  Returns the aria-current value for a menu entry: "page" if it links to the
  current page, "true" if the current page is below it (Hugo's HasMenuCurrent,
  which includes pages inside the entry's section), or an empty string.
  @param page   page        The current page.
  @param entry  menu entry  The menu entry.
*/ -}}
{{- $current := "" -}}
{{- if .page.IsMenuCurrent "main" .entry -}}
  {{- $current = "page" -}}
{{- else if .page.HasMenuCurrent "main" .entry -}}
  {{- $current = "true" -}}
{{- end -}}
{{- return $current -}}
layouts/_partials/func/header/GetNavigationClasses.html
New file
@@ -0,0 +1,28 @@
{{- /*
  Returns the classes for each navigation element: the value from
  page front matter, cascade, site parameters, or the theme default.
  @return map  Element name -> class string.
*/ -}}
{{- $rtl := compare.Eq site.Language.Direction "rtl" -}}
{{- $background := site.Params.background_color_class | compare.Default "bg-black" -}}
{{- $defaults := collections.Dictionary
  "nav" "pv3 ph3 ph4-ns"
  "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"))
  "link" "hover-white white-90 no-underline"
  "submenu_toggle" "hover-white white-90"
  "submenu" (printf "list ma0 pv2 ph0 br2 ba b--white-20 %s" $background)
  "submenu_link" "db pv2 ph3 f5 white-90 hover-white hover-bg-white-10 no-underline"
-}}
{{- $classes := collections.Dictionary -}}
{{- range $key, $default := $defaults -}}
  {{- $value := $.Param (printf "ananke.navigation.classes.%s" $key) | compare.Default $default -}}
  {{- $classes = collections.Merge $classes (collections.Dictionary $key $value) -}}
{{- end -}}
{{- return $classes -}}
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/func/header/IncludeChecked.html
New file
@@ -0,0 +1,30 @@
{{- /* @deprecated 2.21.0 remove in 3.0.0: remove this check and include the header partials directly (see #1120) */ -}}
{{- /*
  Includes a header partial and prints a deprecation notice if the site
  project overrides it.
  The theme versions of site-header.html, page-header.html, and
  site-navigation.html set a marker in the page store. If the marker is
  missing after the include, a site partial replaced the theme partial.
  Overriding these partials is deprecated: sites should use the header hooks
  and `[params.ananke.header]`. The notice prints once per build, and a site
  can suppress it with `ignoreLogs = ['ananke-deprecated-<name>']`.
  @param name  string  The partial: "site-header.html", "page-header.html", or
                       "site-navigation.html".
  @param page  page    The current page.
  @return      HTML    The output of the partial.
*/ -}}
{{- $name := .name -}}
{{- $page := .page -}}
{{- $key := fmt.Printf "ananke.deprecated.theme-partial.%s" $name -}}
{{- $page.Store.Delete $key -}}
{{- $output := partials.Include $name $page -}}
{{- if not ($page.Store.Get $key) -}}
  {{- partials.Include "func/debug-cli.html" (collections.Dictionary
      "severity" "deprecated"
      "id" (fmt.Printf "ananke-deprecated-%s" (strings.TrimSuffix ".html" $name))
      "message" (fmt.Printf "Your project overrides layouts/_partials/%s. Overriding the header partials is deprecated and stops working in Ananke v3. Use the header hooks (layouts/_partials/hooks/header/) and [params.ananke.header] instead. See https://github.com/gohugo-ananke/ananke/issues/1120" $name)
  ) -}}
{{- end -}}
{{- return $output -}}
layouts/_partials/header/component.html
New file
@@ -0,0 +1,38 @@
{{- /*
  Renders one header component through the hook system.
  For a component named `<name>`, this fires three hooks in order:
    - `header/<name>-before`  (empty by default; add your own markup)
    - `header/<name>`         (the component itself; the theme ships defaults
                               for logo, languages, menu, social, title, and
                               description)
    - `header/<name>-after`   (empty by default; add your own markup)
  Each hook partial lives in `layouts/_partials/hooks/header/` and receives the
  header context dictionary:
    - `page`            the current page
    - `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)
  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
New file
@@ -0,0 +1,17 @@
{{- /*
  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.
  @param variant         string  "site" (list pages) or "page" (single pages).
  @param featured_image  string  Featured image URL, or an empty string.
*/ -}}
{{- $header := collections.Merge . (collections.Dictionary "region" "content") -}}
{{- $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/header/menu-toggle-icon.html
New file
@@ -0,0 +1,2 @@
{{- /* Icon of the menu button (three lines that turn into a cross). */ -}}
<svg class="ananke-nav-toggle-icon" aria-hidden="true" focusable="false" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"><path class="ananke-nav-toggle-line" d="M3 5h14"/><path class="ananke-nav-toggle-line" d="M3 10h14"/><path class="ananke-nav-toggle-line" d="M3 15h14"/></svg>
layouts/_partials/header/submenu-icon.html
New file
@@ -0,0 +1,2 @@
{{- /* Chevron icon of a submenu toggle button. */ -}}
<svg class="ananke-submenu-icon" aria-hidden="true" focusable="false" width="12" height="12" viewBox="0 0 12 12"><path d="M2 4.5l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
layouts/_partials/header/submenu.html
New file
@@ -0,0 +1,40 @@
{{- /*
  Renders the child entries of a main menu entry. The top level gets the
  `ananke-submenu` class and an id for its toggle button; deeper levels render
  as nested lists without their own toggle.
  @param page     page    The current page.
  @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">
    {{- if .URL }}
    <a class="ananke-submenu-link {{ $classes.submenu_link }}" href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}"{{ with $current }} aria-current="{{ . }}"{{ end }}>{{ .Name }}</a>
    {{- else }}
    <span class="ananke-submenu-link {{ $classes.submenu_link }}">{{ .Name }}</span>
    {{- end }}
    {{- with .Children }}
    {{ partials.Include "header/submenu.html" (dict "page" $page "entries" . "classes" $classes) }}
    {{- end }}
  </li>
  {{- end }}
</ul>
layouts/_partials/hooks/header/description.html
New file
@@ -0,0 +1,23 @@
{{- /*
  Header component: the `description` from the front matter of the page.
  Renders nothing if the page has no description.
  The `site` variant (list pages) renders an `h2`. The `page` variant (single
  pages) renders a `div`.
*/ -}}
{{- $context := . -}}
{{- with .page.Params.description -}}
  {{- if compare.Eq $context.variant "page" -}}
    <div class="fw1 f5 f3-l white-80 measure-wide-l center lh-copy mt3 mb4">
      {{ . }}
    </div>
  {{- else if $context.featured_image -}}
    <h2 class="fw1 f5 f3-l white-80 measure-wide-l center mt3">
      {{ . }}
    </h2>
  {{- else -}}
    <h2 class="fw1 f5 f3-l white-80 measure-wide-l center lh-copy mt3 mb4">
      {{ . }}
    </h2>
  {{- end -}}
{{- end -}}
layouts/_partials/hooks/header/languages.html
New file
@@ -0,0 +1,5 @@
{{- /*
  Header component: links to the translations of the current page.
  Renders nothing if the page has no translations.
*/ -}}
{{- partials.Include "i18nlist.html" .page -}}
layouts/_partials/hooks/header/logo.html
New file
@@ -0,0 +1,12 @@
{{- /*
  Header component: site logo or site title, linked to the home page.
  Uses `site_logo` from the site parameters if it is set.
*/ -}}
{{- $site := .page.Site -}}
<a href="{{ $site.Home.RelPermalink }}" class="ananke-nav-brand {{ .classes.brand }}">
  {{ with $site.Params.site_logo }}
    <img src="{{ urls.RelURL . }}" class="w100 mw5-ns" alt="{{ $site.Title }}" />
  {{ else }}
    {{ $site.Title }}
  {{ end }}
</a>
layouts/_partials/hooks/header/menu.html
New file
@@ -0,0 +1,2 @@
{{- /* The header uses the same renderer as explicitly included menus. */ -}}
{{- partials.Include "navigation/menu.html" . -}}
layouts/_partials/hooks/header/social.html
New file
@@ -0,0 +1,5 @@
{{- /*
  Header component: "follow" links to the social media profiles that are
  configured in `params.ananke.social.follow.networks`.
*/ -}}
{{- partials.IncludeCached "social/follow.html" .page -}}
layouts/_partials/hooks/header/title.html
New file
@@ -0,0 +1,15 @@
{{- /*
  Header component: the page title, or the site title if the page has none.
  The `site` variant (list pages) renders an `h1`. The `page` variant (single
  pages) renders a `div`, because the article itself contains the `h1`.
*/ -}}
{{- $page := .page -}}
{{- $title := $page.Title | compare.Default $page.Site.Title -}}
{{- if compare.Eq .variant "page" -}}
  <div class="f2 f1-l fw2 white-90 mb0 lh-title">{{ $title }}</div>
{{- else -}}
  <h1 class="f2 f-subheadline-l fw2 {{ compare.Conditional (compare.Ne .featured_image "") "white-90" "light-silver" }} mb0 lh-title">
    {{ $title }}
  </h1>
{{- end -}}
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/page-header.html
@@ -1,3 +1,5 @@
{{- /* @deprecated 2.21.0 remove in 3.0.0: remove this marker, it only detects site overrides of this partial (see #1120) */ -}}
{{- .Store.Set "ananke.deprecated.theme-partial.page-header.html" true -}}
{{ $featured_image := partials.Include "func/GetFeaturedImage.html" . }}
{{ if $featured_image }}
  {{/* Trimming the slash and adding absURL make sure the image works no matter where our site lives */}}
@@ -8,15 +10,11 @@
  {{ 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" . }}
      {{/* @deprecated 2.21.0 remove in 3.0.0: include site-navigation.html directly (see #1120) */ -}}
      {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "site-navigation.html" "page" .) }}
      <div class="{{ $header_section_class }}">
        {{ if not .Params.omit_header_text }}
          <div class="f2 f1-l fw2 white-90 mb0 lh-title">{{ .Title | compare.Default .Site.Title }}</div>
          {{ with .Params.description  }}
            <div class="fw1 f5 f3-l white-80 measure-wide-l center lh-copy mt3 mb4">
              {{ . }}
            </div>
          {{ end }}
          {{ partials.Include "header/content.html" (collections.Dictionary "page" . "variant" "page" "featured_image" $featured_image) }}
        {{ end }}
      </div>
    </div>
@@ -24,7 +22,8 @@
{{ else }}
  <header>
    <div class="{{ .Site.Params.background_color_class | compare.Default "bg-black" }}">
      {{ partials.Include "site-navigation.html" . }}
      {{/* @deprecated 2.21.0 remove in 3.0.0: include site-navigation.html directly (see #1120) */ -}}
      {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "site-navigation.html" "page" .) }}
    </div>
  </header>
{{ end }}
layouts/_partials/site-header.html
@@ -1,4 +1,7 @@
{{- /* @deprecated 2.21.0 remove in 3.0.0: remove this marker, it only detects site overrides of this partial (see #1120) */ -}}
{{- .Store.Set "ananke.deprecated.theme-partial.site-header.html" true -}}
{{ $featured_image := partials.Include "func/GetFeaturedImage.html" . }}
{{ $header := collections.Dictionary "page" . "variant" "site" "featured_image" $featured_image }}
{{ if $featured_image }}
  {{/* 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" }}
@@ -8,33 +11,21 @@
  <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" .}}
      {{/* @deprecated 2.21.0 remove in 3.0.0: include site-navigation.html directly (see #1120) */ -}}
      {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "site-navigation.html" "page" .) }}
      <div class="{{ $header_section_class }}">
        <h1 class="f2 f-subheadline-l fw2 white-90 mb0 lh-title">
          {{ .Title | compare.Default .Site.Title }}
        </h1>
        {{ with .Params.description }}
          <h2 class="fw1 f5 f3-l white-80 measure-wide-l center mt3">
            {{ . }}
          </h2>
        {{ end }}
        {{ partials.Include "header/content.html" $header }}
      </div>
    </div>
  </header>
{{ else }}
  <header>
    <div class="pb3-m pb6-l {{ .Site.Params.background_color_class | compare.Default "bg-black" }}">
      {{ partials.Include "site-navigation.html" . }}
      {{/* @deprecated 2.21.0 remove in 3.0.0: include site-navigation.html directly (see #1120) */ -}}
      {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "site-navigation.html" "page" .) }}
      {{ $header_section_class := .Param "header_section_class" | compare.Default "tc-l pv3 ph3 ph4-ns" }}
      <div class="{{ $header_section_class }}">
        <h1 class="f2 f-subheadline-l fw2 light-silver mb0 lh-title">
          {{ .Title | compare.Default .Site.Title }}
        </h1>
        {{ with .Params.description }}
          <h2 class="fw1 f5 f3-l white-80 measure-wide-l center lh-copy mt3 mb4">
            {{ . }}
          </h2>
        {{ end }}
        {{ partials.Include "header/content.html" $header }}
      </div>
    </div>
  </header>
layouts/_partials/site-navigation.html
@@ -1,26 +1,96 @@
<nav class="pv3 ph3 ph4-ns" role="navigation">
  <div class="flex-l center items-center justify-between">
    <a href="{{ .Site.Home.RelPermalink }}" class="f3 fw2 hover-white white-90 dib no-underline">
      {{ with .Site.Params.site_logo }}
        <img src="{{ urls.RelURL . }}" class="w100 mw5-ns" alt="{{ $.Site.Title }}" />
      {{ else }}
        {{ .Site.Title }}
      {{ end }}
    </a>
    <div class="flex-l items-center">
      {{ partials.Include "i18nlist.html" . }}
      {{ if .Site.Menus.main }}
        <ul class="{{ compare.Conditional (compare.Eq $.Site.Language.Direction "rtl") "pr0 ml3" "pl0 mr3" }}">
          {{ range .Site.Menus.main }}
          <li class="list f5 f4-ns fw4 dib {{ compare.Conditional (compare.Eq $.Site.Language.Direction "rtl") "pl3" "pr3" }}">
            <a class="hover-white white-90 no-underline" href="{{ .URL }}" title="{{ lang.Translate "pageTitle" . }}">
              {{ .Name }}
            </a>
          </li>
          {{ end }}
        </ul>
      {{ end }}
      {{ partials.IncludeCached "social/follow.html" . }}
{{- /* @deprecated 2.21.0 remove in 3.0.0: remove this marker, it only detects site overrides of this partial (see #1120) */ -}}
{{- .Store.Set "ananke.deprecated.theme-partial.site-navigation.html" true -}}
{{- /*
  Site header navigation.
  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 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.
*/ -}}
{{- $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
       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" data-submenu-mode="{{ $mode }}">
  <div class="ananke-nav-inner {{ $classes.inner }}">
    {{- 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-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>
layouts/_partials/site-scripts.html
@@ -1,13 +1,18 @@
{{- /*
  Copy-to-clipboard behaviour for code blocks rendered by
  layouts/_markup/render-codeblock.html.
  Site scripts. Each block is progressive enhancement: its buttons are hidden
  in the markup and only revealed here, so a site with JavaScript disabled
  never shows an inert button.
  Progressive enhancement: the buttons are hidden in the markup and only
  revealed here, so a site with JavaScript disabled never shows an inert
  button. A single delegated listener handles every code block on the page.
  1. Copy-to-clipboard behaviour for code blocks rendered by
     layouts/_markup/render-codeblock.html. A single delegated listener
     handles every code block on the page. Disable the copy buttons entirely
     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 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;
  disable the copy buttons entirely with `[ananke] copy_code = false`.
  Override this partial in your own project to add or replace site scripts.
*/ -}}
{{- if ne false site.Params.ananke.copy_code -}}
<script>
@@ -82,3 +87,200 @@
  })();
</script>
{{- end -}}
{{- if site.Menus.main -}}
<script>
  (function () {
    "use strict";
    // 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"));
    }
    function setSubmenu(button, expanded) {
      var submenu = controlled(button);
      if (!submenu || !desktopMedia.matches) return;
      window.clearTimeout(hoverCloseTimer);
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
      submenu.hidden = !expanded;
      submenu.classList.remove("ananke-submenu-flip");
      if (expanded) {
        // Align the dropdown to the other edge of its parent if it would
        // leave the viewport.
        var rect = submenu.getBoundingClientRect();
        if (rect.right > document.documentElement.clientWidth || rect.left < 0) {
          submenu.classList.add("ananke-submenu-flip");
        }
      }
      openButton = expanded ? button : null;
    }
    function closeSubmenu(returnFocus) {
      var button = openButton;
      if (!button) return;
      setSubmenu(button, false);
      if (returnFocus) button.focus();
    }
    function setMenu(button, expanded) {
      var nav = button.closest(".ananke-nav");
      if (!nav) return;
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
      nav.classList.toggle("ananke-nav-collapsed", !expanded);
    }
    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++) {
        if (!controlled(menuButtons[i])) continue;
        setMenu(menuButtons[i], false);
        menuButtons[i].hidden = false;
      }
      updateSubmenus();
      var buttons = document.querySelectorAll(".ananke-submenu-toggle");
      for (var j = 0; j < buttons.length; j++) {
        enhanceHover(buttons[j]);
      }
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", enhance);
    } else {
      enhance();
    }
    document.addEventListener("click", function (event) {
      var menuButton = event.target.closest(".ananke-nav-toggle");
      if (menuButton) {
        setMenu(menuButton, menuButton.getAttribute("aria-expanded") !== "true");
        return;
      }
      var button = event.target.closest(".ananke-submenu-toggle");
      if (button && desktopMedia.matches) {
        var expand = button.getAttribute("aria-expanded") !== "true";
        if (openButton && openButton !== button) closeSubmenu(false);
        setSubmenu(button, expand);
      } else if (openButton && !openButton.parentNode.contains(event.target)) {
        closeSubmenu(false);
      }
    });
    document.addEventListener("keydown", function (event) {
      if (event.key !== "Escape") return;
      if (openButton) {
        // Return focus to the button only if focus was inside the menu item.
        closeSubmenu(openButton.parentNode.contains(document.activeElement));
        return;
      }
      var menuButton = document.querySelector('.ananke-nav-toggle[aria-expanded="true"]');
      if (!menuButton) return;
      var panel = controlled(menuButton);
      var inside = panel && panel.contains(document.activeElement);
      setMenu(menuButton, false);
      if (inside) menuButton.focus();
    });
    // Close a submenu when keyboard focus leaves its menu item. Pointer users
    // 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) {
      if (!keyboardFocus || !openButton || !event.relatedTarget) return;
      var item = openButton.parentNode;
      if (item.contains(event.target) && !item.contains(event.relatedTarget)) {
        closeSubmenu(false);
      }
    });
  })();
</script>
{{- end -}}
layouts/baseof.html
@@ -74,7 +74,8 @@
  <body class="{{ delimit $body_classes " " }}">
    {{- partials.Include "hook.html" (dict "hook" "body-start" "context" .) -}}
    {{- partials.Include "hook.html" (dict "hook" "header-before" "context" .) -}}
    {{ block "header" . }}{{ partials.Include "site-header.html" .}}{{ end }}
    {{/* @deprecated 2.21.0 remove in 3.0.0: include site-header.html directly (see #1120) */ -}}
    {{ block "header" . }}{{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "site-header.html" "page" .) }}{{ end }}
    {{- partials.Include "hook.html" (dict "hook" "header-after" "context" .) -}}
    <main class="pb7" role="main">
      {{- partials.Include "hook.html" (dict "hook" "main-before" "context" .) -}}
layouts/page/single.html
@@ -1,4 +1,7 @@
{{ define "header" }}{{ partials.Include "page-header.html" . }}{{ end }}
{{ define "header" }}
  {{/* @deprecated 2.21.0 remove in 3.0.0: include page-header.html directly (see #1120) */ -}}
  {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "page-header.html" "page" .) }}
{{ end }}
{{ define "main" }}
  <div class="flex-l mt2 mw8 center">
    {{/* Calculate a unique class for this page */}}
layouts/single.html
@@ -1,6 +1,7 @@
{{ define "header" }}
   {{/* We can override any block in the baseof file be defining it in the template */}}
  {{ partials.Include "page-header.html" . }}
  {{/* @deprecated 2.21.0 remove in 3.0.0: include page-header.html directly (see #1120) */ -}}
  {{ partials.Include "func/header/IncludeChecked.html" (collections.Dictionary "name" "page-header.html" "page" .) }}
{{ end }}
{{ define "main" }}
scripts/test-hugo-quickstart.ts
@@ -1634,6 +1634,10 @@
    await assertDateSettings(projectRoot, options.themeName);
    console.log("[OK ] Independent single and summary dates (issue #1112)");
    console.log("\n[RUN] Deprecated header partial overrides (issue #1120)");
    await assertHeaderDeprecations(projectRoot, options.themeName);
    console.log("[OK ] Deprecated header partial overrides (issue #1120)");
    console.log("\nResult: PASS");
    if (options.keepOnSuccess) {
@@ -1671,6 +1675,102 @@
}
/**
 * Assert the deprecation notice for overridden header partials (issue #1120).
 *
 * Builds the project three times: without an override (no notice), with a
 * project override of `site-navigation.html` (exactly one notice, and the
 * override renders), and with that notice in `ignoreLogs` (no notice).
 *
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @param themeName Theme name used in the project configuration.
 * @throws Error when a notice is missing, repeated, or not suppressible.
 */
async function assertHeaderDeprecations(
  projectRoot: string,
  themeName: string,
): Promise<void> {
  const configPath = join(projectRoot, "hugo.toml");
  const overrideDir = join(projectRoot, "layouts", "_partials");
  const overridePath = join(overrideDir, "site-navigation.html");
  const notice = "ananke/DEPR";
  const marker = "deprecated-nav-override";
  const baseConfig = [
    "baseURL = 'https://example.com/'",
    "title = 'Ananke Test Quickstart'",
    `theme = '${themeName}'`,
  ];
  const build = async (label: string): Promise<string> => {
    await removePublicDir(projectRoot);
    const result = await runCommand("hugo", [], projectRoot);
    if (result.code !== 0) {
      throw new Error(`Build failed (${label}):\n${result.combined}`);
    }
    return result.combined;
  };
  const count = (output: string): number => output.split(notice).length - 1;
  const failures: string[] = [];
  await writeTextFile(configPath, [...baseConfig, ""].join("\n"));
  const plain = await build("no override");
  if (count(plain) !== 0) {
    failures.push("- a build without overrides printed a deprecation notice");
  }
  await mkdir(overrideDir, { recursive: true });
  await writeTextFile(overridePath, `<nav class="${marker}">custom</nav>\n`);
  try {
    const overridden = await build("site-navigation.html override");
    if (count(overridden) !== 1) {
      failures.push(
        `- expected exactly 1 deprecation notice for the override, got ${count(overridden)}`,
      );
    }
    if (
      !overridden.includes("overrides layouts/_partials/site-navigation.html")
    ) {
      failures.push("- the notice did not name site-navigation.html");
    }
    if (!overridden.includes("ananke-deprecated-site-navigation")) {
      failures.push("- the notice did not show its ignoreLogs id");
    }
    const homepage = await readTextFile(
      join(projectRoot, "public", "index.html"),
    );
    if (!homepage.includes(marker)) {
      failures.push(
        "- the project override of site-navigation.html did not render",
      );
    }
    await writeTextFile(
      configPath,
      [
        "ignoreLogs = ['ananke-deprecated-site-navigation']",
        ...baseConfig,
        "",
      ].join("\n"),
    );
    const suppressed = await build("override with ignoreLogs");
    if (count(suppressed) !== 0) {
      failures.push("- ignoreLogs did not suppress the deprecation notice");
    }
  } finally {
    await rm(overridePath, { force: true });
  }
  if (failures.length > 0) {
    throw new Error(
      [
        "Strict assertion failed: header deprecation notices did not behave as expected.",
        "Failed assertions:",
        ...failures,
      ].join("\n"),
    );
  }
}
/**
 * Main entry point.
 */
async function main(): Promise<void> {
tests/catalog.yaml
@@ -16,6 +16,32 @@
    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: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.brand:
    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: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.item:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.link:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.submenu_toggle:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.submenu:
    tests: ["tests/e2e/navigation.spec.ts"]
  ananke.navigation.classes.submenu_link:
    tests: ["tests/e2e/navigation.spec.ts"]
shortcodes:
  form-contact:
tests/coverage-gate.mjs
@@ -3,7 +3,8 @@
 * Feature -> test coverage gate.
 *
 * Fails when a user-facing feature has no test catalogued:
 *   - every direct key under the [ananke] table in config/_default/params.toml
 *   - every direct key under the tables in GATED_TABLES in
 *     config/_default/params.toml
 *   - every shortcode in layouts/_shortcodes/
 * must appear in tests/catalog.yaml with a non-empty `tests` list.
 *
@@ -11,9 +12,9 @@
 * (stale entries), so the catalog stays in sync as features are added, renamed,
 * or removed.
 *
 * Scope note: only the direct [ananke] toggles are gated here (not the deep
 * [ananke.social.networks.*] catalog). Widen `collectAnankeParams` as the gate
 * matures.
 * Scope note: only the direct keys of the tables in GATED_TABLES are gated
 * here (not the deep [ananke.social.networks.*] catalog). Widen GATED_TABLES
 * as the gate matures.
 */
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
@@ -23,23 +24,31 @@
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..");
/** Direct `key = value` entries under the top-level [ananke] table. */
/** Tables in config/_default/params.toml whose direct keys are gated. */
const GATED_TABLES = [
  "ananke",
  "ananke.navigation",
  "ananke.navigation.classes",
];
/** Direct `key = value` entries under the gated tables. */
function collectAnankeParams() {
  const toml = readFileSync(
    join(repoRoot, "config", "_default", "params.toml"),
    "utf8",
  );
  const keys = new Set();
  let inAnanke = false;
  let table = null;
  for (const raw of toml.split("\n")) {
    const line = raw.trim();
    if (line.startsWith("[")) {
      inAnanke = line === "[ananke]";
      const name = line.slice(1, -1).trim();
      table = GATED_TABLES.includes(name) ? name : null;
      continue;
    }
    if (!inAnanke || line === "" || line.startsWith("#")) continue;
    if (!table || line === "" || line.startsWith("#")) continue;
    const eq = line.indexOf("=");
    if (eq > 0) keys.add(`ananke.${line.slice(0, eq).trim()}`);
    if (eq > 0) keys.add(`${table}.${line.slice(0, eq).trim()}`);
  }
  return keys;
}
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",
@@ -45,3 +46,52 @@
    expect(results.violations).toEqual([]);
  });
}
/**
 * Header submenus (tests/e2e/navigation.spec.ts): audit the header with every
 * submenu closed and with one submenu open, on a plain header and on a header
 * with a featured image.
 */
for (const path of ["/", "/featured/"]) {
  test(`header with closed submenus on ${path} has no automatically detectable a11y violations`, async ({
    page,
  }) => {
    await page.goto(path);
    await expect(page.locator(".ananke-submenu-toggle").first()).toBeVisible();
    const results = await new AxeBuilder({ page })
      .include("header")
      .withTags(TAGS)
      .analyze();
    expect(results.violations).toEqual([]);
  });
  for (const toggle of ["Posts submenu", "Topics"]) {
    test(`header with the open "${toggle}" button on ${path} has no automatically detectable a11y violations`, async ({
      page,
    }) => {
      await page.goto(path);
      const button = page.getByRole("button", { name: toggle });
      await button.click();
      await expect(button).toHaveAttribute("aria-expanded", "true");
      const results = await new AxeBuilder({ page })
        .include("header")
        .withTags(TAGS)
        .analyze();
      expect(results.violations).toEqual([]);
    });
  }
}
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 expect(page.locator(".ananke-submenu-toggle:visible")).toHaveCount(0);
  const results = await new AxeBuilder({ page })
    .include("header")
    .withTags(TAGS)
    .analyze();
  expect(results.violations).toEqual([]);
});
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-modes.spec.ts
New file
@@ -0,0 +1,441 @@
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("resolves each navigation class through page, cascade, and site settings", async ({
  page,
}) => {
  for (const [path, marker] of [
    ["/", "fixture-site-link"],
    [CLICK, "fixture-cascade-link"],
    [HOVER, "fixture-page-link"],
  ] as const) {
    await page.goto(path);
    await expect(page.locator("header .ananke-nav-link").first()).toHaveClass(
      new RegExp(`\\b${marker}\\b`),
    );
    // A page override of one class must retain independently configured site classes.
    await expect(page.locator(".ananke-nav-toggle")).toHaveClass(
      /\bfixture-menu-button\b/,
    );
  }
});
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
New file
@@ -0,0 +1,351 @@
import { expect, type Page, test } from "@playwright/test";
/**
 * Two-level main menu (disclosure pattern) in the site header.
 *
 * Fixture menu (tests/fixtures/site/hugo.toml):
 *   Posts  - parent with its own page; children "Hello World" (front matter)
 *            and "Second Post" (config)
 *   Topics - parent without a URL; children "Categories" and "Tags", and
 *            "Alpha" one level below "Tags"
 *   About  - flat entry
 */
const nav = (page: Page) => page.getByRole("navigation");
const postsToggle = (page: Page) =>
  nav(page).getByRole("button", { name: "Posts submenu" });
const topicsToggle = (page: Page) =>
  nav(page).getByRole("button", { name: "Topics" });
const postsSubmenu = (page: Page) => page.locator("#ananke-submenu-0");
const topicsSubmenu = (page: Page) => page.locator("#ananke-submenu-1");
const menuButton = (page: Page) =>
  nav(page).getByRole("button", { name: "Menu", exact: true });
const panel = (page: Page) => page.locator("#ananke-nav-panel");
test.describe("header submenus", () => {
  test("toggle buttons are revealed and submenus start closed", async ({
    page,
  }) => {
    await page.goto("/");
    await expect(postsToggle(page)).toBeVisible();
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "false");
    await expect(postsToggle(page)).toHaveAttribute(
      "aria-controls",
      "ananke-submenu-0",
    );
    await expect(postsSubmenu(page)).toBeHidden();
    // The parent with its own page keeps its link next to the button.
    await expect(
      nav(page).getByRole("link", { name: "Posts", exact: true }),
    ).toHaveAttribute("href", "/posts/");
    // The parent without a URL is only a button; its no-JS label is hidden.
    await expect(topicsToggle(page)).toBeVisible();
    await expect(page.locator(".ananke-submenu-label")).toBeHidden();
  });
  test("opens and closes with the mouse", async ({ page }) => {
    await page.goto("/");
    await postsToggle(page).click();
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "true");
    await expect(postsSubmenu(page)).toBeVisible();
    await expect(
      postsSubmenu(page).getByRole("link", { name: "Hello World" }),
    ).toBeVisible();
    await postsToggle(page).click();
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "false");
    await expect(postsSubmenu(page)).toBeHidden();
  });
  test("keeps only one submenu open", async ({ page }) => {
    await page.goto("/");
    await postsToggle(page).click();
    await topicsToggle(page).click();
    await expect(topicsSubmenu(page)).toBeVisible();
    await expect(postsSubmenu(page)).toBeHidden();
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "false");
  });
  test("closes on a click outside", async ({ page }) => {
    await page.goto("/");
    await topicsToggle(page).click();
    await expect(topicsSubmenu(page)).toBeVisible();
    await page.locator("main").click({ position: { x: 5, y: 5 } });
    await expect(topicsSubmenu(page)).toBeHidden();
    await expect(topicsToggle(page)).toHaveAttribute("aria-expanded", "false");
  });
  test("works with the keyboard in reading order", async ({ page }) => {
    await page.goto("/");
    await nav(page).getByRole("link", { name: "Posts", exact: true }).focus();
    await page.keyboard.press("Tab");
    await expect(postsToggle(page)).toBeFocused();
    await page.keyboard.press("Enter");
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "true");
    await page.keyboard.press("Tab");
    await expect(
      postsSubmenu(page).getByRole("link", { name: "Hello World" }),
    ).toBeFocused();
    // Escape closes the submenu and returns focus to its button.
    await page.keyboard.press("Escape");
    await expect(postsSubmenu(page)).toBeHidden();
    await expect(postsToggle(page)).toBeFocused();
    // Space toggles as well.
    await page.keyboard.press("Space");
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "true");
    await page.keyboard.press("Space");
    await expect(postsToggle(page)).toHaveAttribute("aria-expanded", "false");
  });
  test("closes when focus leaves the submenu", async ({ page }) => {
    await page.goto("/");
    await postsToggle(page).focus();
    await page.keyboard.press("Enter");
    // Button -> Hello World -> Second Post -> next top-level item.
    await page.keyboard.press("Tab");
    await page.keyboard.press("Tab");
    await expect(
      postsSubmenu(page).getByRole("link", { name: "Second Post" }),
    ).toBeFocused();
    await page.keyboard.press("Tab");
    await expect(topicsToggle(page)).toBeFocused();
    await expect(postsSubmenu(page)).toBeHidden();
  });
  test("shows deeper levels as a nested list inside the submenu", async ({
    page,
  }) => {
    await page.goto("/");
    await topicsToggle(page).click();
    const alpha = topicsSubmenu(page).getByRole("link", { name: "Alpha" });
    await expect(alpha).toBeVisible();
    await expect(alpha).toHaveAttribute("href", "/tags/alpha/");
    // No toggle button below the second level.
    await expect(topicsSubmenu(page).getByRole("button")).toHaveCount(0);
  });
  test("shows a visible focus indicator on the toggle", async ({ page }) => {
    await page.goto("/");
    await postsToggle(page).focus();
    await page.keyboard.press("Shift+Tab");
    await page.keyboard.press("Tab");
    const outline = await postsToggle(page).evaluate(
      (el) => getComputedStyle(el).outlineStyle,
    );
    expect(outline).toBe("solid");
  });
});
// The submenus are closed here, so the lookups include hidden elements.
test.describe("current page markers", () => {
  test("marks the child page and its parent", async ({ page }) => {
    await page.goto("/posts/hello/");
    await expect(
      nav(page).getByRole("link", { name: "Posts", exact: true }),
    ).toHaveAttribute("aria-current", "true");
    await expect(
      postsSubmenu(page).getByRole("link", {
        name: "Hello World",
        includeHidden: true,
      }),
    ).toHaveAttribute("aria-current", "page");
    await expect(
      postsSubmenu(page).getByRole("link", {
        name: "Second Post",
        includeHidden: true,
      }),
    ).not.toHaveAttribute("aria-current", /.*/);
  });
  test("marks a parent page itself as the current page", async ({ page }) => {
    await page.goto("/posts/");
    await expect(
      nav(page).getByRole("link", { name: "Posts", exact: true }),
    ).toHaveAttribute("aria-current", "page");
  });
  test("marks a parent without a URL on its button", async ({ page }) => {
    await page.goto("/tags/alpha/");
    await expect(topicsToggle(page)).toHaveAttribute("aria-current", "true");
    await expect(
      topicsSubmenu(page).getByRole("link", {
        name: "Alpha",
        includeHidden: true,
      }),
    ).toHaveAttribute("aria-current", "page");
  });
  test("marks a flat entry", async ({ page }) => {
    await page.goto("/about/");
    await expect(
      nav(page).getByRole("link", { name: "About" }),
    ).toHaveAttribute("aria-current", "page");
  });
});
for (const width of [320, 375, 768, 1024, 1280]) {
  for (const path of ["/", "/featured/"]) {
    test(`submenus stay in the viewport and above the header at ${width}px on ${path}`, async ({
      page,
    }) => {
      await page.setViewportSize({ width, height: 800 });
      await page.goto(path);
      // Below 60em (960px) the menu is behind the menu button.
      if (width < 960) await menuButton(page).click();
      for (const [toggle, submenu] of [
        [postsToggle(page), postsSubmenu(page)],
        [topicsToggle(page), topicsSubmenu(page)],
      ] as const) {
        if (width >= 960) await toggle.click();
        await expect(submenu).toBeVisible();
        const box = await submenu.boundingBox();
        expect(box).not.toBeNull();
        if (!box) continue;
        expect(box.x).toBeGreaterThanOrEqual(0);
        expect(box.x + box.width).toBeLessThanOrEqual(width);
        // The submenu is painted above the header text below it.
        const onTop = await submenu.evaluate((el) => {
          const r = el.getBoundingClientRect();
          const hit = document.elementFromPoint(
            r.left + r.width / 2,
            r.bottom - 4,
          );
          return el.contains(hit);
        });
        expect(onTop).toBe(true);
      }
    });
  }
}
test.describe("menu button below the large breakpoint", () => {
  test.use({ viewport: { width: 375, height: 800 } });
  test("collapses the menu behind the button", async ({ page }) => {
    await page.goto("/");
    await expect(menuButton(page)).toBeVisible();
    await expect(menuButton(page)).toHaveAttribute("aria-expanded", "false");
    await expect(menuButton(page)).toHaveAttribute(
      "aria-controls",
      "ananke-nav-panel",
    );
    await expect(panel(page)).toBeHidden();
    // The brand link and the search slot stay visible.
    await expect(
      nav(page).getByRole("link", { name: "Ananke Test Fixture" }),
    ).toBeVisible();
    await expect(page.getByRole("searchbox", { name: "Search" })).toBeVisible();
  });
  test("opens and closes the menu", async ({ page }) => {
    await page.goto("/");
    await menuButton(page).click();
    await expect(menuButton(page)).toHaveAttribute("aria-expanded", "true");
    await expect(panel(page)).toBeVisible();
    await expect(nav(page).getByRole("link", { name: "About" })).toBeVisible();
    // 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();
    await menuButton(page).click();
    await expect(menuButton(page)).toHaveAttribute("aria-expanded", "false");
    await expect(panel(page)).toBeHidden();
  });
  test("closes on Escape and returns focus to the button", async ({ page }) => {
    await page.goto("/");
    await menuButton(page).focus();
    await page.keyboard.press("Enter");
    await expect(panel(page)).toBeVisible();
    await page.keyboard.press("Tab");
    await page.keyboard.press("Escape");
    await expect(panel(page)).toBeHidden();
    await expect(menuButton(page)).toBeFocused();
  });
  test("gives touch targets of at least 44px to navigation links", async ({
    page,
  }) => {
    await page.goto("/");
    await menuButton(page).click();
    for (const link of await panel(page).getByRole("link").all()) {
      const box = await link.boundingBox();
      expect(box?.height ?? 0).toBeGreaterThanOrEqual(44);
    }
  });
});
test.describe("menu button on large screens", () => {
  test("is hidden and the menu is visible", async ({ page }) => {
    await page.goto("/");
    await expect(menuButton(page)).toBeHidden();
    await expect(panel(page)).toBeVisible();
  });
});
test.describe("customisation", () => {
  test("uses classes from [params.ananke.navigation.classes]", async ({
    page,
  }) => {
    await page.goto("/");
    // The fixture replaces the classes of the menu button.
    await expect(page.locator(".ananke-nav-toggle")).toHaveClass(
      /\bfixture-menu-button\b/,
    );
    // Other elements keep their default Tachyons classes.
    await expect(page.locator(".ananke-nav-brand")).toHaveClass(/\bf3\b/);
  });
  test("renders a custom component in its own slot group", async ({ page }) => {
    await page.goto("/");
    await expect(
      page.locator(".ananke-nav-slot").getByRole("search"),
    ).toBeVisible();
  });
});
test.describe("without JavaScript (progressive enhancement)", () => {
  test.use({ javaScriptEnabled: false });
  test("shows all child links and no toggle buttons", async ({ page }) => {
    await page.goto("/");
    await expect(page.locator(".ananke-submenu-toggle")).toHaveCount(2);
    for (const toggle of await page.locator(".ananke-submenu-toggle").all()) {
      await expect(toggle).toBeHidden();
    }
    for (const name of [
      "Hello World",
      "Second Post",
      "Categories",
      "Tags",
      "Alpha",
    ]) {
      await expect(nav(page).getByRole("link", { name })).toBeVisible();
    }
    // The parent without a URL shows its name as text.
    await expect(page.locator(".ananke-submenu-label")).toHaveText("Topics");
    await expect(page.locator(".ananke-submenu-label")).toBeVisible();
  });
  test("keeps the menu and child links reachable at a narrow width", async ({
    page,
  }) => {
    await page.setViewportSize({ width: 320, height: 800 });
    await page.goto("/");
    await expect(page.locator(".ananke-nav-toggle")).toBeHidden();
    await expect(panel(page)).toBeVisible();
    const alpha = nav(page).getByRole("link", { name: "Alpha" });
    await expect(alpha).toBeVisible();
    const box = await alpha.boundingBox();
    expect(box).not.toBeNull();
    if (box) expect(box.x + box.width).toBeLessThanOrEqual(320);
  });
});
tests/fixtures/site/content/featured.md
New file
@@ -0,0 +1,7 @@
---
title: "Featured Image"
description: "A page with a featured image, for the header with a background image."
featured_image: "/images/gohugo-default-sample-hero-image.jpg"
---
A standalone page whose header uses a featured image. The navigation tests open submenus over this header.
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/content/navigation-modes/_index.md
New file
@@ -0,0 +1,11 @@
---
title: Navigation modes
cascade:
  ananke:
    navigation:
      submenu_mode: click
      classes:
        link: hover-white white-90 no-underline fixture-cascade-link
---
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,10 @@
---
title: Hover navigation
ananke:
  navigation:
    submenu_mode: hover
    classes:
      link: hover-white white-90 no-underline fixture-page-link
---
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/content/posts/hello.md
@@ -4,6 +4,10 @@
description: "A post with a fenced code block for the copy-button tests."
categories: ["News"]
tags: ["alpha", "beta"]
menus:
  main:
    parent: posts
    weight: 10
---
A post body with a fenced code block, used by the copy-button E2E tests.
tests/fixtures/site/hugo.toml
@@ -15,9 +15,59 @@
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"]]
# 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]
link = "hover-white white-90 no-underline fixture-site-link"
toggle = "f5 white-90 hover-white fixture-menu-button"
# Main menu with submenus (tests/e2e/navigation.spec.ts):
#   Posts  - parent with its own page; children from config and front matter
#   Topics - parent without a URL; Tags has a third-level child
#   About  - flat entry
[[menus.main]]
name = "Posts"
pageRef = "/posts/"
identifier = "posts"
weight = 10
[[menus.main]]
name = "Second Post"
pageRef = "/posts/second/"
parent = "posts"
weight = 20
[[menus.main]]
name = "Topics"
identifier = "topics"
weight = 15
[[menus.main]]
name = "Categories"
pageRef = "/categories/"
parent = "topics"
weight = 10
[[menus.main]]
name = "Tags"
pageRef = "/tags/"
identifier = "tags"
parent = "topics"
weight = 20
[[menus.main]]
name = "Alpha"
pageRef = "/tags/alpha/"
parent = "tags"
weight = 10
[[menus.main]]
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 }}
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>