{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"sliding-tabs","type":"registry:component","title":"Sliding tabs","description":"An underline stretches toward the tab you pick while a soft pill follows your pointer.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/sliding-tabs.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  type AnimationPlaybackControls,\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 };\ntype Custom = { dir: number; reduce: boolean };\ntype Hover = {\n  tab: string | null;\n  visible: boolean;\n  // Every time the pointer comes back into the list the pill gets a fresh\n  // layoutId, so it fades in where you are instead of sliding over from\n  // wherever it was when you left.\n  session: number;\n  entering: boolean;\n};\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// The underline travels like a stretched band: the edge facing the new tab\n// leaves first and fast, the far edge lets go later and catches up, so the\n// line reaches toward the tab, then pulls its tail in. No bounce, it answers\n// \"where am I\". The tail settles by ~340ms, over the usual 300ms, because\n// the stretch is the part that reads; the lead lands inside 200ms.\nconst LEAD = { type: \"spring\", visualDuration: 0.2, bounce: 0 } as const;\nconst TAIL = { type: \"spring\", visualDuration: 0.34, bounce: 0 } as const;\n// The hover pill only echoes the pointer, so it is quicker still.\nconst HOVER = { type: \"spring\", visualDuration: 0.15, bounce: 0 } as const;\nconst INSTANT = { duration: 0 } as const;\n\n// Enters 8px from the side you moved toward and leaves 6px the other way,\n// so the panels read as a strip sliding along with the underline.\nconst panel = {\n  enter: ({ dir, reduce }: Custom) => ({\n    opacity: 0,\n    x: reduce ? 0 : dir * 8,\n    filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n  }),\n  center: {\n    opacity: 1,\n    x: 0,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.25, ease: EASE_OUT },\n  },\n  // Softer and faster than the entrance, so the old panel is gone before\n  // the new one draws the eye.\n  exit: ({ dir, reduce }: Custom) => ({\n    opacity: 0,\n    x: reduce ? 0 : dir * -6,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.15, ease: EASE_OUT },\n  }),\n};\n\n/*\n * The lab's segmented control clips an inverted copy of the whole row, so\n * each label recolors exactly as the pill's edge crosses it. An underline is\n * too thin to cover any text, so there is nothing to recolor here. Instead\n * its two ends move separately, which a shared layoutId can't do: the line\n * stretches toward the new tab and then gathers itself under it.\n */\nexport function SlidingTabs({\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 tabRefs = useRef(new Map<string, HTMLButtonElement>());\n  const [dir, setDir] = useState(1);\n  const [hover, setHover] = useState<Hover>({\n    tab: null,\n    visible: false,\n    session: 0,\n    entering: false,\n  });\n\n  const index = Math.max(\n    tabs.findIndex((t) => t.id === value),\n    0,\n  );\n  const active = tabs[index];\n\n  // The underline's two edges, in px from the list's left, moved on their\n  // own springs. It is one full-width line clipped down to the tab, so the\n  // stretch costs no layout.\n  const listRef = useRef<HTMLDivElement>(null);\n  const edgeL = useMotionValue(0);\n  const edgeR = useMotionValue(0);\n  const runs = useRef<AnimationPlaybackControls[]>([]);\n  const activeId = useRef(active.id);\n  const clip = useMotionTemplate`inset(0 calc(100% - ${edgeR}px) 0 ${edgeL}px round 1px)`;\n\n  const measure = (id: string) => {\n    const el = tabRefs.current.get(id);\n    return el ? [el.offsetLeft, el.offsetLeft + el.offsetWidth] : null;\n  };\n\n  useLayoutEffect(() => {\n    const target = measure(active.id);\n    const list = listRef.current;\n    if (!target || !list) return;\n    const [l, r] = target;\n    const first = list.dataset.ready !== \"true\";\n    activeId.current = active.id;\n    runs.current.forEach((run) => run.stop());\n    if (first || reduce) {\n      edgeL.jump(l);\n      edgeR.jump(r);\n      // Hands over from the server-rendered underline to the clipped one.\n      list.dataset.ready = \"true\";\n      return;\n    }\n    const rightward = r > edgeR.get();\n    runs.current = [\n      animate(edgeL, l, rightward ? TAIL : LEAD),\n      animate(edgeR, r, rightward ? LEAD : TAIL),\n    ];\n  }, [active.id, reduce, edgeL, edgeR]);\n\n  // Tabs change width with the viewport (padding and text size step at sm),\n  // so the underline re-fits without animating.\n  useEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n    const observer = new ResizeObserver(() => {\n      const target = measure(activeId.current);\n      if (!target) return;\n      runs.current.forEach((run) => run.stop());\n      edgeL.jump(target[0]);\n      edgeR.jump(target[1]);\n    });\n    observer.observe(list);\n    return () => {\n      observer.disconnect();\n      runs.current.forEach((run) => run.stop());\n    };\n  }, [edgeL, edgeR]);\n\n  const select = (next: string) => {\n    const nextIndex = tabs.findIndex((t) => t.id === next);\n    if (nextIndex === index) return;\n    setDir(nextIndex > index ? 1 : -1);\n    onChange(next);\n  };\n\n  const enter = (id: string) =>\n    setHover((h) =>\n      h.visible\n        ? h.tab === id\n          ? h\n          : { ...h, tab: id, entering: false }\n        : { tab: id, visible: true, session: h.session + 1, entering: true },\n    );\n\n  const tabId = (id: string) => `${base}-tab-${id}`;\n  const panelId = (id: string) => `${base}-panel-${id}`;\n  const custom: Custom = { dir, reduce };\n\n  return (\n    <LayoutGroup id={base}>\n      <div className={cn(\"flex flex-col\", className)}>\n        <div\n          role=\"tablist\"\n          aria-label={label}\n          ref={listRef}\n          className=\"group/tabs relative flex gap-0.5 border-b border-border px-0.5\"\n          onPointerLeave={() =>\n            setHover((h) => (h.visible ? { ...h, visible: false } : h))\n          }\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, and the\n            // underline slides exactly as it does for a click.\n            const next = tabs[(target + tabs.length) % tabs.length].id;\n            select(next);\n            tabRefs.current.get(next)?.focus();\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={() => select(tab.id)}\n                onPointerEnter={(e) => {\n                  if (e.pointerType !== \"touch\") enter(tab.id);\n                }}\n                className={cn(\n                  \"group relative flex h-11 touch-manipulation items-center rounded-lg px-2.5 text-sm font-medium sm:px-4 sm:text-[15px] 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                {hover.tab === tab.id && (\n                  <motion.span\n                    key={hover.session}\n                    layoutId={`hover-${hover.session}`}\n                    aria-hidden\n                    // 6px in from top and bottom so the pill floats inside the\n                    // 44px tab without touching the underline.\n                    className=\"absolute inset-x-0 inset-y-1.5 rounded-md bg-muted\"\n                    initial={hover.entering ? { opacity: 0 } : false}\n                    animate={{ opacity: hover.visible ? 1 : 0 }}\n                    transition={{\n                      layout: reduce ? INSTANT : HOVER,\n                      opacity: {\n                        duration: hover.visible ? 0.15 : 0.1,\n                        ease: EASE_OUT,\n                      },\n                    }}\n                  />\n                )}\n                {/* Only the label presses in. Scaling the whole button would\n                    skew the box Motion measures for the underline mid-press. */}\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                  // What the server renders, so the line is there before\n                  // hydration; the clipped underline takes over once measured.\n                  <span\n                    aria-hidden\n                    className=\"absolute inset-x-0 -bottom-px h-0.5 rounded-full bg-foreground group-data-[ready=true]/tabs:hidden\"\n                  />\n                )}\n              </button>\n            );\n          })}\n          <motion.span\n            aria-hidden\n            style={{ clipPath: clip }}\n            // Overlaps the list's 1px border so the two read as one line.\n            className=\"pointer-events-none absolute inset-x-0 -bottom-px hidden h-0.5 bg-foreground group-data-[ready=true]/tabs:block\"\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={custom}>\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={custom}\n              variants={panel}\n              initial=\"enter\"\n              animate=\"center\"\n              exit=\"exit\"\n              className=\"col-start-1 row-start-1 rounded-lg px-4 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\nconst TABS: Tab[] = [\n  {\n    id: \"overview\",\n    label: \"Overview\",\n    content: (\n      <>\n        <span className=\"text-foreground\">3 projects</span> are live. Build\n        times are down 12% since last week.\n      </>\n    ),\n  },\n  {\n    id: \"activity\",\n    label: \"Activity\",\n    content: (\n      <>\n        <span className=\"text-foreground\">Mira</span> deployed main 4 minutes\n        ago. Two previews are still building.\n      </>\n    ),\n  },\n  {\n    id: \"settings\",\n    label: \"Settings\",\n    content: (\n      <>\n        Deploys run on every push to{\" \"}\n        <span className=\"text-foreground\">main</span>. Previews expire after 30\n        days.\n      </>\n    ),\n  },\n  {\n    id: \"billing\",\n    label: \"Billing\",\n    content: (\n      <>\n        You are on the <span className=\"text-foreground\">Pro</span> plan. The\n        next invoice lands on October 1.\n      </>\n    ),\n  },\n];\n\nexport default function SlidingTabsDemo() {\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-55 w-[min(480px,100%)] rounded-[20px] bg-background p-3 shadow-raised\">\n      <SlidingTabs 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/sliding-tabs"}