# Navigation Menu

A site's navigation: links, and buttons that show more links, opening on a press and when the pointer rests on them. It is the WAI-ARIA disclosure pattern as its navigation example applies it, not a menu: a <nav> landmark with a list, links, and buttons with aria-expanded and aria-controls, which is what WAI-ARIA asks of site navigation. One Item is open at a time. Hovering a Trigger opens its Panel after a delay; once one is open, moving along the bar opens the next at once. The pointer can cross the gap onto the Panel, and a Panel opened by a press, or holding focus, stays open when the pointer leaves, as WCAG 1.4.13 asks. Escape closes it, and puts focus back on the Trigger if it was inside; focus moving out of the <nav>, a press outside it and a Link all close it. A Panel is in the page's flow, not the top layer: it is hidden while closed, so its links are in the server HTML, and your CSS places it under its Item with position: absolute, so an ancestor with overflow: hidden would clip it. Opening on focus, arrow keys and an animated shared area are left out.

- Entry point: `menhir/navigation-menu`
- Size: 2.6 kB, minified and gzipped, Solid left out

> To add Navigation Menu to a project, install the packages below with the project's package manager, then copy the example that matches how the project is styled, Tailwind CSS or plain CSS, and adapt its markup and class names to the project.

## Install

```sh
pnpm add menhir solid-js @solidjs/web
```

## Anatomy

```tsx
<NavigationMenu.Root>
  <ul>
    <NavigationMenu.Item>
      <NavigationMenu.Trigger />
      <NavigationMenu.Panel>
        <NavigationMenu.Link />
      </NavigationMenu.Panel>
    </NavigationMenu.Item>
    <li>
      <NavigationMenu.Link />
    </li>
  </ul>
</NavigationMenu.Root>
```

## Example

### Tailwind CSS

`NavigationMenuExample.tsx`:

```tsx
import { NavigationMenu } from "menhir/navigation-menu";
import { For } from "solid-js";

const sections = [
  {
    name: "Components",
    links: [
      {
        label: "Switch",
        href: "/docs/components/switch",
        text: "Turns a setting on or off.",
      },
      {
        label: "Dialog",
        href: "/docs/components/dialog",
        text: "A window over the page.",
      },
      {
        label: "Navigation Menu",
        href: "/docs/components/navigation-menu",
        text: "This page.",
      },
    ],
  },
  {
    name: "Docs",
    links: [
      {
        label: "Getting started",
        href: "/docs/getting-started",
        text: "Install Menhir.",
      },
      { label: "Styling", href: "/docs/styling", text: "Style a component." },
    ],
  },
];

const trigger =
  "flex cursor-pointer items-center gap-1 rounded-md px-3 py-1.5 font-medium no-underline hover:bg-stone-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-stone-500 data-open:bg-stone-100 dark:hover:bg-stone-800 dark:data-open:bg-stone-800";
// In the page's flow, placed under its Item, and fading in with
// @starting-style (starting:). Tailwind's preflight hides [hidden] with
// display: none !important, which no transition outlasts, so it closes at
// once.
const panel =
  "absolute top-[calc(100%+0.5rem)] left-0 z-10 w-64 rounded-lg border border-stone-200 bg-white p-2 shadow-lg transition-[opacity,translate] duration-150 dark:border-stone-800 dark:bg-stone-900 starting:-translate-y-1 starting:opacity-0";
const link =
  "block rounded-md p-2 text-stone-600 no-underline hover:bg-stone-100 focus-visible:outline-2 focus-visible:outline-stone-500 aria-[current=page]:bg-stone-100 dark:text-stone-400 dark:hover:bg-stone-800 dark:aria-[current=page]:bg-stone-800";

export default function NavigationMenuExample() {
  return (
    <NavigationMenu.Root aria-label="Example" class="text-sm">
      <ul class="m-0 flex list-none gap-1 p-0">
        <For each={sections}>
          {(section) => (
            <NavigationMenu.Item class="relative">
              <NavigationMenu.Trigger
                class={`${trigger} after:transition-[rotate] after:content-['▾'] data-open:after:rotate-180`}
              >
                {section.name}
              </NavigationMenu.Trigger>
              <NavigationMenu.Panel class={panel}>
                <ul class="m-0 grid list-none gap-0.5 p-0">
                  <For each={section.links}>
                    {(item) => (
                      <li class="m-0">
                        <NavigationMenu.Link
                          class={link}
                          href={item.href}
                          aria-current={
                            item.href === "/docs/components/navigation-menu"
                              ? "page"
                              : undefined
                          }
                        >
                          <span class="block font-medium text-stone-950 dark:text-white">
                            {item.label}
                          </span>
                          {item.text}
                        </NavigationMenu.Link>
                      </li>
                    )}
                  </For>
                </ul>
              </NavigationMenu.Panel>
            </NavigationMenu.Item>
          )}
        </For>
        <li class="m-0">
          <NavigationMenu.Link
            class={trigger}
            href="https://github.com/j13n/menhir"
          >
            GitHub
          </NavigationMenu.Link>
        </li>
      </ul>
    </NavigationMenu.Root>
  );
}
```

### CSS

`NavigationMenuExample.tsx`:

```tsx
import { NavigationMenu } from "menhir/navigation-menu";
import { For } from "solid-js";

import "./navigation-menu.css";

const sections = [
  {
    name: "Components",
    links: [
      {
        label: "Switch",
        href: "/docs/components/switch",
        text: "Turns a setting on or off.",
      },
      {
        label: "Dialog",
        href: "/docs/components/dialog",
        text: "A window over the page.",
      },
      {
        label: "Navigation Menu",
        href: "/docs/components/navigation-menu",
        text: "This page.",
      },
    ],
  },
  {
    name: "Docs",
    links: [
      {
        label: "Getting started",
        href: "/docs/getting-started",
        text: "Install Menhir.",
      },
      { label: "Styling", href: "/docs/styling", text: "Style a component." },
    ],
  },
];

export default function NavigationMenuExample() {
  return (
    <NavigationMenu.Root aria-label="Example" class="nav-menu">
      <ul class="nav-menu-list">
        <For each={sections}>
          {(section) => (
            <NavigationMenu.Item class="nav-menu-item">
              <NavigationMenu.Trigger class="nav-menu-trigger">
                {section.name}
              </NavigationMenu.Trigger>
              <NavigationMenu.Panel class="nav-menu-panel">
                <ul class="nav-menu-links">
                  <For each={section.links}>
                    {(link) => (
                      <li>
                        <NavigationMenu.Link
                          class="nav-menu-link"
                          href={link.href}
                          aria-current={
                            link.href === "/docs/components/navigation-menu"
                              ? "page"
                              : undefined
                          }
                        >
                          <span class="nav-menu-link-label">{link.label}</span>
                          {link.text}
                        </NavigationMenu.Link>
                      </li>
                    )}
                  </For>
                </ul>
              </NavigationMenu.Panel>
            </NavigationMenu.Item>
          )}
        </For>
        <li>
          <NavigationMenu.Link
            class="nav-menu-trigger"
            href="https://github.com/j13n/menhir"
          >
            GitHub
          </NavigationMenu.Link>
        </li>
      </ul>
    </NavigationMenu.Root>
  );
}
```

`navigation-menu.css`:

```css
/* The least CSS that makes the Navigation Menu look like one: a row of
   buttons, each Panel placed under its Item with position: absolute. The
   Panels are in the page's flow, hidden by their hidden attribute; an
   ancestor with overflow: hidden would clip them. They fade in with
   @starting-style and out with a transition on display, which
   allow-discrete keeps shown until it ends. Colours are Tailwind's stone
   palette; light-dark() picks the second one in dark mode
   (color-scheme: dark). */
.nav-menu {
  font:
    0.875rem system-ui,
    sans-serif;
}

.nav-menu-list {
  display: flex;
  gap: 0.25rem;
  margin: 0;
  padding: 0;
  list-style: none;
}

.nav-menu-item {
  position: relative;
}

/* The Triggers, and the top-level link beside them. */
.nav-menu-trigger {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.375rem 0.75rem;
  border: 0;
  border-radius: 0.375rem;
  background: transparent;
  color: inherit;
  font: inherit;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
}

.nav-menu-trigger:hover,
.nav-menu-trigger[data-open] {
  background: light-dark(
    oklch(97% 0.001 106.424) /* stone-100 */,
    oklch(26.8% 0.007 34.298) /* stone-800 */
  );
}

button.nav-menu-trigger::after {
  content: "▾";
  transition: rotate 150ms;
}

.nav-menu-trigger[data-open]::after {
  rotate: 180deg;
}

.nav-menu-panel {
  position: absolute;
  top: calc(100% + 0.5rem);
  left: 0;
  z-index: 10;
  width: 16rem;
  padding: 0.5rem;
  border: 1px solid
    light-dark(
      oklch(92.3% 0.003 48.717) /* stone-200 */,
      oklch(26.8% 0.007 34.298) /* stone-800 */
    );
  border-radius: 0.5rem;
  background: light-dark(white, oklch(21.6% 0.006 56.043) /* stone-900 */);
  box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
  transition:
    opacity 150ms,
    translate 150ms,
    display 150ms allow-discrete;
}

.nav-menu-panel[hidden] {
  opacity: 0;
  translate: 0 -0.25rem;
}

@starting-style {
  .nav-menu-panel:not([hidden]) {
    opacity: 0;
    translate: 0 -0.25rem;
  }
}

.nav-menu-links {
  display: grid;
  gap: 0.125rem;
  margin: 0;
  padding: 0;
  list-style: none;
}

.nav-menu-link {
  display: block;
  padding: 0.5rem;
  border-radius: 0.375rem;
  color: light-dark(
    oklch(44.4% 0.011 73.639) /* stone-600 */,
    oklch(70.9% 0.01 56.259) /* stone-400 */
  );
  text-decoration: none;
}

.nav-menu-link:hover,
.nav-menu-link[aria-current="page"] {
  background: light-dark(
    oklch(97% 0.001 106.424) /* stone-100 */,
    oklch(26.8% 0.007 34.298) /* stone-800 */
  );
}

.nav-menu-link-label {
  display: block;
  color: light-dark(oklch(14.7% 0.004 49.25) /* stone-950 */, white);
  font-weight: 500;
}
```

## API reference

### Root

<nav> that holds which Item is open, and the hover delays. Name it with aria-label when the page has another <nav>. Focus moving to an element outside it, or a press outside it, closes the open Item.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string \| null` | — | The open Item's value, null when none is, when controlled. Pair it with onValueChange. |
| `defaultValue` | `string \| null` | `null` | The value of the Item open at first, when uncontrolled. The server renders its Panel open. |
| `onValueChange` | `(value: string \| null, details: { reason, event }) => void` | — | Called with the new value when the user opens or closes an Item, and why: "trigger-press", "trigger-hover", "escape-key", "focus-out", "outside-press" or "link-press". A controlled menu changes only if value does. |
| `delay` | `number` | `300` | How long the pointer rests on a Trigger before its Panel opens, in milliseconds. While an Item is open, or just after one closed, the next opens at once. |
| `closeDelay` | `number` | `200` | How long after the pointer has left a Trigger and its Panel the Panel closes, in milliseconds. The pointer can cross the gap to the Panel without it. |
| `timeout` | `number` | `400` | How long after the last close hovering a Trigger still opens its Panel at once, in milliseconds. |
| `render` | `(props) => JSX.Element` | — | Renders the root with your own component. Read once. |

### Item

<li> around a Trigger and its Panel. It generates the Panel's id. Every part of it has data-open or data-closed.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | — | Identifies the Item in the Root's value. Without one, the Item uses a generated value. |
| `render` | `(props) => JSX.Element` | — | Renders the item with your own component. Read once. |

### Trigger

<button type="button"> with aria-expanded, and aria-controls naming its Panel. A press opens or closes the Panel; resting the pointer on it opens the Panel, which a press then closes. Its render function must render a <button>.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the trigger with your own button component. Read once. |

### Panel

<div> with the links, hidden while closed. It is in the page's flow: place it under its Item with position: absolute. Its id is generated, for the Trigger to name.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the panel with your own component. Read once. |

### Link

<a> that closes the open Panel when it is activated, so a router's page change leaves no menu open. Put aria-current="page" on the current page's link. Place it in a Panel, or beside the Triggers in an <li> of your own.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `href` | `string` | — | Where the link goes. |
| `render` | `(props) => JSX.Element` | — | Renders the link with your own component, such as a router's link. Read once. |

## Keyboard

| Keys | Action |
| --- | --- |
| `Tab` | Moves through the Triggers, and through the links of the open Panel. Out of the navigation, closes the open Panel. |
| `Shift + Tab` | Moves back the same way. |
| `Enter` | On a Trigger, opens or closes its Panel. On a Link, follows it and closes the Panel. |
| `Space` | On a Trigger, opens or closes its Panel. |
| `Escape` | Closes the open Panel, and puts focus on its Trigger if focus was in it. |

## Without hover

A navigation that opens on a press only, as the WAI-ARIA example does, needs no Navigation Menu: it is a Collapsible for each section, rendered as an <li>, with a signal for the open one, and two listeners on the <nav>, for Escape and for focus leaving. It costs a Collapsible and these lines, and has no hover delays, safe area or press outside.

`NavigationWithoutHover.tsx`:

```tsx
import { Collapsible } from "menhir/collapsible";
import { createSignal, For } from "solid-js";

const sections = [
  {
    name: "Components",
    links: [
      { label: "Switch", href: "/docs/components/switch" },
      { label: "Dialog", href: "/docs/components/dialog" },
    ],
  },
  {
    name: "Docs",
    links: [{ label: "Getting started", href: "/docs/getting-started" }],
  },
];

export default function NavigationWithoutHover() {
  // The open section's name, null when none is: one open at a time.
  const [open, setOpen] = createSignal<string | null>(null);
  const triggers: Record<string, HTMLElement> = {};
  let nav!: HTMLElement;
  return (
    <nav
      ref={nav}
      aria-label="Main"
      onKeyDown={(event) => {
        // Escape closes the open list and puts focus on its button.
        const name = open();
        if (event.key !== "Escape" || name === null) return;
        setOpen(null);
        triggers[name]?.focus();
      }}
      onFocusOut={(event) => {
        // Focus moving out of the navigation closes the open list.
        const to = event.relatedTarget as Node | null;
        if (to && !nav.contains(to)) setOpen(null);
      }}
    >
      <ul>
        <For each={sections}>
          {(section) => (
            <Collapsible.Root
              render={(props) => <li {...props} />}
              open={open() === section.name}
              onOpenChange={(next) => setOpen(next ? section.name : null)}
            >
              <Collapsible.Trigger
                ref={(element) => {
                  triggers[section.name] = element;
                }}
              >
                {section.name}
              </Collapsible.Trigger>
              <Collapsible.Panel render={(props) => <ul {...props} />}>
                <For each={section.links}>
                  {(link) => (
                    <li>
                      <a href={link.href}>{link.label}</a>
                    </li>
                  )}
                </For>
              </Collapsible.Panel>
            </Collapsible.Root>
          )}
        </For>
      </ul>
    </nav>
  );
}
```
