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

站点的主要链接用 Navigation Menu:链接分组到面板里,由一排触发器打开。操作列表请用 Menu。

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuLinkIcon,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import type { JSX } from "@solidjs/web"
import { For } from "solid-js"

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 icon = (children: JSX.Element) => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    {children}
  </svg>
)
const CircleQuestionMark = () =>
  icon(
    <>
      <circle cx="12" cy="12" r="10" />
      <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />
      <path d="M12 17h.01" />
    </>
  )
const Circle = () => icon(<circle cx="12" cy="12" r="10" />)
const CircleCheck = () =>
  icon(
    <>
      <circle cx="12" cy="12" r="10" />
      <path d="m16 9-5.5 5.5L8 12" />
    </>
  )
const ArrowRight = () =>
  icon(
    <>
      <path d="M5 12h14" />
      <path d="m12 5 7 7-7 7" />
    </>
  )

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 Example() {
  return (
    <NavigationMenu aria-label="Main">
      <NavigationMenuList>
        <NavigationMenuItem value="getting-started">
          <NavigationMenuTrigger>
            Getting started
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul data-slot="grid">
              <li>
                <NavigationMenuLink href="#" data-variant="featured">
                  <span>ui-sdk</span>
                  <span data-slot="hint">
                    Accessible components for React, Vue, Svelte, Solid and Web
                    Components.
                  </span>
                </NavigationMenuLink>
              </li>
              <For each={gettingStarted}>
                {(page) => (
                  <li>
                    <NavigationMenuLink href={page.href}>
                      <span>{page.title}</span>
                      <span data-slot="hint">{page.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem value="components">
          <NavigationMenuTrigger>
            Components
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul data-slot="grid">
              <For each={components}>
                {(page) => (
                  <li>
                    <NavigationMenuLink href={page.href}>
                      <span>{page.title}</span>
                      <span data-slot="hint">{page.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem value="with-icon">
          <NavigationMenuTrigger>
            With Icon
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul>
              <For each={statuses}>
                {(status) => (
                  <li>
                    <NavigationMenuLink href={status.href}>
                      <NavigationMenuLinkIcon mirror={status.mirror}>
                        <status.icon />
                      </NavigationMenuLinkIcon>
                      {status.title}
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem>
          <NavigationMenuLink href="#">Docs</NavigationMenuLink>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

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

安装

npm install @ui-sdk/solid @ui-sdk/core

组合

用下面的组合构建 NavigationMenu:

NavigationMenu
├── NavigationMenuList
│   ├── NavigationMenuItem
│   │   ├── NavigationMenuTrigger
│   │   └── NavigationMenuContent
│   │       └── NavigationMenuLink
│   └── NavigationMenuItem
│       ├── NavigationMenuTrigger
│       └── NavigationMenuContent
│           └── NavigationMenuLink
└── NavigationMenuViewport

给导航一个 aria-label。每个条目里是一个触发器和它的面板,或者一个普通链接。这遵循展开式导航模式:按钮显示成组的普通链接。操作请改用 Menu。

视口容纳打开的面板,并跟随它的大小和位置。使用视口时,用 --viewport-width 和 --viewport-height 给它定尺寸,并裁剪它的溢出内容;视口里的内容解释了其中的几何关系。你也可以省掉视口,单独给每个面板定位。

用法

导入部件并把它们组合起来:

import {
  NavigationMenu,
  NavigationMenuList,
  NavigationMenuItem,
  NavigationMenuTrigger,
  NavigationMenuContent,
  NavigationMenuLink,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"

function Example() {
  return (
    <NavigationMenu aria-label="Main">
      <NavigationMenuList>
        <NavigationMenuItem value="guides">
          <NavigationMenuTrigger>Guides</NavigationMenuTrigger>
          <NavigationMenuContent>
            <NavigationMenuLink href="/docs">Introduction</NavigationMenuLink>
          </NavigationMenuContent>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport />
    </NavigationMenu>
  )
}

export { Example }

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

把路由器的链接传给 render,比如 render={(props) => <A {...props} href="/docs" />}。

控制台
import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import type { JSX } from "@solidjs/web"
import { createSignal, For, merge, omit } from "solid-js"
import { useLog } 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 Link(
  props: JSX.IntrinsicElements["a"] & {
    href: string
    onNavigate: (href: string) => void
  }
) {
  const onClick: JSX.EventHandler<HTMLAnchorElement, MouseEvent> = (event) => {
    if (typeof props.onClick === "function") {
      props.onClick(event)
    }
    event.preventDefault()
    props.onNavigate(props.href)
  }
  const link = merge(omit(props, "href", "onNavigate", "onClick"), {
    get href() {
      return props.href
    },
    onClick,
  })
  return <a {...link} />
}

function Example() {
  const log = useLog()
  const [route, setRoute] = createSignal("#introduction")
  const navigate = (href: string) => {
    setRoute(href)
    log(`Navigated to ${href}`)
  }

  return (
    <NavigationMenu aria-label="Docs">
      <NavigationMenuList>
        <NavigationMenuItem value="guides">
          <NavigationMenuTrigger>
            Guides
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul>
              <For each={gettingStarted}>
                {(page) => (
                  <li>
                    <NavigationMenuLink
                      render={(props) => (
                        <Link
                          {...props}
                          href={page.href}
                          onNavigate={navigate}
                        />
                      )}
                      current={route() === page.href}
                    >
                      <span>{page.title}</span>
                      <span data-slot="hint">{page.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem>
          <NavigationMenuLink
            render={(props) => (
              <Link {...props} href="#components" onNavigate={navigate} />
            )}
            current={route() === "#components"}
          >
            Components
          </NavigationMenuLink>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

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

路由器在链接的点击上调用 preventDefault(),以便不加载页面就完成导航。导航菜单在链接元素本身上监听,所以客户端路由变化之后它仍会关闭。带修饰键的按压,或鼠标中键按压,会在别处打开链接,并让菜单保持打开。把 closeOnSelect 设为 false 可以让它在每次按压后都保持打开,见选中后关闭。

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

<NavigationMenuItem value="products">
  <NavigationMenuLink href="/products">Products</NavigationMenuLink>
  <NavigationMenuTrigger aria-label="More in Products">▾</NavigationMenuTrigger>
  <NavigationMenuContent>
    <NavigationMenuLink href="/products/analytics">
      Analytics
    </NavigationMenuLink>
  </NavigationMenuContent>
</NavigationMenuItem>

图标

把链接的图标放进 NavigationMenuLinkIcon,放在文字前面,就像页面顶部菜单里的 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 另有指定。

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import { For } from "solid-js"

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 Example() {
  return (
    <NavigationMenu aria-label="Sidebar" orientation="vertical">
      <NavigationMenuList>
        <For each={sections}>
          {(section) => (
            <NavigationMenuItem value={section.value}>
              <NavigationMenuTrigger>
                {section.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m9 18 6-6-6-6" />
                </svg>
              </NavigationMenuTrigger>
              <NavigationMenuContent>
                <ul>
                  <For each={section.links}>
                    {(link) => (
                      <li>
                        <NavigationMenuLink href={link.href}>
                          <span>{link.title}</span>
                          <span data-slot="hint">{link.description}</span>
                        </NavigationMenuLink>
                      </li>
                    )}
                  </For>
                </ul>
              </NavigationMenuContent>
            </NavigationMenuItem>
          )}
        </For>
        <NavigationMenuItem>
          <NavigationMenuLink href="#">Docs</NavigationMenuLink>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

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

仅点击

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

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import { For } from "solid-js"

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 Example() {
  return (
    <NavigationMenu aria-label="Main" openOnHover={false}>
      <NavigationMenuList>
        <For each={sections}>
          {(section) => (
            <NavigationMenuItem value={section.value}>
              <NavigationMenuTrigger>
                {section.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </NavigationMenuTrigger>
              <NavigationMenuContent>
                <ul>
                  <For each={section.links}>
                    {(link) => (
                      <li>
                        <NavigationMenuLink href={link.href}>
                          <span>{link.title}</span>
                          <span data-slot="hint">{link.description}</span>
                        </NavigationMenuLink>
                      </li>
                    )}
                  </For>
                </ul>
              </NavigationMenuContent>
            </NavigationMenuItem>
          )}
        </For>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

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

嵌套

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

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import { For } from "solid-js"

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 Example() {
  return (
    <NavigationMenu aria-label="Main">
      <NavigationMenuList>
        <NavigationMenuItem value="guides">
          <NavigationMenuTrigger>
            Guides
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul>
              <For each={gettingStarted}>
                {(link) => (
                  <li>
                    <NavigationMenuLink href={link.href}>
                      <span>{link.title}</span>
                      <span data-slot="hint">{link.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem value="components">
          <NavigationMenuTrigger>
            Components
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <NavigationMenu orientation="vertical">
              <NavigationMenuList>
                <For each={groups}>
                  {(group) => (
                    <NavigationMenuItem value={group.value}>
                      <NavigationMenuTrigger>
                        {group.label}
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          aria-hidden="true"
                        >
                          <path d="m9 18 6-6-6-6" />
                        </svg>
                      </NavigationMenuTrigger>
                      <NavigationMenuContent sideOffset={9} alignOffset={-5}>
                        <ul>
                          <For each={group.links}>
                            {(link) => (
                              <li>
                                <NavigationMenuLink href={link.href}>
                                  {link.title}
                                </NavigationMenuLink>
                              </li>
                            )}
                          </For>
                        </ul>
                      </NavigationMenuContent>
                    </NavigationMenuItem>
                  )}
                </For>
              </NavigationMenuList>
            </NavigationMenu>
          </NavigationMenuContent>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

export { Example }
打开 Components,再打开 Overlays 或 Forms。Escape 会先关闭内层面板。

动画

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

onOpenChangeComplete 在导航菜单完成打开或关闭后运行,在任何动画之后,并带上新的打开状态。在条目之间切换不算。

控制台
import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import { For } from "solid-js"
import { useLog } 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 Example() {
  const log = useLog()

  return (
    <NavigationMenu
      aria-label="Main"
      onValueChange={(value) => log(value ? `Showing ${value}` : "Closing")}
      onOpenChangeComplete={(open) =>
        log(open ? "Finished opening" : "Finished closing")
      }
    >
      <NavigationMenuList>
        <NavigationMenuItem value="guides">
          <NavigationMenuTrigger>
            Guides
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul>
              <For each={gettingStarted}>
                {(page) => (
                  <li>
                    <NavigationMenuLink href={page.href}>
                      <span>{page.title}</span>
                      <span data-slot="hint">{page.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
        <NavigationMenuItem value="components">
          <NavigationMenuTrigger>
            Components
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </NavigationMenuTrigger>
          <NavigationMenuContent>
            <ul data-slot="grid">
              <For each={components}>
                {(page) => (
                  <li>
                    <NavigationMenuLink href={page.href}>
                      <span>{page.title}</span>
                      <span data-slot="hint">{page.description}</span>
                    </NavigationMenuLink>
                  </li>
                )}
              </For>
            </ul>
          </NavigationMenuContent>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} data-variant="slide" />
    </NavigationMenu>
  )
}

export { Example }
在 Guides 和 Components 之间切换,看看视口如何改变大小、面板如何滑动。

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

延迟

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

<NavigationMenu aria-label="Main" delay={400} closeDelay={600}>
  ...
</NavigationMenu>

指示器

NavigationMenuIndicator 位于打开的触发器下方;所有面板都关闭时,则位于带 current 的顶层链接下方。它的盒子来自 --active-item-* 变量,相对于它的定位祖先,并在有东西可以覆盖时得到 data-visible。屏幕阅读器会跳过它。

<NavigationMenu aria-label="Main">
  <NavigationMenuList>...</NavigationMenuList>
  <NavigationMenuIndicator />
  <NavigationMenuViewport />
</NavigationMenu>
[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;
}

给它 followHover,它就会跟随指针下的顶层触发器或链接;指针离开列表后,再回到打开的触发器或当前链接。

视口的放置位置

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

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

<NavigationMenuViewport
  side="bottom"
  align="center"
  sideOffset={8}
  collisionPadding={16}
  anchor="#site-header"
/>

不使用视口

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

<NavigationMenu aria-label="Main">
  <NavigationMenuList>
    <NavigationMenuItem value="guides">
      <NavigationMenuTrigger>Guides</NavigationMenuTrigger>
      <NavigationMenuContent side="bottom" align="start" sideOffset={8}>
        ...
      </NavigationMenuContent>
    </NavigationMenuItem>
  </NavigationMenuList>
</NavigationMenu>

受控

传入 value 和 onValueChange 来控制哪个条目打开。value 是打开条目的 value;所有面板都关闭时是 null。用 defaultValue 让一开始就有一个面板打开,而不受控。

每个条目都接受 value,省略时会自动生成。每次变更都带一个原因,比如 trigger-hover、trigger-press、link-press 或 outside-press。调用 details.cancel() 可以阻止它。

const [value, setValue] = createSignal<string | null>(null)

<NavigationMenu aria-label="Main" value={value()} onValueChange={setValue}>
  ...
</NavigationMenu>

从任意位置打开

由 createNavigationMenuController() 创建的控制器可以从任意位置打开、关闭和聚焦菜单,而不控制它。把它作为 controller 传入。

const menu = createNavigationMenuController()

<button onClick={() => menu.setValue("components")}>Browse Components</button>
<NavigationMenu aria-label="Main" controller={menu}>
  ...
</NavigationMenu>

保持挂载

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

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

<NavigationMenuContent hiddenUntilFound>...</NavigationMenuContent>

选中后关闭

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

<NavigationMenu aria-label="Main" closeOnSelect={false}>
  ...
  <NavigationMenuLink href="/docs/components" closeOnSelect>
    Browse All
  </NavigationMenuLink>
</NavigationMenu>

容器

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

<NavigationMenu aria-label="Main" container={container()}>
  ...
</NavigationMenu>

自定义渲染

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  NavigationMenuViewport,
} from "@ui-sdk/solid/navigation-menu"
import { For } from "solid-js"

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 Example() {
  return (
    <NavigationMenu aria-label="Main">
      <NavigationMenuList>
        <For each={sections}>
          {(section) => (
            <NavigationMenuItem value={section.value}>
              <NavigationMenuTrigger
                render={(props, state) => (
                  <button {...props}>
                    {section.label}
                    {state.open ? (
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="M5 12h14" />
                      </svg>
                    ) : (
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="M5 12h14" />
                        <path d="M12 5v14" />
                      </svg>
                    )}
                  </button>
                )}
              />
              <NavigationMenuContent
                render={(props) => (
                  <section {...props} aria-label={section.label} />
                )}
              >
                {(state) => (
                  <>
                    <p data-slot="hint">
                      {state.motion ? `Moved in ${state.motion}` : "Opened"}
                    </p>
                    <ul>
                      <For each={section.links}>
                        {(link, index) => (
                          <li>
                            <NavigationMenuLink
                              href={link.href}
                              current={index() === 0}
                              render={(props, linkState) => (
                                <a {...props}>
                                  <span>{link.title}</span>
                                  {linkState.current && (
                                    <span data-slot="hint" data-show="current">
                                      You're here
                                    </span>
                                  )}
                                </a>
                              )}
                            />
                          </li>
                        )}
                      </For>
                    </ul>
                  </>
                )}
              </NavigationMenuContent>
            </NavigationMenuItem>
          )}
        </For>
        <NavigationMenuItem value="pricing">
          <NavigationMenuTrigger
            disabled
            render={(props, state) => (
              <button {...props}>
                Pricing
                {state.disabled && (
                  <span data-slot="badge" data-show="disabled">
                    Soon
                  </span>
                )}
              </button>
            )}
          />
          <NavigationMenuContent>Plans for teams.</NavigationMenuContent>
        </NavigationMenuItem>
      </NavigationMenuList>
      <NavigationMenuViewport sideOffset={8} />
    </NavigationMenu>
  )
}

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

用渲染函数改变标记,或读取部件的状态。这里内容读取 motion,禁用的触发器显示一个徽标。

触发器上的 disabled 阻止它打开面板。每个部件的状态列在状态下。

样式

部件没有样式。通过它们渲染出的属性来设置样式,这些属性在每个框架里都一样。每个部件都有一个 data-slot,比如 navigation-menu-trigger,它的状态属性列在数据属性下。

视口里的内容

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

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

用纯 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;
  }
}

NavigationMenuContent

变量内容
--anchor-widthWithout a viewport: width of the anchor, usually the trigger. Use it to match widths.
--anchor-heightWithout a viewport: height of the anchor.
--available-widthWithout a viewport: space beside the popup, up to the viewport edge. Not inherited either.
--available-heightWithout 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-originWithout a viewport: the point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWithout a viewport: where the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it.

NavigationMenuViewport

变量内容
--anchor-widthWidth of the anchor, usually the trigger. Use it to match widths.
--anchor-heightHeight of the anchor.
--available-widthSpace beside the popup, up to the viewport edge. Not inherited either.
--available-heightSpace 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-originThe point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWhere the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it.
--viewport-widthThe open content's width plus the viewport's own border. Transition width for a viewport that resizes as it switches.
--viewport-heightThe open content's height plus the viewport's own border.

NavigationMenuIndicator

变量内容
--active-item-leftDistance from its positioned ancestor's left edge to the open trigger, or the current page's link.
--active-item-rightDistance from its positioned ancestor's right edge to the item.
--active-item-topDistance from its positioned ancestor's top edge to the item.
--active-item-bottomDistance from its positioned ancestor's bottom edge to the item.
--active-item-widthWidth of the item it sits under.
--active-item-heightHeight of the item it sits under.

数据属性

NavigationMenu

[data-slot="navigation-menu"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between the items, and where panels open.
data-nestedPresent on a menu inside another menu's content.

NavigationMenuList

[data-slot="navigation-menu-list"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between the items, and where panels open.
data-has-iconsPresent while any link inside holds an icon part, so items without one can line up.

NavigationMenuItem

[data-slot="navigation-menu-item"]

属性含义
data-closedPresent while the item's panel is closed, including while it animates out.
data-openPresent while the item's panel is open.

NavigationMenuTrigger

[data-slot="navigation-menu-trigger"]

属性含义
data-closedPresent while the item's panel is closed, including while it animates out.
data-disabledPresent when the trigger is disabled.
data-openPresent while the item's panel is open.

NavigationMenuContent

[data-slot="navigation-menu-content"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between the items, and where panels open.
data-closedPresent while the item's panel is closed, including while it animates out.
data-openPresent while the item's panel is open.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while it animates out. Style the state you animate to.
data-motionfrom-startfrom-endto-startto-endWhich 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-sidetoprightbottomleftWhere the viewport, or a content without one, ended up after flipping away from edges.
data-alignstartcenterendHow it lines up with the trigger.

[data-slot="navigation-menu-link"]

属性含义
data-has-iconPresent on a link while it holds an icon part.

NavigationMenuLinkIcon

[data-slot="navigation-menu-link-icon"]

属性含义
data-mirrorPresent on an icon that flips in right-to-left text, with mirror.

NavigationMenuViewport

[data-slot="navigation-menu-viewport"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between the items, and where panels open.
data-closedPresent while every panel is closed, including while it animates out.
data-openPresent while a panel is open.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while it animates out. Style the state you animate to.
data-sidetoprightbottomleftWhere the viewport, or a content without one, ended up after flipping away from edges.
data-alignstartcenterendHow it lines up with the trigger.

NavigationMenuIndicator

[data-slot="navigation-menu-indicator"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between the items, and where panels open.
data-closedPresent while every panel is closed.
data-openPresent while a panel is open, so it sits under a trigger.
data-visiblePresent while there's a trigger or a current page's link to sit under.

API 参考

属性和回调与下面相同,都作为 Solid props。

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.
onValueChange?((value: T | null, details: ChangeDetails<NavigationMenuValueChangeReason>) => void)
Runs when an item wants to open or the open one to close. details.reason says why, and details.cancel() stops it.
onOpenChangeComplete?((open: boolean) => void)
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.
value?string
Identifies the item, for value and onValueChange. Generated when left out.
disabled?boolean
Stops the trigger from opening its panel. A native button can't be focused or pressed.
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.
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.
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.
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.

NavigationMenuList 没有自己的 props。

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.

状态

每个部件的渲染函数、基于状态的类名和槽位会收到什么。

NavigationMenu:

valueT | null
The open item's value, or null.
openboolean
Whether a panel is open.
orientationNavigationMenuOrientation
The menu's orientation option, or "horizontal" when it's unset or invalid.
nestedboolean
Whether the menu sits inside another one's content.

NavigationMenuList:

openboolean
Whether a panel is open.
orientationNavigationMenuOrientation
The menu's orientation option, or "horizontal" when it's unset or invalid.

NavigationMenuItem:

openboolean
Whether this item's panel is open.

NavigationMenuTrigger:

openboolean
Whether this trigger's panel is open.
disabledboolean
Set by the trigger's disabled prop, which stops it opening its panel.

NavigationMenuContent:

openboolean
Whether this content's item is open. False while it animates out.
motionNavigationMenuMotion | null
Which way it moves when another item takes over or gives way, or null when the menu opened or closed as a whole.
orientationNavigationMenuOrientation
The menu's orientation option, or "horizontal" when it's unset or invalid.

NavigationMenuLink:

currentboolean
Whether the link is the current page.

NavigationMenuLinkIcon:

mirrorboolean
Whether it flips in right-to-left text.

NavigationMenuViewport:

openboolean
Whether a panel is open. False while it animates out.
orientationNavigationMenuOrientation
The menu's orientation option, or "horizontal" when it's unset or invalid.

NavigationMenuIndicator:

openboolean
Whether a panel is open.
orientationNavigationMenuOrientation
The menu's orientation option, or "horizontal" when it's unset or invalid.

原因

details.reason 说明条目为什么打开或关闭。

trigger-hoverPointerEvent
The pointer rested on a trigger, or left it, with hover opening.
trigger-pressMouseEvent | 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-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
outside-pressMouseEvent
A press outside the layer.
focus-outKeyboardEvent | FocusEvent
Focus left the layer, or Tab moved it out.
link-pressMouseEvent | KeyboardEvent
A link was pressed, which closes the navigation menu it is in, like after a route change.
find-in-pageEvent
The browser's find in page matched hidden content.
parent-closenone
The parent layer closed.
imperativenone
A controller or api call.

控制器

用 createNavigationMenuController() 创建一个,并作为 controller 传入。

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

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.

事件

回调先收到新状态,然后收到详情。

属性所属收到
onValueChangeNavigationMenu(value, details):打开的条目,以及原因
onOpenChangeCompleteNavigationMenu(open),在动画之后

无障碍

导航菜单遵循展开式导航模式:一个地标,里面是一个按钮列表,按钮显示和隐藏成组的链接。

键盘

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.

运行于 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 运行。
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.

运行于 React、Vue 和 web components。

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

  • Announcements while opening a panel and tabbing through it.

运行于 React、Vue 和 web components。