Tabs
An ink block slides under the labels and swaps their colour exactly at its edge, stretching the way it travels. Grab the block and drag it, and the labels turn under your finger.
npx shadcn@latest add https://uimaxxer.com/r/tabs.jsonPasskeysSettings · Changes
Changes
- app/api/webhooks/stripe/route.ts+28−11
- lib/billing/idempotency.ts+9−2
- tests/webhooks.test.ts+5−4
"use client";
// uimaxxer · Tabs, MIT. Idea: the ink block swaps each label's colour exactly at its edge, mid-travel. Delight: grab the block and drag it across; the labels turn under your finger and it settles on the tab you let go over.
import { AnimatePresence, animate, motion, useMotionValue, useMotionTemplate, useReducedMotion } from "motion/react";
import { useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
import { EASE, clamp, cx, rubber, 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;
/** md for toolbars, lg for a feature moment: 44px tabs at 16px. */
size?: "md" | "lg";
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, size = "md", 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 round = size === "lg" ? 9 : 6;
const clip = useMotionTemplate`inset(0 ${right}px 0 ${left}px round ${round}px)`;
const grab = useRef<{ id: number; x: number; c0: number; moved: boolean; t: number; last: number; v: number } | null>(null);
const swallow = useRef(false);
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);
};
// Dragging the block: its centre follows the finger, its width eases between the two tabs it is crossing.
const boxes = () => tabs.current.map((el) => ({ l: el?.offsetLeft ?? 0, w: el?.offsetWidth ?? 0 }));
const placeAt = (c: number) => {
const g = boxes();
const W = wrap.current?.clientWidth ?? 0;
const mid = g.map((b) => b.l + b.w / 2);
const lo = mid[0] ?? 0;
const hi = mid[mid.length - 1] ?? 0;
const cc = c < lo ? lo + rubber(c - lo, 28) : c > hi ? hi + rubber(c - hi, 28) : c;
let j = 0;
while (j < mid.length - 2 && cc > (mid[j + 1] ?? 0)) j++;
const a = g[j]!;
const b = g[Math.min(j + 1, g.length - 1)]!;
const span = (mid[j + 1] ?? lo) - (mid[j] ?? lo) || 1;
const t = clamp((cc - (mid[j] ?? lo)) / span, 0, 1);
const w = a.w + (b.w - a.w) * t;
left.set(cc - w / 2);
right.set(W - (cc + w / 2));
};
const down = (i: number) => (e: PointerEvent<HTMLButtonElement>) => {
if (i !== index || e.button !== 0 || reduce) return;
const el = tabs.current[i];
if (!el) return;
e.currentTarget.setPointerCapture(e.pointerId);
grab.current = { id: e.pointerId, x: e.clientX, c0: el.offsetLeft + el.offsetWidth / 2, moved: false, t: performance.now(), last: e.clientX, v: 0 };
};
const move = (e: PointerEvent<HTMLButtonElement>) => {
const g = grab.current;
if (!g || g.id !== e.pointerId) return;
const dx = e.clientX - g.x;
if (!g.moved && Math.abs(dx) < 4) return;
if (!g.moved) {
g.moved = true;
left.stop();
right.stop();
}
const now = performance.now();
g.v = ((e.clientX - g.last) / Math.max(1, now - g.t)) * 1000;
g.t = now;
g.last = e.clientX;
placeAt(g.c0 + dx);
};
const up = (e: PointerEvent<HTMLButtonElement>) => {
const g = grab.current;
if (!g || g.id !== e.pointerId) return;
grab.current = null;
if (!g.moved) return;
swallow.current = true;
const W = wrap.current?.clientWidth ?? 0;
// A flick carries the block on: aim where it would coast to, not only where it was let go.
const c = (left.get() + W - right.get()) / 2 + clamp(g.v, -1200, 1200) * 0.08;
const mid = boxes().map((b) => b.l + b.w / 2);
let to = index;
let best = Infinity;
mid.forEach((m, k) => {
if (!items[k]?.disabled && Math.abs(m - c) < best) {
best = Math.abs(m - c);
to = k;
}
});
if (to !== index) {
select(to);
tabs.current[to]?.focus();
} else {
const el = tabs.current[index];
if (el) {
animate(left, el.offsetLeft, LEAD);
animate(right, W - (el.offsetLeft + el.offsetWidth), LEAD);
}
}
};
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 =
size === "lg"
? "relative h-10 flex-auto rounded-[9px] px-2.5 text-[15px] font-medium whitespace-nowrap sm:h-12 sm:px-5 sm:text-[17px]"
: "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={cx("relative max-w-full", size === "lg" ? "well w-full rounded-[13px] p-1" : "w-fit")}>
<div role="tablist" aria-label={rest["aria-label"]} className={cx("flex", size === "lg" ? "gap-1" : "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={() => {
if (swallow.current) {
swallow.current = false;
return;
}
select(i);
}}
onPointerDown={down(i)}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
onKeyDown={key}
className={cx(
tabClass,
i === index && "cursor-grab touch-pan-y active:cursor-grabbing",
"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={cx("pointer-events-none absolute inset-0 flex bg-primary", size === "lg" ? "gap-1 rounded-[13px] p-1" : "gap-0.5")} 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. | |
| size | "md" | "lg" | "md" | lg sets 48px tabs that share the width, in a recessed tray. |
| 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.