Panel tabs
160 lines · 2 files · MIT
Several lists in one card, switched by a sliding underline.
- /pricing4,120
- /blog/launch2,904
- /1,877
- google.com5,210
- x.com1,348
- Italy3,002
- Germany1,970
import { Tabs as BaseTabs } from "@base-ui/react/tabs";
import { useState, type ReactNode } from "react";
import { cn } from "./cn";
import { StableLabel } from "./stable-label";
/** What sits in the tab row's corner: the open tab's own, else the card's. */
function cornerOf(
tabs: { value: string; end?: ReactNode }[],
active: string | undefined,
fallback: ReactNode,
): ReactNode {
return tabs.find((t) => t.value === active)?.end ?? fallback;
}
/**
* Several lists in one card, switched by underline tabs (rdyrct-design, "The
* app's surfaces"): "Top links · Decaying · Dead", "Referrers · Campaigns".
* The tab names the list, so the card needs no title of its own. Base UI owns
* the keyboard and ARIA: arrow keys move between tabs, Tab moves into the
* panel.
*/
export function PanelTabs({
tabs,
defaultValue,
end,
className,
}: {
/** `count` follows the label, muted, when there is one. `end` replaces
* the card's own `end` while that tab is open (a list's Show all). */
tabs: { value: string; label: string; count?: number; panel: ReactNode; end?: ReactNode }[];
defaultValue?: string;
/** Something on the right of the tab row, e.g. an "All links" link. */
end?: ReactNode;
className?: string;
}) {
const [active, setActive] = useState(defaultValue ?? tabs[0]?.value);
const corner = cornerOf(tabs, active, end);
return (
<BaseTabs.Root
value={active}
onValueChange={(value: string) => setActive(value)}
className={cn("rounded-xl bg-surface px-4 pt-3 pb-3.5 smooth-shadow-ring-xs", className)}
>
<div className="mb-3 flex items-center gap-4 shadow-[inset_0_-1px_0_var(--border)]">
<BaseTabs.List className="relative flex min-w-0 gap-4 overflow-x-auto">
{tabs.map((tab) => (
<BaseTabs.Tab
key={tab.value}
value={tab.value}
className="cursor-pointer pb-2.5 text-sm whitespace-nowrap text-muted outline-none focus-visible:text-text data-[active]:font-semibold data-[active]:text-text [@media(hover:hover)]:hover:text-text"
>
<StableLabel>{tab.label}</StableLabel>
{tab.count !== undefined && (
<span className="tnum ml-1.5 font-normal text-muted">{tab.count}</span>
)}
</BaseTabs.Tab>
))}
{/* One underline that slides to the chosen tab; the panel itself
swaps at once. */}
<BaseTabs.Indicator className="absolute bottom-0 left-0 h-[1.5px] w-(--active-tab-width) translate-x-(--active-tab-left) bg-text transition-[translate,width] duration-200 ease-out motion-reduce:transition-none" />
</BaseTabs.List>
{corner && <div className="ml-auto shrink-0 pb-2.5 text-xs text-muted">{corner}</div>}
</div>
{/* Every panel stays mounted in the same grid cell and only the active
one is visible, so the card is as tall as its tallest list and
switching tabs never moves the card, or the one beside it in a row. */}
<div className="grid">
{tabs.map((tab) => (
<BaseTabs.Panel
key={tab.value}
value={tab.value}
keepMounted
// Base UI hides an inactive panel with the `hidden` attribute,
// which Tailwind's base layer turns into display: none
// !important, out of reach of any utility. Dropped here: the
// panel keeps its place but goes invisible (data-hidden), and
// Base UI's `inert` keeps it out of focus and the a11y tree.
render={(props) => <div {...props} hidden={undefined} />}
className="col-start-1 row-start-1 min-w-0 data-[hidden]:invisible"
>
{tab.panel}
</BaseTabs.Panel>
))}
</div>
</BaseTabs.Root>
);
}
import { useLayoutEffect, useRef, type RefObject } from "react";
import { cn } from "./cn";
/**
* Keeps an absolutely placed element (an underline, a segmented control's
* pill) over whichever child of `bar` matches `selector`: as wide as it,
* moved across to it. Measured after every render and whenever the bar
* changes size (fonts loading, a phone turning). The first placement does
* not animate (the element starts with `data-still`), so a page opens with
* it in place, not sliding in from the left.
*/
export function useSlideTo<T extends HTMLElement>(
bar: RefObject<HTMLElement | null>,
selector: string,
) {
const slider = useRef<T>(null);
useLayoutEffect(() => {
const el = bar.current;
const moving = slider.current;
if (!el || !moving) return;
const place = () => {
const current = el.querySelector<HTMLElement>(selector);
moving.style.opacity = current ? "1" : "0";
if (!current) return;
moving.style.width = `${current.offsetWidth}px`;
moving.style.translate = `${current.offsetLeft}px 0`;
};
place();
// Animate from the second placement on.
const raf = requestAnimationFrame(() => moving.removeAttribute("data-still"));
const resized = new ResizeObserver(place);
resized.observe(el);
return () => {
cancelAnimationFrame(raf);
resized.disconnect();
};
});
return slider;
}
/**
* The underline of a tab bar whose tabs are links or plain buttons (API,
* Platform): one bar that slides to the current tab, instead of each tab
* drawing its own and the line jumping. PanelTabs gets the same from Base
* UI's Tabs.Indicator.
*
* It follows whichever child of `bar` has `aria-current="page"`, measured
* after every render and whenever the bar changes size (fonts loading, a
* phone turning). The first placement does not animate: a page opens with
* its underline in place, not sliding in from the left.
*/
export function TabUnderline({
bar,
className,
}: {
bar: RefObject<HTMLElement | null>;
className?: string;
}) {
const line = useSlideTo<HTMLSpanElement>(bar, '[aria-current="page"]');
return (
<span
ref={line}
aria-hidden
data-still=""
className={cn(
"pointer-events-none absolute bottom-0 left-0 h-[1.5px] bg-text transition-[translate,width] duration-200 ease-out data-[still]:transition-none motion-reduce:transition-none",
className,
)}
/>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/tabs- Category
- Navigation
- Files
- tabs.tsxtab-underline.tsx
- Brings in
- @base-ui/react