Project page
Overview, Tasks and Files sit under the project title, in the pill track or, on a page with its own rule, the line variant. The tab names never change, so people learn where things are.
Components / NavigationStable
Splits related content into panels so the reader sees one at a time without leaving the page.
'use client'
import { useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { motionOk, tokenMs, useIndicator } from './Indicator'
// Nacre Tabs. React plus Tailwind classes only; needs nacre-theme.css and Indicator.tsx (the gliding indicator it
// shares with Segmented control). The indicator glides to the selected tab (base 240, out; the line reaches across
// both tabs on the way), retargeted mid-flight. Panels cross-fade in place: the old one fades out on top (quick 160)
// while the new one, already in the flow, fades in and rises 4 px (base 240), so nothing below jumps twice. Arrow
// keys, Home and End switch at once, with no movement; so do reduced motion and Motion off.
export type TabItem = { value: string; label: string; content: ReactNode; disabled?: boolean }
export type TabsVariant = 'line' | 'pill'
export type TabsSize = 'sm' | 'md'
export type TabsProps = {
label: string
items: TabItem[]
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
variant?: TabsVariant
size?: TabsSize
className?: string
}
const tabSize: Record<TabsVariant, Record<TabsSize, string>> = {
line: { sm: 'h-8 text-label', md: 'h-10 text-body' },
pill: { sm: 'h-7 px-2.5 text-label', md: 'h-8 px-3.5 text-body' },
}
export function Tabs({ label, items, value, defaultValue, onValueChange, variant = 'pill', size = 'md', className = '' }: TabsProps) {
const id = useId()
const [inner, setInner] = useState(defaultValue ?? items.find((i) => !i.disabled)?.value)
const current = value ?? inner
const list = useRef<HTMLDivElement>(null)
const keyboard = useRef(false)
const thumb = useIndicator(list, current, keyboard, variant === 'line')
const enabled = items.filter((i) => !i.disabled)
const index = (v: string) => items.findIndex((i) => i.value === v)
const tabId = (v: string) => `${id}-tab-${index(v)}`
const panelId = (v: string) => `${id}-panel-${index(v)}`
const choose = (v: string) => {
if (value === undefined) setInner(v)
onValueChange?.(v)
}
const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
const n = enabled.length
const at = enabled.findIndex((i) => i.value === current)
const to =
e.key === 'ArrowRight' ? enabled[at < 0 ? 0 : (at + 1) % n]
: e.key === 'ArrowLeft' ? enabled[at < 0 ? n - 1 : (at - 1 + n) % n]
: e.key === 'Home' ? enabled[0]
: e.key === 'End' ? enabled[n - 1]
: undefined
if (!to) return
e.preventDefault()
choose(to.value)
document.getElementById(tabId(to.value))?.focus()
}
const line = variant === 'line'
// The panel that was showing stays on top while it fades out. Keyboard changes and reduced motion skip it.
const panels = useRef<HTMLDivElement>(null)
const [shown, setShown] = useState(current)
const [leaving, setLeaving] = useState<string | undefined>(undefined)
if (shown !== current) {
setShown(current)
setLeaving(shown)
}
useLayoutEffect(() => {
const box = panels.current
if (!box) return
// A hidden panel drops what is left of its fade, so it shows at full strength next time.
for (const p of box.querySelectorAll<HTMLElement>(':scope > [hidden]')) p.getAnimations().forEach((a) => a.cancel())
const now = box.querySelector<HTMLElement>(':scope > [data-part="panel"]:not([hidden]):not([data-leaving])')
const old = box.querySelector<HTMLElement>(':scope > [data-leaving]')
if (!old || !now) return
if (keyboard.current || !motionOk(box)) return setLeaving(undefined)
const easing = getComputedStyle(box).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
// The panels' box glides between the two heights (base 240 out), so what sits below slides instead of jumping. A
// switch mid-glide starts from the height drawn now.
const running = box.getAnimations()
const fromH = running.length ? box.getBoundingClientRect().height : old.offsetHeight
running.forEach((a) => a.cancel())
const toH = now.offsetHeight
if (fromH !== toH) {
box.style.overflow = 'hidden'
const done = () => { box.style.overflow = '' }
box.animate([{ height: `${fromH}px` }, { height: `${toH}px` }], { duration: tokenMs(box, '--nx-dur-base', 240), easing }).finished.then(done, done)
}
// Retarget: start the new panel from the opacity it is drawn at now (it may be mid-fade from a quick switch back).
const from = now.getAnimations().length ? getComputedStyle(now).opacity : '0'
now.getAnimations().forEach((a) => a.cancel())
now.animate([{ opacity: from, transform: 'translateY(4px)' }, { opacity: 1, transform: 'none' }], { duration: tokenMs(box, '--nx-dur-base', 240), easing })
const fade = old.animate([{ opacity: getComputedStyle(old).opacity }, { opacity: 0 }], { duration: tokenMs(box, '--nx-dur-quick', 160), easing, fill: 'forwards' })
const name = leaving
fade.finished.then(() => setLeaving((l) => (l === name ? undefined : l)), () => {})
}, [leaving])
return (
<div
data-part="root"
className={`flex min-w-0 flex-col gap-4 ${className}`}
onKeyDown={() => { keyboard.current = true }}
onPointerDown={() => { keyboard.current = false }}
>
<div
ref={list}
role="tablist"
aria-label={label}
data-part="list"
className={`relative flex flex-wrap ${line ? 'gap-x-5 border-b border-line-subtle' : 'w-fit max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ring-line-subtle'}`}
>
<span ref={thumb} aria-hidden="true" data-part="indicator" className={`pointer-events-none absolute top-0 left-0 origin-top-left rounded-full opacity-0 ${line ? 'bg-action' : 'bg-surface shadow-1'}`} />
{items.map((it) => {
const on = it.value === current
// Until the indicator is placed ([data-ready] on the list), the selected tab draws its own selection.
const fallback = line ? 'shadow-[inset_0_-2px_0_var(--nx-action)]' : 'bg-surface shadow-1'
return (
<button
key={it.value}
id={tabId(it.value)}
type="button"
role="tab"
aria-selected={on}
aria-controls={panelId(it.value)}
tabIndex={on ? 0 : -1}
disabled={it.disabled}
data-state={on ? 'on' : 'off'}
data-part="tab"
onClick={() => choose(it.value)}
onKeyDown={onKey}
className={`relative cursor-pointer font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled ${line ? 'rounded-xs' : 'rounded-full'} ${tabSize[variant][size]} ${on ? `text-fg-strong ${fallback} [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]` : 'text-fg-muted enabled:hover:text-fg-strong'}`}
>
{it.label}
</button>
)
})}
</div>
<div ref={panels} data-part="panels" className="relative min-w-0">
{items.map((it) => {
const out = it.value === leaving
return (
<div
key={it.value}
id={panelId(it.value)}
role="tabpanel"
aria-labelledby={tabId(it.value)}
tabIndex={out ? -1 : 0}
hidden={it.value !== current && !out}
aria-hidden={out || undefined}
inert={out || undefined}
data-part="panel"
data-leaving={out ? '' : undefined}
className={`min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ${out ? 'pointer-events-none absolute inset-x-0 top-0' : ''}`}
>
{it.content}
</div>
)
})}
</div>
</div>
)
}
'use client'
import { useLayoutEffect, useRef, type RefObject } from 'react'
// Nacre gliding indicator: the one moving selection that Segmented control and Tabs share. React only; copy it next
// to SegmentedControl.tsx or Tabs.tsx. Motion: base 240 out (a line stretches across on the way), by transform only,
// retargeted from where it is drawn.
type Box = { x: number; y: number; w: number; h: number }
const same = (a: Box, b: Box) => a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h
/** A duration token in ms, read from CSS so a slowed-down parent slows this too. */
export function tokenMs(el: Element, name: string, fallback: number): number {
const v = getComputedStyle(el).getPropertyValue(name).trim()
const n = parseFloat(v)
if (!Number.isFinite(n)) return fallback
return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}
/** Reduced motion, or an ancestor that switched motion off, means no movement. */
export function motionOk(el: Element): boolean {
return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}
/**
* One thumb under the child of `list` marked data-state="on". The thumb is laid out at the new item at once (width and
* height set, never animated) and a FLIP transform carries it from where it is drawn now, so a change in mid-flight
* continues from there instead of jumping or restarting. First placement, resizes, keyboard changes (keyboard.current)
* and reduced motion are instant. `line` draws a 2 px bar on the item's bottom edge instead of a fill; it reaches over
* both items before it lets go of the old one. The list gets data-ready once the thumb is placed; until then the
* selected item draws its own selection.
*/
export function useIndicator(list: RefObject<HTMLElement | null>, active: string | undefined, keyboard: RefObject<boolean>, line = false) {
const thumb = useRef<HTMLSpanElement>(null)
const last = useRef<Box | null>(null)
useLayoutEffect(() => {
const c = list.current
const t = thumb.current
if (!c || !t) return
const place = (animate: boolean) => {
const item = c.querySelector<HTMLElement>(':scope > [data-state="on"]')
if (!item || !item.offsetWidth) {
c.removeAttribute('data-ready')
t.style.opacity = '0'
last.current = null
return
}
const box: Box = line
? { x: item.offsetLeft, y: item.offsetTop + item.offsetHeight - 1, w: item.offsetWidth, h: 2 }
: { x: item.offsetLeft, y: item.offsetTop, w: item.offsetWidth, h: item.offsetHeight }
if (!animate && last.current && same(last.current, box)) return
const running = t.getAnimations()
let from = last.current
if (running.length) {
const cr = c.getBoundingClientRect()
const tr = t.getBoundingClientRect()
from = { x: tr.left - cr.left - c.clientLeft, y: tr.top - cr.top - c.clientTop, w: tr.width, h: tr.height }
running.forEach((a) => a.cancel())
}
t.style.width = `${box.w}px`
t.style.height = `${box.h}px`
t.style.transform = `translate(${box.x}px, ${box.y}px)`
t.style.opacity = '1'
c.setAttribute('data-ready', '')
last.current = box
if (!animate || !from || same(from, box) || keyboard.current || !motionOk(c)) return
const easing = getComputedStyle(c).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
const at = (b: Box) => `translate(${b.x}px, ${b.y}px) scale(${b.w / box.w}, ${b.h / box.h})`
// The line stretches over both tabs on the way (leading edge first), then lets go of the old one.
const reach = { x: Math.min(from.x, box.x), y: box.y, w: Math.max(from.x + from.w, box.x + box.w) - Math.min(from.x, box.x), h: box.h }
const frames = line && from.y === box.y ? [{ transform: at(from) }, { transform: at(reach), offset: 0.4 }, { transform: at(box) }] : [{ transform: at(from) }, { transform: at(box) }]
t.animate(frames, { duration: tokenMs(c, '--nx-dur-base', 240), easing })
}
let cancelled = false
place(true)
const ro = new ResizeObserver(() => place(false))
ro.observe(c)
document.fonts?.ready.then(() => { if (!cancelled) place(false) })
return () => {
cancelled = true
ro.disconnect()
}
}, [list, active, keyboard, line])
return thumb
}
<div data-part="root" class="flex min-w-0 flex-col gap-4 ">
<div role="tablist" aria-label="Project sections" data-part="list" class="relative flex flex-wrap w-fit max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ring-line-subtle">
<span aria-hidden="true" data-part="indicator" class="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full opacity-0 bg-surface shadow-1"></span>
<button id="_R_0_-tab-0" type="button" role="tab" aria-selected="true" aria-controls="_R_0_-panel-0" tabindex="0" data-state="on" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled rounded-full h-8 px-3.5 text-body text-fg-strong bg-surface shadow-1 [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]">Overview</button>
<button id="_R_0_-tab-1" type="button" role="tab" aria-selected="false" aria-controls="_R_0_-panel-1" tabindex="-1" data-state="off" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled rounded-full h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Tasks</button>
<button id="_R_0_-tab-2" type="button" role="tab" aria-selected="false" aria-controls="_R_0_-panel-2" tabindex="-1" data-state="off" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled rounded-full h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Files</button>
</div>
<div data-part="panels" class="relative min-w-0">
<div id="_R_0_-panel-0" role="tabpanel" aria-labelledby="_R_0_-tab-0" tabindex="0" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">Launch plan for the Q3 release. Next review on Thursday at 10:00.</div>
<div id="_R_0_-panel-1" role="tabpanel" aria-labelledby="_R_0_-tab-1" tabindex="0" hidden="" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">12 open tasks, 3 due this week. Ana has the most.</div>
<div id="_R_0_-panel-2" role="tabpanel" aria-labelledby="_R_0_-tab-2" tabindex="0" hidden="" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">Brief.pdf, Timeline.fig and 4 more, last changed today.</div>
</div>
</div>/* The Tailwind theme lines Tabs uses. They come from nacre-theme.css (Resources, Tokens), which also defines
the --nx-* values these lines point at. Import that file once; this list is what this component needs from it. */
@theme inline {
--color-surface: var(--nx-surface);
--color-sunken: var(--nx-sunken);
--color-fg-strong: var(--nx-fg-strong);
--color-fg: var(--nx-fg);
--color-fg-muted: var(--nx-fg-muted);
--color-fg-disabled: var(--nx-fg-disabled);
--color-line-subtle: var(--nx-line-subtle);
--color-focus: var(--nx-focus);
--color-action: var(--nx-action);
--color-transparent: transparent;
--text-body: 0.875rem;
--text-body--line-height: 1.25rem;
--text-body--letter-spacing: 0em;
--text-body--font-weight: 400;
--text-label: 0.8125rem;
--text-label--line-height: 1rem;
--text-label--letter-spacing: 0em;
--text-label--font-weight: 600;
--spacing: 0.25rem;
--radius-xs: 0.5rem;
--shadow-1: var(--nx-shadow-1);
--ease-out: cubic-bezier(.23, 1, .32, 1);
--breakpoint-sm: 40rem;
--breakpoint-md: 48rem;
}
Overview, Tasks and Files sit under the project title, in the pill track or, on a page with its own rule, the line variant. The tab names never change, so people learn where things are.
In the inbox side panel, the default pill variant switches between All, Mentions and Unread in a narrow column.
DoKeep labels to one or two words and the count of tabs low, up to six.
Don'tLet tabs wrap onto three lines or scroll sideways.
DoKeep the panel content related, so moving between tabs feels like one object.
Don'tHide a required form step behind a tab people may never open.