# Navigation Menu

把站点链接分组到面板里，由一排触发器打开。

站点的主要链接用 Navigation Menu：链接分组到面板里，由一排触发器打开。操作列表请用 [Menu](/docs/web-components/components/menu)。

```ts title="basic.ts"
import "@ui-sdk/web/navigation-menu"
import {
  ArrowRight,
  ChevronDown,
  Circle,
  CircleCheck,
  CircleQuestionMark,
  createElement,
} from "lucide"

const gettingStarted = [
  {
    title: "Introduction",
    href: "#",
    description: "Unstyled components with one core for every framework.",
  },
  {
    title: "Installation",
    href: "#",
    description:
      "Add the package for your framework and render your first part.",
  },
  {
    title: "Styling",
    href: "#",
    description: "Style parts with data attributes, CSS variables and any CSS.",
  },
]

const components = [
  {
    title: "Alert Dialog",
    href: "#",
    description:
      "Asks for a decision before anything else on the page can be used.",
  },
  {
    title: "Hover Card",
    href: "#",
    description:
      "A preview of what a link points to, for people who pause on it.",
  },
  {
    title: "Progress",
    href: "#",
    description: "Shows how far along a task is, like an upload.",
  },
  {
    title: "Scroll Area",
    href: "#",
    description: "Scrolls its content with scrollbars you can style.",
  },
  {
    title: "Tabs",
    href: "#",
    description:
      "Shows one panel of content at a time, picked from a list of tabs.",
  },
  {
    title: "Tooltip",
    href: "#",
    description:
      "A short label for a control, shown on hover or keyboard focus.",
  },
]

const statuses = [
  { title: "Backlog", href: "#", icon: CircleQuestionMark },
  { title: "To do", href: "#", icon: Circle },
  { title: "Done", href: "#", icon: CircleCheck },
  { title: "All issues", href: "#", icon: ArrowRight, mirror: true },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Main">
      <ui-navigation-menu-list>
        <ui-navigation-menu-item value="getting-started">
          <ui-navigation-menu-trigger>
            <button>
              Getting started
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul data-slot="grid">
              <li>
                <ui-navigation-menu-link>
                  <a href="#" data-variant="featured">
                    <span>ui-sdk</span>
                    <span data-slot="hint">Accessible components for React, Vue, Svelte, Solid and Web Components.</span>
                  </a>
                </ui-navigation-menu-link>
              </li>
              ${gettingStarted
                .map(
                  (page) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${page.href}">
                    <span>${page.title}</span>
                    <span data-slot="hint">${page.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item value="components">
          <ui-navigation-menu-trigger>
            <button>
              Components
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul data-slot="grid">
              ${components
                .map(
                  (page) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${page.href}">
                    <span>${page.title}</span>
                    <span data-slot="hint">${page.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item value="with-icon">
          <ui-navigation-menu-trigger>
            <button>
              With Icon
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${statuses
                .map(
                  (status) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${status.href}">
                    <ui-navigation-menu-link-icon${status.mirror ? " mirror" : ""}>${createElement(status.icon, { "aria-hidden": "true" }).outerHTML}</ui-navigation-menu-link-icon>
                    ${status.title}
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item>
          <ui-navigation-menu-link>
            <a href="#">Docs</a>
          </ui-navigation-menu-link>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
}

export { mount }
```

打开每个栏目，然后用 Tab 或方向键在它的链接之间移动。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件就会定义它的元素。在服务器上，这次导入什么也不做。

```ts
import "@ui-sdk/web/navigation-menu"
```

## 组合
用下面的组合构建 `ui-navigation-menu`：

```text
ui-navigation-menu
├── ui-navigation-menu-list
│   ├── ui-navigation-menu-item
│   │   ├── ui-navigation-menu-trigger
│   │   │   └── button
│   │   └── ui-navigation-menu-content
│   │       └── ui-navigation-menu-link
│   │           └── a
│   └── ui-navigation-menu-item
│       ├── ui-navigation-menu-trigger
│       │   └── button
│       └── ui-navigation-menu-content
│           └── ui-navigation-menu-link
│               └── a
└── ui-navigation-menu-viewport
```

触发器和链接包裹你自己的 `<button>` 和 `<a>`，所以它们仍然是真正的按钮和真正的链接。列表和它的条目带有 `list` 和 `listitem` 角色。

给导航一个 `aria-label`。每个条目里是一个触发器和它的面板，或者一个普通链接。这遵循[展开式导航模式](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/examples/disclosure-navigation/)：按钮显示成组的普通链接。操作请改用 [Menu](/docs/web-components/components/menu)。

视口容纳打开的面板，并跟随它的大小和位置。使用视口时，用 `--viewport-width` 和 `--viewport-height` 给它定尺寸，并裁剪它的溢出内容；[视口里的内容](https://ui-sdk.cn/docs/web-components/components/navigation-menu#contents-in-the-viewport)解释了其中的几何关系。你也可以[省掉视口](https://ui-sdk.cn/docs/web-components/components/navigation-menu#without-a-viewport)，单独给每个面板定位。

## 用法
导入部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/navigation-menu"
</script>

<ui-navigation-menu aria-label="Main">
  <ui-navigation-menu-list>
    <ui-navigation-menu-item value="guides">
      <ui-navigation-menu-trigger
        ><button>Guides</button></ui-navigation-menu-trigger
      >
      <ui-navigation-menu-content>
        <ui-navigation-menu-link
          ><a href="/docs">Introduction</a></ui-navigation-menu-link
        >
      </ui-navigation-menu-content>
    </ui-navigation-menu-item>
  </ui-navigation-menu-list>
  <ui-navigation-menu-viewport></ui-navigation-menu-viewport>
</ui-navigation-menu>
```

## 链接组件
为客户端导航渲染路由器的链接。`current` 用 `aria-current="page"` 和 `data-current` 把链接标记为当前页面。

链接包裹你自己的 `<a>`，所以路由器的点击处理仍然留在它上面。路由变化时切换 `current` 属性。

```ts title="link-component.ts"
import "@ui-sdk/web/navigation-menu"
import { ChevronDown, createElement } from "lucide"
import { log } from "./log"

const gettingStarted = [
  {
    title: "Introduction",
    href: "#introduction",
    description: "Unstyled components with one core for every framework.",
  },
  {
    title: "Installation",
    href: "#installation",
    description:
      "Add the package for your framework and render your first part.",
  },
  {
    title: "Styling",
    href: "#styling",
    description: "Style parts with data attributes, CSS variables and any CSS.",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Docs">
      <ui-navigation-menu-list>
        <ui-navigation-menu-item value="guides">
          <ui-navigation-menu-trigger>
            <button>
              Guides
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${gettingStarted
                .map(
                  (page) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${page.href}" data-router>
                    <span>${page.title}</span>
                    <span data-slot="hint">${page.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item>
          <ui-navigation-menu-link>
            <a href="#components" data-router>Components</a>
          </ui-navigation-menu-link>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
  function setRoute(route: string) {
    for (const link of root.querySelectorAll("ui-navigation-menu-link")) {
      link.toggleAttribute(
        "current",
        link.querySelector("a")!.getAttribute("href") === route
      )
    }
  }
  for (const link of root.querySelectorAll<HTMLAnchorElement>(
    "a[data-router]"
  )) {
    link.addEventListener("click", (event) => {
      event.preventDefault()
      const href = link.getAttribute("href")!
      setRoute(href)
      log(root, `Navigated to ${href}`)
    })
  }
  setRoute("#introduction")
}

export { mount }
```

选择一个链接，在不重新加载示例的情况下更新当前页面。

路由器在链接的点击上调用 `preventDefault()`，以便不加载页面就完成导航。导航菜单在链接元素本身上监听，所以客户端路由变化之后它仍会关闭。带修饰键的按压，或鼠标中键按压，会在别处打开链接，并让菜单保持打开。把 `closeOnSelect` 设为 false 可以让它在每次按压后都保持打开，见[选中后关闭](https://ui-sdk.cn/docs/web-components/components/navigation-menu#close-on-select)。

## 链接与面板
顶层条目可以既链接到它所在栏目的页面，又打开一个面板。把链接和一个小触发器并排放进条目里。链接指向页面，触发器则在悬停、键盘操作和触摸时打开面板。Tab 和方向键都能到达两者。给触发器一个自己的名称，因为它可能只显示一个箭头。

```html
<ui-navigation-menu-item value="products">
  <ui-navigation-menu-link
    ><a href="/products">Products</a></ui-navigation-menu-link
  >
  <ui-navigation-menu-trigger>
    <button aria-label="More in Products">▾</button>
  </ui-navigation-menu-trigger>
  <ui-navigation-menu-content>
    <ui-navigation-menu-link>
      <a href="/products/analytics">Analytics</a>
    </ui-navigation-menu-link>
  </ui-navigation-menu-content>
</ui-navigation-menu-item>
```

## 图标
把链接的图标放进 `ui-navigation-menu-link-icon`，放在文字前面，就像页面顶部菜单里的 With Icon 面板那样。屏幕阅读器会跳过它，所以 SVG 的 `<title>`、图标字体的字形或 emoji 永远不会进入链接的名称。

- **指向某个方向的图标**，比如 All issues 上的箭头，在从右到左的文本里用 `mirror` 翻转。
- **只有图标的链接** 需要 `aria-label`。开发模式下，没有名称的链接会给出警告。
- **对齐链接。** 带图标的链接会得到 `data-has-icon`；只要有一个链接带图标，它们周围的内容或列表就会得到 `data-has-icons`，这样没有图标的链接就可以让出它的位置：`[data-has-icons] [data-slot="navigation-menu-link"]:not([data-has-icon])`。

## 垂直
`orientation="vertical"` 用于侧边栏：上、下方向键在条目之间移动，面板在菜单旁边、行内末端打开，除非 `side` 另有指定。

```ts title="vertical.ts"
import "@ui-sdk/web/navigation-menu"
import { ChevronRight, createElement } from "lucide"

const sections = [
  {
    value: "guides",
    label: "Guides",
    links: [
      {
        title: "Introduction",
        href: "#",
        description: "Unstyled components with one core for every framework.",
      },
      {
        title: "Installation",
        href: "#",
        description:
          "Add the package for your framework and render your first part.",
      },
      {
        title: "Styling",
        href: "#",
        description:
          "Style parts with data attributes, CSS variables and any CSS.",
      },
    ],
  },
  {
    value: "components",
    label: "Components",
    links: [
      {
        title: "Alert Dialog",
        href: "#",
        description:
          "Asks for a decision before anything else on the page can be used.",
      },
      {
        title: "Hover Card",
        href: "#",
        description:
          "A preview of what a link points to, for people who pause on it.",
      },
      {
        title: "Progress",
        href: "#",
        description: "Shows how far along a task is, like an upload.",
      },
      {
        title: "Scroll Area",
        href: "#",
        description: "Scrolls its content with scrollbars you can style.",
      },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Sidebar" orientation="vertical">
      <ui-navigation-menu-list>
        ${sections
          .map(
            (section) => `
        <ui-navigation-menu-item value="${section.value}">
          <ui-navigation-menu-trigger>
            <button>
              ${section.label}
              ${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${section.links
                .map(
                  (link) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${link.href}">
                    <span>${link.title}</span>
                    <span data-slot="hint">${link.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>`
          )
          .join("")}
        <ui-navigation-menu-item>
          <ui-navigation-menu-link><a href="#">Docs</a></ui-navigation-menu-link>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
}

export { mount }
```

用上、下方向键在侧边栏条目之间移动，然后打开触发器旁边的面板。

## 仅点击
指针停在触发器上会打开它的面板。把 `openOnHover` 设为 false 后，导航菜单只在点击时打开：按压触发器会打开和关闭它的面板，移动指针没有任何作用。无论哪种设置，键盘和触摸的操作都一样。

```ts title="click-only.ts"
import "@ui-sdk/web/navigation-menu"
import { ChevronDown, createElement } from "lucide"

const sections = [
  {
    value: "guides",
    label: "Guides",
    links: [
      {
        title: "Introduction",
        href: "#",
        description: "Unstyled components with one core for every framework.",
      },
      {
        title: "Installation",
        href: "#",
        description:
          "Add the package for your framework and render your first part.",
      },
      {
        title: "Styling",
        href: "#",
        description:
          "Style parts with data attributes, CSS variables and any CSS.",
      },
    ],
  },
  {
    value: "components",
    label: "Components",
    links: [
      {
        title: "Alert Dialog",
        href: "#",
        description:
          "Asks for a decision before anything else on the page can be used.",
      },
      {
        title: "Hover Card",
        href: "#",
        description:
          "A preview of what a link points to, for people who pause on it.",
      },
      {
        title: "Progress",
        href: "#",
        description: "Shows how far along a task is, like an upload.",
      },
      {
        title: "Scroll Area",
        href: "#",
        description: "Scrolls its content with scrollbars you can style.",
      },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Main" open-on-hover="false">
      <ui-navigation-menu-list>
        ${sections
          .map(
            (section) => `
        <ui-navigation-menu-item value="${section.value}">
          <ui-navigation-menu-trigger>
            <button>
              ${section.label}
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${section.links
                .map(
                  (link) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${link.href}">
                    <span>${link.title}</span>
                    <span data-slot="hint">${link.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>`
          )
          .join("")}
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
}

export { mount }
```

点击触发器把它打开。在触发器之间移动指针不会打开另一个面板。

## 嵌套
另一个菜单内容里的导航菜单就是子菜单。它渲染一个普通元素，而不是第二个 `<nav>` 地标；它会得到 `data-nested`，并在父级转向另一个条目时随父级一起关闭。它没有自己的视口，面板就在触发器旁边打开。按压其中的链接会关闭所有菜单。

```ts title="nested.ts"
import "@ui-sdk/web/navigation-menu"
import { ChevronDown, ChevronRight, createElement } from "lucide"

const gettingStarted = [
  {
    title: "Introduction",
    href: "#",
    description: "Unstyled components with one core for every framework.",
  },
  {
    title: "Installation",
    href: "#",
    description:
      "Add the package for your framework and render your first part.",
  },
  {
    title: "Styling",
    href: "#",
    description: "Style parts with data attributes, CSS variables and any CSS.",
  },
]

const groups = [
  {
    value: "overlays",
    label: "Overlays",
    links: [
      { title: "Dialog", href: "#" },
      { title: "Popover", href: "#" },
      { title: "Tooltip", href: "#" },
    ],
  },
  {
    value: "forms",
    label: "Forms",
    links: [
      { title: "Input", href: "#" },
      { title: "Select", href: "#" },
      { title: "Checkbox", href: "#" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Main">
      <ui-navigation-menu-list>
        <ui-navigation-menu-item value="guides">
          <ui-navigation-menu-trigger>
            <button>
              Guides
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${gettingStarted
                .map(
                  (link) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${link.href}">
                    <span>${link.title}</span>
                    <span data-slot="hint">${link.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item value="components">
          <ui-navigation-menu-trigger>
            <button>
              Components
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ui-navigation-menu orientation="vertical">
              <ui-navigation-menu-list>
                ${groups
                  .map(
                    (group) => `
                <ui-navigation-menu-item value="${group.value}">
                  <ui-navigation-menu-trigger>
                    <button>
                      ${group.label}
                      ${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
                    </button>
                  </ui-navigation-menu-trigger>
                  <ui-navigation-menu-content side-offset="9" align-offset="-5">
                    <ul>
                      ${group.links
                        .map(
                          (link) => `
                      <li>
                        <ui-navigation-menu-link>
                          <a href="${link.href}">${link.title}</a>
                        </ui-navigation-menu-link>
                      </li>`
                        )
                        .join("")}
                    </ul>
                  </ui-navigation-menu-content>
                </ui-navigation-menu-item>`
                  )
                  .join("")}
              </ui-navigation-menu-list>
            </ui-navigation-menu>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
}

export { mount }
```

打开 Components，再打开 Overlays 或 Forms。Escape 会先关闭内层面板。

## 动画
视口和内容会在第一帧得到 `data-starting-style`，在退场动画期间得到 `data-ending-style`，并保持挂载直到动画结束。另一个条目接管时，内容还会得到 `data-motion`：进来的那个得到 `from-end` 或 `from-start`，让位的那个得到 `to-start` 或 `to-end`。顺序按逻辑方向，所以在从右到左的布局里，末端在左边。视口跟随打开的条目时，可以对 `width`、`height`、`left` 和 `top` 做过渡。

`openchangecomplete` 在导航菜单完成打开或关闭后触发，在任何动画之后，新的打开状态在 `event.detail.value` 里。在条目之间切换不算。

```ts title="animation.ts"
import "@ui-sdk/web/navigation-menu"
import type { UiNavigationMenuElement } from "@ui-sdk/web"
import { ChevronDown, createElement } from "lucide"
import { log } from "./log"

const gettingStarted = [
  {
    title: "Introduction",
    href: "#",
    description: "Unstyled components with one core for every framework.",
  },
  {
    title: "Installation",
    href: "#",
    description:
      "Add the package for your framework and render your first part.",
  },
  {
    title: "Styling",
    href: "#",
    description: "Style parts with data attributes, CSS variables and any CSS.",
  },
]

const components = [
  {
    title: "Alert Dialog",
    href: "#",
    description:
      "Asks for a decision before anything else on the page can be used.",
  },
  {
    title: "Hover Card",
    href: "#",
    description:
      "A preview of what a link points to, for people who pause on it.",
  },
  {
    title: "Progress",
    href: "#",
    description: "Shows how far along a task is, like an upload.",
  },
  {
    title: "Scroll Area",
    href: "#",
    description: "Scrolls its content with scrollbars you can style.",
  },
  {
    title: "Tabs",
    href: "#",
    description:
      "Shows one panel of content at a time, picked from a list of tabs.",
  },
  {
    title: "Tooltip",
    href: "#",
    description:
      "A short label for a control, shown on hover or keyboard focus.",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Main">
      <ui-navigation-menu-list>
        <ui-navigation-menu-item value="guides">
          <ui-navigation-menu-trigger>
            <button>
              Guides
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul>
              ${gettingStarted
                .map(
                  (page) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${page.href}">
                    <span>${page.title}</span>
                    <span data-slot="hint">${page.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
        <ui-navigation-menu-item value="components">
          <ui-navigation-menu-trigger>
            <button>
              Components
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>
            <ul data-slot="grid">
              ${components
                .map(
                  (page) => `
              <li>
                <ui-navigation-menu-link>
                  <a href="${page.href}">
                    <span>${page.title}</span>
                    <span data-slot="hint">${page.description}</span>
                  </a>
                </ui-navigation-menu-link>
              </li>`
                )
                .join("")}
            </ul>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8" data-variant="slide"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
  const menu =
    root.querySelector<UiNavigationMenuElement>("ui-navigation-menu")!
  menu.addEventListener("valuechange", (event) => {
    log(root, event.detail.value ? `Showing ${event.detail.value}` : "Closing")
  })
  menu.addEventListener("openchangecomplete", (event) => {
    log(root, event.detail.value ? "Finished opening" : "Finished closing")
  })
}

export { mount }
```

在 Guides 和 Components 之间切换，看看视口如何改变大小、面板如何滑动。

导航菜单会等待实际运行的动画，也只等待这些。对要求减少动效的用户，用 `prefers-reduced-motion` 媒体查询把它们关掉，面板就会立即切换和关闭。

## 延迟
`delay` 是指针在触发器上停多久之后它的面板才打开，`closeDelay` 是指针离开触发器和面板之后面板还留多久：默认各 50 毫秒。指针可以跨过触发器和它的面板之间的空隙而不关闭面板。面板打开后，移到另一个触发器会立刻切换，除非指针只是在进入已打开面板的途中经过它。关闭后马上回来会跳过延迟。

```html
<ui-navigation-menu aria-label="Main" delay="400" close-delay="600">
  ...
</ui-navigation-menu>
```

## 指示器
`ui-navigation-menu-indicator` 位于打开的触发器下方；所有面板都关闭时，则位于带 `current` 的顶层链接下方。它的盒子来自 `--active-item-*` [变量](https://ui-sdk.cn/docs/web-components/components/navigation-menu#styling-navigationmenuindicator)，相对于它的定位祖先，并在有东西可以覆盖时得到 `data-visible`。屏幕阅读器会跳过它。

```html
<ui-navigation-menu aria-label="Main">
  <ui-navigation-menu-list>...</ui-navigation-menu-list>
  <ui-navigation-menu-indicator></ui-navigation-menu-indicator>
  <ui-navigation-menu-viewport></ui-navigation-menu-viewport>
</ui-navigation-menu>
```

```css
[data-slot="navigation-menu"] {
  position: relative;
}

[data-slot="navigation-menu-indicator"] {
  position: absolute;
  left: var(--active-item-left);
  bottom: var(--active-item-bottom);
  width: var(--active-item-width);
  height: 2px;
  opacity: 0;
}

[data-slot="navigation-menu-indicator"][data-visible] {
  opacity: 1;
}
```

给它 `follow-hover`，它就会跟随指针下的顶层触发器或链接；指针离开列表后，再回到打开的触发器或当前链接。

## 视口的放置位置
视口位于打开的触发器下方，与它的起始边对齐；在垂直菜单里则位于它旁边。`side` 和 `align` 可以改变这一点，`sideOffset` 是间距（默认 4 像素），`alignOffset` 沿触发器平移，`collisionPadding` 是与窗口边缘保持的距离。它会翻转和平移，以留在屏幕内。

`anchor` 让它相对于别的东西定位：一个元素、一个 CSS 选择器、像 `{ x, y }` 这样的点，或者任何有 `getBoundingClientRect()` 的东西。锚定到整条导航栏上，就得到一个在内容变化时保持原位的下拉浮层。

```html
<ui-navigation-menu-viewport
  side="bottom"
  align="center"
  side-offset="8"
  collision-padding="16"
  anchor="#site-header"
></ui-navigation-menu-viewport>
```

## 不使用视口
省掉视口后，每个内容都是自己的浮层，相对于它的触发器放置。此时内容接受与视口相同的放置 props：`side`、`align`、`sideOffset`、`alignOffset`、`collisionPadding` 和 `anchor`。把每个内容当作浮层来设置样式，而不是把它定位在某个浮层内部。

```html
<ui-navigation-menu aria-label="Main">
  <ui-navigation-menu-list>
    <ui-navigation-menu-item value="guides">
      <ui-navigation-menu-trigger
        ><button>Guides</button></ui-navigation-menu-trigger
      >
      <ui-navigation-menu-content side="bottom" align="start" side-offset="8">
        ...
      </ui-navigation-menu-content>
    </ui-navigation-menu-item>
  </ui-navigation-menu-list>
</ui-navigation-menu>
```

## 受控
元素的 `value` property 是实时的：读取它；把它设成某个条目的 `value` 来打开那个条目，或设成 `null` 来关闭所有面板。`value` 属性设置它的起始值。监听 `valuechange` 来跟随变化。

每个条目都接受 `value`，省略时会自动生成。每次变更都会在 `event.detail.reason` 中带一个[原因](https://ui-sdk.cn/docs/web-components/components/navigation-menu#reasons)，比如 `trigger-hover`、`trigger-press`、`link-press` 或 `outside-press`。调用 `event.preventDefault()` 可以阻止它。

```html
<ui-navigation-menu aria-label="Main"> ... </ui-navigation-menu>

<script type="module">
  const menu = document.querySelector("ui-navigation-menu")
  menu.addEventListener("valuechange", (event) => (value = event.detail.value))
  menu.value = "components"
</script>
```

## 从任意位置打开
元素的 `api` property 就是它的[控制器](https://ui-sdk.cn/docs/web-components/components/navigation-menu#controller)：它可以从任意位置打开、关闭和聚焦菜单，而不控制菜单。

```html
<button type="button">Browse Components</button>
<ui-navigation-menu aria-label="Main"> ... </ui-navigation-menu>

<script type="module">
  const { api: menu } = document.querySelector("ui-navigation-menu")
  document
    .querySelector("button")
    .addEventListener("click", () => menu.setValue("components"))
</script>
```

## 保持挂载
关闭的内容默认会离开页面。`keepMounted` 把它们隐藏着留在页面里，这样服务器返回的 HTML 和爬虫都能拿到每个链接。`hiddenUntilFound` 还让在页面中查找也能找到它们：关闭的内容会得到 `hidden="until-found"`，匹配时会以 `find-in-page` 原因打开它所在的条目。它隐含 `keepMounted`。

关闭的内容留在它的条目里，带着自己的类名，打开时移进视口。把内边距放在它内部的元素上，而不是放在内容上，这样隐藏的盒子在它所在的位置就没有尺寸。

```html
<ui-navigation-menu-content hidden-until-found>...</ui-navigation-menu-content>
```

## 选中后关闭
按压链接默认会关闭菜单，就像路由变化之后那样。把菜单上的 `closeOnSelect` 设为 false，它会保持打开；链接自己的 `closeOnSelect` 优先于菜单的。

```html
<ui-navigation-menu aria-label="Main" close-on-select="false">
  ...
  <ui-navigation-menu-link close-on-select>
    <a href="/docs/components">Browse All</a>
  </ui-navigation-menu-link>
</ui-navigation-menu>
```

## 容器
面板就地渲染，并显示在顶层，所以没有祖先会裁剪或遮住它们。`container` 把视口，或没有视口时的每个内容，渲染到别处，用 CSS 选择器指定，用于 iframe、影子根（shadow root）或特定的层叠上下文。可以在菜单上设置，也可以在视口或某个内容上设置。

```html
<ui-navigation-menu aria-label="Main" container="#menu-host">
  ...
</ui-navigation-menu>
```

## 自定义渲染
```ts title="custom-rendering.ts"
import "@ui-sdk/web/navigation-menu"
import { Minus, Plus, createElement } from "lucide"

const sections = [
  {
    value: "guides",
    label: "Guides",
    links: [
      {
        title: "Introduction",
        href: "#",
        description: "Unstyled components with one core for every framework.",
      },
      {
        title: "Installation",
        href: "#",
        description:
          "Add the package for your framework and render your first part.",
      },
      {
        title: "Styling",
        href: "#",
        description:
          "Style parts with data attributes, CSS variables and any CSS.",
      },
    ],
  },
  {
    value: "components",
    label: "Components",
    links: [
      {
        title: "Alert Dialog",
        href: "#",
        description:
          "Asks for a decision before anything else on the page can be used.",
      },
      {
        title: "Hover Card",
        href: "#",
        description:
          "A preview of what a link points to, for people who pause on it.",
      },
      {
        title: "Progress",
        href: "#",
        description: "Shows how far along a task is, like an upload.",
      },
      {
        title: "Scroll Area",
        href: "#",
        description: "Scrolls its content with scrollbars you can style.",
      },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-navigation-menu aria-label="Main">
      <ui-navigation-menu-list>
        ${sections
          .map(
            (section) => `
        <ui-navigation-menu-item value="${section.value}">
          <ui-navigation-menu-trigger>
            <button>
              ${section.label}
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content as-child>
            <section aria-label="${section.label}">
              <p data-slot="hint">
                <span data-hide="motion">Opened</span>
                <span data-show="from-end">Moved in from-end</span>
                <span data-show="from-start">Moved in from-start</span>
              </p>
              <ul>
                ${section.links
                  .map(
                    (link, index) => `
                <li>
                  <ui-navigation-menu-link${index === 0 ? " current" : ""}>
                    <a href="${link.href}">
                      <span>${link.title}</span>
                      <span data-slot="hint" data-show="current">You're here</span>
                    </a>
                  </ui-navigation-menu-link>
                </li>`
                  )
                  .join("")}
              </ul>
            </section>
          </ui-navigation-menu-content>
        </ui-navigation-menu-item>`
          )
          .join("")}
        <ui-navigation-menu-item value="pricing">
          <ui-navigation-menu-trigger disabled>
            <button>
              Pricing
              <span data-slot="badge" data-show="disabled">Soon</span>
            </button>
          </ui-navigation-menu-trigger>
          <ui-navigation-menu-content>Plans for teams.</ui-navigation-menu-content>
        </ui-navigation-menu-item>
      </ui-navigation-menu-list>
      <ui-navigation-menu-viewport side-offset="8"></ui-navigation-menu-viewport>
    </ui-navigation-menu>
  `
}

export { mount }
```

打开 Guides 查看它的渲染状态，然后比较当前链接和禁用的触发器。

元素没有渲染函数。触发器和链接包裹你自己的元素，`as-child` 把内容渲染成它的第一个子元素，比如一个 `<section>`。状态以数据属性的形式显示在每个元素上，所以它的子元素可以据此显示和隐藏。这里内容显示它的 `data-motion`，禁用的触发器显示一个徽标。

触发器上的 `disabled` 阻止它打开面板。每个部件的状态列在[状态](https://ui-sdk.cn/docs/web-components/components/navigation-menu#state)下。

## 样式
部件没有样式。通过它们渲染出的属性来设置样式，这些属性在每个框架里都一样。每个部件都有一个 `data-slot`，比如 `navigation-menu-trigger`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/navigation-menu#data-attributes)下。

### 视口里的内容
视口是一个浮层，容纳当前打开的那个内容。要让它取用该内容的大小：

- 把内容放在视口的角落，并给它们自己的宽度：`position: absolute; top: 0; inset-inline-start: 0`，宽度比如 `400px` 或 `max-content`。宽度不同的内容会让视口在切换时改变大小。
- 把内边距放在内容上，而不是视口上。`--viewport-width` 和 `--viewport-height` 是打开内容的大小加上视口自己的边框。
- 用这些变量给视口定尺寸并裁剪它，让滑进滑出的内容留在里面。
- 把 `--available-height` 复制到一个可继承的变量，比如 `--panel-height`，再用它限制内容的高度，让长面板可以滚动。定位变量本身不继承。

用纯 CSS 写就是：

```css
[data-slot="navigation-menu-viewport"] {
  --panel-height: var(--available-height);
  width: var(--viewport-width);
  height: var(--viewport-height);
  overflow: hidden;
  transition:
    width 200ms,
    height 200ms,
    left 200ms,
    top 200ms,
    opacity 200ms;
}

[data-slot="navigation-menu-viewport"] > [data-slot="navigation-menu-content"] {
  position: absolute;
  top: 0;
  inset-inline-start: 0;
  max-height: var(--available-height, var(--panel-height));
  overflow-y: auto;
}

[data-slot="navigation-menu-content"][data-motion="from-end"][data-starting-style],
[data-slot="navigation-menu-content"][data-motion="to-end"][data-ending-style] {
  translate: 48px 0;
}

[data-slot="navigation-menu-content"][data-motion="from-start"][data-starting-style],
[data-slot="navigation-menu-content"][data-motion="to-start"][data-ending-style] {
  translate: -48px 0;
}

[data-slot="navigation-menu-content"]:dir(
    rtl
  )[data-motion="from-end"][data-starting-style],
[data-slot="navigation-menu-content"]:dir(
    rtl
  )[data-motion="to-end"][data-ending-style] {
  translate: -48px 0;
}

[data-slot="navigation-menu-content"]:dir(
    rtl
  )[data-motion="from-start"][data-starting-style],
[data-slot="navigation-menu-content"]:dir(
    rtl
  )[data-motion="to-start"][data-ending-style] {
  translate: 48px 0;
}

@media (prefers-reduced-motion: reduce) {
  [data-slot="navigation-menu-viewport"],
  [data-slot="navigation-menu-content"] {
    transition: none;
  }
}
```

### `<ui-navigation-menu-content>`
- `--anchor-width`: Without a viewport: width of the anchor, usually the trigger. Use it to match widths.
- `--anchor-height`: Without a viewport: height of the anchor.
- `--available-width`: Without a viewport: space beside the popup, up to the viewport edge. Not inherited either.
- `--available-height`: Without a viewport: space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like `[--list-height:var(--available-height)]`, and reads `max-h-(--list-height)`. The first popup registers both names for the whole page with `CSS.registerProperty`, so they don't inherit anywhere. A page that needs them to inherit calls it first, with `inherits: true`. An `@property` rule can't, since a registration in script wins.
- `--transform-origin`: Without a viewport: the point on the anchor the popup opens from. Use it to scale from the right place.
- `--arrow-offset`: Without a viewport: where the anchor's center falls along the popup's edge, kept `arrowPadding` from the corners. Position a ::before arrow with it.

### `<ui-navigation-menu-viewport>`
- `--anchor-width`: Width of the anchor, usually the trigger. Use it to match widths.
- `--anchor-height`: Height of the anchor.
- `--available-width`: Space beside the popup, up to the viewport edge. Not inherited either.
- `--available-height`: Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like `[--list-height:var(--available-height)]`, and reads `max-h-(--list-height)`. The first popup registers both names for the whole page with `CSS.registerProperty`, so they don't inherit anywhere. A page that needs them to inherit calls it first, with `inherits: true`. An `@property` rule can't, since a registration in script wins.
- `--transform-origin`: The point on the anchor the popup opens from. Use it to scale from the right place.
- `--arrow-offset`: Where the anchor's center falls along the popup's edge, kept `arrowPadding` from the corners. Position a ::before arrow with it.
- `--viewport-width`: The open content's width plus the viewport's own border. Transition width for a viewport that resizes as it switches.
- `--viewport-height`: The open content's height plus the viewport's own border.

### `<ui-navigation-menu-indicator>`
- `--active-item-left`: Distance from its positioned ancestor's left edge to the open trigger, or the current page's link.
- `--active-item-right`: Distance from its positioned ancestor's right edge to the item.
- `--active-item-top`: Distance from its positioned ancestor's top edge to the item.
- `--active-item-bottom`: Distance from its positioned ancestor's bottom edge to the item.
- `--active-item-width`: Width of the item it sits under.
- `--active-item-height`: Height of the item it sits under.

## 数据属性
### `<ui-navigation-menu>`
`[data-slot="navigation-menu"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between the items, and where panels open.
- `data-nested`: Present on a menu inside another menu's content.

### `<ui-navigation-menu-list>`
`[data-slot="navigation-menu-list"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between the items, and where panels open.
- `data-has-icons`: Present while any link inside holds an icon part, so items without one can line up.

### `<ui-navigation-menu-item>`
`[data-slot="navigation-menu-item"]`

- `data-closed`: Present while the item's panel is closed, including while it animates out.
- `data-open`: Present while the item's panel is open.

### `<ui-navigation-menu-trigger>`
`[data-slot="navigation-menu-trigger"]`

- `data-closed`: Present while the item's panel is closed, including while it animates out.
- `data-disabled`: Present when the trigger is disabled.
- `data-open`: Present while the item's panel is open.

### `<ui-navigation-menu-content>`
`[data-slot="navigation-menu-content"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between the items, and where panels open.
- `data-closed`: Present while the item's panel is closed, including while it animates out.
- `data-open`: Present while the item's panel is open.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while it animates out. Style the state you animate to.
- `data-motion` (`from-start`, `from-end`, `to-start`, `to-end`): Which way the content moves while another item takes over. Order is logical, so in right-to-left layouts the end is on the left.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the viewport, or a content without one, ended up after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How it lines up with the trigger.

### `<ui-navigation-menu-link>`
`[data-slot="navigation-menu-link"]`

- `data-has-icon`: Present on a link while it holds an icon part.

### `<ui-navigation-menu-link-icon>`
`[data-slot="navigation-menu-link-icon"]`

- `data-mirror`: Present on an icon that flips in right-to-left text, with `mirror`.

### `<ui-navigation-menu-viewport>`
`[data-slot="navigation-menu-viewport"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between the items, and where panels open.
- `data-closed`: Present while every panel is closed, including while it animates out.
- `data-open`: Present while a panel is open.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while it animates out. Style the state you animate to.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the viewport, or a content without one, ended up after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How it lines up with the trigger.

### `<ui-navigation-menu-indicator>`
`[data-slot="navigation-menu-indicator"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between the items, and where panels open.
- `data-closed`: Present while every panel is closed.
- `data-open`: Present while a panel is open, so it sits under a trigger.
- `data-visible`: Present while there's a trigger or a current page's link to sit under.

## API 参考
props 是短横线命名（kebab case）的属性，比如 `close-delay` 和 `side-offset`：`"false"` 表示 false，数字就是数字。`anchor` 和 `container` 接受 CSS 选择器。回调是 DOM 事件。

### NavigationMenu
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `value?` (`T | null`): The open item's value. Pass it to control the menu. `null` closes every panel.
- `defaultValue?` (`T | null`): The item open at first, when uncontrolled.
- `valuechange event`: Runs when an item wants to open or the open one to close. `details.reason` says why, and `details.cancel()` stops it.
- `openchangecomplete event`: Runs once the menu has finished opening or closing, after any animation. Switching items doesn't count.
- `delay?` (`number`): Milliseconds the pointer rests on a trigger before its panel opens. Moving to another trigger while one is open switches at once.
- `closeDelay?` (`number`): Milliseconds before the open panel closes once the pointer leaves its trigger and the panel.
- `openOnHover?` (`boolean`): Whether resting the pointer on a trigger opens its panel. Pressing a trigger always does, so `false` makes a click-only menu.
- `closeOnSelect?` (`boolean`): Whether pressing a link closes the menu, like after a client-side route change. A link's own `closeOnSelect` wins. A press with a modifier key, which opens a new tab, never closes it.
- `orientation?` (`NavigationMenuOrientation`): Which arrow keys move between the top-level items, and the side panels open on: below a horizontal menu, beside a vertical one.
- `controller?` (`object`): Opens and closes panels from anywhere. Create one with `createNavigationMenuController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### NavigationMenuItem
- `value?` (`string`): Identifies the item, for `value` and `valuechange`. Generated when left out.

### NavigationMenuTrigger
- `disabled?` (`boolean`): Stops the trigger from opening its panel. A native button can't be focused or pressed.

### NavigationMenuContent
- `side?` (`Side`): Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger it opens on: below a horizontal menu, at the inline end of a vertical one.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How it lines up with the trigger along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the trigger and it, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the trigger, in pixels.
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels.
- `arrowPadding?` (`number`): Space to keep between the arrow and the popup's corners, in pixels.
- `anchor?` (`string | Anchor | null`): Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `keepMounted?` (`boolean`): Whether the content stays in the page, hidden, while its item is closed, so crawlers and the server's HTML have it. Closed content stays in its item; it moves into the viewport when it opens.
- `hiddenUntilFound?` (`boolean`): Whether closed content stays findable with `hidden="until-found"`, so find in page opens its item. Implies `keepMounted`.

### NavigationMenuLink
- `current?` (`boolean`): Whether the link is the current page. Sets `aria-current="page"` and `data-current`.
- `closeOnSelect?` (`boolean`): Whether pressing the link closes the menu. Overrides the menu's `closeOnSelect`.

### NavigationMenuLinkIcon
- `mirror?` (`boolean`): Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.

### NavigationMenuViewport
- `side?` (`Side`): Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger it opens on: below a horizontal menu, at the inline end of a vertical one.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How it lines up with the trigger along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the trigger and it, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the trigger, in pixels.
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels.
- `arrowPadding?` (`number`): Space to keep between the arrow and the popup's corners, in pixels.
- `anchor?` (`string | Anchor | null`): Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

`ui-navigation-menu-list` 没有自己的 props。

### NavigationMenuIndicator
- `followHover?` (`boolean`): Whether it follows the top-level trigger or link under the pointer, and goes back to the open or current one when the pointer leaves the list.

### 状态
相同的状态会作为数据属性显示在每个元素上。

`ui-navigation-menu`:

- `value` (`T | null`): The open item's value, or null.
- `open` (`boolean`): Whether a panel is open.
- `orientation` (`NavigationMenuOrientation`): The menu's `orientation` option, or `"horizontal"` when it's unset or invalid.
- `nested` (`boolean`): Whether the menu sits inside another one's content.

`ui-navigation-menu-list`:

- `open` (`boolean`): Whether a panel is open.
- `orientation` (`NavigationMenuOrientation`): The menu's `orientation` option, or `"horizontal"` when it's unset or invalid.

`ui-navigation-menu-item`:

- `open` (`boolean`): Whether this item's panel is open.

`ui-navigation-menu-trigger`:

- `open` (`boolean`): Whether this trigger's panel is open.
- `disabled` (`boolean`): Set by the trigger's `disabled` prop, which stops it opening its panel.

`ui-navigation-menu-content`:

- `open` (`boolean`): Whether this content's item is open. False while it animates out.
- `motion` (`NavigationMenuMotion | null`): Which way it moves when another item takes over or gives way, or null when the menu opened or closed as a whole.
- `orientation` (`NavigationMenuOrientation`): The menu's `orientation` option, or `"horizontal"` when it's unset or invalid.

`ui-navigation-menu-link`:

- `current` (`boolean`): Whether the link is the current page.

`ui-navigation-menu-link-icon`:

- `mirror` (`boolean`): Whether it flips in right-to-left text.

`ui-navigation-menu-viewport`:

- `open` (`boolean`): Whether a panel is open. False while it animates out.
- `orientation` (`NavigationMenuOrientation`): The menu's `orientation` option, or `"horizontal"` when it's unset or invalid.

`ui-navigation-menu-indicator`:

- `open` (`boolean`): Whether a panel is open.
- `orientation` (`NavigationMenuOrientation`): The menu's `orientation` option, or `"horizontal"` when it's unset or invalid.

### 原因
`event.detail.reason` 说明条目为什么打开或关闭。

- `trigger-hover` (`PointerEvent`): The pointer rested on a trigger, or left it, with hover opening.
- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `link-press` (`MouseEvent | KeyboardEvent`): A link was pressed, which closes the navigation menu it is in, like after a route change.
- `find-in-page` (`Event`): The browser's find in page matched hidden content.
- `parent-close` (`none`): The parent layer closed.
- `imperative` (`none`): A controller or `api` call.

### 控制器
元素的 `api` property 拥有相同的方法。

每个写入方法都接受一个可选的 `{ reason, event }`，传给 `valuechange`。

- `getValue()` (`() => T | null`): The open item's value, or null when every panel is closed.
- `setValue(value, options?)` (`(value: T | null, options?: NavigationMenuChangeOptions | undefined) => boolean`): Opens an item's panel, or closes the open one with `null`. Returns false when canceled.
- `isOpen()` (`() => boolean`): Whether a panel is open.
- `close(options?)` (`(options?: NavigationMenuChangeOptions | undefined) => boolean`): Closes the open panel. Returns false when canceled or already closed.
- `focus(value?)` (`(value?: T | undefined) => void`): Moves focus to an item's trigger: the open one, or the first one, without a value.

### 事件
事件在各自的元素上触发，不冒泡，新状态在 `event.detail.value` 里，`reason` 和 `event` 在旁边。在 `valuechange` 上调用 `preventDefault()` 可以取消这次变更。要用带类型的监听器，把元素类型写成 `UiNavigationMenuElement`。

| 成员                        | 所属                 | 说明                                           |
| --------------------------- | -------------------- | ---------------------------------------------- |
| `value` property, attribute | `ui-navigation-menu` | 打开条目的值。属性设置它的起始值，而且是实时的 |
| `api` property              | `ui-navigation-menu` | [控制器](https://ui-sdk.cn/docs/web-components/components/navigation-menu#controller)                          |
| `valuechange` event         | `ui-navigation-menu` | `detail: { value, reason, event }`             |
| `openchangecomplete` event  | `ui-navigation-menu` | `detail: { value: open }`，在动画之后          |

## 无障碍
导航菜单遵循[展开式导航模式](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/examples/disclosure-navigation/)：一个地标，里面是一个按钮列表，按钮显示和隐藏成组的链接。

### 键盘
Tab 按顺序经过触发器和顶层链接，就像页面上的任何链接一样。在触发器上按 Enter 或 Space 会打开它的面板，并把焦点留在触发器上；从打开的触发器按 Tab 会进入它的面板，无论面板渲染在哪里。按 Tab 越过面板的最后一个链接，会移到下一个条目；从它的第一个链接按 Shift+Tab，会回到触发器。Escape 关闭面板并把焦点返回它的触发器，焦点离开导航也会关闭它。

方向键补充 Tab，正如模式所允许的：左、右方向键在顶层条目之间移动（垂直菜单里是上、下方向键），Home 和 End 移到第一个和最后一个，下方向键（垂直菜单里的行内末端方向）打开触发器的面板并进入其中；在面板里，上、下方向键或左、右方向键在链接之间移动，Home 和 End 移到第一个和最后一个。不会回绕，带修饰键的按键，比如用 Alt+左方向键返回，交给浏览器处理。

触摸屏没有悬停：轻点触发器会打开它的面板，再轻点一次会关闭它。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Pointer**

- Resting the pointer on a trigger opens its panel.
- The panel waits for its delay before opening.
- Moving to another trigger while a panel is open switches at once.
- Moving along the bar to another trigger switches before the pointer rests.
- Crossing another trigger on the way to the open panel keeps the panel.
- Resting on another trigger on the way to the open panel switches to it.
- Moving the pointer away closes the panel after its close delay.
- Moving the pointer into the panel keeps it open.
- Opening on hover leaves focus where it was.
- Clicking a trigger opens its panel, and clicking it again closes it.
- Clicking a trigger the pointer just opened keeps it open.
- A press outside closes the panel.
- A tap opens a panel and another tap closes it.
- Escape closes a panel the pointer opened, which stays closed while the pointer rests.
- Sweeping across every trigger leaves the menu working.

**Keyboard**

- Tab moves through the triggers and links in order while closed.
- Enter opens a panel and leaves focus on its trigger.
- Space toggles a panel.
- Enter on another trigger switches panels.
- Tab from an open trigger moves into its panel.
- Tab past the panel's last link moves on to the next trigger.
- Shift+Tab from the panel's first link returns to its trigger.
- Shift+Tab from the item after an open panel goes back into the panel.
- Tab from the last item past an open panel leaves the navigation and closes it.
- Tab from the last item past an open panel closes it without going back in when nothing follows the navigation.
- Escape inside a panel closes it and returns focus to its trigger.
- Escape on an open trigger closes its panel.
- Focus leaving the navigation closes the panel.
- Right and Left arrows move between the top-level items.
- Arrows stop at the first and last items.
- ArrowDown on a trigger opens its panel.
- Down and Up arrows move between the links in a panel.
- An editable element in a panel keeps Down, and a tab stop that isn't editable passes it on.
- A vertical menu moves between items with Down and Up.

**Links**

- A link in a panel follows its href and closes the menu.
- Enter on a link follows it.
- A link with closing turned off leaves the menu open.
- The current page's link says so.

**Viewport**

- The viewport opens below the open trigger, lined up with its start.
- The viewport takes the open panel's size.
- The viewport moves to the newly open trigger.

**Kept content**

- Closed content kept mounted stays in the page, hidden.
- The viewport follows the open panel when its size changes.

**Animation**

- The viewport and its content animate in from their starting style.
- The viewport stays in the page while it animates out.
- A menu opening from closed has no motion.
- With reduced motion, panels switch and close without waiting.
- The viewport appears in place, without sliding in from the corner.
- Exit keyframes keyed on data-closed play on the content that gave way.
- The content that gave way animates out while the next one comes in.

**Reasons**

- Changes report why the menu opened, switched and closed.

**Nested**

- A menu inside a panel opens its own panel.
- A link in a nested panel closes every menu.

Runs in React、Vue 和 web components.

在模式的基线之外：

**Keyboard**

- ArrowDown on a trigger opens its panel and moves focus to its first link.
- ArrowDown on an open trigger moves into its panel.
- Home and End move to the first and last top-level items.
- The same keys pressed without waiting still land.

**Pointer**

- With hover opening off, resting the pointer opens nothing and a click still does.
- A click long after the pointer opened a panel still keeps it open.
- An outside press reports itself, not a focus change.
- The panel stays open while focus is in it, even when the pointer leaves.

**Links**

- A link pressed with a modifier key, which opens a new tab, leaves the menu open.

**Without a viewport**

- Each panel opens as its own popup below its trigger.
- Panels switch, close on Escape and return focus like with one.

**Motion**

- Content coming from a later item enters from the end, and the one it replaced leaves toward the start.
- Content coming from an earlier item enters from the start.

**Indicator**

- The indicator rests on the current page's link while closed.
- With followHover, the indicator follows the hovered item and goes back when the pointer leaves.
- The indicator moves under the open trigger.
- The indicator follows an item added later as it grows. Web components only.

**Find in page**

- Find in page opens the item whose closed panel matched.

**Nested**

- A nested menu adds no second navigation landmark.
- Escape closes only the nested panel, then the outer one.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while opening a panel and tabbing through it.

Runs in React、Vue 和 web components.
