Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

13.5 KB
Raw Blame
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  SidebarGroup,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  useSidebar,
} from '@spree/dashboard-ui'
import { Link, useRouterState } from '@tanstack/react-router'
import type { LucideIcon } from 'lucide-react'
import { type ComponentType, useCallback, useEffect, useRef, useState } from 'react'
import { isPathWithin } from '../lib/nav-registry'
import type { ActionName, SubjectName } from '../lib/permissions'

export type NavItem = {
  title: string
  url: string
  icon: LucideIcon
  /** CanCanCan subject required to see this item. If omitted, item is always visible. */
  subject?: SubjectName
  /** Action checked against `subject`. Defaults to `'read'`. */
  action?: ActionName
  /** Component rendered after the label (e.g. a count badge). May return null. */
  badge?: ComponentType
  items?: {
    title: string
    url: string
    subject?: SubjectName
    action?: ActionName
    /** Component rendered after the label, same contract as the parent's. */
    badge?: ComponentType
  }[]
}

export function NavIcon({ icon: Icon, isActive }: { icon: NavItem['icon']; isActive?: boolean }) {
  return (
    <span
      className={
        'inline-flex shrink-0 items-center justify-center rounded-lg p-[0.2rem] transition-colors duration-100 ' +
        (isActive ? 'text-foreground' : 'group-hover/menu-button:text-foreground')
      }
    >
      <Icon size={16} strokeWidth={2} />
    </span>
  )
}

/** Grace period between leaving the trigger/menu and the menu closing. */
const HOVER_CLOSE_DELAY_MS = 150

/**
 * Which collapsed-nav menu is open, shared across the whole rail.
 *
 * One value rather than per-item state, so the menus are mutually exclusive by
 * construction: hovering a neighbour replaces the open key instantly instead of
 * leaving the previous menu on screen for the close delay, which read as two
 * panels flickering over each other.
 */
interface HoverMenuController {
  openKey: string | null
  /** Opens `key` immediately, replacing whatever was open. */
  open: (key: string) => void
  /** Schedules a close, but only if `key` is still the open one. */
  closeSoon: (key: string) => void
  /** Closes right away — for explicit dismissals (Escape, selecting an item). */
  closeNow: () => void
  /** Cancels a pending close (pointer came back). */
  cancelClose: () => void
}

function useHoverMenuController(): HoverMenuController {
  const [openKey, setOpenKey] = useState<string | null>(null)
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)

  const cancelClose = useCallback(() => {
    if (closeTimer.current) {
      clearTimeout(closeTimer.current)
      closeTimer.current = null
    }
  }, [])

  const open = useCallback(
    (key: string) => {
      cancelClose()
      setOpenKey(key)
    },
    [cancelClose],
  )

  const closeSoon = useCallback(
    (key: string) => {
      cancelClose()
      closeTimer.current = setTimeout(() => {
        // Guarded so a late timer from the menu the pointer just left can't
        // close the one it has since moved to.
        setOpenKey((current) => (current === key ? null : current))
      }, HOVER_CLOSE_DELAY_MS)
    },
    [cancelClose],
  )

  const closeNow = useCallback(() => {
    cancelClose()
    setOpenKey(null)
  }, [cancelClose])

  useEffect(
    () => () => {
      if (closeTimer.current) clearTimeout(closeTimer.current)
    },
    [],
  )

  return { openKey, open, closeSoon, closeNow, cancelClose }
}

function CollapsedDropdown({
  item,
  controller,
  children,
}: {
  item: NavItem
  controller: HoverMenuController
  children: React.ReactNode
}) {
  const key = item.title
  const open = controller.openKey === key
  const openNow = () => controller.open(key)
  const closeSoon = () => controller.closeSoon(key)

  return (
    <DropdownMenu
      open={open}
      // Base UI's own open/close signals (Escape, outside click, selecting an
      // item) are explicit dismissals, so they close immediately — the grace
      // period exists only for the pointer leaving on its way somewhere.
      onOpenChange={(next) => {
        if (next) controller.open(key)
        else controller.closeNow()
      }}
    >
      {/* `nativeButton={false}` because the trigger renders a `<div>` wrapping
          a `SidebarMenuButton` (whose inner element is a `<Link>` → `<a>`),
          not a `<button>`. The wrapper exists to attach `onMouseLeave` for
          the hover-out close, so we can't drop it; instead we tell Base UI
          we're rendering a non-button trigger and let it apply menu role +
          keyboard semantics. */}
      <DropdownMenuTrigger asChild nativeButton={false} onMouseEnter={openNow}>
        {/* biome-ignore lint/a11y/noStaticElementInteractions: hover trigger for collapsed nav */}
        <div onMouseLeave={closeSoon}>{children}</div>
      </DropdownMenuTrigger>
      {/* `sideOffset={0}` plus inline-start *padding* closes the dead zone the
          pointer used to cross: an offset (or a margin) puts those pixels
          outside both elements, so travelling to the menu reads as leaving
          both. Padding keeps the gap inside the panel's own hover area, so the
          visual inset costs nothing in reachability. */}
      <DropdownMenuContent
        side="right"
        align="start"
        sideOffset={0}
        className="ps-1"
        onMouseLeave={closeSoon}
        onMouseEnter={openNow}
      >
        {/* The section itself leads the list. Collapsed, the icon is the only
            route to it, and hovering opens this panel instead — so without an
            entry here "Products" is reachable by a click most people won't
            guess at, and not at all by keyboard. */}
        <DropdownMenuItem asChild>
          <Link to={item.url} className="no-underline font-medium">
            {item.title}
          </Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        {item.items!.map((subItem) => (
          <DropdownMenuItem key={subItem.title} asChild>
            <Link to={subItem.url} className="no-underline">
              {subItem.title}
              {subItem.badge && (
                <span className="ms-auto shrink-0 ps-3">
                  <subItem.badge />
                </span>
              )}
            </Link>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function NavItemContent({
  item,
  currentPath,
  isCollapsed,
  isMobile,
  hoverMenu,
}: {
  item: NavItem
  currentPath: string
  isCollapsed: boolean
  isMobile: boolean
  hoverMenu: HoverMenuController
}) {
  const isExactActive = currentPath === item.url || currentPath === `${item.url}/`
  // Only prefix-match for items with a sub-path after the storeId segment (e.g. /store_abc/orders)
  const hasSubPath = item.url.split('/').filter(Boolean).length > 1
  const isActive = isExactActive || (hasSubPath && isPathWithin(currentPath, item.url))
  const hasActiveChild = item.items?.some((sub) => isPathWithin(currentPath, sub.url))
  // Desktop reveals children on hover or when the section is active. Touch has
  // no hover, and the drawer closes on navigation, so a collapsed child would
  // take three taps to reach — show every child up front instead.
  const showSubmenu = isMobile || isActive || hasActiveChild
  const itemIsActive = isActive || !!hasActiveChild

  const button = (
    <SidebarMenuButton
      tooltip={!item.items || !isCollapsed ? item.title : undefined}
      asChild
      isActive={itemIsActive}
    >
      {/* `aria-label` because the visible label is hidden in collapsed icon
          mode, which would otherwise leave the link with no accessible name —
          an icon-only link is unusable to a screen reader. */}
      <Link to={item.url} aria-label={isCollapsed ? item.title : undefined}>
        <NavIcon icon={item.icon} isActive={itemIsActive} />
        {/* Explicitly hide in collapsed icon mode: a trailing badge span would
            otherwise steal the `span:last-child` position the base button style
            relies on to hide the label, leaving the title visible. */}
        <span className="group-data-[collapsible=icon]:hidden">{item.title}</span>
        {/* `shrink-0` so the badge keeps its shape while the sidebar width
            animates — a squeezed badge deforms before the label clips. */}
        {item.badge && (
          <span className="ml-auto shrink-0 group-data-[collapsible=icon]:hidden">
            <item.badge />
          </span>
        )}
      </Link>
    </SidebarMenuButton>
  )

  return (
    // Hovering an item with no submenu dismisses whatever menu is open: the
    // pointer has clearly moved on, and leaving a neighbour's panel hanging
    // over the rail reads as a stuck popup.
    <SidebarMenuItem onMouseEnter={isCollapsed && !item.items ? hoverMenu.closeNow : undefined}>
      {isCollapsed && item.items ? (
        <CollapsedDropdown item={item} controller={hoverMenu}>
          {button}
        </CollapsedDropdown>
      ) : (
        button
      )}
      {item.items && showSubmenu && (
        <SidebarMenuSub>
          {item.items.map((subItem) => {
            const subActive = isPathWithin(currentPath, subItem.url)
            return (
              <SidebarMenuSubItem key={subItem.title}>
                <SidebarMenuSubButton asChild isActive={subActive}>
                  <Link to={subItem.url}>
                    <span className="truncate">{subItem.title}</span>
                    {subItem.badge && (
                      <span className="ml-auto shrink-0">
                        <subItem.badge />
                      </span>
                    )}
                  </Link>
                </SidebarMenuSubButton>
              </SidebarMenuSubItem>
            )
          })}
        </SidebarMenuSub>
      )}
    </SidebarMenuItem>
  )
}

// Close the drawer as the link is tapped. Done here rather than in an effect
// watching the path: this tree renders *inside* the Sheet, so it remounts on
// every open and an effect could not tell "just opened" from "just navigated".
function useCloseDrawerOnLinkTap() {
  const { isMobile, setOpenMobile } = useSidebar()
  return useCallback(
    (event: React.MouseEvent) => {
      if (isMobile && (event.target as HTMLElement).closest('a')) setOpenMobile(false)
    },
    [isMobile, setOpenMobile],
  )
}

export function NavMain({ items }: { items: NavItem[] }) {
  const routerState = useRouterState()
  const currentPath = routerState.location.pathname
  const { state, isMobile } = useSidebar()
  const isCollapsed = state === 'collapsed'
  const handleLinkTap = useCloseDrawerOnLinkTap()
  // One controller for the whole rail so only a single hover menu is ever open.
  const hoverMenu = useHoverMenuController()

  // Expanding the rail unmounts the dropdowns but leaves `openKey` set, so
  // collapsing again would restore a menu the user never opened.
  const { closeNow } = hoverMenu
  useEffect(() => {
    if (!isCollapsed) closeNow()
  }, [isCollapsed, closeNow])

  return (
    // The close handler sits on the list rather than each `<Link>`: those links
    // are rendered through nested `asChild` Slots (Tooltip → SidebarMenuButton),
    // which clone their own `onClick` over anything the child declares. A
    // bubble-phase listener here sees the tap regardless.
    // biome-ignore lint/a11y/noStaticElementInteractions: delegated link taps only
    // biome-ignore lint/a11y/useKeyWithClickEvents: links keep their own keyboard behaviour
    <div onClick={handleLinkTap} className="contents">
      <SidebarGroup>
        <SidebarMenu>
          {items.map((item) => (
            <NavItemContent
              key={item.title}
              item={item}
              currentPath={currentPath}
              isCollapsed={isCollapsed}
              isMobile={isMobile}
              hoverMenu={hoverMenu}
            />
          ))}
        </SidebarMenu>
      </SidebarGroup>
    </div>
  )
}

/** The entries kept apart from the main list — Settings, and anything registered beside it. */
export function NavBottom({ items, className }: { items: NavItem[]; className?: string }) {
  const currentPath = useRouterState().location.pathname
  const isCollapsed = useSidebar().state === 'collapsed'
  const handleLinkTap = useCloseDrawerOnLinkTap()

  if (items.length === 0) return null

  return (
    // biome-ignore lint/a11y/noStaticElementInteractions: delegated link taps only
    // biome-ignore lint/a11y/useKeyWithClickEvents: links keep their own keyboard behaviour
    <div onClick={handleLinkTap} className="contents">
      <SidebarGroup className={className}>
        <SidebarMenu>
          {items.map((item) => {
            const isActive =
              currentPath === item.url || (item.url !== '/' && isPathWithin(currentPath, item.url))

            return (
              <SidebarMenuItem key={item.title}>
                <SidebarMenuButton tooltip={item.title} asChild isActive={isActive}>
                  {/* `aria-label` for the same reason as the main nav: collapsed
                      mode hides the label, and Settings lives here — the one
                      place the rail is collapsed by default. */}
                  <Link to={item.url} aria-label={isCollapsed ? item.title : undefined}>
                    <NavIcon icon={item.icon} isActive={isActive} />
                    <span>{item.title}</span>
                  </Link>
                </SidebarMenuButton>
              </SidebarMenuItem>
            )
          })}
        </SidebarMenu>
      </SidebarGroup>
    </div>
  )
}