Components

Navigation Menu

A site's top navigation: triggers and links in DM Sans Medium, each trigger opening a panel of links in the card's #262626 fill. It opens under a resting pointer, switches at once between triggers, and opens at once from the keyboard.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add navigation-menu
<script type="module" src="/spyglass-ds/elements/navigation-menu.js"></script>
The site's header

Usage

The website's header: the product's parts, resources, pricing. A few entries, each panel a handful of links with a line each.

Never

  • App navigation: use the Sidebar
  • Actions: use Dropdown Menu or Menubar
  • A chevron that turns or moves on hover

Adds with it: popover packages lucide-react

Props

The web component takes the same as attributes or properties (<spyglass-navigation-menu>); title is heading there.

<NavigationMenu>

PropTypeDefault
labelstring

The navigation's name for assistive tech.

'Main'
childrenReactNode

NavigationMenuItem elements.

classNamestring

<NavigationMenuItem>

PropTypeDefault
labelstring

The trigger's or the link's text.

hrefstring

A plain link in the row, when it has no panel.

activeboolean

The page you are on (a plain link).

widthstring

The panel's width (a CSS length).

'400px'
childrenReactNode

The panel's links.

<NavigationMenuLink>

PropTypeDefault
hrefstring
titlestring

The link's title.

descriptionstring

A line under it.

childrenReactNode

Examples

The same example in React and as web components; both render identically.

react/examples/navigation-menu/Site.tsx
import { NavigationMenu } from '@/react/components/ui/NavigationMenu'
import { NavigationMenuItem } from '@/react/components/ui/NavigationMenuItem'
import { NavigationMenuLink } from '@/react/components/ui/NavigationMenuLink'
// The site's top navigation: the product and resources open panels of links, pricing and about are plain links. Point
// at Product, then move to Resources: it switches at once.
const product = [
  { title: 'Search', description: 'Find any ad in seconds, by hook, brand or format.' },
  { title: 'Boards', description: 'Save and share the creatives that work.' },
  { title: 'Brand tracking', description: 'Every new ad from the brands you follow.' },
  { title: 'Creators', description: 'The faces behind the ads that run longest.' },
]
const resources = [
  { title: 'Blog', description: 'What the best ads have in common.' },
  { title: 'Changelog', description: 'New in Spyglass, every week.' },
  { title: 'Help center', description: 'Answers in under a minute.' },
]

export default function Site() {
  return (
    <div className="min-h-80">
      <NavigationMenu label="Site">
        <NavigationMenuItem label="Product" width="440px">
          <div className="grid gap-1 sm:grid-cols-2">
            {product.map((l) => <NavigationMenuLink key={l.title} href="#" title={l.title} description={l.description} />)}
          </div>
        </NavigationMenuItem>
        <NavigationMenuItem label="Resources" width="280px">
          <div className="grid gap-1">
            {resources.map((l) => <NavigationMenuLink key={l.title} href="#" title={l.title} description={l.description} />)}
          </div>
        </NavigationMenuItem>
        <NavigationMenuItem label="Pricing" href="#" />
        <NavigationMenuItem label="About" href="#" />
      </NavigationMenu>
    </div>
  )
}
elements/examples/navigation-menu/Site.html
<!-- The site's top navigation: the product and resources open panels of links, pricing and about are plain links.
     Point at Product, then move to Resources: it switches at once. -->
<div class="min-h-80">
  <spyglass-navigation-menu label="Site">
    <spyglass-navigation-menu-item label="Product" width="440px">
      <div class="grid gap-1 sm:grid-cols-2">
        <spyglass-navigation-menu-link href="#" heading="Search" description="Find any ad in seconds, by hook, brand or format."></spyglass-navigation-menu-link>
        <spyglass-navigation-menu-link href="#" heading="Boards" description="Save and share the creatives that work."></spyglass-navigation-menu-link>
        <spyglass-navigation-menu-link href="#" heading="Brand tracking" description="Every new ad from the brands you follow."></spyglass-navigation-menu-link>
        <spyglass-navigation-menu-link href="#" heading="Creators" description="The faces behind the ads that run longest."></spyglass-navigation-menu-link>
      </div>
    </spyglass-navigation-menu-item>
    <spyglass-navigation-menu-item label="Resources" width="280px">
      <div class="grid gap-1">
        <spyglass-navigation-menu-link href="#" heading="Blog" description="What the best ads have in common."></spyglass-navigation-menu-link>
        <spyglass-navigation-menu-link href="#" heading="Changelog" description="New in Spyglass, every week."></spyglass-navigation-menu-link>
        <spyglass-navigation-menu-link href="#" heading="Help center" description="Answers in under a minute."></spyglass-navigation-menu-link>
      </div>
    </spyglass-navigation-menu-item>
    <spyglass-navigation-menu-item label="Pricing" href="#"></spyglass-navigation-menu-item>
    <spyglass-navigation-menu-item label="About" href="#"></spyglass-navigation-menu-item>
  </spyglass-navigation-menu>
</div>

Source

react/components/ui/NavigationMenu.tsx
'use client'
import { createContext, useRef, useState, type Dispatch, type ReactNode, type SetStateAction } from 'react'

// A site's top navigation (shadcn's navigation menu): a row of triggers and links in DM Sans Medium, each trigger
// opening a panel of links in the card's #262626 fill under it (NavigationMenuItem with NavigationMenuLink rows). Under
// a pointer a panel opens after a short wait and closes a moment after the pointer leaves both; while one is open,
// pointing at another trigger switches at once. A click toggles it; Enter, Space or Down opens it at once with focus on
// its first link; Left and Right move along the triggers; Escape closes it and returns focus. The chevron stays still.
export interface NavigationMenuContextValue {
  active: string | null
  setActive: Dispatch<SetStateAction<string | null>>
  /** The triggers and links of the row, in order, for Left and Right. */
  row: () => HTMLElement[]
}
export const NavigationMenuContext = createContext<NavigationMenuContextValue | null>(null)

export interface NavigationMenuProps {
  /** The navigation's name for assistive tech. */
  label?: string
  /** NavigationMenuItem elements. */
  children?: ReactNode
  className?: string
}

export function NavigationMenu({ label = 'Main', children, className }: NavigationMenuProps) {
  const [active, setActive] = useState<string | null>(null)
  const list = useRef<HTMLUListElement | null>(null)
  const row = () => [...(list.current?.querySelectorAll<HTMLElement>('[data-nav-trigger]') ?? [])]
  return (
    <NavigationMenuContext.Provider value={{ active, setActive, row }}>
      <nav data-ds="navigation-menu" aria-label={label} className={className}>
        <ul ref={list} className="flex flex-wrap items-center gap-1">{children}</ul>
      </nav>
    </NavigationMenuContext.Provider>
  )
}

export default NavigationMenu
react/components/ui/NavigationMenuItem.tsx
'use client'
import { useContext, useEffect, useId, useRef, type FocusEvent, type KeyboardEvent, type MouseEvent, type PointerEvent, type ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { NavigationMenuContext } from '@/react/components/ui/NavigationMenu'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { firstFocusable, usePopover } from '@/react/hooks/usePopover'
import { cn } from '@/react/lib/cn'

// One entry of a NavigationMenu: with children, a trigger and its panel of links (NavigationMenuLink); with `href` and
// no children, a plain link in the row (`active` for the page you are on). The open trigger takes the #262626 fill.
export interface NavigationMenuItemProps {
  /** The trigger's or the link's text. */
  label: string
  /** A plain link in the row, when it has no panel. */
  href?: string
  /** The page you are on (a plain link). */
  active?: boolean
  /** The panel's width (a CSS length). */
  width?: string
  /** The panel's links. */
  children?: ReactNode
}

const WAIT = 80 // the site's menu intent (--dur-menu-intent)
const GRACE = 240 // the site's menu grace (--dur-menu-grace)
const ROW = 'inline-flex h-control-md cursor-pointer items-center gap-1.5 rounded-control px-4 type-ui-strong -outline-offset-2 transition-[background-color,color] duration-160 ease-standard max-md:h-control-touch'

export function NavigationMenuItem({ label, href, active, width = '400px', children }: NavigationMenuItemProps) {
  const nav = useContext(NavigationMenuContext)!
  const key = useId()
  const pop = usePopover({ side: 'bottom', align: 'start', gap: 8 })
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
  const hovered = useRef(0)

  useEffect(() => {
    if (pop.open) nav.setActive(key)
    else nav.setActive((a) => (a === key ? null : a))
  }, [pop.open]) // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (nav.active !== key && pop.open) pop.hide(false, true)
  }, [nav.active]) // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => () => clearTimeout(timer.current), [])

  function move(event: KeyboardEvent) {
    if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return false
    event.preventDefault()
    const row = nav.row()
    const at = row.indexOf(event.currentTarget as HTMLElement)
    row[(at + (event.key === 'ArrowRight' ? 1 : -1) + row.length) % row.length]?.focus()
    return true
  }

  if (!children) {
    return (
      <li data-ds="navigation-menu-item" className="flex">
        <a data-nav-trigger="" href={href} aria-current={active ? 'page' : undefined} className={cn(ROW, active ? 'text-fg' : 'text-fg-soft hover:bg-action-ghost-hover hover:text-fg')} onKeyDown={move}>{label}</a>
      </li>
    )
  }

  async function openAt(keyboard: boolean, focus: boolean) {
    clearTimeout(timer.current)
    await pop.show({ keyboard })
    if (focus) (firstFocusable(pop.panel.current) ?? pop.panel.current)?.focus({ preventScroll: true })
  }
  function enter(event: PointerEvent) {
    if (event.pointerType !== 'mouse') return
    clearTimeout(timer.current)
    if (pop.open) return
    // Another panel open: switch at once.
    if (nav.active && nav.active !== key) {
      hovered.current = Date.now()
      return void openAt(true, false)
    }
    // ds-latency: the wait keeps a passing pointer from opening it.
    timer.current = setTimeout(() => {
      hovered.current = Date.now()
      void openAt(false, false)
    }, WAIT)
  }
  function leave(event: PointerEvent) {
    if (event.pointerType !== 'mouse') return
    clearTimeout(timer.current)
    // ds-latency: a grace to cross the gap into the panel.
    timer.current = setTimeout(() => pop.hide(), GRACE)
  }
  // A click toggles it; a click right after the pointer opened it keeps it open.
  function onClick(event: MouseEvent) {
    const keyboard = event.detail === 0
    if (pop.open) {
      if (!keyboard && Date.now() - hovered.current < 400) return
      pop.hide(keyboard, keyboard)
    }
    else void openAt(keyboard, keyboard)
  }
  function onKey(event: KeyboardEvent) {
    if (move(event)) return
    if (event.key === 'ArrowDown') {
      event.preventDefault()
      void openAt(true, true)
    }
  }
  function onBlur(event: FocusEvent) {
    const next = event.relatedTarget as Node | null
    if (next && !pop.panel.current?.contains(next) && !pop.anchor.current?.contains(next)) pop.hide()
  }
  return (
    <li data-ds="navigation-menu-item" className="flex" onPointerEnter={enter} onPointerLeave={leave}>
      <button
        data-nav-trigger=""
        ref={(el) => { pop.anchor.current = el }}
        type="button"
        aria-expanded={pop.open}
        className={cn(ROW, 'text-fg-soft hover:not-aria-expanded:bg-action-ghost-hover hover:text-fg aria-expanded:bg-action-secondary aria-expanded:text-fg')}
        onClick={onClick}
        onKeyDown={onKey}
        onBlur={onBlur}
      >
        {label}
        <ChevronDown size={16} strokeWidth={1.5} aria-hidden="true" className="shrink-0 text-fg-muted" />
      </button>
      <PopoverPanel data-ds="navigation-menu-item" pop={pop} aria-label={label} tabIndex={-1} className="p-2" style={{ width }} onPointerEnter={enter} onPointerLeave={leave}>
        {children}
      </PopoverPanel>
    </li>
  )
}

export default NavigationMenuItem
react/components/ui/NavigationMenuLink.tsx
import type { AnchorHTMLAttributes, ReactNode } from 'react'
import { cn } from '@/react/lib/cn'

// A link in a NavigationMenuItem's panel: its title in DM Sans Medium and a muted line under it, the small corner; the
// link under the pointer or focus takes the #262626 fill. Other props (onClick) land on the <a>.
export interface NavigationMenuLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'title'> {
  href?: string
  /** The link's title. */
  title: string
  /** A line under it. */
  description?: string
  children?: ReactNode
}

export function NavigationMenuLink({ href, title, description, className, ...rest }: NavigationMenuLinkProps) {
  return (
    <a data-ds="navigation-menu-link" href={href} className={cn('flex flex-col gap-1 rounded-ds-sm p-3 -outline-offset-2 transition-[background-color] duration-160 ease-standard hover:bg-action-secondary focus-visible:bg-action-secondary', className)} {...rest}>
      <span className="type-ui-strong text-fg">{title}</span>
      {description && <span className="type-caption text-fg-muted">{description}</span>}
    </a>
  )
}

export default NavigationMenuLink
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
elements/components/ui/navigation-menu.ts
import { html } from 'lit'
import { DsElement, define, tagName } from '@/elements/lib/element'
import styles from 'virtual:tw'

// NavigationMenu.tsx as <spyglass-navigation-menu>: a site's top navigation, a row of triggers and links in DM Sans
// Medium (<spyglass-navigation-menu-item>), each trigger opening a panel of links in the card's #262626 fill. Under a
// pointer a panel opens after a short wait and closes a moment after the pointer leaves both; while one is open,
// pointing at another trigger switches at once. A click toggles it; Enter, Space or Down opens it at once with focus on
// its first link; Left and Right move along the row; Escape closes it.

/** What a <spyglass-navigation-menu-item> offers its menu. */
export interface NavigationMenuEntry extends HTMLElement { focusTrigger(): void }

/**
 * @summary A site's top navigation, with panels of links.
 * @slot - The entries: <spyglass-navigation-menu-item>.
 */
export class NavigationMenu extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = { label: {} }

	/** The navigation's name for assistive tech. */
	label = 'Main'
	/** The open entry, if any. */
	active: Element | null = null

	entries() {
		return [...this.querySelectorAll<NavigationMenuEntry>(tagName('navigation-menu-item'))]
	}
	setActive(item: Element | null) {
		if (this.active === item) return
		this.active = item
		for (const e of this.entries()) (e as unknown as { requestUpdate(): void }).requestUpdate?.()
	}
	move(from: Element, step: number) {
		const list = this.entries()
		const at = list.indexOf(from as NavigationMenuEntry)
		list[(at + step + list.length) % list.length]?.focusTrigger()
	}

	render() {
		return html`<nav data-ds="navigation-menu" aria-label=${this.label}><ul class="flex flex-wrap items-center gap-1"><slot></slot></ul></nav>`
	}
}

define('navigation-menu', NavigationMenu)
elements/components/ui/navigation-menu-item.ts
import { html, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { ChevronDown } from 'lucide'
import { DsElement, define, tagName } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { firstFocusable, PopoverController, popoverStyles, within } from '@/elements/lib/popover'
import type { NavigationMenu } from '@/elements/components/ui/navigation-menu'
import styles from 'virtual:tw'

// NavigationMenuItem.tsx as <spyglass-navigation-menu-item>: one entry of a navigation menu: with content, a trigger
// and its panel of links (<spyglass-navigation-menu-link>); with `href` and no content, a plain link in the row
// (`active` for the page you are on). The open trigger takes the #262626 fill.
const WAIT = 80 // the site's menu intent (--dur-menu-intent)
const GRACE = 240 // the site's menu grace (--dur-menu-grace)
const ROW = 'inline-flex h-control-md cursor-pointer items-center gap-1.5 rounded-control px-4 type-ui-strong -outline-offset-2 transition-[background-color,color] duration-160 ease-standard max-md:h-control-touch'

/**
 * @summary One entry of a navigation menu: a trigger with a panel, or a link.
 * @slot - The panel's links.
 */
export class NavigationMenuItem extends DsElement {
	static styles = [DsElement.styles, popoverStyles, styles]
	static properties = { label: {}, href: {}, active: { type: Boolean }, width: {} }

	/** The trigger's or the link's text. */
	label = ''
	/** A plain link in the row, when it has no panel. */
	href?: string
	/** The page you are on (a plain link). */
	active = false
	/** The panel's width (a CSS length). */
	width = '400px'
	private timer?: ReturnType<typeof setTimeout>
	private hovered = 0
	private wasOpen = false
	private pop = new PopoverController(this, {
		side: 'bottom',
		align: 'start',
		gap: 8,
		anchor: () => this.renderRoot.querySelector<HTMLElement>('[data-nav-trigger]'),
		panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
	})

	private get nav() {
		const n = this.closest(tagName('navigation-menu')) as NavigationMenu | null
		return n && typeof n.setActive === 'function' ? n : null
	}
	/** Focuses the trigger or the link (the menu's arrows). */
	focusTrigger() {
		this.renderRoot.querySelector<HTMLElement>('[data-nav-trigger]')?.focus()
	}
	disconnectedCallback() {
		super.disconnectedCallback()
		clearTimeout(this.timer)
	}

	private move = (event: KeyboardEvent) => {
		if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return false
		event.preventDefault()
		this.nav?.move(this, event.key === 'ArrowRight' ? 1 : -1)
		return true
	}
	private async openAt(keyboard: boolean, focus: boolean) {
		clearTimeout(this.timer)
		await this.pop.show({ keyboard })
		if (!focus) return
		const panel = this.renderRoot.querySelector<HTMLElement>('.ds-pop')
		;(firstFocusable(panel) ?? panel)?.focus({ preventScroll: true })
	}
	private enter = (event: PointerEvent) => {
		if (event.pointerType !== 'mouse') return
		clearTimeout(this.timer)
		if (this.pop.open) return
		// Another panel open: switch at once.
		const nav = this.nav
		if (nav?.active && nav.active !== this) {
			this.hovered = Date.now()
			return void this.openAt(true, false)
		}
		// ds-latency: the wait keeps a passing pointer from opening it.
		this.timer = setTimeout(() => {
			this.hovered = Date.now()
			void this.openAt(false, false)
		}, WAIT)
	}
	private leave = (event: PointerEvent) => {
		if (event.pointerType !== 'mouse') return
		clearTimeout(this.timer)
		// ds-latency: a grace to cross the gap into the panel.
		this.timer = setTimeout(() => this.pop.hide(), GRACE)
	}
	// A click toggles it; a click right after the pointer opened it keeps it open.
	private onClick = (event: MouseEvent) => {
		const keyboard = event.detail === 0
		if (this.pop.open) {
			if (!keyboard && Date.now() - this.hovered < 400) return
			this.pop.hide(keyboard, keyboard)
		} else void this.openAt(keyboard, keyboard)
	}
	private onKey = (event: KeyboardEvent) => {
		if (this.move(event)) return
		if (event.key === 'ArrowDown') {
			event.preventDefault()
			void this.openAt(true, true)
		}
	}
	private onBlur = (event: FocusEvent) => {
		const next = event.relatedTarget as Node | null
		if (next && !within(this.renderRoot.querySelector('.ds-pop'), next) && !within(this.renderRoot.querySelector('[data-nav-trigger]'), next)) this.pop.hide()
	}

	protected updated(changed: PropertyValues<this>) {
		super.updated(changed)
		const nav = this.nav
		if (!nav) return
		if (this.pop.open !== this.wasOpen) {
			this.wasOpen = this.pop.open
			if (this.pop.open) nav.setActive(this)
			else if (nav.active === this) nav.setActive(null)
		}
		if (nav.active !== this && this.pop.open) this.pop.hide(false, true)
	}

	render() {
		if (!this.hasSlot()) {
			return html`<li data-ds="navigation-menu-item" class="flex"><a data-nav-trigger href=${ifDefined(this.href)} aria-current=${ifDefined(this.active ? 'page' : undefined)} class=${`${ROW} ${this.active ? 'text-fg' : 'text-fg-soft hover:bg-action-ghost-hover hover:text-fg'}`} @keydown=${this.move}>${this.label}</a></li>`
		}
		const panel = this.pop.rendered
			? html`<div data-ds="navigation-menu-item" popover="manual" class="ds-pop p-2 fade-y" aria-label=${this.label} tabindex="-1" data-side=${this.pop.pos.side} ?data-instant=${this.pop.instant} ?data-placed=${this.pop.pos.placed} style=${this.pop.style(`width: ${this.width}`)} @pointerenter=${this.enter} @pointerleave=${this.leave} @focusout=${this.pop.onFocusOut}><slot></slot></div>`
			: nothing
		return html`<li data-ds="navigation-menu-item" class="flex" @pointerenter=${this.enter} @pointerleave=${this.leave}><button data-nav-trigger type="button" aria-expanded=${String(this.pop.open)} class=${`${ROW} text-fg-soft hover:not-aria-expanded:bg-action-ghost-hover hover:text-fg aria-expanded:bg-action-secondary aria-expanded:text-fg`} @click=${this.onClick} @keydown=${this.onKey} @blur=${this.onBlur}>${this.label}${icon(ChevronDown, 'chevron-down', { size: 16, strokeWidth: 1.5, class: 'shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}</button>${panel}</li>`
	}
}

define('navigation-menu-item', NavigationMenuItem)
elements/components/ui/navigation-menu-link.ts
import { html, nothing } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import styles from 'virtual:tw'

// NavigationMenuLink.tsx as <spyglass-navigation-menu-link>: a link in a navigation menu's panel: its title (`heading`,
// React's `title`) in DM Sans Medium and a muted line under it, the small corner; the link under the pointer or focus
// takes the #262626 fill.

/**
 * @summary A link with a line under it, in a navigation menu's panel.
 */
export class NavigationMenuLink extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('a'))
	static properties = { href: {}, heading: {}, description: {} }

	href?: string
	/** The link's title (React's `title`). */
	heading = ''
	/** A line under it. */
	description?: string

	render() {
		return html`<a data-ds="navigation-menu-link" href=${ifDefined(this.href)} class="flex flex-col gap-1 rounded-ds-sm p-3 -outline-offset-2 transition-[background-color] duration-160 ease-standard hover:bg-action-secondary focus-visible:bg-action-secondary"><span class="type-ui-strong text-fg">${this.heading}</span>${this.description ? html`<span class="type-caption text-fg-muted">${this.description}</span>` : nothing}</a>`
	}
}

define('navigation-menu-link', NavigationMenuLink)

Reference: Derived from the brand guidelines (no navigation menu in the brand assets): Black ground, DM Sans Medium for entries, the plan card's #262626 fill for panels, the neutral steps for fills.