Tabs
A set of tabbed panels with a sliding pill indicator animated by Motion.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/tabs.jsonUsage
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"Examples
Horizontal
Default
Each TabsTrigger is tied to its panel by a matching value string. Mistype either one and the tab still selects, the panel just comes up blank, with nothing to tell you why.
Sizes
size steps the tabs along the control scale: sm (h-7, 12px), default (h-8, 13px), lg (h-10, 14px). One prop on Tabs sizes the triggers, the list, and the count chips. The height sits on the trigger, so a tab lines up with a Nav item of the same size; the list adds its 4px gutter on top.
With Icons
Pass an icon to a trigger to render it before the label.
With Count
Pass a count to add a counter chip. It fills solid accent on the active tab. Add an aria-label where a bare number needs context (aria-label="Open, 18 issues").
With Icons and Count
icon and count compose. Cap large counts at "99+" so a growing number can't widen the tab.
Icon Only
Omit the children for an icon-only trigger; the pill tightens to a square. Each text-less trigger needs an aria-label for an accessible name.
Line
variant="line" drops the track for plain labels over a sliding underline. Use it where the tabs sit inside other chrome, like a DashboardCardHeader action slot, where the framed pill fills the band. Same sizes and counts.
Overflow
More tabs than fit scroll sideways, and the active tab scrolls toward the middle when it changes. With a mouse, an arrow shows at each edge with more past it. On a touch screen the strip runs to the screen edge so the next tab shows cut off. Give the Tabs a width, or nothing overflows.
Vertical
Default
orientation="vertical" stacks the triggers into a column beside the panels instead of above them, the settings-pane pattern. The gap moves to the inline axis with it, so the list takes mr-3 where a horizontal one takes mb-3. Labels align to the leading edge, and the sliding indicator travels vertically.
Sizes
The same three rungs as a horizontal strip, and the same heights: sm (h-7, 12px), default (h-8, 13px), lg (h-10, 14px). One prop on Tabs sizes the triggers, the labels, and the count chips in either orientation, so a vertical strip lines up with a Nav sidebar of the same size.
With Count
A count sits at the trailing edge of a vertical trigger, not against the label, so a column of numbers reads as a column. That needs a width on the TabsList: the strip sizes to its own content, and there is no shared trailing edge to push a count to until you give it one.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| defaultValueTabs | string | None | The tab that is active when initially rendered, for uncontrolled usage. |
| valueTabs | string | None | The controlled active tab. Pair with onValueChange. |
| onValueChangeTabs | (value: string) => void | None | Called with the new value when the active tab changes. |
| sizeTabs | "sm" | "default" | "lg" | "default" | Steps the triggers, list, and count chips along the control scale, from sm (h-7, 12px type) up to lg (h-10, 14px type). The height sits on the trigger, matching Nav item for item; the list adds its 4px gutter on top. |
| orientationTabs | "horizontal" | "vertical" | "horizontal" | Axis of the tab strip. vertical stacks the triggers into a column and moves the strip beside the panels instead of above them; the sliding indicator travels vertically to match. |
| value*TabsTrigger | string | None | Identifier linking each <TabsTrigger /> to its matching <TabsContent />. |
| fullWidthTabsList | boolean | false | Stretches the list to fill its container so triggers share the width evenly. Horizontal lists share the width between triggers; a vertical list sizes each row to its content. |
| iconTabsTrigger | React.ReactNode | None | Leading icon rendered before the trigger label, e.g. <Star />. |
| countTabsTrigger | React.ReactNode | None | Trailing counter chip, e.g. 18 or "99+". Arrives and leaves like Button's count. |
| defaultValueTabsstringThe tab that is active when initially rendered, for uncontrolled usage. |
valueTabsstringThe controlled active tab. Pair with onValueChange. |
| onValueChangeTabs(value: string) => voidCalled with the new value when the active tab changes. |
sizeTabs"sm" | "default" | "lg" = "default"Steps the triggers, list, and count chips along the control scale, from sm (h-7, 12px type) up to lg (h-10, 14px type). The height sits on the trigger, matching Nav item for item; the list adds its 4px gutter on top. |
orientationTabs"horizontal" | "vertical" = "horizontal"Axis of the tab strip. vertical stacks the triggers into a column and moves the strip beside the panels instead of above them; the sliding indicator travels vertically to match. |
value*TabsTriggerstringIdentifier linking each <TabsTrigger /> to its matching <TabsContent />. |
| fullWidthTabsListboolean = falseStretches the list to fill its container so triggers share the width evenly. Horizontal lists share the width between triggers; a vertical list sizes each row to its content. |
iconTabsTriggerReact.ReactNodeLeading icon rendered before the trigger label, e.g. <Star />. |
countTabsTriggerReact.ReactNodeTrailing counter chip, e.g. 18 or "99+". Arrives and leaves like Button's count. |
"use client"
import * as React from "react"
import {
createContext,
useContext,
useState,
useCallback,
useRef,
useEffect,
useLayoutEffect,
} from "react"
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
import { IconChevronLeft as ChevronLeft, IconChevronRight as ChevronRight } from "@tabler/icons-react"
import { animate, motion, useReducedMotion } from "motion/react"
import { cn } from "@/registry/lib/utils"
import { CountArrival } from "@/registry/lib/count-arrival"
import { Button } from "@/registry/ui/button"
/* ─────────────────────────────────────────────────────────
* ANIMATION: SLIDING PILL
*
* ONE persistent indicator lives in TabsList and is moved to
* the measured box of the active trigger.
*
* It is deliberately NOT a per-trigger `layoutId` shared
* element. That approach mounts a new pill and unmounts the
* old one on every switch, and Motion's hand-off paints both
* boxes at once: on a long slide the pair reads as a single
* lozenge stretched across two or three tabs before it snaps
* onto the target. Dropping `AnimatePresence` reduced that
* but could not remove it, because the mount/unmount hand-off
* IS the bug. A single element that never unmounts has no
* hand-off, and its width can only interpolate between two
* real trigger widths, so it cannot balloon past either end.
*
* Spring: visualDuration 0.15, bounce 0 (see PILL below).
*
* `width` is animated, which is a deliberate exception to
* "animate transform and opacity only". The indicator is
* absolutely positioned with no children, so its layout is
* contained to itself and never reflows a sibling: measured
* over a full slide it drops 0 frames in 73. The alternative,
* scaleX, puts a non-unit scale on a 6px radius and visibly
* distorts the corners. Position still rides a transform;
* only width touches layout.
* ───────────────────────────────────────────────────────── */
// Paired with the trigger's own `transition-[color] duration-small ease-small`: the pill and
// the label are ONE selection, so they share a duration and land together.
// A 200ms spring under a 150ms color change made the destination read as
// selected while the pill was still in transit. `bounce: 0` because tabs are
// chrome you click all day, and one bouncy control in a crisp kit reads as a
// mistake. Change one of these two values and you must change the other.
const PILL = {
spring: { type: "spring" as const, visualDuration: 0.15, bounce: 0 },
}
// How far the overflow fade reaches in from an edge (px). ScrollFade's default
// skim, so a scrolling strip and a scrolling region fade alike.
const FADE = 24
// With a mouse, an overflowing strip shows an arrow at each edge that has more
// past it, sitting in a fade wide enough to hold it. A touch screen has no arrow:
// the strip runs to the screen edge instead, so the next tab shows cut off, the
// way phone apps signal a row that scrolls. Under the arrow the strip is fully
// clear (HOLD), so no half-faded label shows through it; the fade runs inward
// from there.
const ARROW_HOLD = 32
const FADE_ARROW = ARROW_HOLD + FADE
// useLayoutEffect warns during SSR; fall back to useEffect there.
const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect
// The trigger's box in the list's padding-box space, to the sub-pixel.
// `offsetLeft` and `offsetWidth` round to whole pixels, and they round
// apart: a 57.6px option read as 58 wide at 55 instead of 55.4, so the pill
// came out up to half a pixel off its trigger and the gutter on one side read
// wider than the other three (os analytics, 2026-10-22). The centre comes
// from getBoundingClientRect, divided by the track's own scale so a parent
// mid-zoom (a Dialog opening) does not shrink the reading; the size comes from
// the computed width and height, which a transform never touches, so the
// option's own press scale (centred) cannot either.
function boxIn(container: HTMLElement, el: HTMLElement) {
const c = container.getBoundingClientRect()
const r = el.getBoundingClientRect()
const own = parseFloat(getComputedStyle(container).width)
const scale = own ? c.width / own : 1
const style = getComputedStyle(el)
const width = parseFloat(style.width)
const height = parseFloat(style.height)
return {
x: (r.left + r.width / 2 - c.left) / scale - container.clientLeft + container.scrollLeft - width / 2,
y: (r.top + r.height / 2 - c.top) / scale - container.clientTop + container.scrollTop - height / 2,
width,
height,
}
}
// The trigger for `value`, matched on its own value rather than a presence
// attribute, so a lookup never races the primitive setting `data-active`.
function findTrigger(list: HTMLElement, value: unknown) {
return Array.from(
list.querySelectorAll<HTMLElement>('[data-slot="tabs-trigger"]')
).find((el) => el.dataset.value === String(value))
}
type TabsSize = "sm" | "default" | "lg"
// `pill` (default) is the framed track with a sliding pill: a row of labels
// that owns its own band. `line` drops the track for plain labels over a 3px
// underline, for a strip that sits INSIDE something with its own chrome, such
// as a `DashboardCardHeader`'s action slot, where a framed 36px track filled
// the 48px band and read as squeezed (os, 2026-10-22). Same sizes, same
// counts, same sliding indicator; only the paint changes.
//
// A line strip fills the height its parent gives it and reaches 1px past its
// bottom, so the underline lands ON the rule below it rather than floating
// above it: in a `DashboardCardHeader` the bar's last pixel covers the
// header's border. The bar is 3px so 2px still show above that rule. Every
// box here is a whole pixel (48px band, 28px trigger, 6px either side), so
// nothing lands on a half pixel and blurs.
type TabsVariant = "pill" | "line"
// Sizes ride the kit's control scale (Button's tiers), and the trigger is
// what carries them: heights h-7 / h-8 / h-10, type 12px / 13px / 14px, icons
// one step behind, padding and icon gap stepping with it. Every value here is
// the one a horizontal NavItem uses at the same size, so a tab and a nav item
// are the same object at the same scale.
//
// The height belongs on the trigger, not the list. The trigger is the pill you
// click, the same role NavItem plays; the list is only the track around it. Put
// the control height on the list instead and the pill silently renders SHORTER
// than its size name by however much padding the list happens to carry. The
// list now sizes itself from the trigger plus its `p-1` (36 / 40 / 48px),
// which is also the "children own their spacing" rule.
//
// Only `sm` carries a pointer-coarse bump. It is the one rung under the 32px
// floor (h-7), so it grows to 32; `default` (32) and `lg` (40) already clear it,
// and bumping them would only reflow a dense strip for nothing. Same reasoning
// as button-variants.ts's short rungs; NavItem's `sm` does the same thing.
//
// Text padding steps 8 / 12 / 12 rather than 8 / 10 / 12: 10px is off the 4px
// grid, and `default` is a 32px control carrying 13px type, the same object a
// 32px Button is, so it takes the same 12px inset. `lg` shares that inset but is
// 8px taller, so the two never read alike.
const TRIGGER_SIZE: Record<
TabsSize,
{ shared: string; text: string; iconStart: string; iconOnly: string; label: string }
> = {
sm: {
shared: "h-7 pointer-coarse:min-h-8 text-1xs [&_svg:not([class*='size-'])]:size-3",
text: "px-2",
iconStart: "ps-1.5",
iconOnly: "px-1.5",
label: "gap-1",
},
default: {
shared: "h-8 text-xs [&_svg:not([class*='size-'])]:size-3.5",
text: "px-3",
iconStart: "ps-2.5",
iconOnly: "px-1.5",
label: "gap-1.5",
},
lg: {
shared: "h-10 text-sm [&_svg:not([class*='size-'])]:size-4",
text: "px-3",
iconStart: "ps-2.5",
iconOnly: "px-2",
label: "gap-1.5",
},
}
const COUNT_SIZE: Record<TabsSize, string> = {
sm: "h-4 min-w-4 px-1 text-2xs [&_svg]:!size-2.5",
default: "h-4 min-w-4 px-1 text-2xs [&_svg]:!size-2.5",
lg: "h-5 min-w-5 px-1.5 text-1xs [&_svg]:!size-3",
}
// `line` spaces labels apart instead of padding them: the underline is the
// trigger's own width, so trigger padding would run it past the words. The
// gap steps with the size, one rung per step.
const LINE_GAP: Record<TabsSize, string> = {
sm: "gap-3",
default: "gap-4",
lg: "gap-5",
}
const TabsContext = createContext<{
activeValue: string | undefined
size: TabsSize
variant: TabsVariant
orientation: "horizontal" | "vertical"
}>({ activeValue: undefined, size: "default", variant: "pill", orientation: "horizontal" })
// @use-when swapping the content panel below a row of labels, including
// filtering one list by status (All, Open, Closed), each tab showing that slice.
function Tabs({
className,
defaultValue,
value,
onValueChange,
size = "default",
variant = "pill",
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root> & {
size?: TabsSize
/** `line`: plain labels over an underline, for tabs inside a header. Horizontal only. */
variant?: TabsVariant
}) {
const [internalValue, setInternalValue] = useState(defaultValue)
const activeValue = value ?? internalValue
const handleValueChange = useCallback(
(...args: Parameters<NonNullable<typeof onValueChange>>) => {
setInternalValue(args[0])
onValueChange?.(...args)
},
[onValueChange]
)
return (
<TabsContext.Provider value={{ activeValue, size, variant, orientation }}>
<TabsPrimitive.Root
data-slot="tabs"
// Vertical puts the strip BESIDE the panels rather than above them, so
// the root's own axis flips with it. The gap is the same either way.
className={cn(
// Strip-to-panel gap is the bind rung (8px), read as a rung so a
// panel of fields can pass another rung through className.
"flex gap-(--spacing-rhythm-bind)",
orientation === "vertical" ? "flex-row" : "flex-col",
variant === "line" && orientation !== "vertical" && "self-stretch",
className
)}
orientation={orientation}
value={activeValue}
onValueChange={handleValueChange}
{...props}
/>
</TabsContext.Provider>
)
}
function TabsList({
className,
fullWidth = false,
children,
...props
}: React.ComponentProps<typeof TabsPrimitive.List> & {
fullWidth?: boolean
}) {
// Size is not read here: the list has no size-dependent class of its own, and
// a size change reaches the indicator through the ResizeObserver on the
// triggers, which is what actually resized.
const { activeValue, size, variant, orientation } = useContext(TabsContext)
const isVertical = orientation === "vertical"
const isLine = variant === "line" && !isVertical
const listRef = useRef<HTMLDivElement>(null)
const [pill, setPill] = useState<{
x: number
y: number
width: number
height: number
/** Set when the box moved because a trigger resized (a count's slot
* opening or closing, a font landing), not because the pick changed. */
follow?: boolean
} | null>(null)
const shouldReduceMotion = useReducedMotion()
const trackRef = useRef<HTMLDivElement>(null)
// Which ends have more past them, for the arrows. Set only when one flips, so
// scrolling does not re-render.
const [more, setMore] = useState({ start: false, end: false })
useIsomorphicLayoutEffect(() => {
const list = listRef.current
if (!list) return
const measure = (follow = false) => {
const active = findTrigger(list, activeValue)
// Measure the trigger's full box, vertical too. An absolute child is
// positioned against the list's PADDING box, while the trigger sits
// inside the list's `p-1`. Deriving the vertical box from the trigger
// keeps the indicator inset correctly whatever that padding is. The list
// scrolls, and `boxIn` folds its scroll offset back in, so the position
// is in content space, where an absolute child of a scroller lives.
setPill(active ? { ...boxIn(list, active), follow } : null)
}
measure()
// Triggers resize on font load, container resize, and count changes. A
// resize is followed frame by frame with no spring: a count's slot tweens
// the trigger's width, and a spring retargeted every frame would trail
// the trigger's edge. Only a change of pick slides. The observer reports
// once on connect, which `measure()` above already covered, so that first
// report is skipped or it would cancel the slide a new pick just started.
let connected = false
const observer = new ResizeObserver(() => {
if (connected) measure(true)
connected = true
})
observer.observe(list)
list
.querySelectorAll('[data-slot="tabs-trigger"]')
.forEach((el) => observer.observe(el))
return () => observer.disconnect()
}, [activeValue, children])
// Overflow fades. Each edge fades only while there is more to see past it,
// ramping in with scroll distance, so a strip that fits shows no fade at all
// and a fresh one fades only its far end. It is a MASK, not a painted
// gradient: the strip turns transparent toward the edge and the track's own
// fill shows through, so it matches whatever colour the track is in either
// theme, or after a consumer restyles it. Written straight to the DOM, the
// same way ScrollFade does it, so scrolling never re-renders.
useIsomorphicLayoutEffect(() => {
const list = listRef.current
if (!list) return
const fine = window.matchMedia("(pointer: fine)")
const coarse = window.matchMedia("(pointer: coarse)")
const track = trackRef.current
const update = () => {
// Bleed: on a touch screen a strip wider than its space runs on to the
// screen's edge. Decided against the space the track was GIVEN, never its
// own width, which the bleed itself changes, so the two cannot feed back.
if (track && !isVertical) {
const space = track.parentElement?.getBoundingClientRect()
const strip = list.scrollWidth + track.offsetWidth - track.clientWidth
const bleeds = coarse.matches && !!space && strip > space.width + 1
track.toggleAttribute("data-bleed", bleeds)
if (bleeds && space) {
const rtl = getComputedStyle(track).direction === "rtl"
const gap = Math.max(rtl ? space.left : document.documentElement.clientWidth - space.right, 0)
track.style.setProperty("--tabs-bleed", `${gap}px`)
} else {
track.style.removeProperty("--tabs-bleed")
}
}
// scrollLeft runs negative in a right-to-left strip; the distance from
// the start is its size either way.
const scroll = Math.abs(isVertical ? list.scrollTop : list.scrollLeft)
const overflow = isVertical
? list.scrollHeight - list.clientHeight
: list.scrollWidth - list.clientWidth
const start = scroll > 1
const end = overflow - scroll > 1
const arrows = fine.matches && !isVertical
// Without arrows a fade ramps in with scroll distance; with them it is
// full width at once, since the arrow needs its clear room straight away.
let fadeStart = 0
let fadeEnd = 0
if (start) fadeStart = arrows ? FADE_ARROW : Math.min(scroll, FADE)
if (end) fadeEnd = arrows ? FADE_ARROW : Math.min(overflow - scroll, FADE)
list.style.setProperty("--tabs-fade-start", `${fadeStart}px`)
list.style.setProperty("--tabs-fade-end", `${fadeEnd}px`)
list.style.setProperty("--tabs-hold-start", `${arrows && start ? ARROW_HOLD : 0}px`)
list.style.setProperty("--tabs-hold-end", `${arrows && end ? ARROW_HOLD : 0}px`)
const next = { start: arrows && start, end: arrows && end }
setMore((prev) => (prev.start === next.start && prev.end === next.end ? prev : next))
}
update()
list.addEventListener("scroll", update, { passive: true })
fine.addEventListener("change", update)
coarse.addEventListener("change", update)
const observer = new ResizeObserver(update)
observer.observe(list)
if (track?.parentElement) observer.observe(track.parentElement)
list
.querySelectorAll('[data-slot="tabs-trigger"]')
.forEach((el) => observer.observe(el))
return () => {
list.removeEventListener("scroll", update)
fine.removeEventListener("change", update)
coarse.removeEventListener("change", update)
observer.disconnect()
}
}, [isVertical, children])
// An arrow moves the strip most of a width, keeping the last tab in view.
const page = (towardEnd: boolean) => {
const list = listRef.current
if (!list) return
const rtl = getComputedStyle(list).direction === "rtl"
const step = list.clientWidth * 0.75 * (towardEnd ? 1 : -1) * (rtl ? -1 : 1)
list.scrollBy({ left: step, behavior: shouldReduceMotion ? "auto" : "smooth" })
}
// Keep the active tab in view, centred where the strip allows. The browser
// already scrolls a FOCUSED tab into view, but only to the nearest edge, where
// it sits under the fade; and a click or a controlled `value` change moves no
// focus at all. The first run jumps (a page should load with its tab already
// showing); later ones glide unless the reader asked for less motion.
//
// The glide runs on the PILL's spring, never the browser's smooth scroll. The
// pill slides through the strip's content while the strip scrolls under it, so
// what the eye sees is the difference of the two motions. On two clocks (a
// 150ms spring against a smooth scroll of roughly twice that, its length up to
// the browser) they fought: moving left, the strip scrolled right as the pill
// slid left, the pill all but stood still while the labels slid beneath it, and
// the strip kept drifting after the pill had landed. On one clock the
// difference is itself that spring, so pill, labels and strip land together.
const hasScrolled = useRef(false)
useIsomorphicLayoutEffect(() => {
const list = listRef.current
if (!list) return
const active = findTrigger(list, activeValue)
if (!active) return
const axis = isVertical ? "scrollTop" : "scrollLeft"
const range = isVertical
? list.scrollHeight - list.clientHeight
: list.scrollWidth - list.clientWidth
// Clamped by hand: a tab near either end settles flush against it rather
// than centring past the content, and a spring aimed past the range would
// stall at the edge and land late.
const target = Math.min(
Math.max(
isVertical
? active.offsetTop - (list.clientHeight - active.offsetHeight) / 2
: active.offsetLeft - (list.clientWidth - active.offsetWidth) / 2,
0
),
Math.max(range, 0)
)
const glide = hasScrolled.current && !shouldReduceMotion
hasScrolled.current = true
if (!glide) {
list[axis] = target
return
}
// Starts from the live scroll position, so a second click mid-glide
// retargets instead of jumping. A wheel or touch on the strip hands it back
// to the reader.
const controls = animate(list[axis], target, {
...PILL.spring,
onUpdate: (value) => {
list[axis] = value
},
})
const stop = () => controls.stop()
list.addEventListener("wheel", stop, { passive: true })
list.addEventListener("touchstart", stop, { passive: true })
return () => {
stop()
list.removeEventListener("wheel", stop)
list.removeEventListener("touchstart", stop)
}
}, [activeValue, isVertical])
const mask = `linear-gradient(${isVertical ? "to bottom" : "to right"}, transparent var(--tabs-hold-start, 0px), #000 var(--tabs-fade-start, 0px), #000 calc(100% - var(--tabs-fade-end, 0px)), transparent calc(100% - var(--tabs-hold-end, 0px)))`
return (
// The TRACK (edge, fill, corners) is this wrapper; the strip inside it is
// what scrolls. They were one element, and a fade on it would have faded
// the track's own border and fill along with the tabs. `overflow-hidden`
// clips the strip to the track's inner corners, so a pill sliding past an
// end never pokes out of the rounded edge.
// `className` lands here: it is where width, margin and every other
// outside-facing class already meant to go.
// No external margin: spacing below the tabs is the caller's job. For the
// tabs-above-content pattern, add your own gap (e.g. `mb-3`).
<div
ref={trackRef}
data-slot="tabs-list-track"
className={cn(
// `line` has no track: the labels sit straight on whatever holds them.
// The 1px overhang lives on the strip inside (below), not here, so a
// margin class passed to TabsList cannot cancel it: os passed `mb-0`
// and tailwind-merge dropped the overhang, leaving the bar above the
// rule (2026-10-22). No `overflow-hidden` either: it would clip it.
isLine
? "relative flex flex-1"
: "relative flex overflow-hidden rounded-lg border border-border bg-neutral-50 dark:bg-neutral-900",
isVertical ? "flex-col max-h-full" : "max-w-full",
fullWidth ? "w-full" : "w-fit",
// Bleeding on a touch screen: the strip runs on to the screen edge, so
// a tab is cut off there and reads as more to swipe to. The track's box
// goes, since a frame that ends short of the edge is what let the cut
// fall in a gap between tabs and look like the end of the row.
"data-bleed:max-w-[calc(100%+var(--tabs-bleed))] data-bleed:-me-(--tabs-bleed) data-bleed:rounded-none data-bleed:border-transparent data-bleed:bg-transparent dark:data-bleed:bg-transparent",
className
)}
>
<TabsPrimitive.List
ref={listRef}
data-slot="tabs-list"
style={{ maskImage: mask, WebkitMaskImage: mask }}
className={cn(
// `relative` anchors the indicator: `boxIn` measures in this element's
// padding box, which is where an absolute child's left:0 resolves,
// and an absolute child of a scroller scrolls with its content.
// Nested radii are concentric: outer = inner + gutter, so the 12px track
// needs a 4px `p-1` around its 8px pill. A 2px gutter would call for a
// 10px inner radius, which is not a step on the ladder.
// No height here: the list takes its size from the triggers plus this
// padding, so a tab is exactly as tall as the NavItem of the same size.
// `line` keeps the `p-1`: it is the room a trigger's focus ring needs
// inside a strip that clips, and the underline sits in its bottom 4px.
"text-muted-foreground relative flex min-w-0 min-h-0 flex-1 p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
// `line`: the strip reaches 1px past the track's bottom, so the bar
// at its bottom edge covers the rule under it. `z-10` paints it over
// that rule and over anything after it in the page that touches it.
// `-ms-1.5` pulls the strip out by its own padding plus the
// trigger's (4 + 2px), so the first label starts on the content
// edge like the title above it. The room stays for the focus ring.
isLine && cn(LINE_GAP[size], "z-10 -mb-px -ms-1.5"),
// The strip scrolls along its OWN axis, and never bounces or hands its
// scroll on to the page at its ends. Horizontal leaves the vertical
// axis alone so a wheel over the strip still scrolls the page.
// No `justify-center`: on a strip wider than its track that centres the
// overflow too, pushing the first tabs past the START edge, where no
// scroll position can reach them. A fitting strip is `w-fit` or has
// `flex-1` triggers, so centring never did anything there anyway.
isVertical
? "flex-col items-stretch overflow-y-auto overscroll-y-none"
: "items-center overflow-x-auto overflow-y-hidden overscroll-x-none"
)}
{...props}
>
{/* Rendered before the triggers so they paint over it. */}
{pill && (
<motion.span
aria-hidden
data-slot="tabs-indicator"
// `line`: a 3px accent bar on the strip's bottom edge, under the
// label, not a fill behind it, whose last pixel covers the rule
// below (see TabsVariant). Square corners, so its ends meet that
// rule flush, and the plain accent in both themes, the colour of
// the rule it sits on is the kit's border, not the pill's tint.
// It slides on `left`, not a transform: a transformed bar is
// painted on its own layer at the page's fractional offset and
// blurs against the 1px rule it covers, while a laid-out box snaps
// to the same device pixel the rule does. It rides the same spring.
className={cn(
// ui-md-allow-physical-direction: the indicator is placed by a translate from the tab's measured offset, which is physical
"pointer-events-none absolute left-0",
isLine
? "bottom-0 h-0.75 bg-accent"
: "top-0 rounded-md bg-accent-100 dark:bg-accent-800"
)}
// Height is set, not animated: every trigger in a list shares one
// height from its size tier, so it is identical for all of them in
// either orientation.
// BOTH axes animate. `y` used to be an inline `top`, which is correct
// for a horizontal strip (every trigger shares one `y`) but meant a
// vertical strip JUMPED the pill between rows with no transition,
// since only `x` and `width` were ever animated and `x` never changes
// in a column. Animating `y` unconditionally costs a horizontal list
// nothing: its value is constant, so the spring never runs.
style={isLine ? undefined : { height: pill.height }}
// initial={false}: adopt the first measurement instead of animating
// in from x:0/width:0 on mount.
initial={false}
animate={isLine ? { left: Math.round(pill.x), width: Math.round(pill.width) } : { x: pill.x, y: pill.y, width: pill.width }}
transition={shouldReduceMotion || pill.follow ? { duration: 0 } : PILL.spring}
/>
)}
{children}
</TabsPrimitive.List>
{/* Mouse only (see FADE_ARROW). Out of the tab order and hidden from
screen readers: the tablist's arrow keys already reach every tab. */}
{(["start", "end"] as const).map((edge) =>
more[edge] ? (
<div
key={edge}
className={cn(
"absolute inset-y-0 flex items-center",
edge === "start" ? "start-0 ps-1" : "end-0 pe-1"
)}
>
<Button
variant="ghost"
size="icon-sm"
tabIndex={-1}
aria-hidden
onClick={() => page(edge === "end")}
iconStart={edge === "start" ? <ChevronLeft className="rtl:rotate-180" /> : <ChevronRight className="rtl:rotate-180" />}
/>
</div>
) : null
)}
</div>
)
}
function TabsTrigger({
className,
children,
value,
icon,
count,
...props
}: React.ComponentProps<typeof TabsPrimitive.Tab> & {
icon?: React.ReactNode
count?: React.ReactNode
}) {
const { activeValue, size, variant, orientation } = useContext(TabsContext)
const isActive = value === activeValue
const isLine = variant === "line" && orientation !== "vertical"
// Icon-only: an icon with no label. Uses symmetric padding so the lone icon
// sits in a square-ish pill instead of the text-tuned `px-3`. Callers MUST
// pass an `aria-label` for a text-less trigger (there is no visible name).
// A counter is a visible datum, so a trigger carrying one is never icon-only.
const isIconOnly = icon != null && children == null && count == null
return (
<TabsPrimitive.Tab
data-slot="tabs-trigger"
// Read by TabsList to measure the indicator's target box.
data-value={String(value)}
value={value}
className={cn(
// svg size is scoped with :not so a nested icon (e.g. inside a count
// chip) can set its own size-* instead of losing to this rule.
// No `motion-reduce:transition-none` on the color fade: a color change
// is non-vestibular and aids comprehension, so reduced motion keeps it.
// Only the indicator's travel is suppressed. The press scale is a
// movement, so it joins the transition list and goes under reduced
// motion (the release would otherwise snap).
// The active label sits on the pill's accent tint, so it takes the
// darker step in light and the lighter one in dark (accent on its own
// tint is only 3.2:1).
// `transition-[color]`, NOT `transition-colors`: background-color must
// NOT transition here. The indicator renders before the triggers so
// they paint over it, which means a hover fill that fades out sits ON
// TOP of the arriving pill and muddies it. Clearing the fill instantly
// also matches the frequency principle: a tab is a 100+/day hover, and
// those should not animate.
"relative data-[active]:text-accent-700 dark:data-[active]:text-accent-200 text-muted-foreground font-medium transition-[color,transform] duration-small ease-small motion-reduce:transition-[color] rotate-[0.0001deg] active:scale-[0.98] outline-hidden focus-visible:ring-ring-focus inline-flex items-center gap-2 rounded-md normal-case tracking-normal whitespace-nowrap focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:shrink-0",
// `flex-1` is HORIZONTAL-ONLY. It means "start from a zero main-axis
// basis and grow to fill", and in a column the main axis is HEIGHT, so
// every trigger in a vertical strip collapsed to a sliver: the list
// takes its height from its triggers, so there was no height to grow
// into. A vertical strip sizes each row to its content and stretches
// them to a common width instead, which `items-stretch` on the list
// already does.
// `justify-between` rather than `justify-start`: the count is a SIBLING
// of the label span, so between pushes it to the trailing edge, which is
// how a column of counts is read (every mail sidebar does this). With no
// count there is only one child, and between puts a lone child at the
// start, so a trigger without one is unaffected and nothing reflows.
// `line` triggers hug their label (no `flex-1`): the underline is the
// trigger's width, and the list's gap spaces them. The selected label
// is the foreground colour, since the accent bar already marks it;
// the rest darken on hover, as plain text links do.
orientation === "vertical" ? "justify-between" : isLine ? "justify-center" : "flex-1 justify-center",
isLine && "px-0.5 data-[active]:text-foreground hover:text-foreground",
TRIGGER_SIZE[size].shared,
isLine ? null : isIconOnly ? TRIGGER_SIZE[size].iconOnly : TRIGGER_SIZE[size].text,
// An icon-led horizontal trigger trims its start padding 2px, as Button
// and NavItem do, so the label side reads as wide as the icon side.
!isLine && !isIconOnly && icon != null && orientation !== "vertical" && TRIGGER_SIZE[size].iconStart,
className
)}
{...props}
>
<span
className={cn(
"relative z-10 inline-flex items-center",
TRIGGER_SIZE[size].label
)}
>
{icon}
{children}
</span>
<CountArrival
count={count}
// The trigger's own `gap-2`, the same at every size. A vertical
// trigger pushes the chip to its far edge, so it holds still there.
gap="gap-2"
pinned={orientation === "vertical" ? "end" : "start"}
data-slot="tabs-trigger-count"
className={cn(
// tabular-nums so a live count doesn't jitter. `transition-colors`
// is correct HERE and nowhere else in this file: `z-10` puts the
// chip above the pill, not under it, so its colour can cross-fade
// without muddying the indicator. 150ms pairs it with the label.
"relative z-10 inline-flex items-center justify-center gap-1 rounded-full font-medium tabular-nums transition-colors duration-small ease-small [&_svg]:shrink-0",
COUNT_SIZE[size],
// One quiet chip on every tab, picked or not. The label's colour
// and the pill already mark the pick; a solid accent count on top
// was the loudest mark on the row, louder than the page's own
// primary button. Its number follows the label to the picked colour.
"bg-neutral-500/10 dark:bg-neutral-500/15",
isActive ? "text-current" : "text-muted-foreground"
)}
/>
</TabsPrimitive.Tab>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Panel>) {
return (
<TabsPrimitive.Panel
data-slot="tabs-content"
className={cn(
// The panel takes focus (Base UI gives it a tab stop), so it shows the
// neutral ring when the keyboard lands there.
"flex-1 rounded-md outline-none focus-visible:ring-ring-focus focus-visible:ring-[3px]",
className
)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }