{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"overflow-tabs","type":"registry:component","title":"Overflow tabs","description":"Scrolls a long row of tabs, fading whichever edge still hides more.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/overflow-tabs.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Tab = { id: string; label: string; content: React.ReactNode };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst UNDERLINE = { type: \"spring\", visualDuration: 0.25, bounce: 0 } as const;\nconst INSTANT = { duration: 0 } as const;\n// The fade grows with distance from the edge and tops out here, so it\n// appears gradually as you scroll instead of switching on.\nconst FADE = 48;\n// A page leaves one fade's worth of overlap, so the tab that was half hidden\n// under the fade lands fully in view instead of scrolling past unseen.\nconst PAGE_OVERLAP = FADE;\n// Time constant of the wheel glide in ms: each notch settles in about 250ms,\n// and notches that land mid-glide add to the target instead of restarting.\nconst GLIDE = 60;\n// Mouse wheels send whole notches (around 100px); trackpads send a stream of\n// small deltas that are already smooth and must stay 1:1 with the fingers.\nconst NOTCH = 50;\n\nconst panel = {\n  enter: (reduce: boolean) => ({\n    opacity: 0,\n    y: reduce ? 0 : 4,\n    filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n  }),\n  center: {\n    opacity: 1,\n    y: 0,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.22, ease: EASE_OUT },\n  },\n  // Softer and faster than the entrance, so the old panel is gone before the\n  // new one draws the eye.\n  exit: {\n    opacity: 0,\n    y: 0,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.12, ease: EASE_OUT },\n  },\n};\n\nexport function OverflowTabs({\n  tabs,\n  value,\n  onChange,\n  label,\n  className,\n}: {\n  tabs: readonly Tab[];\n  value: string;\n  onChange: (id: string) => void;\n  label: string;\n  className?: string;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const base = useId();\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const tabRefs = useRef(new Map<string, HTMLButtonElement>());\n  const [edges, setEdges] = useState({ start: false, end: false });\n  const [hovering, setHovering] = useState(false);\n  // Lets the arrows and keyboard take over from a wheel glide mid-flight.\n  const stopGlide = useRef(() => {});\n\n  // Fade widths live in motion values, so scrolling never re-renders.\n  const fadeStart = useMotionValue(0);\n  const fadeEnd = useMotionValue(0);\n  const mask = useMotionTemplate`linear-gradient(to right, transparent, #000 ${fadeStart}px, #000 calc(100% - ${fadeEnd}px), transparent)`;\n\n  useEffect(() => {\n    const el = scrollerRef.current;\n    if (!el) return;\n\n    const update = () => {\n      const max = el.scrollWidth - el.clientWidth;\n      // Clamped at both ends: overscroll on touch can report past the range.\n      const before = Math.min(Math.max(el.scrollLeft, 0), max);\n      const after = max - before;\n      fadeStart.set(Math.min(before, FADE));\n      fadeEnd.set(Math.min(after, FADE));\n      // One pixel of slack, since zoomed layouts rarely land exactly on 0.\n      const start = before > 1;\n      const end = after > 1;\n      setEdges((e) => (e.start === start && e.end === end ? e : { start, end }));\n    };\n\n    // Tracked separately from scrollLeft, which some browsers round to whole\n    // pixels and would stall the last few frames of the glide.\n    let target = 0;\n    let position = 0;\n    let frame = 0;\n    let last = 0;\n\n    const glide = (now: number) => {\n      const t = 1 - Math.exp(-(now - last) / GLIDE);\n      last = now;\n      position += (target - position) * t;\n      if (Math.abs(target - position) < 0.5) position = target;\n      el.scrollLeft = position;\n      frame = position === target ? 0 : requestAnimationFrame(glide);\n    };\n    const stop = () => {\n      cancelAnimationFrame(frame);\n      frame = 0;\n    };\n    stopGlide.current = stop;\n\n    // Shift + wheel and a plain vertical wheel both scroll the strip\n    // sideways. A vertical wheel only does so while there's room, so the page\n    // takes over again at either end.\n    const wheel = (e: WheelEvent) => {\n      if (e.ctrlKey) return;\n      const vertical = !e.shiftKey && Math.abs(e.deltaY) > Math.abs(e.deltaX);\n      const delta =\n        Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;\n      const precise = e.deltaMode === 0 && Math.abs(delta) < NOTCH;\n      // A trackpad swiping sideways is already smooth; leave it native.\n      if (precise && !vertical) return;\n\n      const max = el.scrollWidth - el.clientWidth;\n      // Picks up from wherever the strip is when nothing is gliding, so a\n      // tab click or scrollbar drag in between is respected.\n      if (!frame) target = position = el.scrollLeft;\n      if ((delta < 0 && target <= 0) || (delta > 0 && target >= max - 1)) {\n        return;\n      }\n      e.preventDefault();\n      const px = e.deltaMode === 1 ? delta * 16 : delta;\n      target = Math.min(Math.max(target + px, 0), max);\n\n      if (precise || reduce) {\n        stop();\n        el.scrollLeft = position = target;\n        return;\n      }\n      if (!frame) {\n        last = performance.now();\n        frame = requestAnimationFrame(glide);\n      }\n    };\n\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    if (el.firstElementChild) observer.observe(el.firstElementChild);\n    el.addEventListener(\"scroll\", update, { passive: true });\n    el.addEventListener(\"wheel\", wheel, { passive: false });\n    return () => {\n      stop();\n      observer.disconnect();\n      el.removeEventListener(\"scroll\", update);\n      el.removeEventListener(\"wheel\", wheel);\n    };\n  }, [fadeStart, fadeEnd, reduce]);\n\n  const index = Math.max(\n    tabs.findIndex((t) => t.id === value),\n    0,\n  );\n  const active = tabs[index];\n\n  const page = (direction: 1 | -1) => {\n    const el = scrollerRef.current;\n    if (!el) return;\n    stopGlide.current();\n    el.scrollBy({\n      left: direction * (el.clientWidth - PAGE_OVERLAP),\n      behavior: reduce ? \"auto\" : \"smooth\",\n    });\n  };\n\n  const tabId = (id: string) => `${base}-tab-${id}`;\n  const panelId = (id: string) => `${base}-panel-${id}`;\n\n  return (\n    <LayoutGroup id={base}>\n      <div className={cn(\"flex min-w-0 flex-col\", className)}>\n        <div\n          className=\"relative\"\n          onPointerEnter={(e) => {\n            if (e.pointerType !== \"touch\") setHovering(true);\n          }}\n          onPointerLeave={() => setHovering(false)}\n        >\n          {/* Outside the scroller, so the baseline spans the full width and\n              never scrolls or fades with the tabs. */}\n          <div aria-hidden className=\"absolute inset-x-0 bottom-0 h-px bg-border\" />\n          <motion.div\n            ref={scrollerRef}\n            layoutScroll\n            style={{ maskImage: mask, WebkitMaskImage: mask }}\n            // scroll-padding keeps keyboard-selected tabs clear of the fades.\n            className=\"scroll-px-12 overflow-x-auto overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n          >\n            <div\n              role=\"tablist\"\n              aria-label={label}\n              className=\"flex w-max gap-0.5 px-0.5\"\n              onKeyDown={(e) => {\n                const target = {\n                  ArrowRight: index + 1,\n                  ArrowLeft: index - 1,\n                  Home: 0,\n                  End: tabs.length - 1,\n                }[e.key];\n                if (target === undefined) return;\n                e.preventDefault();\n                // Automatic activation: arrows select as well as focus.\n                const next = tabs[(target + tabs.length) % tabs.length].id;\n                onChange(next);\n                const el = tabRefs.current.get(next);\n                if (!el) return;\n                // Native focus scrolling jumps; this glides the tab in, and\n                // \"nearest\" leaves it alone when it's already visible.\n                el.focus({ preventScroll: true });\n                stopGlide.current();\n                el.scrollIntoView({\n                  block: \"nearest\",\n                  inline: \"nearest\",\n                  behavior: reduce ? \"auto\" : \"smooth\",\n                });\n              }}\n            >\n              {tabs.map((tab) => {\n                const selected = tab.id === active.id;\n                return (\n                  <button\n                    key={tab.id}\n                    ref={(el) => {\n                      if (el) tabRefs.current.set(tab.id, el);\n                      else tabRefs.current.delete(tab.id);\n                    }}\n                    type=\"button\"\n                    role=\"tab\"\n                    id={tabId(tab.id)}\n                    aria-selected={selected}\n                    aria-controls={selected ? panelId(tab.id) : undefined}\n                    tabIndex={selected ? 0 : -1}\n                    onClick={() => onChange(tab.id)}\n                    className={cn(\n                      \"group relative flex h-11 shrink-0 touch-manipulation items-center rounded-lg px-3 text-sm font-medium whitespace-nowrap text-muted-foreground outline-hidden transition-[color] duration-150 ease-out select-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-4 focus-visible:outline-foreground\",\n                      selected && \"text-foreground\",\n                    )}\n                  >\n                    {/* Only the label presses in. Scaling the whole button\n                        would skew the box Motion measures for the underline. */}\n                    <span className=\"relative transition-[scale] duration-150 ease-out group-active:scale-[0.96] motion-reduce:transition-none\">\n                      {tab.label}\n                    </span>\n                    {selected && (\n                      <motion.span\n                        layoutId=\"underline\"\n                        aria-hidden\n                        // Sits on the baseline so the two read as one line.\n                        className=\"absolute inset-x-1.5 bottom-0 h-0.5 rounded-full bg-foreground\"\n                        transition={reduce ? INSTANT : UNDERLINE}\n                      />\n                    )}\n                  </button>\n                );\n              })}\n            </div>\n          </motion.div>\n\n          <Arrow\n            direction={-1}\n            visible={hovering && edges.start}\n            onPress={() => page(-1)}\n          />\n          <Arrow\n            direction={1}\n            visible={hovering && edges.end}\n            onPress={() => page(1)}\n          />\n        </div>\n\n        {/* Both panels share one grid cell while they cross, so the old one\n            never pushes the new one down. */}\n        <div className=\"grid\">\n          <AnimatePresence initial={false} custom={reduce}>\n            <motion.div\n              key={active.id}\n              role=\"tabpanel\"\n              id={panelId(active.id)}\n              aria-labelledby={tabId(active.id)}\n              tabIndex={0}\n              custom={reduce}\n              variants={panel}\n              initial=\"enter\"\n              animate=\"center\"\n              exit=\"exit\"\n              className=\"col-start-1 row-start-1 rounded-lg px-3 pt-5 pb-1 text-[15px] leading-relaxed text-pretty text-muted-foreground outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground\"\n            >\n              {active.content}\n            </motion.div>\n          </AnimatePresence>\n        </div>\n      </div>\n    </LayoutGroup>\n  );\n}\n\n// Mouse-only shortcuts: keyboard users already page with the arrow keys, so\n// these stay out of the tab order and away from screen readers.\nfunction Arrow({\n  direction,\n  visible,\n  onPress,\n}: {\n  direction: 1 | -1;\n  visible: boolean;\n  onPress: () => void;\n}) {\n  return (\n    <button\n      type=\"button\"\n      tabIndex={-1}\n      aria-hidden\n      // Leaves focus on the active tab, so arrow keys keep working after a\n      // click here.\n      onMouseDown={(e) => e.preventDefault()}\n      onClick={onPress}\n      className={cn(\n        \"absolute top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-full bg-background text-foreground shadow-raised transition-[opacity,scale] ease-[cubic-bezier(0.23,1,0.32,1)] select-none active:scale-[0.96] motion-reduce:transition-[opacity]\",\n        direction < 0 ? \"left-1\" : \"right-1\",\n        // Arrives in 150ms, leaves in 100ms, and stops catching clicks the\n        // moment it starts to go.\n        visible\n          ? \"scale-100 opacity-100 duration-150\"\n          : \"pointer-events-none scale-[0.96] opacity-0 duration-100 motion-reduce:scale-100\",\n      )}\n    >\n      <svg\n        viewBox=\"0 0 16 16\"\n        className={cn(\"size-4\", direction < 0 && \"-scale-x-100\")}\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        {/* Nudged 0.5px toward the point: a chevron's visual mass sits\n            behind its tip. */}\n        <path d=\"m6.5 4 4 4-4 4\" transform=\"translate(0.5 0)\" />\n      </svg>\n    </button>\n  );\n}\n\nconst line = (strong: string, rest: string) => (\n  <>\n    <span className=\"text-foreground\">{strong}</span> {rest}\n  </>\n);\n\nconst TABS: Tab[] = [\n  { id: \"overview\", label: \"Overview\", content: line(\"3 projects\", \"are live. Build times are down 12% since last week.\") },\n  { id: \"deployments\", label: \"Deployments\", content: line(\"Mira\", \"deployed main 4 minutes ago. Two previews are still building.\") },\n  { id: \"analytics\", label: \"Analytics\", content: line(\"18.2k visitors\", \"this week, most of them landing on the docs.\") },\n  { id: \"logs\", label: \"Logs\", content: line(\"No errors\", \"in the last 24 hours. Warnings are down to 3.\") },\n  { id: \"storage\", label: \"Storage\", content: line(\"2.4 GB\", \"of 10 GB used across two buckets and one database.\") },\n  { id: \"domains\", label: \"Domains\", content: line(\"lab.xevrion.dev\", \"is verified. Certificates renew in 41 days.\") },\n  { id: \"integrations\", label: \"Integrations\", content: line(\"GitHub and Slack\", \"are connected. Linear is waiting on approval.\") },\n  { id: \"environment\", label: \"Environment\", content: line(\"12 variables\", \"set for production, 9 shared with previews.\") },\n  { id: \"security\", label: \"Security\", content: line(\"Two-factor\", \"is on for every member. One key expires soon.\") },\n  { id: \"usage\", label: \"Usage\", content: line(\"64%\", \"of this month's build minutes used, resetting on the 1st.\") },\n  { id: \"settings\", label: \"Settings\", content: line(\"Deploys\", \"run on every push to main. Previews expire after 30 days.\") },\n];\n\nexport default function OverflowTabsDemo() {\n  const [tab, setTab] = useState(\"overview\");\n  return (\n    // A fixed height keeps the card still when panels of different lengths\n    // swap in. 20px radius = the tabs' 8px plus the 12px padding.\n    <div className=\"h-44 w-[min(480px,100%)] rounded-[20px] bg-background p-3 shadow-raised\">\n      <OverflowTabs label=\"Project\" tabs={TABS} value={tab} onChange={setTab} />\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/overflow-tabs"}