Calendar range
Day, Week and Month sit above the calendar. The thumb glides to the new range while the grid redraws under it.
Components / InputsStable
Switches between two to five views or modes of the same content, and the change shows at once.
'use client'
import { useId, useRef, useState, type KeyboardEvent, type Ref } from 'react'
import { useIndicator } from './Indicator'
// Nacre Segmented control: switch between two to five views of the same content. React plus Tailwind classes only;
// needs nacre-theme.css and Indicator.tsx (the gliding thumb it shares with Tabs). One thumb glides to the selection
// (base 240, out), retargeted mid-flight; arrow keys, Home and End move it at once.
// invalid rings the track; error is the message under it and implies invalid. ref reaches the root.
export type SegmentedOption = { value: string; label: string; disabled?: boolean }
export type SegmentedSize = 'sm' | 'md'
export type SegmentedControlProps = {
label: string
options: SegmentedOption[]
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
size?: SegmentedSize
disabled?: boolean
fullWidth?: boolean
className?: string
invalid?: boolean
error?: string
ref?: Ref<HTMLDivElement>
}
const heights: Record<SegmentedSize, string> = { sm: 'h-7 px-2.5 text-label', md: 'h-8 px-3.5 text-body' }
export function SegmentedControl({ label, options, value, defaultValue, onValueChange, size = 'md', disabled = false, fullWidth = false, invalid = false, error, className = '', ref }: SegmentedControlProps) {
const [inner, setInner] = useState(defaultValue)
const current = value ?? inner
const list = useRef<HTMLDivElement>(null)
const keyboard = useRef(false)
const thumb = useIndicator(list, current, keyboard)
const errorId = `${useId()}-error`
const bad = invalid || Boolean(error)
const enabled = disabled ? [] : options.filter((o) => !o.disabled)
// The tab stop is the selected option, or the first enabled one when nothing is selected yet.
const tabStop = options.some((o) => o.value === current) ? current : enabled[0]?.value
const choose = (v: string) => {
if (value === undefined) setInner(v)
onValueChange?.(v)
}
const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
const n = enabled.length
if (!n) return
const at = enabled.findIndex((o) => o.value === current)
const next = e.key === 'ArrowRight' || e.key === 'ArrowDown'
const prev = e.key === 'ArrowLeft' || e.key === 'ArrowUp'
const to =
next ? enabled[at < 0 ? 0 : (at + 1) % n]
: prev ? 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)
list.current?.querySelector<HTMLElement>(`[data-value="${CSS.escape(to.value)}"]`)?.focus()
}
return (
<div ref={ref} data-part="root" className={`max-w-full flex-col gap-1.5 ${fullWidth ? 'flex w-full' : 'inline-flex items-start'} ${className}`}>
<div
ref={list}
role="radiogroup"
aria-label={label}
aria-disabled={disabled || undefined}
aria-invalid={bad || undefined}
aria-describedby={error ? errorId : undefined}
data-part="track"
onKeyDown={() => { keyboard.current = true }}
onPointerDown={() => { keyboard.current = false }}
className={`relative max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ${fullWidth ? 'flex w-full' : 'inline-flex'} ${bad ? 'ring-error' : 'ring-line-subtle'}`}
>
<span ref={thumb} aria-hidden="true" data-part="thumb" className="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full bg-surface opacity-0 shadow-1" />
{options.map((o) => {
const on = o.value === current
return (
<button
key={o.value}
type="button"
role="radio"
aria-checked={on}
data-state={on ? 'on' : 'off'}
data-value={o.value}
data-part="segment"
disabled={disabled || o.disabled}
tabIndex={o.value === tabStop ? 0 : -1}
onClick={() => choose(o.value)}
onKeyDown={onKey}
className={`relative min-w-0 ${fullWidth ? 'flex-1' : 'flex-auto'} cursor-pointer truncate rounded-full font-[600] 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 ${heights[size]} ${on ? 'bg-surface text-fg-strong shadow-1 [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]' : 'text-fg-muted enabled:hover:text-fg-strong'}`}
>
{o.label}
</button>
)
})}
</div>
{error && <p data-part="error" id={errorId} className="text-caption text-error-strong transition-opacity duration-(--nx-dur-quick) ease-out starting:opacity-0">{error}</p>}
</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="max-w-full flex-col gap-1.5 inline-flex items-start ">
<div role="radiogroup" aria-label="Calendar range" data-part="track" class="relative max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 inline-flex ring-line-subtle">
<span aria-hidden="true" data-part="thumb" class="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full bg-surface opacity-0 shadow-1"></span>
<button type="button" role="radio" aria-checked="false" data-state="off" data-value="day" data-part="segment" tabindex="-1" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] 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 h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Day</button>
<button type="button" role="radio" aria-checked="true" data-state="on" data-value="week" data-part="segment" tabindex="0" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] 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 h-8 px-3.5 text-body bg-surface text-fg-strong shadow-1 [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]">Week</button>
<button type="button" role="radio" aria-checked="false" data-state="off" data-value="month" data-part="segment" tabindex="-1" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] 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 h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Month</button>
</div>
</div>/* The Tailwind theme lines Segmented control 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-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-error-strong: var(--nx-error-strong);
--color-error: var(--nx-error);
--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;
--text-caption: 0.75rem;
--text-caption--line-height: 1rem;
--text-caption--letter-spacing: 0.01em;
--text-caption--font-weight: 400;
--spacing: 0.25rem;
--shadow-1: var(--nx-shadow-1);
--ease-out: cubic-bezier(.23, 1, .32, 1);
--breakpoint-sm: 40rem;
--breakpoint-md: 48rem;
}
Day, Week and Month sit above the calendar. The thumb glides to the new range while the grid redraws under it.
The project toolbar has a two-option control for Board and List; the choice is remembered per person.
DoUse one or two short words per option, all about the same length.
Don'tPut more than five options in one control; it stops reading as one choice.
DoApply the change the moment an option is chosen.
Don'tPair it with an Apply button.