Date Time Picker
A compact calendar and time-wheel picker with a softly unfolding popover, AM/PM selection, local timezone readout, Now shortcut and explicit confirmation. Defaults to a 36px trigger, 32px day cells and a 480px desktop panel. Supports keyboard navigation, controlled or uncontrolled local date-time values, forms and reduced motion. Customize individual parts with classNames: trigger, content, calendar, day, selectedDay, time and confirmButton.
Preview
Pick a moment. Make it happen.
"use client";
import { useState } from "react";
import { DateTimePicker } from "@/components/motion/date-time-picker";
export function DateTimePickerPreview() {
const [value, setValue] = useState("2026-10-15T09:30");
return (<div className="flex w-full flex-col items-center gap-5 px-2 py-16">
<DateTimePicker value={value} onValueChange={setValue} name="scheduledAt"/>
<p className="text-xs text-muted-foreground">
Pick a moment. Make it happen.
</p>
</div>);
}
"use client";
// asharca.github.io/ui/components/motion/date-time-picker
import {
CalendarDays,
ChevronDown,
ChevronLeft,
ChevronRight,
Clock3,
} from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import {
type KeyboardEvent,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { Button } from "@/components/motion/button/base";
import {
DAY,
iso,
monthOf,
parse,
shiftMonth,
} from "@/components/motion/date-range-picker/date-utils";
import {
MorphPopover,
MorphPopoverContent,
MorphPopoverTrigger,
} from "@/components/motion/popover-morph";
import { WheelPicker } from "@/components/motion/wheel-picker";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type DateTimePickerClassNames = {
trigger?: string;
content?: string;
calendar?: string;
day?: string;
selectedDay?: string;
time?: string;
confirmButton?: string;
};
export interface DateTimePickerProps {
/** Local wall-clock time, YYYY-MM-DDTHH:mm. No timezone conversion is applied. */
value?: string;
defaultValue?: string;
/** Called only when Confirm is pressed. Dismissing discards the draft. */
onValueChange?: (value: string) => void;
label?: string;
disabled?: boolean;
name?: string;
className?: string;
classNames?: DateTimePickerClassNames;
}
const pad = (value: number) => String(value).padStart(2, "0");
const HOURS = Array.from({ length: 12 }, (_, index) => pad(index + 1));
const MINUTES = Array.from({ length: 60 }, (_, index) => pad(index));
const dateFormat = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
});
const monthFormat = new Intl.DateTimeFormat("en-US", {
month: "long",
year: "numeric",
timeZone: "UTC",
});
const dayFormat = new Intl.DateTimeFormat("en-US", {
dateStyle: "full",
timeZone: "UTC",
});
const focusClass =
"outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
function localNow() {
const now = new Date();
return `${String(now.getFullYear()).padStart(4, "0")}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
}
function validate(value: string) {
if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d$/.test(value))
throw new Error(
"DateTimePicker expects local time in YYYY-MM-DDTHH:mm format.",
);
parse(value.slice(0, 10));
return value;
}
function timeLabel(value: string) {
const hour = Number(value.slice(11, 13));
return `${pad(hour % 12 || 12)}:${value.slice(14)} ${hour < 12 ? "AM" : "PM"}`;
}
/** Calendar and time-wheel popover with an explicit draft/confirm boundary. */
export function DateTimePicker({
value: controlledValue,
defaultValue = "",
onValueChange,
label = "Choose date and time",
disabled = false,
name,
className,
classNames,
}: DateTimePickerProps) {
const [internal, setInternal] = useState(defaultValue);
const value = controlledValue ?? internal;
if (value) validate(value);
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState("");
const [session, setSession] = useState(0);
const trigger = useRef<HTMLButtonElement>(null);
const changeOpen = (next: boolean) => {
if (disabled) return;
if (next) {
setDraft(value || localNow());
setSession((current) => current + 1);
}
setOpen(next);
};
return (
<MorphPopover
open={open && !disabled}
onOpenChange={changeOpen}
className={cn("max-w-full", className)}
>
{name && (
<input type="hidden" name={name} value={value} disabled={disabled} />
)}
<MorphPopoverTrigger>
<Button
ref={trigger}
variant="outline"
disabled={disabled}
aria-label={`${label}: ${value ? `${dateFormat.format(parse(value.slice(0, 10)))}, ${timeLabel(value)}` : "not selected"}`}
className={cn(
"h-9 max-w-full gap-2 rounded-xl bg-background px-3 text-[13px] font-medium",
focusClass,
classNames?.trigger,
)}
>
<CalendarDays aria-hidden="true" className="size-4 shrink-0" />
{value ? (
<>
<span className="whitespace-nowrap">
{dateFormat.format(parse(value.slice(0, 10)))}
</span>
<span aria-hidden="true" className="h-4 w-px bg-border" />
<Clock3
aria-hidden="true"
className="hidden size-4 shrink-0 min-[400px]:block"
/>
<span className="whitespace-nowrap tabular-nums">
{timeLabel(value)}
</span>
</>
) : (
<span className="text-muted-foreground">{label}</span>
)}
<ChevronDown
aria-hidden="true"
className={cn(
"ml-1 size-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none",
open && "rotate-180",
)}
/>
</Button>
</MorphPopoverTrigger>
<MorphPopoverContent
align="start"
radius={16}
sideOffset={8}
className={cn("w-[480px] max-w-[calc(100vw-1.5rem)]", classNames?.content)}
onOpenAutoFocus={(content) =>
content
.querySelector<HTMLElement>('[data-calendar-day][tabindex="0"]')
?.focus({ preventScroll: true })
}
>
{draft && (
<DateTimePanel
key={session}
initialValue={draft}
classNames={classNames}
onConfirm={(next) => {
if (controlledValue === undefined) setInternal(next);
onValueChange?.(next);
setOpen(false);
trigger.current?.focus({ preventScroll: true });
}}
/>
)}
</MorphPopoverContent>
</MorphPopover>
);
}
function DateTimePanel({
initialValue,
onConfirm,
classNames,
}: {
initialValue: string;
onConfirm: (value: string) => void;
classNames?: DateTimePickerClassNames;
}) {
const [draft, setDraft] = useState(initialValue);
const [cursor, setCursor] = useState(initialValue.slice(0, 10));
const reduce = useReducedMotion() ?? false;
const id = useId();
const calendar = useRef<HTMLTableElement>(null);
const moveFocus = useRef(true);
const date = draft.slice(0, 10);
const month = monthOf(cursor);
const hour = Number(draft.slice(11, 13));
const period = hour < 12 ? "AM" : "PM";
const first = parse(month);
const start = first - ((new Date(first).getUTCDay() + 6) % 7) * DAY;
const daysInView =
Math.ceil((parse(shiftMonth(month, 1)) - start) / DAY / 7) * 7;
const days = Array.from({ length: daysInView }, (_, index) =>
iso(start + index * DAY),
);
useLayoutEffect(() => {
if (!moveFocus.current) return;
calendar.current
?.querySelector<HTMLElement>(`[data-calendar-day="${cursor}"]`)
?.focus({ preventScroll: true });
moveFocus.current = false;
}, [cursor]);
const setHour = (next: number) =>
setDraft(
(current) => `${current.slice(0, 11)}${pad(next)}${current.slice(13)}`,
);
const navigate = (event: KeyboardEvent<HTMLButtonElement>) => {
const offsets: Record<string, number> = {
ArrowLeft: -1,
ArrowRight: 1,
ArrowUp: -7,
ArrowDown: 7,
};
const key = event.key;
if (
!(key in offsets) &&
!["Home", "End", "PageUp", "PageDown"].includes(key)
)
return;
event.preventDefault();
moveFocus.current = true;
setCursor((current) => {
if (key === "PageUp" || key === "PageDown")
return shiftMonth(
current,
(key === "PageUp" ? -1 : 1) * (event.shiftKey ? 12 : 1),
);
const weekday = (new Date(parse(current)).getUTCDay() + 6) % 7;
return iso(
parse(current) +
(key === "Home"
? -weekday
: key === "End"
? 6 - weekday
: offsets[key]) *
DAY,
);
});
};
return (
<div>
<div className="grid grid-cols-1 min-[520px]:grid-cols-[1fr_160px]">
<section aria-label="Calendar" className={cn("min-w-0 p-3.5", classNames?.calendar)}>
<div className="mb-2 flex items-center justify-between gap-2">
<Button
variant="outline"
size="icon"
aria-label="Previous month"
className={focusClass}
onClick={() => setCursor((current) => shiftMonth(current, -1))}
>
<ChevronLeft aria-hidden="true" className="size-4" />
</Button>
<h3
id={`${id}-month`}
aria-live="polite"
className="text-sm font-medium"
>
{monthFormat.format(first)}
</h3>
<Button
variant="outline"
size="icon"
aria-label="Next month"
className={focusClass}
onClick={() => setCursor((current) => shiftMonth(current, 1))}
>
<ChevronRight aria-hidden="true" className="size-4" />
</Button>
</div>
<p id={`${id}-help`} className="sr-only">
Use arrow keys for days, Home and End for the week, Page Up and Page
Down for months, or hold Shift for years. Enter selects a date.
Confirm saves the date and time; Escape discards changes.
</p>
<motion.table
key={month}
ref={calendar}
role="grid"
aria-labelledby={`${id}-month`}
aria-describedby={`${id}-help`}
className="w-full table-fixed"
initial={{ opacity: reduce ? 1 : 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.15, ease: EASE_OUT }}
>
<thead>
<tr>
{["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"].map((day) => (
<th
key={day}
scope="col"
className="pb-3 text-center text-xs font-normal text-muted-foreground"
>
{day}
</th>
))}
</tr>
</thead>
<tbody>
{Array.from({ length: daysInView / 7 }, (_, week) => (
<tr key={days[week * 7]}>
{days.slice(week * 7, week * 7 + 7).map((day) => (
// biome-ignore lint/a11y/useFocusableInteractive: Calendar cells delegate focus to the contained day button.
<td
// biome-ignore lint/a11y/noNoninteractiveElementToInteractiveRole: Gridcell selection semantics belong on the native table cell.
role="gridcell"
key={day}
aria-selected={day === date}
className="py-0.5"
>
<motion.button
type="button"
data-calendar-day={day}
tabIndex={day === cursor ? 0 : -1}
aria-label={dayFormat.format(parse(day))}
onKeyDown={navigate}
onClick={() => {
moveFocus.current = true;
setCursor(day);
setDraft((current) => `${day}${current.slice(10)}`);
}}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className={cn(
"relative mx-auto flex size-8 items-center justify-center rounded-xl text-xs tabular-nums transition-colors",
focusClass,
day === date
? "bg-foreground font-medium text-background shadow-sm"
: "hover:bg-muted",
day !== date &&
monthOf(day) !== month &&
"text-muted-foreground/40",
classNames?.day,
day === date && classNames?.selectedDay,
)}
>
{Number(day.slice(8))}
</motion.button>
</td>
))}
</tr>
))}
</tbody>
</motion.table>
</section>
<section
aria-label="Time"
className={cn("m-3.5 mt-0 border-t border-border pt-3.5 min-[520px]:ml-0 min-[520px]:mt-3.5 min-[520px]:border-l min-[520px]:border-t-0 min-[520px]:pl-3.5 min-[520px]:pt-0", classNames?.time)}
>
<h3 className="mb-3 text-sm font-medium">Time</h3>
<div className="flex items-center gap-1 tabular-nums">
{reduce ? (
<label className="flex flex-1 flex-col gap-1 text-xs text-muted-foreground">
Hour
<select
aria-label="Hour"
value={pad(hour % 12 || 12)}
onChange={(event) =>
setHour(
(Number(event.target.value) % 12) +
(period === "PM" ? 12 : 0),
)
}
className={cn(
"h-10 rounded-lg border border-border bg-background px-2 text-sm text-foreground",
focusClass,
)}
>
{HOURS.map((value) => (
<option key={value}>{value}</option>
))}
</select>
</label>
) : (
<WheelPicker
aria-label="Hour"
options={HOURS}
value={pad(hour % 12 || 12)}
onValueChange={(next) =>
setHour((Number(next) % 12) + (period === "PM" ? 12 : 0))
}
itemHeight={32}
className="flex-1 rounded-lg border-0 bg-transparent text-base"
/>
)}
<span aria-hidden="true" className="text-muted-foreground">
:
</span>
{reduce ? (
<label className="flex flex-1 flex-col gap-1 text-xs text-muted-foreground">
Minute
<select
aria-label="Minute"
value={draft.slice(14)}
onChange={(event) =>
setDraft(
(current) =>
`${current.slice(0, 14)}${event.target.value}`,
)
}
className={cn(
"h-10 rounded-lg border border-border bg-background px-2 text-sm text-foreground",
focusClass,
)}
>
{MINUTES.map((value) => (
<option key={value}>{value}</option>
))}
</select>
</label>
) : (
<WheelPicker
aria-label="Minute"
options={MINUTES}
value={draft.slice(14)}
onValueChange={(next) =>
setDraft((current) => `${current.slice(0, 14)}${next}`)
}
itemHeight={32}
className="flex-1 rounded-lg border-0 bg-transparent text-base"
/>
)}
</div>
<fieldset
aria-label="Time period"
className="mt-3 flex rounded-xl border border-border bg-muted/50 p-1"
>
{["AM", "PM"].map((next) => (
<button
key={next}
type="button"
aria-pressed={next === period}
onClick={() => setHour((hour % 12) + (next === "PM" ? 12 : 0))}
className={cn(
"relative flex h-8 flex-1 items-center justify-center rounded-lg text-xs",
focusClass,
)}
>
{next === period && (
<motion.span
aria-hidden="true"
layoutId={reduce ? undefined : `${id}-period`}
transition={SPRING_LAYOUT}
className="absolute inset-0 rounded-lg border border-border bg-background shadow-sm"
/>
)}
<span className="relative">{next}</span>
</button>
))}
</fieldset>
</section>
</div>
<div className="flex items-center justify-between gap-2 border-t border-border px-3.5 py-2.5">
<span className="text-[11px] text-muted-foreground">
Local time ·{" "}
{new Intl.DateTimeFormat("en-US", { timeZoneName: "shortOffset" })
.formatToParts(new Date(draft))
.find((part) => part.type === "timeZoneName")
?.value.replace("GMT", "UTC")}
</span>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className={cn("rounded-lg", focusClass)}
onClick={() => {
const now = localNow();
setDraft(now);
setCursor(now.slice(0, 10));
}}
>
Now
</Button>
<Button
size="sm"
className={cn(
"rounded-lg bg-foreground px-4 text-background hover:bg-foreground/90",
focusClass,
classNames?.confirmButton,
)}
onClick={() => onConfirm(draft)}
>
Confirm
</Button>
</div>
</div>
</div>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
// Synthesizes a short, dry mechanical detent for gesture feedback (e.g. the
// WheelPicker row-cross click) entirely at runtime. Several inharmonic modes
// make it read as a tiny physical impact instead of an oscillator beep, while
// the high-passed transient gives it definition through phone speakers.
const DURATION = 0.016; // seconds, short enough to stay distinct during a fling
const MASTER_GAIN = 0.055;
const MODES = [
{ frequency: 980, decay: 0.0038, gain: 0.5, phase: 0 },
{ frequency: 1820, decay: 0.0024, gain: 0.3, phase: 0.65 },
{ frequency: 3160, decay: 0.00115, gain: 0.12, phase: 1.3 },
] as const;
type AudioContextCtor = typeof AudioContext;
function getAudioContextCtor(): AudioContextCtor | undefined {
if (typeof window === "undefined") return undefined;
return (
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor })
.webkitAudioContext
);
}
// One shared context/buffer/gain for the whole page, ref-counted across every
// `createTickPlayer()` caller. Components like WheelPicker commonly compose
// several side by side (a date made of month/day/year drums) — giving each
// its own AudioContext would waste resources and risk hitting a browser's cap
// on concurrent contexts. The context only closes once every consumer that
// created a player has called `dispose()`.
let ctx: AudioContext | null = null;
let masterGain: GainNode | null = null;
let clickBuffer: AudioBuffer | null = null;
let consumers = 0;
function buildClickBuffer(context: AudioContext): AudioBuffer {
const sampleRate = context.sampleRate;
const length = Math.ceil(DURATION * sampleRate);
const buffer = context.createBuffer(1, length, sampleRate);
const data = buffer.getChannelData(0);
let peak = 0;
let previousNoise = 0;
for (let i = 0; i < length; i++) {
const t = i / sampleRate;
const attack = Math.min(1, t / 0.00012);
const fadeOut = Math.min(1, (DURATION - t) / 0.001);
let resonance = 0;
for (const mode of MODES) {
resonance +=
Math.sin(2 * Math.PI * mode.frequency * t + mode.phase) *
Math.exp(-t / mode.decay) *
mode.gain;
}
// Differencing consecutive noise samples removes the low, papery part of
// white noise and leaves only a tiny impact at the front of the sound.
const noise = Math.random() * 2 - 1;
const transient =
(noise - previousNoise) * Math.exp(-t / 0.00038) * 0.035;
previousNoise = noise;
data[i] = (resonance + transient) * attack * fadeOut;
peak = Math.max(peak, Math.abs(data[i]));
}
if (peak > 0) {
const norm = 0.9 / peak;
for (let i = 0; i < length; i++) data[i] *= norm;
}
return buffer;
}
function ensureContext() {
if (ctx) return;
const Ctor = getAudioContextCtor();
if (!Ctor) return;
ctx = new Ctor();
masterGain = ctx.createGain();
masterGain.gain.value = MASTER_GAIN;
masterGain.connect(ctx.destination);
clickBuffer = buildClickBuffer(ctx);
}
function prepareContext() {
ensureContext();
if (ctx?.state === "suspended") {
// Browsers may reject this when it is not called from a trusted gesture.
// Pointer, touch, wheel and keyboard entry points call `prepare()` first;
// this repeat attempt keeps direct `play()` calls safe as well.
void ctx.resume().catch(() => undefined);
}
}
interface TickPlayer {
prepare: () => void;
play: () => void;
dispose: () => void;
}
/**
* Lazily-initialized tick player. No `AudioContext` is created until the first
* `prepare()` or `play()` call anywhere on the page. Every player shares the
* same context/buffer, ref-counted so `dispose()` only tears it down once the
* last consumer is gone. Safe during SSR or in browsers without Web Audio:
* `prepare()` and `play()` become silent no-ops.
*/
export function createTickPlayer(): TickPlayer {
consumers++;
let disposed = false;
let activeSource: AudioBufferSourceNode | null = null;
return {
prepare() {
if (disposed) return;
prepareContext();
},
play() {
if (disposed) return;
prepareContext();
if (!ctx || !masterGain || !clickBuffer) return;
// A fast fling can cross rows more quickly than the tail of a tick.
// Cutting that tail keeps the feedback dry instead of stacking into a
// louder metallic ring.
activeSource?.stop();
const source = ctx.createBufferSource();
source.buffer = clickBuffer;
source.connect(masterGain);
source.onended = () => {
source.disconnect();
if (activeSource === source) activeSource = null;
};
activeSource = source;
source.start();
},
dispose() {
if (disposed) return;
disposed = true;
activeSource?.stop();
activeSource = null;
consumers = Math.max(0, consumers - 1);
if (consumers === 0 && ctx) {
ctx.close();
ctx = null;
masterGain = null;
clickBuffer = null;
}
},
};
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// asharca.github.io/ui/components/motion/date-time-picker
import {
CalendarDays,
ChevronDown,
ChevronLeft,
ChevronRight,
Clock3,
} from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import {
type KeyboardEvent,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { Button } from "@/components/motion/button/base";
import {
DAY,
iso,
monthOf,
parse,
shiftMonth,
} from "@/components/motion/date-range-picker/date-utils";
import {
MorphPopover,
MorphPopoverContent,
MorphPopoverTrigger,
} from "@/components/motion/popover-morph";
import { WheelPicker } from "@/components/motion/wheel-picker";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type DateTimePickerClassNames = {
trigger?: string;
content?: string;
calendar?: string;
day?: string;
selectedDay?: string;
time?: string;
confirmButton?: string;
};
export interface DateTimePickerProps {
/** Local wall-clock time, YYYY-MM-DDTHH:mm. No timezone conversion is applied. */
value?: string;
defaultValue?: string;
/** Called only when Confirm is pressed. Dismissing discards the draft. */
onValueChange?: (value: string) => void;
label?: string;
disabled?: boolean;
name?: string;
className?: string;
classNames?: DateTimePickerClassNames;
}
const pad = (value: number) => String(value).padStart(2, "0");
const HOURS = Array.from({ length: 12 }, (_, index) => pad(index + 1));
const MINUTES = Array.from({ length: 60 }, (_, index) => pad(index));
const dateFormat = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
});
const monthFormat = new Intl.DateTimeFormat("en-US", {
month: "long",
year: "numeric",
timeZone: "UTC",
});
const dayFormat = new Intl.DateTimeFormat("en-US", {
dateStyle: "full",
timeZone: "UTC",
});
const focusClass =
"outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
function localNow() {
const now = new Date();
return `${String(now.getFullYear()).padStart(4, "0")}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
}
function validate(value: string) {
if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d$/.test(value))
throw new Error(
"DateTimePicker expects local time in YYYY-MM-DDTHH:mm format.",
);
parse(value.slice(0, 10));
return value;
}
function timeLabel(value: string) {
const hour = Number(value.slice(11, 13));
return `${pad(hour % 12 || 12)}:${value.slice(14)} ${hour < 12 ? "AM" : "PM"}`;
}
/** Calendar and time-wheel popover with an explicit draft/confirm boundary. */
export function DateTimePicker({
value: controlledValue,
defaultValue = "",
onValueChange,
label = "Choose date and time",
disabled = false,
name,
className,
classNames,
}: DateTimePickerProps) {
const [internal, setInternal] = useState(defaultValue);
const value = controlledValue ?? internal;
if (value) validate(value);
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState("");
const [session, setSession] = useState(0);
const trigger = useRef<HTMLButtonElement>(null);
const changeOpen = (next: boolean) => {
if (disabled) return;
if (next) {
setDraft(value || localNow());
setSession((current) => current + 1);
}
setOpen(next);
};
return (
<MorphPopover
open={open && !disabled}
onOpenChange={changeOpen}
className={cn("max-w-full", className)}
>
{name && (
<input type="hidden" name={name} value={value} disabled={disabled} />
)}
<MorphPopoverTrigger>
<Button
ref={trigger}
variant="outline"
disabled={disabled}
aria-label={`${label}: ${value ? `${dateFormat.format(parse(value.slice(0, 10)))}, ${timeLabel(value)}` : "not selected"}`}
className={cn(
"h-9 max-w-full gap-2 rounded-xl bg-background px-3 text-[13px] font-medium",
focusClass,
classNames?.trigger,
)}
>
<CalendarDays aria-hidden="true" className="size-4 shrink-0" />
{value ? (
<>
<span className="whitespace-nowrap">
{dateFormat.format(parse(value.slice(0, 10)))}
</span>
<span aria-hidden="true" className="h-4 w-px bg-border" />
<Clock3
aria-hidden="true"
className="hidden size-4 shrink-0 min-[400px]:block"
/>
<span className="whitespace-nowrap tabular-nums">
{timeLabel(value)}
</span>
</>
) : (
<span className="text-muted-foreground">{label}</span>
)}
<ChevronDown
aria-hidden="true"
className={cn(
"ml-1 size-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none",
open && "rotate-180",
)}
/>
</Button>
</MorphPopoverTrigger>
<MorphPopoverContent
align="start"
radius={16}
sideOffset={8}
className={cn("w-[480px] max-w-[calc(100vw-1.5rem)]", classNames?.content)}
onOpenAutoFocus={(content) =>
content
.querySelector<HTMLElement>('[data-calendar-day][tabindex="0"]')
?.focus({ preventScroll: true })
}
>
{draft && (
<DateTimePanel
key={session}
initialValue={draft}
classNames={classNames}
onConfirm={(next) => {
if (controlledValue === undefined) setInternal(next);
onValueChange?.(next);
setOpen(false);
trigger.current?.focus({ preventScroll: true });
}}
/>
)}
</MorphPopoverContent>
</MorphPopover>
);
}
function DateTimePanel({
initialValue,
onConfirm,
classNames,
}: {
initialValue: string;
onConfirm: (value: string) => void;
classNames?: DateTimePickerClassNames;
}) {
const [draft, setDraft] = useState(initialValue);
const [cursor, setCursor] = useState(initialValue.slice(0, 10));
const reduce = useReducedMotion() ?? false;
const id = useId();
const calendar = useRef<HTMLTableElement>(null);
const moveFocus = useRef(true);
const date = draft.slice(0, 10);
const month = monthOf(cursor);
const hour = Number(draft.slice(11, 13));
const period = hour < 12 ? "AM" : "PM";
const first = parse(month);
const start = first - ((new Date(first).getUTCDay() + 6) % 7) * DAY;
const daysInView =
Math.ceil((parse(shiftMonth(month, 1)) - start) / DAY / 7) * 7;
const days = Array.from({ length: daysInView }, (_, index) =>
iso(start + index * DAY),
);
useLayoutEffect(() => {
if (!moveFocus.current) return;
calendar.current
?.querySelector<HTMLElement>(`[data-calendar-day="${cursor}"]`)
?.focus({ preventScroll: true });
moveFocus.current = false;
}, [cursor]);
const setHour = (next: number) =>
setDraft(
(current) => `${current.slice(0, 11)}${pad(next)}${current.slice(13)}`,
);
const navigate = (event: KeyboardEvent<HTMLButtonElement>) => {
const offsets: Record<string, number> = {
ArrowLeft: -1,
ArrowRight: 1,
ArrowUp: -7,
ArrowDown: 7,
};
const key = event.key;
if (
!(key in offsets) &&
!["Home", "End", "PageUp", "PageDown"].includes(key)
)
return;
event.preventDefault();
moveFocus.current = true;
setCursor((current) => {
if (key === "PageUp" || key === "PageDown")
return shiftMonth(
current,
(key === "PageUp" ? -1 : 1) * (event.shiftKey ? 12 : 1),
);
const weekday = (new Date(parse(current)).getUTCDay() + 6) % 7;
return iso(
parse(current) +
(key === "Home"
? -weekday
: key === "End"
? 6 - weekday
: offsets[key]) *
DAY,
);
});
};
return (
<div>
<div className="grid grid-cols-1 min-[520px]:grid-cols-[1fr_160px]">
<section aria-label="Calendar" className={cn("min-w-0 p-3.5", classNames?.calendar)}>
<div className="mb-2 flex items-center justify-between gap-2">
<Button
variant="outline"
size="icon"
aria-label="Previous month"
className={focusClass}
onClick={() => setCursor((current) => shiftMonth(current, -1))}
>
<ChevronLeft aria-hidden="true" className="size-4" />
</Button>
<h3
id={`${id}-month`}
aria-live="polite"
className="text-sm font-medium"
>
{monthFormat.format(first)}
</h3>
<Button
variant="outline"
size="icon"
aria-label="Next month"
className={focusClass}
onClick={() => setCursor((current) => shiftMonth(current, 1))}
>
<ChevronRight aria-hidden="true" className="size-4" />
</Button>
</div>
<p id={`${id}-help`} className="sr-only">
Use arrow keys for days, Home and End for the week, Page Up and Page
Down for months, or hold Shift for years. Enter selects a date.
Confirm saves the date and time; Escape discards changes.
</p>
<motion.table
key={month}
ref={calendar}
role="grid"
aria-labelledby={`${id}-month`}
aria-describedby={`${id}-help`}
className="w-full table-fixed"
initial={{ opacity: reduce ? 1 : 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.15, ease: EASE_OUT }}
>
<thead>
<tr>
{["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"].map((day) => (
<th
key={day}
scope="col"
className="pb-3 text-center text-xs font-normal text-muted-foreground"
>
{day}
</th>
))}
</tr>
</thead>
<tbody>
{Array.from({ length: daysInView / 7 }, (_, week) => (
<tr key={days[week * 7]}>
{days.slice(week * 7, week * 7 + 7).map((day) => (
// biome-ignore lint/a11y/useFocusableInteractive: Calendar cells delegate focus to the contained day button.
<td
// biome-ignore lint/a11y/noNoninteractiveElementToInteractiveRole: Gridcell selection semantics belong on the native table cell.
role="gridcell"
key={day}
aria-selected={day === date}
className="py-0.5"
>
<motion.button
type="button"
data-calendar-day={day}
tabIndex={day === cursor ? 0 : -1}
aria-label={dayFormat.format(parse(day))}
onKeyDown={navigate}
onClick={() => {
moveFocus.current = true;
setCursor(day);
setDraft((current) => `${day}${current.slice(10)}`);
}}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className={cn(
"relative mx-auto flex size-8 items-center justify-center rounded-xl text-xs tabular-nums transition-colors",
focusClass,
day === date
? "bg-foreground font-medium text-background shadow-sm"
: "hover:bg-muted",
day !== date &&
monthOf(day) !== month &&
"text-muted-foreground/40",
classNames?.day,
day === date && classNames?.selectedDay,
)}
>
{Number(day.slice(8))}
</motion.button>
</td>
))}
</tr>
))}
</tbody>
</motion.table>
</section>
<section
aria-label="Time"
className={cn("m-3.5 mt-0 border-t border-border pt-3.5 min-[520px]:ml-0 min-[520px]:mt-3.5 min-[520px]:border-l min-[520px]:border-t-0 min-[520px]:pl-3.5 min-[520px]:pt-0", classNames?.time)}
>
<h3 className="mb-3 text-sm font-medium">Time</h3>
<div className="flex items-center gap-1 tabular-nums">
{reduce ? (
<label className="flex flex-1 flex-col gap-1 text-xs text-muted-foreground">
Hour
<select
aria-label="Hour"
value={pad(hour % 12 || 12)}
onChange={(event) =>
setHour(
(Number(event.target.value) % 12) +
(period === "PM" ? 12 : 0),
)
}
className={cn(
"h-10 rounded-lg border border-border bg-background px-2 text-sm text-foreground",
focusClass,
)}
>
{HOURS.map((value) => (
<option key={value}>{value}</option>
))}
</select>
</label>
) : (
<WheelPicker
aria-label="Hour"
options={HOURS}
value={pad(hour % 12 || 12)}
onValueChange={(next) =>
setHour((Number(next) % 12) + (period === "PM" ? 12 : 0))
}
itemHeight={32}
className="flex-1 rounded-lg border-0 bg-transparent text-base"
/>
)}
<span aria-hidden="true" className="text-muted-foreground">
:
</span>
{reduce ? (
<label className="flex flex-1 flex-col gap-1 text-xs text-muted-foreground">
Minute
<select
aria-label="Minute"
value={draft.slice(14)}
onChange={(event) =>
setDraft(
(current) =>
`${current.slice(0, 14)}${event.target.value}`,
)
}
className={cn(
"h-10 rounded-lg border border-border bg-background px-2 text-sm text-foreground",
focusClass,
)}
>
{MINUTES.map((value) => (
<option key={value}>{value}</option>
))}
</select>
</label>
) : (
<WheelPicker
aria-label="Minute"
options={MINUTES}
value={draft.slice(14)}
onValueChange={(next) =>
setDraft((current) => `${current.slice(0, 14)}${next}`)
}
itemHeight={32}
className="flex-1 rounded-lg border-0 bg-transparent text-base"
/>
)}
</div>
<fieldset
aria-label="Time period"
className="mt-3 flex rounded-xl border border-border bg-muted/50 p-1"
>
{["AM", "PM"].map((next) => (
<button
key={next}
type="button"
aria-pressed={next === period}
onClick={() => setHour((hour % 12) + (next === "PM" ? 12 : 0))}
className={cn(
"relative flex h-8 flex-1 items-center justify-center rounded-lg text-xs",
focusClass,
)}
>
{next === period && (
<motion.span
aria-hidden="true"
layoutId={reduce ? undefined : `${id}-period`}
transition={SPRING_LAYOUT}
className="absolute inset-0 rounded-lg border border-border bg-background shadow-sm"
/>
)}
<span className="relative">{next}</span>
</button>
))}
</fieldset>
</section>
</div>
<div className="flex items-center justify-between gap-2 border-t border-border px-3.5 py-2.5">
<span className="text-[11px] text-muted-foreground">
Local time ·{" "}
{new Intl.DateTimeFormat("en-US", { timeZoneName: "shortOffset" })
.formatToParts(new Date(draft))
.find((part) => part.type === "timeZoneName")
?.value.replace("GMT", "UTC")}
</span>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className={cn("rounded-lg", focusClass)}
onClick={() => {
const now = localNow();
setDraft(now);
setCursor(now.slice(0, 10));
}}
>
Now
</Button>
<Button
size="sm"
className={cn(
"rounded-lg bg-foreground px-4 text-background hover:bg-foreground/90",
focusClass,
classNames?.confirmButton,
)}
onClick={() => onConfirm(draft)}
>
Confirm
</Button>
</div>
</div>
</div>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
ripple && "relative overflow-hidden",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
import type { DateRange } from "./types";
export const DAY = 86_400_000;
export function parse(date: string) {
const time = Date.parse(`${date}T00:00:00Z`);
if (
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
!Number.isFinite(time) ||
new Date(time).toISOString().slice(0, 10) !== date
)
throw new Error(`Invalid calendar date: ${date}. Use YYYY-MM-DD.`);
return time;
}
export function iso(time: number) {
return new Date(time).toISOString().slice(0, 10);
}
export function monthOf(date: string) {
return `${date.slice(0, 7)}-01`;
}
export function shiftMonth(date: string, offset: number) {
const day = new Date(parse(date));
const month = new Date(parse(monthOf(date)));
month.setUTCMonth(month.getUTCMonth() + offset);
const end = new Date(month);
end.setUTCMonth(end.getUTCMonth() + 1);
end.setUTCDate(0);
month.setUTCDate(Math.min(day.getUTCDate(), end.getUTCDate()));
return iso(month.getTime());
}
export function ordered(a: string, b: string): Required<DateRange> {
return a <= b ? { from: a, to: b } : { from: b, to: a };
}
"use client";
import {
AnimatePresence,
motion,
animate,
useMotionValue,
usePresence,
useReducedMotion,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT, SPRING_PANEL } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "end";
type MorphContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
triggerId: string;
contentId: string;
/** The element the panel measures against — see `registerTrigger`. */
triggerRef: React.MutableRefObject<HTMLElement | null>;
registerTrigger: (node: HTMLElement | null) => void;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
};
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);
return ctx;
}
export interface MorphPopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
/**
* A popover whose panel morphs open from the trigger corner: it's laid out at
* full size but clipped to the corner nearest the trigger, then unclips as one
* piece. Closes on outside pointer / Escape. Controlled or uncontrolled.
*/
export function MorphPopover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: MorphPopoverProps) {
const baseId = useId();
const [root, setRoot] = useState<HTMLDivElement | null>(null);
const [trigger, setTrigger] = useState<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
// A trigger normally registers itself through MorphPopoverTrigger. It can't
// when something else already clones the element — a Tooltip wrapping the
// button, say — and an unregistered trigger leaves the panel with nothing to
// measure against, so it renders permanently invisible. The root boxes the
// trigger exactly (the content portals out of it), so it stands in until a
// real trigger registers, and stands in again if that one unmounts. Both are
// state, so a trigger arriving while the panel is open re-anchors it.
const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(
() => ({ current: trigger ?? root }),
[root, trigger],
);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: a dismissal hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded. When no trigger has
// registered, the root anchor stands in only if it can actually hold focus;
// there is nowhere better than where the keyboard already is, so leave it.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (!inPanel) return;
const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);
restore?.focus();
}, [root, setOpen, trigger]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();
const onPointer = (e: PointerEvent) => {
const target = e.target as Node;
if (
root &&
!root.contains(target) &&
!contentRef.current?.contains(target)
)
close();
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, root, close]);
const ctx = useMemo<MorphContextValue>(
() => ({
open,
setOpen,
toggle,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef: anchorRef,
registerTrigger: setTrigger,
contentRef,
}),
[open, setOpen, toggle, baseId, anchorRef],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={setRoot} className={cn("relative inline-flex", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphPopoverTriggerProps {
children: ReactElement;
}
function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref && typeof ref === "object")
(ref as React.MutableRefObject<T | null>).current = node;
}
};
}
/** Wraps a single element, toggling the popover on click. */
export function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {
const ctx = useMorphContext("MorphPopoverTrigger");
const child = children as ReactElement<Record<string, unknown>>;
const childOnClick = child?.props?.onClick as
| ((e: unknown) => void)
| undefined;
const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)
?.ref;
// Register once per actual ref change, not once per open-state render.
const mergedRef = useMemo(
() => mergeRefs(childRef, ctx.registerTrigger),
[childRef, ctx.registerTrigger],
);
if (!isValidElement(children)) return children;
return cloneElement(child, {
id: ctx.triggerId,
ref: mergedRef,
onClick: (e: unknown) => {
childOnClick?.(e);
ctx.toggle();
},
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
});
}
const originFor = (side: Side, align: Align) =>
`${side === "bottom" ? "top" : "bottom"} ${align === "end" ? "right" : "left"}`;
// A clip that hides everything but the corner nearest the trigger, so the
// panel appears to grow out of it. inset(top right bottom left).
function clipAt(side: Side, align: Align, radius: number, inset: number) {
const top = side === "bottom" ? "0%" : `${inset}%`;
const bottom = side === "bottom" ? `${inset}%` : "0%";
const right = align === "end" ? "0%" : `${inset}%`;
const left = align === "end" ? `${inset}%` : "0%";
return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;
}
// Preserve the original spring character on the wrapper, but tween the complex
// clip-path so it cannot snap when the spring resolves its final distance.
const MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;
export interface MorphPopoverContentProps {
children: ReactNode;
side?: Side;
align?: Align;
/** Gap between trigger and panel, in px. Default 8. */
sideOffset?: number;
/** Panel corner radius, in px. Default 16. */
radius?: number;
/** Draw the surface shadow. Default true. */
shadow?: boolean;
/** Runs after the portalled surface is positioned and visible. */
onOpenAutoFocus?: (content: HTMLDivElement) => void;
/** Override the panel landmark. Menus pass "menu" instead of the dialog default. */
role?: "dialog" | "menu";
className?: string;
}
export function MorphPopoverContent(props: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const [portalReady, setPortalReady] = useState(false);
useEffect(() => setPortalReady(true), []);
if (!portalReady) return null;
return createPortal(
<AnimatePresence>
{ctx.open && <MorphPopoverSurface {...props} />}
</AnimatePresence>,
document.body,
);
}
// Measurement belongs to the mounted portal session: reopening must not start
// an entrance at the previous session's coordinates before measuring this one.
function MorphPopoverSurface({
children,
side = "bottom",
align = "end",
sideOffset = 8,
radius = 16,
shadow = true,
onOpenAutoFocus,
role = "dialog",
className,
}: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const reduce = useReducedMotion() ?? false;
const [isPresent, safeToRemove] = usePresence();
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
isPresent,
);
const preferredLeft = layout
? align === "end"
? layout.trigger.left + layout.trigger.width - layout.content.width
: layout.trigger.left
: 0;
// Larger compositions, such as calendars, use the roomier side if needed.
const gutter = 8;
const below = layout
? Math.max(0, window.innerHeight - layout.trigger.top - layout.trigger.height - sideOffset - gutter)
: 0;
const above = layout ? Math.max(0, layout.trigger.top - sideOffset - gutter) : 0;
const requestedSpace = side === "bottom" ? below : above;
const otherSpace = side === "bottom" ? above : below;
const resolvedSide = layout && layout.content.height > requestedSpace && otherSpace > requestedSpace
? side === "bottom" ? "top" : "bottom"
: side;
const availableHeight = resolvedSide === "bottom" ? below : above;
const left = layout
? Math.max(gutter, Math.min(preferredLeft, window.innerWidth - layout.content.width - gutter))
: 0;
const top = layout
? resolvedSide === "bottom"
? layout.trigger.top + layout.trigger.height + sideOffset
: Math.max(gutter, layout.trigger.top - layout.content.height - sideOffset)
: 0;
// Both directions travel between the exact same hidden/show states. Exit
// targets "hidden" directly instead of introducing separate choreography.
const wrap = reduce
? undefined
: {
hidden: { scale: 0.96, transition: SPRING_PANEL },
show: { scale: 1, transition: SPRING_PANEL },
};
const clip = reduce
? undefined
: {
hidden: {
clipPath: clipAt(resolvedSide, align, radius, 92),
transition: MORPH_CLIP_TRANSITION,
},
show: {
clipPath: clipAt(resolvedSide, align, radius, 0),
transition: MORPH_CLIP_TRANSITION,
},
};
// Animate the value directly so opacity stays in the inline style throughout
// the entrance. A native opacity animation can expose the initial inline 0
// for a frame when it finishes, before Motion writes the final value.
const opacity = useMotionValue(0);
const ready = layout !== null;
const focusedOnOpen = useRef(false);
useEffect(() => {
if (!ready || !isPresent || focusedOnOpen.current || !ctx.contentRef.current) return;
focusedOnOpen.current = true;
onOpenAutoFocus?.(ctx.contentRef.current);
}, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);
useEffect(() => {
if (!ready) {
if (!isPresent) safeToRemove?.();
return;
}
const animation = animate(opacity, isPresent ? 1 : 0, {
...(reduce ? { duration: 0.12 } : SPRING_PANEL),
onComplete: () => {
if (!isPresent) safeToRemove?.();
},
});
return () => animation.stop();
}, [opacity, ready, isPresent, reduce, safeToRemove]);
return (
<motion.div
data-morph-popover-portal=""
inert={!isPresent}
// Wrapper carries the shadow as a drop-shadow filter, which hugs the
// clipped shape below (box-shadow would just get clipped away).
variants={wrap}
initial="hidden"
animate={layout ? "show" : "hidden"}
exit="hidden"
style={{
left,
top,
opacity,
pointerEvents: isPresent ? "auto" : "none",
visibility: layout ? "visible" : "hidden",
transformOrigin: originFor(resolvedSide, align),
}}
className={cn("fixed z-[9999]", shadow && "[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]")}
>
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
role={role}
aria-labelledby={ctx.triggerId}
variants={clip}
style={{ borderRadius: radius, maxHeight: layout ? availableHeight : undefined, overflowY: "auto" }}
className={cn(
"overflow-hidden border border-border bg-background",
className,
)}
>
{children}
</motion.div>
</motion.div>
);
}
"use client";
import { useReducedMotion } from "motion/react";
import {
type KeyboardEvent,
type PointerEvent,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createTickPlayer } from "@/lib/tick-sound";
import {
capturePointer,
releasePointer,
TOUCH_GESTURE_CLASS,
} from "@/lib/touch";
import { cn } from "@/lib/utils";
export type WheelPickerOption = string | { label: string; value: string };
export interface WheelPickerProps {
options: WheelPickerOption[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Rows visible through the window, odd. More = flatter curve. Default 5. */
visibleCount?: number;
/** Row height in px. Default 36. */
itemHeight?: number;
disabled?: boolean;
/** Play a short tick each time the selected value changes. Default false. */
sound?: boolean;
className?: string;
"aria-label"?: string;
}
const DEG = Math.PI / 180;
// Physics constants, tuned for an iOS-like flick rather than reused from the
// shared spring tokens: the wheel coasts in whole-row units and springs to an
// integer detent, which a layout spring can't express cleanly.
const DECELERATION = 0.00042; // rows per ms², how fast a flick bleeds off (lower = freer)
const MAX_VELOCITY = 0.18; // rows per ms, caps a hard fling
const VELOCITY_WINDOW = 90; // ms of recent drag to average a release velocity over
const WHEEL_SENS = 0.012; // rows per pixel of wheel delta
const WHEEL_SETTLE = 110; // ms of wheel idle before snapping to a row
const easeOutCubic = (p: number) => 1 - (1 - p) ** 3;
// Overshoots the target by a few percent then settles — the little spring
// bounce as a row snaps home. `BACK` sets how far it drifts past.
const BACK = 1.35;
const easeOutBack = (p: number) =>
1 + (BACK + 1) * (p - 1) ** 3 + BACK * (p - 1) ** 2;
const clamp = (v: number, lo: number, hi: number) =>
Math.max(lo, Math.min(v, hi));
function optionValue(option: WheelPickerOption) {
return typeof option === "string" ? option : option.value;
}
function optionLabel(option: WheelPickerOption) {
return typeof option === "string" ? option : option.label;
}
export function WheelPicker({
options,
value,
defaultValue,
onValueChange,
visibleCount = 5,
itemHeight = 36,
disabled = false,
sound = false,
className,
"aria-label": ariaLabel,
}: WheelPickerProps) {
const reduce = useReducedMotion() ?? false;
const id = useId();
const controlled = value !== undefined;
const last = options.length - 1;
const indexOf = useCallback(
(v: string | undefined) => {
const i = options.findIndex((o) => optionValue(o) === v);
return i < 0 ? 0 : i;
},
[options],
);
const [internal, setInternal] = useState(() => defaultValue ?? value);
const currentValue = controlled ? value : internal;
const activeIndex = indexOf(currentValue);
const [grabbing, setGrabbing] = useState(false);
// Cylinder geometry. Each row spans `itemAngle`; `radius` seats the rows on
// the drum; rows past `hideBeyond` sit behind the horizon and are dropped.
const { itemAngle, radius, height, hideBeyond } = useMemo(() => {
const rowsEachSide = Math.max(1, Math.floor(visibleCount / 2));
const cutoff = rowsEachSide + 1;
const angle = 90 / cutoff;
const r = itemHeight / Math.tan(angle * DEG);
return {
itemAngle: angle,
radius: r,
hideBeyond: cutoff,
height: Math.round(
2 * r * Math.sin(rowsEachSide * angle * DEG) + itemHeight,
),
};
}, [visibleCount, itemHeight]);
const container = useRef<HTMLDivElement>(null);
const drumRef = useRef<HTMLUListElement>(null);
const bandRef = useRef<HTMLUListElement>(null);
// Scroll position measured in rows (a float index). One source of truth for
// both layers: the drum rotates by `itemAngle·scroll`, the crisp band slides
// by `itemHeight·scroll`.
const scroll = useRef(indexOf(currentValue));
const raf = useRef(0);
const emitted = useRef(currentValue);
const tickPlayer = useRef<ReturnType<typeof createTickPlayer> | null>(null);
const lastTick = useRef(indexOf(currentValue));
const paint = useCallback(
(s: number) => {
const drum = drumRef.current;
const band = bandRef.current;
if (drum) {
drum.style.transform = `translateZ(${-radius}px) rotateX(${itemAngle * s}deg)`;
for (const node of Array.from(drum.children)) {
const li = node as HTMLLIElement;
const i = Number(li.dataset.index);
const want = Math.abs(i - s) > hideBeyond ? "hidden" : "visible";
// Write only on change — an unconditional write every frame thrashes
// style recalc and is what made the drag feel draggy on mobile.
if (li.style.visibility !== want) li.style.visibility = want;
}
}
// The band is the SAME drum, clipped to the centre row — driven by the
// identical transform so the crisp copy sits exactly on the dimmed one,
// with no parallax ghost as rows cross the window. It needs the same
// horizon cull, or the row on the back of the drum bleeds into the front.
if (band) {
band.style.transform = `translateZ(${-radius}px) rotateX(${itemAngle * s}deg)`;
for (const node of Array.from(band.children)) {
const li = node as HTMLLIElement;
const i = Number(li.dataset.index);
const want = Math.abs(i - s) > hideBeyond ? "hidden" : "visible";
if (li.style.visibility !== want) li.style.visibility = want;
}
}
},
[radius, itemAngle, hideBeyond],
);
const getPlayer = useCallback(() => {
if (!tickPlayer.current) tickPlayer.current = createTickPlayer();
return tickPlayer.current;
}, []);
const emit = useCallback(
(i: number) => {
const v = optionValue(options[clamp(i, 0, last)]);
if (v === emitted.current) return;
emitted.current = v;
// Reduced motion has no drum/glide path to tick from — it's an
// onClick straight into emit, so the tick lives here instead.
if (sound && reduce) getPlayer().play();
if (!controlled) setInternal(v);
onValueChange?.(v);
},
[options, last, controlled, onValueChange, sound, reduce, getPlayer],
);
// Drum path: fires a tick whenever the nearest row changes, independent of
// `emit` (which only fires on settle during a glide/fling, not per row
// crossed). Gated on `!reduce` since the reduced render never calls this.
const maybeTick = useCallback(
(pos: number) => {
const row = clamp(Math.round(pos), 0, last);
if (!sound || reduce) {
lastTick.current = row;
return;
}
if (row === lastTick.current) return;
lastTick.current = row;
getPlayer().play();
},
[sound, reduce, last, getPlayer],
);
const stop = useCallback(() => cancelAnimationFrame(raf.current), []);
// Ease `scroll` from where it is to an integer detent over `duration`. The
// easing may overshoot (spring bounce) before it resolves exactly on `to`.
const glide = useCallback(
(
to: number,
duration: number,
ease: (p: number) => number = easeOutCubic,
) => {
stop();
const from = scroll.current;
const dist = to - from;
if (!dist || duration <= 0) {
scroll.current = to;
paint(to);
maybeTick(to);
emit(to);
return;
}
const start = performance.now();
const tick = (now: number) => {
const p = (now - start) / duration;
if (p >= 1) {
scroll.current = to;
paint(to);
maybeTick(to);
emit(to);
return;
}
scroll.current = from + dist * ease(p);
paint(scroll.current);
maybeTick(scroll.current);
raf.current = requestAnimationFrame(tick);
};
raf.current = requestAnimationFrame(tick);
},
[stop, paint, emit, maybeTick],
);
// Project where a flick of `velocity` (rows/ms) coasts to, snap to a row.
const fling = useCallback(
(velocity: number) => {
const from = scroll.current;
if (from < 0 || from > last) {
glide(clamp(Math.round(from), 0, last), 260); // rubber-band back
return;
}
const dir = Math.sign(velocity);
const coast = ((velocity * velocity) / (2 * DECELERATION)) * dir;
const to = clamp(Math.round(from + coast), 0, last);
// Long, spring-tipped settle so a hard flick reads as free momentum
// coasting to rest with a gentle bounce, never a clipped stop.
const duration = clamp(
Math.sqrt(Math.abs(to - from)) * 300 + 240,
280,
1700,
);
glide(to, duration, easeOutBack);
},
[glide, last],
);
const step = useCallback(
(by: number) =>
glide(clamp(Math.round(scroll.current) + by, 0, last), 300, easeOutBack),
[glide, last],
);
// Drag: track recent points for a release velocity; rubber-band past the ends.
const drag = useRef<{
y: number;
scroll: number;
pts: [number, number][];
} | null>(null);
// Coalesce touch/pointer moves to one paint per animation frame — raw move
// events fire several times per frame (and off-frame) on high-refresh
// screens, and painting each one is what made the drag feel choppy.
const dragFrame = useRef(0);
const latestY = useRef(0);
// Shared drag core, driven by a Y coordinate from either a mouse pointer or a
// native touch. Touch is bound with non-passive listeners in the effect below
// so the move can preventDefault the page scroll — React's synthetic touch
// events are passive and can't, which is why finger-drag did nothing on
// mobile.
const beginDrag = useCallback(
(y: number) => {
stop();
if (sound) getPlayer().prepare();
setGrabbing(true);
drag.current = {
y,
scroll: scroll.current,
pts: [[y, performance.now()]],
};
},
[stop, sound, getPlayer],
);
const moveDrag = useCallback(
(y: number) => {
const d = drag.current;
if (!d) return;
// Record every sample for an accurate release velocity, but only render
// the newest position once per frame.
latestY.current = y;
d.pts.push([y, performance.now()]);
if (d.pts.length > 8) d.pts.shift();
if (dragFrame.current) return;
dragFrame.current = requestAnimationFrame(() => {
dragFrame.current = 0;
const dd = drag.current;
if (!dd) return;
let next = dd.scroll + (dd.y - latestY.current) / itemHeight;
if (next < 0) next *= 0.3;
else if (next > last) next = last + (next - last) * 0.3;
scroll.current = next;
paint(next);
maybeTick(next);
emit(Math.round(clamp(next, 0, last)));
});
},
[itemHeight, last, paint, emit, maybeTick],
);
const endDrag = useCallback(() => {
const d = drag.current;
if (!d) return;
if (dragFrame.current) {
cancelAnimationFrame(dragFrame.current);
dragFrame.current = 0;
}
drag.current = null;
setGrabbing(false);
// Average velocity over the last `VELOCITY_WINDOW` ms of movement rather
// than the final two samples — a single noisy frame otherwise makes an
// even flick feel like it caught or slipped.
const pts = d.pts;
let v = 0;
if (pts.length > 1) {
const latest = pts[pts.length - 1];
let ref = pts[0];
for (const p of pts) {
if (latest[1] - p[1] <= VELOCITY_WINDOW) {
ref = p;
break;
}
}
const dt = latest[1] - ref[1];
if (dt > 0) {
const raw = (ref[0] - latest[0]) / itemHeight / dt;
v = clamp(raw, -MAX_VELOCITY, MAX_VELOCITY);
}
}
fling(v);
}, [itemHeight, fling]);
// Mouse / pen only — touch runs through the native listeners in the effect.
const onPointerDown = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (disabled || reduce || event.pointerType === "touch") return;
beginDrag(event.clientY);
capturePointer(event.currentTarget, event.pointerId);
},
[disabled, reduce, beginDrag],
);
const onPointerMove = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (event.pointerType === "touch") return;
moveDrag(event.clientY);
},
[moveDrag],
);
const onPointerUp = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (event.pointerType === "touch") return;
// Also the pointercancel handler, where the capture is already gone —
// an unguarded release throws there and the drum never settles.
releasePointer(event.currentTarget, event.pointerId);
endDrag();
},
[endDrag],
);
// Wheel drives `scroll` continuously — like a drag — then snaps once it goes
// idle. Firing a fresh eased step per notch instead stacks overlapping
// animations that keep interrupting each other, which read as lag.
const wheelSnap = useRef<ReturnType<typeof setTimeout> | null>(null);
const onWheel = useCallback(
(event: globalThis.WheelEvent) => {
// Native (non-passive) so preventDefault actually stops the page from
// scrolling behind the wheel — React's synthetic wheel listener is
// passive, so a handler on the element cannot cancel the scroll.
if (disabled || reduce) return;
event.preventDefault();
if (sound) getPlayer().prepare();
stop();
const px = event.deltaMode === 1 ? event.deltaY * 16 : event.deltaY;
const next = clamp(scroll.current + px * WHEEL_SENS, 0, last);
scroll.current = next;
paint(next);
maybeTick(next);
emit(Math.round(next));
if (wheelSnap.current) clearTimeout(wheelSnap.current);
wheelSnap.current = setTimeout(() => {
glide(clamp(Math.round(scroll.current), 0, last), 240, easeOutBack);
}, WHEEL_SETTLE);
},
[
disabled,
reduce,
sound,
last,
paint,
emit,
stop,
glide,
maybeTick,
getPlayer,
],
);
const onKeyDown = useCallback(
(event: KeyboardEvent<HTMLDivElement>) => {
if (disabled) return;
const at = Math.round(scroll.current);
const map: Record<string, number> = {
ArrowUp: -1,
ArrowDown: 1,
Home: -at,
End: last - at,
};
if (event.key in map) {
event.preventDefault();
if (sound) getPlayer().prepare();
step(map[event.key]);
}
},
[disabled, sound, last, step, getPlayer],
);
// Paint the starting frame, and follow controlled/value changes from outside
// unless a gesture is mid-flight.
useEffect(() => {
if (drag.current) return;
const target = indexOf(currentValue);
emitted.current = currentValue;
if (Math.abs(Math.round(scroll.current) - target) < 0.001) {
paint(scroll.current);
return;
}
glide(target, 260);
}, [currentValue, indexOf, paint, glide]);
useEffect(
() => () => {
cancelAnimationFrame(raf.current);
cancelAnimationFrame(dragFrame.current);
if (wheelSnap.current) clearTimeout(wheelSnap.current);
tickPlayer.current?.dispose();
},
[],
);
// Native touch + wheel listeners, bound non-passively so touchmove and wheel
// can block the page from scrolling while the wheel spins. React's synthetic
// touch/wheel handlers are passive, so preventDefault there is a no-op and the
// gesture scrolls the page instead of driving the drum.
useEffect(() => {
const el = container.current;
if (!el || reduce || disabled) return;
const onStart = (e: TouchEvent) => {
const t = e.touches[0];
if (t) beginDrag(t.clientY);
};
const onMove = (e: TouchEvent) => {
const t = e.touches[0];
if (!t || !drag.current) return;
e.preventDefault();
moveDrag(t.clientY);
};
const onEnd = () => endDrag();
el.addEventListener("touchstart", onStart, { passive: true });
el.addEventListener("touchmove", onMove, { passive: false });
el.addEventListener("touchend", onEnd);
el.addEventListener("touchcancel", onEnd);
el.addEventListener("wheel", onWheel, { passive: false });
return () => {
el.removeEventListener("touchstart", onStart);
el.removeEventListener("touchmove", onMove);
el.removeEventListener("touchend", onEnd);
el.removeEventListener("touchcancel", onEnd);
el.removeEventListener("wheel", onWheel);
};
}, [reduce, disabled, beginDrag, moveDrag, endDrag, onWheel]);
const maskFade =
"[mask-image:linear-gradient(to_bottom,transparent,#000_22%,#000_78%,transparent)]";
if (reduce) {
const pad = (height - itemHeight) / 2;
return (
<div
className={cn(
"relative overflow-hidden rounded-2xl border border-border bg-card",
disabled && "pointer-events-none opacity-50",
className,
)}
style={{ height }}
>
<div
className="pointer-events-none absolute inset-x-0 top-1/2 z-10 -translate-y-1/2 border-border border-y bg-foreground/[0.04]"
style={{ height: itemHeight }}
/>
<ul
className={cn(
"h-full snap-y snap-mandatory overflow-y-auto scroll-smooth [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
maskFade,
)}
style={{ paddingTop: pad, paddingBottom: pad }}
>
{options.map((option) => {
const v = optionValue(option);
return (
<li key={v} className="snap-center">
<button
type="button"
disabled={disabled}
onClick={() => emit(options.indexOf(option))}
className={cn(
"flex w-full items-center justify-center font-medium",
v === currentValue
? "text-foreground"
: "text-muted-foreground",
)}
style={{ height: itemHeight }}
>
{optionLabel(option)}
</button>
</li>
);
})}
</ul>
</div>
);
}
return (
<div
ref={container}
role="listbox"
aria-label={ariaLabel}
aria-activedescendant={options.length ? `${id}-option-${activeIndex}` : undefined}
aria-disabled={disabled || undefined}
tabIndex={disabled ? -1 : 0}
onKeyDown={onKeyDown}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
className={cn(
"relative touch-none overflow-hidden rounded-2xl border border-border bg-card outline-none focus-visible:ring-2 focus-visible:ring-foreground/20",
// The drum owns the whole gesture; iOS must not open its callout or
// start a drag out of the same press and cancel ours.
TOUCH_GESTURE_CLASS,
grabbing ? "cursor-grabbing" : "cursor-grab",
disabled && "pointer-events-none opacity-50",
maskFade,
className,
)}
style={{ height, perspective: 1000 }}
>
{options.map((option, index) => (
<span key={optionValue(option)} id={`${id}-option-${index}`} role="option" tabIndex={-1} aria-selected={index === activeIndex} className="sr-only">
{optionLabel(option)}
</span>
))}
{/* Curved drum of dimmed rows. */}
<ul
ref={drumRef}
aria-hidden
className="absolute inset-x-0 top-1/2 m-0 h-0 list-none p-0 [backface-visibility:hidden] [transform-style:preserve-3d] [will-change:transform]"
>
{options.map((option, i) => (
<li
key={optionValue(option)}
data-index={i}
className="absolute inset-x-0 flex items-center justify-center font-medium text-muted-foreground"
style={{
top: -itemHeight / 2,
height: itemHeight,
transform: `rotateX(${-itemAngle * i}deg) translateZ(${radius}px)`,
}}
>
{optionLabel(option)}
</li>
))}
</ul>
{/* Center band: the very same drum, clipped to one row and drawn crisp.
Its own perspective, centred on the container middle, matches the main
drum's projection so the two copies register exactly. */}
<div
className="pointer-events-none absolute inset-x-0 top-1/2 z-10 -translate-y-1/2 overflow-hidden rounded-md bg-foreground/[0.04]"
style={{ height: itemHeight, perspective: 1000 }}
>
<ul
ref={bandRef}
aria-hidden
className="absolute inset-x-0 top-1/2 m-0 h-0 list-none p-0 [backface-visibility:hidden] [transform-style:preserve-3d] [will-change:transform]"
>
{options.map((option, i) => (
<li
key={optionValue(option)}
data-index={i}
className="absolute inset-x-0 flex items-center justify-center font-medium text-foreground"
style={{
top: -itemHeight / 2,
height: itemHeight,
transform: `rotateX(${-itemAngle * i}deg) translateZ(${radius}px)`,
}}
>
{optionLabel(option)}
</li>
))}
</ul>
</div>
</div>
);
}
import type { ReactNode } from "react";
/** Calendar dates, independent of a browser's timezone: YYYY-MM-DD. */
export interface DateRange {
from: string;
to?: string;
}
export interface DateRangePreset {
label: string;
value: DateRange;
}
export interface DateRangePickerProps {
value?: DateRange | null;
defaultValue?: DateRange | null;
onValueChange?: (range: DateRange | null) => void;
defaultMonth?: string;
min?: string;
max?: string;
isDateDisabled?: (date: string) => boolean;
presets?: DateRangePreset[];
locale?: string;
label?: string;
disabled?: boolean;
/** Move focus to the active date on mount, for use inside a popover. */
autoFocus?: boolean;
/** Show the start/end summary above the calendar. Default true. */
showSummary?: boolean;
className?: string;
/** Compose custom controls; omitted children render the inline calendar. */
children?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Close an open popover after a complete range or preset. Default false. */
closeOnSelect?: boolean;
}
"use client";
import {
type MutableRefObject,
useCallback,
useLayoutEffect,
useState,
} from "react";
export type PortalLayout = {
trigger: {
left: number;
top: number;
width: number;
height: number;
};
content: {
width: number;
height: number;
};
};
function sameLayout(a: PortalLayout | null, b: PortalLayout) {
return (
a?.trigger.left === b.trigger.left &&
a.trigger.top === b.trigger.top &&
a.trigger.width === b.trigger.width &&
a.trigger.height === b.trigger.height &&
a.content.width === b.content.width &&
a.content.height === b.content.height
);
}
/** Measures a trigger and portalled panel in viewport coordinates. */
export function usePopoverPortalPosition<
TriggerElement extends HTMLElement,
ContentElement extends HTMLElement,
>(
triggerRef: MutableRefObject<TriggerElement | null>,
contentRef: MutableRefObject<ContentElement | null>,
active: boolean,
) {
const [layout, setLayout] = useState<PortalLayout | null>(null);
const update = useCallback(() => {
const trigger = triggerRef.current;
const content = contentRef.current;
if (!trigger || !content) return;
const rect = trigger.getBoundingClientRect();
const next: PortalLayout = {
trigger: {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
},
content: {
width: content.offsetWidth,
height: content.offsetHeight,
},
};
setLayout((current) => (sameLayout(current, next) ? current : next));
}, [contentRef, triggerRef]);
useLayoutEffect(() => {
update();
if (!active) return;
const trigger = triggerRef.current;
const content = contentRef.current;
const observer = new ResizeObserver(update);
if (trigger) observer.observe(trigger);
if (content) observer.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [active, contentRef, triggerRef, update]);
return layout;
}
API Reference
value?stringLocal wall-clock time, YYYY-MM-DDTHH:mm. No timezone conversion is applied.
—defaultValue?stringonValueChange?((value: string) => void)Called only when Confirm is pressed. Dismissing discards the draft.
—label?stringChoose date and timedisabled?booleanfalsename?string—className?string—classNames?DateTimePickerClassNames—Related components
Date Range Picker
Composable date range picker with root, trigger, popover content, calendar, header, grid, summary, footer, clear and preset parts, plus a shared state hook. Compact inline and dropdown compositions, direct month and year selection, and full keyboard navigation.
Arc Picker
Radial text picker with top, bottom, left or right curves, smooth wheel movement and live selection on each scroll step. One persistent bracket frame grows and squeezes around each label. Supports drag momentum, keyboard input, disabled choices, controlled or uncontrolled values, forms and reduced motion.
Popover
Gooey popover whose panel oozes out of the trigger through an SVG goo filter — a liquid neck that stretches and pinches — with crisp content fading in on top, plus a Morph variant that clip-morphs open from the trigger corner. Click or hover trigger, controlled or uncontrolled.
Updated