Tabs
An ink block slides under the labels and swaps their colour exactly at its edge, stretching the way it travels. The panel slides in from the same side.
npx shadcn@latest add https://captain-ui.vercel.app/r/tabs.json- app/api/webhooks/stripe/route.ts+28−11
- lib/billing/idempotency.ts+9−2
- tests/webhooks.test.ts+5−4
"use client";
// Captain UI · Tabs, MIT. An ink block slides under the labels and clips their colour as it passes; the panel moves the way you travelled.
import { AnimatePresence, animate, motion, useMotionValue, useMotionTemplate, useReducedMotion } from "motion/react";
import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { EASE, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
export type TabItem = { value: string; label: ReactNode; content: ReactNode; disabled?: boolean };
type TabsProps = {
items: TabItem[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
"aria-label"?: string;
className?: string;
panelClassName?: string;
};
// The leading edge moves first and the trailing edge follows, so the ink stretches in the direction of travel.
const LEAD = { type: "spring", stiffness: 620, damping: 46, mass: 0.8 } as const;
const TRAIL = { type: "spring", stiffness: 360, damping: 38, mass: 0.9 } as const;
export function Tabs({ items, value, defaultValue, onValueChange, className, panelClassName, ...rest }: TabsProps) {
const [inner, setInner] = useState(defaultValue ?? items[0]?.value ?? "");
const current = value ?? inner;
const index = Math.max(0, items.findIndex((t) => t.value === current));
const [dir, setDir] = useState(0);
const last = useRef(index);
const wrap = useRef<HTMLDivElement>(null);
const tabs = useRef<Array<HTMLButtonElement | null>>([]);
const left = useMotionValue(0);
const right = useMotionValue(0);
const clip = useMotionTemplate`inset(0 ${right}px 0 ${left}px round 6px)`;
const reduce = useReducedMotion();
const ready = useRef(false);
const id = useId();
useIsoLayoutEffect(() => {
const place = (instant: boolean) => {
const el = tabs.current[index];
const box = wrap.current;
if (!el || !box) return;
const l = el.offsetLeft;
const r = box.clientWidth - (el.offsetLeft + el.offsetWidth);
if (instant || reduce) {
left.jump(l);
right.jump(r);
return;
}
const forward = l > left.get();
animate(left, l, forward ? TRAIL : LEAD);
animate(right, r, forward ? LEAD : TRAIL);
};
place(!ready.current);
ready.current = true;
const ro = new ResizeObserver(() => place(true));
if (wrap.current) ro.observe(wrap.current);
return () => ro.disconnect();
}, [index, reduce, left, right]);
const select = (i: number) => {
const t = items[i];
if (!t || t.disabled) return;
setDir(Math.sign(i - last.current));
last.current = i;
if (value === undefined) setInner(t.value);
if (t.value !== current) onValueChange?.(t.value);
};
const key = (e: KeyboardEvent<HTMLButtonElement>) => {
const n = items.length;
const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
let to = e.key === "Home" ? 0 : e.key === "End" ? n - 1 : step ? index : -1;
if (to < 0) return;
e.preventDefault();
for (let k = 0; k < n; k++) {
if (step) to = (to + step + n) % n;
if (!items[to]?.disabled) break;
if (!step) to += e.key === "Home" ? 1 : -1;
}
select(to);
tabs.current[to]?.focus();
};
const tabClass = "relative h-8 shrink-0 rounded-[6px] px-3 text-[13px] font-medium whitespace-nowrap";
const active = items[index];
return (
<div className={className}>
<div ref={wrap} className="relative w-fit max-w-full">
<div role="tablist" aria-label={rest["aria-label"]} className="flex gap-0.5">
{items.map((t, i) => (
<button
key={t.value}
ref={(el) => {
tabs.current[i] = el;
}}
id={`${id}-tab-${i}`}
type="button"
role="tab"
aria-selected={i === index}
aria-controls={`${id}-panel`}
tabIndex={i === index ? 0 : -1}
disabled={t.disabled}
onClick={() => select(i)}
onKeyDown={key}
className={cx(
tabClass,
"text-ink-2 transition-colors duration-150 hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:text-ink disabled:cursor-not-allowed disabled:opacity-45",
)}
>
{t.label}
</button>
))}
</div>
{/* The same labels in the ink colour, clipped to the indicator: the colour swaps exactly where the block edge is. */}
<motion.div aria-hidden className="pointer-events-none absolute inset-0 flex gap-0.5 bg-primary" style={{ clipPath: clip }}>
{items.map((t, i) => (
<span key={t.value} className={cx(tabClass, "grid place-items-center text-primary-ink", t.disabled && "opacity-45")}>
{t.label}
</span>
))}
</motion.div>
</div>
<div className={cx("relative mt-4", panelClassName)}>
<AnimatePresence initial={false} mode="popLayout" custom={dir}>
<motion.div
key={active?.value}
id={`${id}-panel`}
role="tabpanel"
aria-labelledby={`${id}-tab-${index}`}
tabIndex={0}
custom={dir}
variants={{
enter: (d: number) => ({ opacity: 0, x: reduce ? 0 : d * 28 }),
center: { opacity: 1, x: 0 },
exit: (d: number) => ({ opacity: 0, x: reduce ? 0 : d * -28 }),
}}
initial="enter"
animate="center"
exit="exit"
transition={{ duration: 0.24, ease: EASE }}
className="outline-none"
>
{active?.content}
</motion.div>
</AnimatePresence>
</div>
</div>
);
}Usage
import { Tabs } from "@/components/ui/tabs"
<Tabs
aria-label="Pull request"
items={[
{ value: "overview", label: "Overview", content: <Overview /> },
{ value: "changes", label: "Changes", content: <Changes /> },
]}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| items | { value: string; label: ReactNode; content: ReactNode; disabled?: boolean }[] | The tabs and their panels. | |
| value | string | Controlled value. | |
| defaultValue | string | items[0].value | Initial tab when uncontrolled. |
| onValueChange | (value: string) => void | Called on click or arrow key. | |
| aria-label | string | Names the tab list. | |
| panelClassName | string | Classes for the panel area. |
Keyboard
- ← →
- Previous / next tab
- Home / End
- First / last tab
- Tab
- Into the panel
Accessibility
- role=tablist, tab and tabpanel, with aria-selected, aria-controls and aria-labelledby.
- Roving tabindex with automatic activation, as the WAI-ARIA tabs pattern describes.
- The ink copy of the labels is aria-hidden, so each label is read once.