Toggles & Selectionv0.1.0
Sliding Tabs
Pill, underline and segment indicators on a spring.
Installation
CLI
npx shadcn@latest add https://hantui-theta.vercel.app/r/sliding-tabs.jsonManual
Install the dependencies
npm install clsx motion radix-ui tailwind-mergeAdd the shared helpers
Components use
cn()fromlib/utils.tsand the motion tokens below. See Installation if you have not set them up yet.lib/motion.tsimport type { Transition, Variants } from "motion/react"; /** Durations in seconds. */ export const duration = { instant: 0.1, quick: 0.18, base: 0.28, slow: 0.45, } as const; /** Cubic-bezier curves. */ export const ease = { /** Entering, UI response. */ out: [0.22, 1, 0.36, 1], /** Moving on screen. */ inOut: [0.65, 0, 0.35, 1], /** Sheets and the mobile menu. */ drawer: [0.32, 0.72, 0, 1], } as const; /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */ export const ui = { press: { scale: 0.96, duration: 0.12 }, icon: { type: "spring", duration: 0.3, bounce: 0 }, popover: { duration: 0.18, ease: ease.out }, modal: { duration: 0.24, ease: ease.out }, exitFactor: 0.6, } as const; /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */ export const kinetic = { heroLetter: { duration: 0.6, ease: ease.out }, /** Delay per letter, eased so the wave slows toward the end. */ heroStep: 0.035, reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 }, /** Two afterimages: lag in seconds and opacity of each. */ ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] }, } as const; /** Spring presets. */ export const spring = { snappy: { type: "spring", stiffness: 500, damping: 30 }, smooth: { type: "spring", stiffness: 260, damping: 26 }, bouncy: { type: "spring", stiffness: 300, damping: 15 }, } as const satisfies Record<string, Transition>; /** Stagger between siblings, in seconds (0.03–0.06). */ export const stagger = { tight: 0.03, base: 0.045, loose: 0.06, } as const; /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */ export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.base } }, exit: { opacity: 0, transition: { duration: duration.quick } }, }; } return { hidden: { opacity: 0, y, filter: "blur(4px)" }, visible: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: duration.base, ease: ease.out }, }, exit: { opacity: 0, y: -y / 2, filter: "blur(4px)", transition: { duration: duration.quick, ease: ease.out }, }, }; } /** Scale 0.96 → 1 for popovers, menus and dialogs. */ export function overlayVariants(reduceMotion?: boolean | null): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.quick } }, exit: { opacity: 0, transition: { duration: duration.instant } }, }; } return { hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" }, visible: { opacity: 1, scale: 1, filter: "blur(0px)", transition: { duration: duration.quick, ease: ease.out }, }, exit: { opacity: 0, scale: 0.96, filter: "blur(2px)", transition: { duration: duration.instant + 0.02, ease: ease.out }, }, }; } /** Parent variants that stagger their children in. */ export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants { return { hidden: {}, visible: { transition: { staggerChildren: gap, delayChildren } }, exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } }, }; }Copy the source
components/ui/sliding-tabs/sliding-tabs.tsx"use client"; import { useId, useState, type ComponentProps, type ReactNode } from "react"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react"; import { Tabs as TabsPrimitive } from "radix-ui"; import { cn } from "@/lib/utils"; import { duration, ease, spring } from "@/lib/motion"; export interface SlidingTabItem { /** Unique value for the tab. */ value: string; /** Tab label. */ label: ReactNode; /** Icon shown before the label. */ icon?: ReactNode; /** Panel shown while the tab is active. Omit it to render only the tab bar. */ content?: ReactNode; /** Prevents selecting the tab. */ disabled?: boolean; } export interface SlidingTabsProps extends Omit< ComponentProps<"div">, "defaultValue" | "onChange" | "dir" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd" > { /** The tabs, in order. */ items: SlidingTabItem[]; /** Controlled active tab. */ value?: string; /** Initially active tab when uncontrolled. @default the first tab */ defaultValue?: string; /** Called with the newly active tab. */ onValueChange?: (value: string) => void; /** Indicator style. @default "pill" */ variant?: "pill" | "underline" | "segment"; /** Classes for the tab bar. */ listClassName?: string; } const listClasses = { pill: "gap-1", // The baseline is drawn inside the list so the scroll container can't clip the indicator over it. underline: "gap-1 after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-border after:content-['']", segment: "gap-0.5 rounded-[10px] bg-muted p-[3px]", } as const; const triggerClasses = { pill: "h-9 rounded-full px-4", underline: "h-10 rounded-md px-3", segment: "h-8 rounded-[7px] px-3.5", } as const; export function SlidingTabs({ items, value, defaultValue, onValueChange, variant = "pill", className, listClassName, "aria-label": ariaLabel, ...props }: SlidingTabsProps) { const [internal, setInternal] = useState(defaultValue ?? items[0]?.value); const active = value ?? internal ?? ""; const [hovered, setHovered] = useState<string | null>(null); const reduceMotion = useReducedMotion(); const groupId = useId(); // Panels slide in from the side of the newly chosen tab. const [previous, setPrevious] = useState(active); const [direction, setDirection] = useState(1); if (previous !== active) { const from = items.findIndex((i) => i.value === previous); const to = items.findIndex((i) => i.value === active); setDirection(to >= from ? 1 : -1); setPrevious(active); } const select = (next: string) => { if (next === active) return; if (value === undefined) setInternal(next); onValueChange?.(next); }; const indicatorTransition = reduceMotion ? { duration: 0 } : spring.snappy; const activeItem = items.find((item) => item.value === active); return ( <TabsPrimitive.Root value={active} onValueChange={select} className={cn("w-full", className)} {...props}> <LayoutGroup id={groupId}> <TabsPrimitive.List aria-label={ariaLabel} onPointerLeave={() => setHovered(null)} className={cn("relative flex w-fit max-w-full items-center overflow-x-auto [scrollbar-width:none]", listClasses[variant], listClassName)} > {items.map((item) => { const isActive = item.value === active; return ( <TabsPrimitive.Trigger key={item.value} value={item.value} disabled={item.disabled} onPointerEnter={() => setHovered(item.value)} onMouseDown={(event) => { // Radix focuses on mousedown, which Chrome can paint as a keyboard ring; select without focusing. if (event.button !== 0 || event.ctrlKey || item.disabled) return; event.preventDefault(); select(item.value); }} className={cn( "relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 text-sm font-medium whitespace-nowrap outline-none select-none", "transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40", "[&_svg]:size-4 [&_svg]:shrink-0", triggerClasses[variant], isActive ? variant === "pill" ? "text-background" : "text-foreground" : "text-muted-foreground hover:text-foreground", )} > {variant !== "segment" && hovered === item.value && !isActive ? ( <motion.span layoutId="hover" aria-hidden="true" className={cn("absolute bg-accent", variant === "pill" ? "inset-0 rounded-full" : "inset-x-0 inset-y-1 rounded-md")} transition={indicatorTransition} /> ) : null} {isActive ? ( <motion.span layoutId="indicator" aria-hidden="true" transition={indicatorTransition} className={cn( "absolute", variant === "pill" && "inset-0 rounded-full bg-foreground shadow-sm", variant === "underline" && "inset-x-2 bottom-0 z-10 h-0.5 rounded-full bg-foreground", variant === "segment" && "inset-0 rounded-[7px] bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.04),0_1px_2px_rgb(0_0_0/0.08),0_2px_6px_-2px_rgb(0_0_0/0.08)]", )} /> ) : null} <span className="relative inline-flex items-center gap-2"> {item.icon} {item.label} </span> </TabsPrimitive.Trigger> ); })} </TabsPrimitive.List> </LayoutGroup> {activeItem?.content !== undefined ? ( // The padding (offset by negative margins) leaves room for the panel's focus ring inside the clip. <div className="relative mt-3 -mx-1 -mb-1 overflow-hidden p-1"> <AnimatePresence mode="popLayout" initial={false} custom={direction}> <TabsPrimitive.Content key={activeItem.value} value={activeItem.value} forceMount asChild> <motion.div custom={direction} variants={{ enter: (dir: number) => (reduceMotion ? { opacity: 0 } : { opacity: 0, x: dir * 16, filter: "blur(4px)" }), center: { opacity: 1, x: 0, filter: "blur(0px)" }, exit: (dir: number) => (reduceMotion ? { opacity: 0 } : { opacity: 0, x: dir * -16, filter: "blur(4px)" }), }} initial="enter" animate="center" exit="exit" transition={{ duration: duration.base, ease: ease.out }} className="rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring" > {activeItem.content} </motion.div> </TabsPrimitive.Content> </AnimatePresence> </div> ) : null} </TabsPrimitive.Root> ); }
Usage
import { SlidingTabs } from "@/components/ui/sliding-tabs/sliding-tabs";
export function ProjectTabs() {
return (
<SlidingTabs
aria-label="Project"
variant="underline"
items={[
{ value: "overview", label: "Overview", content: <Overview /> },
{ value: "activity", label: "Activity", content: <Activity /> },
]}
/>
);
}API reference
| Prop | Type | Default | Description |
|---|---|---|---|
items* | SlidingTabItem[] | – | The tabs, in order. |
value | string | – | Controlled active tab. |
defaultValue | string | the first tab | Initially active tab when uncontrolled. |
onValueChange | (value: string) => void | – | Called with the newly active tab. |
variant | "pill" | "underline" | "segment" | "pill" | Indicator style. |
listClassName | string | – | Classes for the tab bar. |
Also accepts every native <div> attribute, including ref and className.
- pill fills the active tab, underline draws a bar on the baseline, and segment raises a white pill on a muted track.
- Panels slide from the side of the newly chosen tab. Leave out content to render only the tab bar and drive your own panels with onValueChange.
Accessibility
- Built on Radix Tabs: role="tablist", "tab" and "tabpanel" with aria-selected and aria-controls wired up.
- Arrow keys move between tabs, Home and End jump to the ends, and disabled tabs are skipped.
- A mouse click selects without moving focus, so a keyboard focus ring never appears on click.
- With reduced motion enabled, the indicator jumps and panels cross-fade without sliding.