{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "section-rail",
  "type": "registry:ui",
  "title": "Section Rail",
  "description": "A responsive section navigation rail with scroll tracking, smooth anchor jumps, link mode, and optional rich hover previews.",
  "author": "Aditya Ojha <https://akoder.xyz>",
  "categories": [
    "navigation",
    "scroll",
    "anchors",
    "accessibility"
  ],
  "dependencies": [
    "radix-ui",
    "motion"
  ],
  "registryDependencies": [
    "tooltip"
  ],
  "meta": {
    "docs": "https://akoder.xyz/components/section-rail",
    "source": "https://github.com/AdityaKodez/adityaojha/blob/main/components/section-rail.tsx"
  },
  "files": [
    {
      "path": "components/section-rail.tsx",
      "content": "\"use client\";\n\nimport Link from \"next/link\";\nimport { motion, useSpring } from \"motion/react\";\nimport {\n  useEffect,\n  useMemo,\n  useState,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\n\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipTrigger,\n} from \"@/components/ui/tooltip\";\nimport { cn } from \"@/lib/utils\";\n\nexport type RailItem = {\n  id: string;\n  label: string;\n  /** With an href the item navigates to another page instead of scrolling. */\n  href?: string;\n  /** Rich hover preview; without it the tooltip shows the plain label. */\n  card?: {\n    title: string;\n    description?: string;\n    icon?: ReactNode;\n  };\n};\n\nexport type SectionRailProps = {\n  items: RailItem[];\n  /** Pin the active item (link rails). Omit it to follow scroll position. */\n  activeId?: string;\n  /** Use contained mode when the rail belongs to an embedded scroll area. */\n  variant?: \"viewport\" | \"contained\";\n  /** Scroll area that owns the target sections in contained mode. */\n  scrollRootRef?: RefObject<HTMLElement | null>;\n  /** Optional callback fired when a section rail item is clicked. */\n  onSectionClick?: (targetSectionId: string, currentSectionId?: string) => void;\n  className?: string;\n};\n\nconst WAVE_SCALES = [1, 44 / 56, 36 / 56, 28 / 56];\n\nfunction RailDash({ scale, isActive }: { scale: number; isActive: boolean }) {\n  const scaleX = useSpring(scale, { stiffness: 260, damping: 30, mass: 0.8 });\n\n  useEffect(() => {\n    const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const updateScale = () => {\n      if (query.matches) {\n        scaleX.jump(scale);\n      } else {\n        scaleX.set(scale);\n      }\n    };\n    updateScale();\n    query.addEventListener(\"change\", updateScale);\n    return () => query.removeEventListener(\"change\", updateScale);\n  }, [scale, scaleX]);\n\n  return (\n    <motion.span\n      aria-hidden\n      className={cn(\n        \"block h-0.5 w-full origin-left rounded-full transition-colors duration-300 ease-out motion-reduce:transition-none\",\n        isActive\n          ? \"bg-foreground\"\n          : \"bg-muted-foreground/40 group-hover:bg-muted-foreground\"\n      )}\n      style={{ scaleX }}\n    />\n  );\n}\n\nexport function SectionRail({\n  items,\n  activeId,\n  variant = \"viewport\",\n  scrollRootRef,\n  onSectionClick,\n  className,\n}: SectionRailProps) {\n  const [tracked, setTracked] = useState(() => items[0]?.id ?? \"\");\n  const active = activeId ?? tracked;\n\n  const scrollIds = useMemo(\n    () => items.filter((item) => !item.href).map((item) => item.id),\n    [items]\n  );\n\n  useEffect(() => {\n    if (scrollIds.length === 0) return;\n\n    const startTracking = () => {\n      const scrollRoot = scrollRootRef?.current ?? null;\n      const findTarget = (id: string) => {\n        const target = document.getElementById(id);\n        if (!target) return null;\n        return scrollRoot && !scrollRoot.contains(target) ? null : target;\n      };\n\n      // Track every target currently inside the center band and keep the one\n      // closest to its midpoint active: deterministic even when several small\n      // targets intersect at once.\n      const visible = new Map<string, number>();\n      const pickClosest = () => {\n        const rootTop = scrollRoot?.getBoundingClientRect().top ?? 0;\n        const rootHeight = scrollRoot?.clientHeight ?? window.innerHeight;\n        const bandCenter = rootTop + rootHeight * 0.4;\n        let best: string | null = null;\n        let bestDistance = Number.POSITIVE_INFINITY;\n        for (const [id, top] of visible) {\n          const distance = Math.abs(top - bandCenter);\n          if (distance < bestDistance) {\n            best = id;\n            bestDistance = distance;\n          }\n        }\n        if (best) setTracked(best);\n      };\n\n      const observer = new IntersectionObserver(\n        (entries) => {\n          for (const entry of entries) {\n            if (entry.isIntersecting) {\n              visible.set(entry.target.id, entry.boundingClientRect.top);\n            } else {\n              visible.delete(entry.target.id);\n            }\n          }\n          pickClosest();\n        },\n        {\n          root: scrollRoot,\n          rootMargin: \"-25% 0px -45% 0px\",\n          threshold: 0,\n        }\n      );\n\n      for (const id of scrollIds) {\n        const element = findTarget(id);\n        if (element) observer.observe(element);\n      }\n\n      // The last section can be too short to cross the center band at max scroll.\n      const onScroll = () => {\n        const remaining = scrollRoot\n          ? scrollRoot.scrollHeight - scrollRoot.scrollTop - scrollRoot.clientHeight\n          : document.documentElement.scrollHeight -\n            window.scrollY -\n            window.innerHeight;\n        if (remaining < 4) setTracked(scrollIds[scrollIds.length - 1]);\n      };\n      const scrollSource: Window | HTMLElement = scrollRoot ?? window;\n      scrollSource.addEventListener(\"scroll\", onScroll, { passive: true });\n\n      return () => {\n        observer.disconnect();\n        scrollSource.removeEventListener(\"scroll\", onScroll);\n      };\n    };\n\n    // Contained rails are always visible and always track. The viewport rail\n    // is display:none below the lg breakpoint, so its observer and scroll\n    // listener stay parked until the breakpoint shows the rail.\n    if (variant !== \"viewport\") return startTracking();\n\n    const query = window.matchMedia(\"(min-width: 64rem)\");\n    let teardown: (() => void) | null = null;\n    const syncTracking = () => {\n      if (query.matches && !teardown) {\n        teardown = startTracking();\n      } else if (!query.matches && teardown) {\n        teardown();\n        teardown = null;\n      }\n    };\n    syncTracking();\n    query.addEventListener(\"change\", syncTracking);\n\n    return () => {\n      query.removeEventListener(\"change\", syncTracking);\n      teardown?.();\n    };\n  }, [scrollIds, scrollRootRef, variant]);\n\n  const scrollTo = (id: string) => {\n    const scrollRoot = scrollRootRef?.current ?? null;\n    const element = document.getElementById(id);\n    if (!element || (scrollRoot && !scrollRoot.contains(element))) return;\n\n    onSectionClick?.(id, active);\n\n    setTracked(id);\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const behavior = reduced ? \"auto\" : \"smooth\";\n\n    if (scrollRoot) {\n      const rootRect = scrollRoot.getBoundingClientRect();\n      const targetRect = element.getBoundingClientRect();\n      scrollRoot.scrollTo({\n        top: scrollRoot.scrollTop + targetRect.top - rootRect.top,\n        behavior,\n      });\n      return;\n    }\n\n    element.scrollIntoView({ behavior, block: \"start\" });\n  };\n\n  const foundActiveIndex = items.findIndex((item) => item.id === active);\n  const activeIndex = foundActiveIndex === -1 ? 0 : foundActiveIndex;\n\n  return (\n    <nav\n      aria-label=\"Sections\"\n      className={cn(\n        \"top-1/2 left-0 z-30 -translate-y-1/2 flex-col items-start gap-2\",\n        variant === \"contained\" ? \"absolute flex\" : \"fixed hidden lg:flex\",\n        className\n      )}\n    >\n      <div\n        aria-hidden\n        className=\"absolute inset-y-1 left-0 border-l border-dashed border-border/60\"\n      />\n      {items.map((item, index) => {\n        const isActive = active === item.id;\n        const distanceFromActive = Math.abs(activeIndex - index);\n        const scale =\n          WAVE_SCALES[Math.min(distanceFromActive, WAVE_SCALES.length - 1)];\n        // The dash stays 2px tall; a 14px row around it (offset by -my-1.5 so\n        // the visible gap is unchanged) is what you actually click.\n        const rowClass = cn(\n          \"group -my-1.5 flex w-14 cursor-pointer items-center py-1.5\",\n          \"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\"\n        );\n        return (\n          <Tooltip key={item.id}>\n            <TooltipTrigger asChild>\n              {item.href ? (\n                <Link\n                  href={item.href}\n                  aria-label={item.label}\n                  aria-current={isActive ? \"page\" : undefined}\n                  className={rowClass}\n                >\n                  <RailDash scale={scale} isActive={isActive} />\n                </Link>\n              ) : (\n                <button\n                  type=\"button\"\n                  aria-label={item.label}\n                  aria-current={isActive ? \"location\" : undefined}\n                  onClick={() => scrollTo(item.id)}\n                  className={rowClass}\n                >\n                  <RailDash scale={scale} isActive={isActive} />\n                </button>\n              )}\n            </TooltipTrigger>\n            <TooltipContent\n              side=\"right\"\n              sideOffset={10}\n              hideArrow={Boolean(item.card)}\n              className={cn(\n                item.card &&\n                  \"block w-60 rounded-xl bg-card p-3 text-card-foreground ring-1 ring-inset ring-foreground/10\"\n              )}\n            >\n              {item.card ? (\n                <div className=\"text-left\">\n                  <div className=\"flex items-center gap-1\">\n                    {item.card.icon ? (\n                      <span className=\"flex size-7 shrink-0 items-center justify-center rounded-sm bg-background text-muted-foreground ring-1 ring-inset ring-muted-foreground/10\">\n                        {item.card.icon}\n                      </span>\n                    ) : null}\n                    <p className=\"text-sm font-medium leading-snug\">\n                      {item.card.title}\n                    </p>\n                  </div>\n                  {item.card.description ? (\n                    <p className=\"mt-2 line-clamp-3 text-sm leading-relaxed text-muted-foreground\">\n                      {item.card.description}\n                    </p>\n                  ) : null}\n                </div>\n              ) : (\n                <p>{item.label}</p>\n              )}\n            </TooltipContent>\n          </Tooltip>\n        );\n      })}\n    </nav>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "## Installation\n\n```bash\nnpx shadcn@latest add @akoder/section-rail\n```\n\n## Usage\n\n```tsx\nimport { SectionRail } from \"@/components/section-rail\";\n\nconst items = [\n  { id: \"about\", label: \"about\" },\n  { id: \"projects\", label: \"projects\" },\n  { id: \"contact\", label: \"contact\" },\n];\n\nexport function Page() {\n  return (\n    <>\n      <SectionRail items={items} />\n      <main>\n        {items.map((item) => (\n          <section key={item.id} id={item.id}>\n            <h2>{item.label}</h2>\n          </section>\n        ))}\n      </main>\n    </>\n  );\n}\n```"
}