Contact Form
Contact section with name, email, a topic select and an auto-growing message textarea with a live character counter, validation that only flags fields after blur, an async submit that shakes on error and morphs the card into a drawn-check thank-you panel, plus a side panel of contact methods.
Preview
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))
}
// 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";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* 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;
"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;
}
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/blocks/contact-form
import {
Clock,
type LucideIcon,
Mail,
MapPin,
MessagesSquare,
User,
} from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import { type FormEvent, type ReactNode, useId, useMemo, useRef, useState } from "react";
import { Button, StatefulButton } from "@/components/motion/button";
import { Input } from "@/components/motion/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/motion/select";
import { Textarea } from "@/components/motion/textarea";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ContactValues = {
name: string;
email: string;
topic: string;
message: string;
};
export type ContactErrors = Partial<Record<keyof ContactValues, string>>;
export type ContactTopic = { value: string; label: string };
export type ContactMethod = {
id: string;
icon: LucideIcon;
label: string;
value: ReactNode;
/** Makes the row a link (mailto:, tel:, https:). */
href?: string;
};
export interface ContactFormProps {
defaultValues?: Partial<ContactValues>;
/** Called with valid values. Reject with a message to show it and shake the form. */
onSubmit?: (values: ContactValues) => void | Promise<void>;
validate?: (values: ContactValues) => ContactErrors;
topics?: ContactTopic[];
/** Side panel rows. Pass `[]` to hide the panel. */
methods?: ContactMethod[];
/** Character limit for the message (counter shows). Default 500. */
maxLength?: number;
/** Minimum message length. Default 10. */
minLength?: number;
title?: ReactNode;
description?: ReactNode;
className?: string;
}
const DEFAULT_TOPICS: ContactTopic[] = [
{ value: "sales", label: "Sales" },
{ value: "support", label: "Support" },
{ value: "partnership", label: "Partnership" },
{ value: "other", label: "Something else" },
];
const DEFAULT_METHODS: ContactMethod[] = [
{
id: "email",
icon: Mail,
label: "Email",
value: "hello@example.com",
href: "mailto:hello@example.com",
},
{ id: "chat", icon: MessagesSquare, label: "Live chat", value: "Mon–Fri, 9am–6pm" },
{ id: "office", icon: MapPin, label: "Office", value: "100 Example St, Springfield" },
{ id: "reply", icon: Clock, label: "Response time", value: "Within one business day" },
];
const EMPTY: ContactValues = { name: "", email: "", topic: "", message: "" };
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const SHAKE = { x: [0, -8, 8, -5, 5, -2, 0] };
function messageOf(reason: unknown) {
if (reason instanceof Error && reason.message) return reason.message;
if (typeof reason === "string" && reason) return reason;
return "Something went wrong. Try again.";
}
/**
* Contact section: name / email / topic `Select` / message `Textarea` with a
* live counter, "reward early, punish late" validation (as in `SignUpForm`),
* an async submit through `StatefulButton` that shakes on failure, and a
* success panel the card morphs into. A side panel lists contact methods.
*/
export function ContactForm({
defaultValues,
onSubmit,
validate,
topics = DEFAULT_TOPICS,
methods = DEFAULT_METHODS,
maxLength = 500,
minLength = 10,
title = "Get in touch",
description = "Tell us what you need and the right person will reply.",
className,
}: ContactFormProps) {
const reduce = useReducedMotion();
const baseId = useId();
const [values, setValues] = useState<ContactValues>({ ...EMPTY, ...defaultValues });
const [touched, setTouched] = useState<Partial<Record<keyof ContactValues, boolean>>>({});
const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
const [formError, setFormError] = useState<string>();
const [sent, setSent] = useState<ContactValues | null>(null);
const shakeRef = useRef<HTMLDivElement>(null);
const errors = useMemo<ContactErrors>(() => {
if (validate) return validate(values);
const next: ContactErrors = {};
if (!values.name.trim()) next.name = "Enter your name.";
if (!values.email.trim()) next.email = "Enter your email.";
else if (!EMAIL_PATTERN.test(values.email))
next.email = "That doesn't look like an email address.";
if (!values.topic) next.topic = "Pick a topic.";
if (values.message.trim().length < minLength)
next.message = `Write at least ${minLength} characters.`;
return next;
}, [values, validate, minLength]);
const shown = (key: keyof ContactValues) => (touched[key] ? errors[key] : undefined);
const ok = (key: keyof ContactValues) =>
Boolean(touched[key]) && !errors[key] && Boolean(values[key]);
const set = (key: keyof ContactValues, next: string) => {
setValues((prev) => ({ ...prev, [key]: next }));
if (status === "error") setStatus("idle");
};
const touch = (key: keyof ContactValues) =>
setTouched((prev) => (prev[key] ? prev : { ...prev, [key]: true }));
const shake = () => {
if (!reduce && shakeRef.current) {
animate(shakeRef.current, SHAKE, { duration: 0.42, ease: EASE_OUT });
}
};
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setTouched({ name: true, email: true, topic: true, message: true });
if (Object.keys(errors).length > 0) {
shake();
return;
}
setFormError(undefined);
setStatus("loading");
try {
await onSubmit?.(values);
setStatus("success");
setSent(values);
} catch (reason) {
setStatus("error");
setFormError(messageOf(reason));
shake();
}
};
const restart = () => {
setValues({ ...EMPTY, name: values.name, email: values.email });
setTouched({});
setStatus("idle");
setSent(null);
};
const busy = status === "loading";
const topicErrorId = `${baseId}-topic-error`;
const topicLabelId = `${baseId}-topic-label`;
const offset = reduce ? 0 : 16;
return (
<div className={cn("@container w-full", className)}>
<div
className={cn(
"grid gap-4 rounded-3xl border border-border bg-card p-4 @lg:p-5",
// Side column only when the card is wide enough (~768px); narrower
// containers move the methods into a compact grid under the form.
methods.length > 0 && "@3xl:grid-cols-[minmax(0,1fr)_14rem]",
)}
>
{/* The card resizes between the form and the thank-you panel; `layout`
is a layout job here by design, with content counter-corrected. */}
<motion.div
layout
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="min-w-0"
>
<AnimatePresence mode="popLayout" initial={false}>
{sent ? (
<motion.div
key="sent"
layout="position"
role="status"
initial={{ opacity: 0, y: offset, filter: reduce ? "blur(0px)" : "blur(4px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: -offset, transition: { duration: 0.15 } }}
transition={{ duration: 0.3, ease: EASE_OUT }}
className="flex min-h-72 flex-col items-center justify-center gap-4 px-4 text-center"
>
<motion.span
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={reduce ? { duration: 0.2 } : { ...SPRING_SWAP, delay: 0.08 }}
className="grid size-14 place-items-center rounded-full bg-success/15 text-success"
>
<svg viewBox="0 0 24 24" className="size-7" fill="none" aria-hidden="true">
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
stroke="currentColor"
strokeWidth={2.4}
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: reduce ? 1 : 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.4, delay: 0.2, ease: EASE_OUT }}
/>
</svg>
</motion.span>
<div className="flex flex-col gap-1">
<h2 className="text-lg font-semibold tracking-tight text-foreground">
Message sent
</h2>
<p className="max-w-xs text-sm text-muted-foreground">
Thanks, {sent.name.split(" ")[0]}. We'll reply to{" "}
<span className="font-medium text-foreground">{sent.email}</span> soon.
</p>
</div>
<Button variant="secondary" size="sm" onClick={restart}>
Send another message
</Button>
</motion.div>
) : (
<motion.form
key="form"
layout="position"
noValidate
onSubmit={handleSubmit}
initial={{ opacity: 0, y: -offset }}
animate={{ opacity: 1, y: 0 }}
exit={{
opacity: 0,
y: -offset,
filter: reduce ? "blur(0px)" : "blur(4px)",
transition: { duration: 0.16 },
}}
transition={{ duration: 0.26, ease: EASE_OUT }}
>
<div ref={shakeRef} className="flex flex-col gap-3.5">
{title || description ? (
<div className="flex flex-col gap-0.5">
{title ? (
<h2 className="text-lg font-semibold tracking-tight text-foreground">
{title}
</h2>
) : null}
{description ? (
<p className="text-sm text-muted-foreground">{description}</p>
) : null}
</div>
) : null}
<div className="grid gap-3.5 @lg:grid-cols-2">
<Input
label="Name"
autoComplete="name"
placeholder="Ada Lovelace"
leftIcon={<User />}
disabled={busy}
value={values.name}
onChange={(next) => set("name", next)}
onBlur={() => touch("name")}
error={shown("name")}
success={ok("name")}
/>
<Input
label="Email"
type="email"
inputMode="email"
autoComplete="email"
placeholder="you@example.com"
leftIcon={<Mail />}
disabled={busy}
value={values.email}
onChange={(next) => set("email", next)}
onBlur={() => touch("email")}
error={shown("email")}
success={ok("email")}
/>
</div>
<div className="relative z-20 flex flex-col gap-1.5">
<span id={topicLabelId} className="px-1 text-sm font-medium text-foreground">
Topic
</span>
<fieldset
aria-labelledby={topicLabelId}
aria-describedby={shown("topic") ? topicErrorId : undefined}
className="m-0 border-0 p-0"
>
<Select
value={values.topic || undefined}
disabled={busy}
onValueChange={(next) => {
set("topic", next);
touch("topic");
}}
onOpenChange={(open) => {
if (!open) touch("topic");
}}
>
<SelectTrigger
className={cn(
"h-11",
shown("topic") && "border-destructive ring-2 ring-destructive/25",
)}
>
<SelectValue placeholder="What's this about?" />
</SelectTrigger>
<SelectContent>
{topics.map((topic) => (
<SelectItem key={topic.value} value={topic.value}>
{topic.label}
</SelectItem>
))}
</SelectContent>
</Select>
</fieldset>
<AnimatePresence initial={false}>
{shown("topic") ? (
<motion.p
id={topicErrorId}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.18 }}
className="px-1 text-xs text-destructive"
>
{shown("topic")}
</motion.p>
) : null}
</AnimatePresence>
</div>
<Textarea
label="Message"
placeholder="How can we help?"
minRows={3}
maxRows={6}
maxLength={maxLength}
disabled={busy}
value={values.message}
onChange={(next) => set("message", next)}
onBlur={() => touch("message")}
error={shown("message")}
/>
<AnimatePresence initial={false}>
{formError && status === "error" ? (
<motion.p
role="alert"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="rounded-2xl border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
{formError}
</motion.p>
) : null}
</AnimatePresence>
<StatefulButton
type="submit"
state={status}
loadingText="Sending"
successText="Sent"
errorText="Try again"
className="w-full @lg:w-fit @lg:self-end"
>
Send message
</StatefulButton>
</div>
</motion.form>
)}
</AnimatePresence>
</motion.div>
{methods.length > 0 ? (
<aside
aria-label="Other ways to reach us"
className="grid content-start gap-1 rounded-2xl bg-muted/50 p-3 @md:grid-cols-2 @3xl:grid-cols-1"
>
<p className="col-span-full px-2 pt-1 pb-1.5 text-xs font-medium text-muted-foreground">
Other ways to reach us
</p>
{methods.map((method) => {
const Icon = method.icon;
const body = (
<>
<span className="grid size-8 shrink-0 place-items-center rounded-xl border border-border bg-card text-foreground">
<Icon className="size-4" aria-hidden />
</span>
<span className="min-w-0">
<span className="block text-xs text-muted-foreground">{method.label}</span>
<span className="block truncate text-sm font-medium text-foreground">
{method.value}
</span>
</span>
</>
);
const rowClass =
"flex items-center gap-2.5 rounded-xl px-2 py-1.5 outline-none transition-colors";
return method.href ? (
<a
key={method.id}
href={method.href}
className={cn(
rowClass,
"hover:bg-card focus-visible:ring-2 focus-visible:ring-ring",
)}
>
{body}
</a>
) : (
<div key={method.id} className={rowClass}>
{body}
</div>
);
})}
</aside>
) : null}
</div>
</div>
);
}
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
useEffect,
useId,
useRef,
useState,
type InputHTMLAttributes,
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
export type InputClassNames = {
root?: string;
label?: string;
field?: string;
input?: string;
leftIcon?: string;
rightIcon?: string;
successIcon?: string;
errorMessage?: string;
};
export interface InputProps extends Omit<
InputHTMLAttributes<HTMLInputElement>,
"value" | "defaultValue" | "onChange"
> {
label?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Truthy error triggers a shake, red border and (if a string) a message. */
error?: string | boolean;
success?: boolean;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
className?: string;
classNames?: InputClassNames;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
label,
value: valueProp,
defaultValue,
onChange,
onFocus,
onBlur,
error,
success,
leftIcon,
rightIcon,
className,
classNames,
disabled,
id: idProp,
type,
...rest
},
ref,
) {
const reactId = useId();
const id = idProp ?? reactId;
const reduce = useReducedMotion();
const controlled = valueProp !== undefined;
const [internal, setInternal] = useState(defaultValue ?? "");
const value = controlled ? (valueProp ?? "") : internal;
const [focused, setFocused] = useState(false);
const fieldRef = useRef<HTMLDivElement>(null);
const hasError = Boolean(error);
const errorMessage = typeof error === "string" ? error : null;
// Right edge shows the success check, otherwise the caller's right icon.
const rightSlot = success ? null : rightIcon;
// Shake the field when an error appears.
useEffect(() => {
if (!fieldRef.current || reduce || !hasError) return;
animate(
fieldRef.current,
{ x: [0, -6, 6, -4, 4, -2, 0] },
{ duration: 0.45 },
);
}, [hasError, reduce]);
const handleChange = (next: string) => {
if (!controlled) setInternal(next);
onChange?.(next);
};
return (
<div
className={cn("flex flex-col gap-1.5", className, classNames?.root)}
>
{label ? (
<label
htmlFor={id}
className={cn(
"px-1 text-sm font-medium text-foreground",
classNames?.label,
)}
>
{label}
</label>
) : null}
<div
ref={fieldRef}
data-state={
hasError
? "error"
: success
? "success"
: focused
? "focused"
: "idle"
}
className={cn(
"relative h-11 overflow-hidden rounded-full border transition-colors duration-200",
"border-border",
focused && !hasError && "border-foreground/40 ring-2 ring-ring/40",
hasError && "border-destructive ring-2 ring-destructive/25",
disabled && "opacity-60",
classNames?.field,
)}
>
{leftIcon ? (
<span
className={cn(
"pointer-events-none absolute left-3 top-1/2 flex -translate-y-1/2 items-center text-muted-foreground [&_svg]:h-4 [&_svg]:w-4",
classNames?.leftIcon,
)}
>
{leftIcon}
</span>
) : null}
<input
ref={ref}
id={id}
type={type}
value={value}
disabled={disabled}
aria-invalid={hasError || undefined}
aria-describedby={errorMessage ? `${id}-error` : undefined}
{...rest}
onChange={(e) => handleChange(e.target.value)}
onFocus={(event) => {
setFocused(true);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
className={cn(
"peer h-full w-full bg-transparent text-base leading-6 text-foreground caret-foreground outline-none",
"placeholder:text-muted-foreground/60",
leftIcon ? "pl-10" : "pl-3.5",
rightSlot || success ? "pr-10" : "pr-3.5",
disabled && "cursor-not-allowed",
classNames?.input,
)}
/>
{success ? (
<motion.svg
viewBox="0 0 24 24"
fill="none"
className={cn(
"absolute right-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-(--color-success)",
classNames?.successIcon,
)}
>
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.35, ease: "easeOut" }}
/>
</motion.svg>
) : rightSlot ? (
<span
className={cn(
"absolute right-0 top-0 flex h-full items-center text-muted-foreground [&_button]:grid [&_button]:size-11 [&_button]:place-items-center [&_svg]:h-4 [&_svg]:w-4",
classNames?.rightIcon,
)}
>
{rightSlot}
</span>
) : null}
</div>
<AnimatePresence initial={false}>
{errorMessage ? (
<motion.p
id={`${id}-error`}
role="alert"
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
transition={{ duration: 0.2 }}
className={cn(
"px-1 text-xs text-destructive",
classNames?.errorMessage,
)}
>
{errorMessage}
</motion.p>
) : null}
</AnimatePresence>
</div>
);
});
"use client";
import { Check, ChevronDown } from "lucide-react";
import {
motion,
type Transition,
useReducedMotion,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
const INSTANT_TRANSITION: Transition = { duration: 0 };
// Spring with bounce powers the unfold/separation; per-property timings in the
// content choreograph it (see SelectContent). Mirrors bouncy-accordion's feel.
const CHEVRON_TRANSITION: Transition = { type: "spring", duration: 0.4, bounce: 0.3 };
const LIST_VARIANTS: Variants = {
hidden: {},
show: { transition: { staggerChildren: 0.035, delayChildren: 0.05 } },
};
const ITEM_VARIANTS: Variants = {
hidden: { opacity: 0, y: -6, filter: "blur(3px)" },
show: { opacity: 1, y: 0, filter: "blur(0px)" },
};
type Placement = "bottom" | "top";
interface SelectContextValue {
value: string | undefined;
open: boolean;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
reduce: boolean;
triggerId: string;
listId: string;
disabled: boolean;
placement: Placement;
setPlacement: (p: Placement) => void;
}
const SelectContext = createContext<SelectContextValue | null>(null);
function useSelectContext(component: string) {
const ctx = useContext(SelectContext);
if (!ctx) throw new Error(`${component} must be used within <Select>`);
return ctx;
}
export interface SelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/**
* Controlled open state of the panel. A layout that stacks selects can hold
* this to keep exactly one panel open — the panel is absolutely positioned
* inside its field, so two open at once paint over each other's options.
*/
open?: boolean;
/** Uncontrolled initial open state. Default false. */
defaultOpen?: boolean;
/**
* Fires whenever the panel opens or closes. The panel is absolutely
* positioned inside the field, so a layout that stacks selects has to know
* which one is open to paint it above its neighbours.
*/
onOpenChange?: (open: boolean) => void;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function Select({
value,
defaultValue,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
className,
children,
}: SelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internal, setInternal] = useState(defaultValue);
const [labels, setLabels] = useState<Map<string, string>>(new Map());
const [placement, setPlacement] = useState<Placement>("bottom");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const openControlled = openProp !== undefined;
const open = openControlled ? openProp : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!openControlled) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, openControlled],
);
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
setOpen(false);
},
[controlled, onValueChange, setOpen],
);
const register = useCallback((v: string, label: string) => {
setLabels((m) => (m.get(v) === label ? m : new Map(m).set(v, label)));
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
if (!m.has(v)) return m;
const next = new Map(m);
next.delete(v);
return next;
});
}, []);
// close on outside pointer / escape
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, setOpen]);
const ctx = useMemo<SelectContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)),
reduce,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
placement,
setPlacement,
}),
[
current,
open,
setOpen,
select,
register,
unregister,
labels,
reduce,
baseId,
disabled,
placement,
],
);
return (
<SelectContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</SelectContext.Provider>
);
}
export interface SelectTriggerProps {
className?: string;
children: ReactNode;
}
export function SelectTrigger({ className, children }: SelectTriggerProps) {
const ctx = useSelectContext("SelectTrigger");
const isTop = ctx.placement === "top";
// edge facing the panel flattens then rounds; the far edge stays rounded.
// All four corners are specified so none gets stranded when placement flips.
const kf = ctx.open ? [0, 0, 12] : [12, 0, 12];
const kfT: Transition = ctx.reduce
? { duration: 0 }
: ctx.open
? { duration: 0.6, times: [0, 0.4, 1], ease: EASE_OUT }
: { duration: 0.42, times: [0, 0.5, 1], ease: EASE_OUT };
return (
<motion.button
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(!ctx.open)}
// Gooey: the edge facing the panel snaps flat (panel attached) then rounds
// back once the panel pulls away — the two pinch apart.
initial={false}
animate={{
borderTopLeftRadius: isTop ? kf : 12,
borderTopRightRadius: isTop ? kf : 12,
borderBottomLeftRadius: isTop ? 12 : kf,
borderBottomRightRadius: isTop ? 12 : kf,
}}
transition={{
borderTopLeftRadius: isTop ? kfT : INSTANT_TRANSITION,
borderTopRightRadius: isTop ? kfT : INSTANT_TRANSITION,
borderBottomLeftRadius: isTop ? INSTANT_TRANSITION : kfT,
borderBottomRightRadius: isTop ? INSTANT_TRANSITION : kfT,
}}
className={cn(
"relative z-10 flex w-full items-center justify-between gap-2 rounded-xl border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition-colors",
"hover:border-(--color-border-strong) focus-visible:ring-2 focus-visible:ring-foreground/20",
"disabled:pointer-events-none disabled:opacity-50",
TOUCH_TARGET_CLASS,
className,
)}
>
{children}
<motion.span
aria-hidden
animate={{ rotate: ctx.open ? 180 : 0 }}
transition={ctx.reduce ? { duration: 0 } : CHEVRON_TRANSITION}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
);
}
export interface SelectValueProps {
placeholder?: string;
className?: string;
}
export function SelectValue({ placeholder, className }: SelectValueProps) {
const ctx = useSelectContext("SelectValue");
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface SelectContentProps {
className?: string;
children: ReactNode;
}
export function SelectContent({ className, children }: SelectContentProps) {
const ctx = useSelectContext("SelectContent");
const innerRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
const open = ctx.open;
const { setPlacement } = ctx;
useLayoutEffect(() => {
const node = innerRef.current;
if (!node) return;
const measure = () => setHeight(node.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
});
// On open, flip upward when there isn't room below and there's more above.
useLayoutEffect(() => {
if (!open) return;
const trigger = document.getElementById(ctx.triggerId);
const node = innerRef.current;
if (!trigger || !node) return;
const rect = trigger.getBoundingClientRect();
const h = node.offsetHeight;
const below = window.innerHeight - rect.bottom;
const above = rect.top;
setPlacement(below < h + 16 && above > below ? "top" : "bottom");
}, [open, ctx.triggerId, setPlacement]);
// Specify EVERY corner + both margins each render. The near edge (facing the
// trigger) animates flat->round and the gap opens on that side; the far edge
// stays rounded and its margin pinned to 0. Setting all of them avoids a
// stranded square corner when the placement flips between opens.
const isTop = ctx.placement === "top";
const nearGap = open ? 8 : 0;
const nearRadius = open ? 12 : 0;
const gapT: Transition = open
? { type: "spring", duration: 0.6, bounce: 0.5, delay: 0.12 }
: { type: "spring", duration: 0.3, bounce: 0.1 };
const radiusT: Transition = open
? { duration: 0.3, ease: EASE_OUT, delay: 0.14 }
: { duration: 0.16, ease: EASE_OUT };
// Items stay mounted (open just animates the panel) so each item's label
// registration persists — otherwise the trigger would fall back to the
// placeholder the moment the panel closes.
return (
<motion.div
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
aria-hidden={!open}
inert={!open}
initial={false}
animate={
ctx.reduce
? { opacity: open ? 1 : 0, height: open ? height : 0 }
: {
opacity: open ? 1 : 0,
height: open ? height : 0,
// gap opens on the side facing the trigger
marginTop: isTop ? 0 : nearGap,
marginBottom: isTop ? nearGap : 0,
// near corners go flat->round; far corners stay rounded
borderTopLeftRadius: isTop ? 12 : nearRadius,
borderTopRightRadius: isTop ? 12 : nearRadius,
borderBottomLeftRadius: isTop ? nearRadius : 12,
borderBottomRightRadius: isTop ? nearRadius : 12,
}
}
transition={
ctx.reduce
? { duration: 0.12 }
: {
opacity: open
? { duration: 0.18 }
: { duration: 0.16, delay: 0.12 },
height: open
? { type: "spring", duration: 0.42, bounce: 0.14 }
: { duration: 0.26, ease: EASE_OUT, delay: 0.14 },
marginTop: isTop ? INSTANT_TRANSITION : gapT,
marginBottom: isTop ? gapT : INSTANT_TRANSITION,
borderTopLeftRadius: isTop ? INSTANT_TRANSITION : radiusT,
borderTopRightRadius: isTop ? INSTANT_TRANSITION : radiusT,
borderBottomLeftRadius: isTop ? radiusT : INSTANT_TRANSITION,
borderBottomRightRadius: isTop ? radiusT : INSTANT_TRANSITION,
}
}
style={{
transformOrigin: isTop ? "bottom" : "top",
overflow: "hidden",
pointerEvents: open ? "auto" : "none",
}}
// flush against the trigger, then separates into its own rounded pill;
// sits above or below depending on available space
className={cn(
"absolute left-0 right-0 z-20 rounded-xl border border-border bg-background shadow-lg",
isTop ? "bottom-full" : "top-full",
className,
)}
>
<motion.div
ref={innerRef}
variants={ctx.reduce ? undefined : LIST_VARIANTS}
initial={false}
animate={open ? "show" : "hidden"}
className="p-1"
>
{children}
</motion.div>
</motion.div>
);
}
export interface SelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function SelectItem({
value,
disabled = false,
className,
children,
}: SelectItemProps) {
const ctx = useSelectContext("SelectItem");
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label]);
return (
<motion.li variants={ctx.reduce ? undefined : ITEM_VARIANTS}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.li>
);
}
"use client";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type TextareaHTMLAttributes,
} from "react";
import { EASE_OUT_CSS, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type TextareaClassNames = {
root?: string;
label?: string;
description?: string;
field?: string;
textarea?: string;
counter?: string;
errorMessage?: string;
};
export interface TextareaProps
extends Omit<
TextareaHTMLAttributes<HTMLTextAreaElement>,
"value" | "defaultValue" | "onChange" | "rows"
> {
label?: string;
/** Helper text under the label, linked through aria-describedby. */
description?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Truthy error triggers a shake, red border and (if a string) a message. */
error?: string | boolean;
/** Rows shown when empty; the field never shrinks below this. */
minRows?: number;
/** Rows the field grows to before it starts scrolling. */
maxRows?: number;
/** Shows the character counter. Defaults to true when `maxLength` is set. */
showCount?: boolean;
/** Fraction of `maxLength` at which the counter turns to the warning color. */
warnAt?: number;
className?: string;
classNames?: TextareaClassNames;
}
const SHAKE = { x: [0, -6, 6, -4, 4, -2, 0] };
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
function Textarea(
{
label,
description,
value: valueProp,
defaultValue,
onChange,
onFocus,
onBlur,
error,
minRows = 3,
maxRows = 8,
maxLength,
showCount,
warnAt = 0.9,
placeholder,
className,
classNames,
disabled,
id: idProp,
...rest
},
forwardedRef,
) {
const reactId = useId();
const id = idProp ?? reactId;
const reduce = useReducedMotion();
const controlled = valueProp !== undefined;
const [internal, setInternal] = useState(defaultValue ?? "");
const value = controlled ? (valueProp ?? "") : internal;
const [focused, setFocused] = useState(false);
const [height, setHeight] = useState<number | null>(null);
const [scrolls, setScrolls] = useState(false);
const fieldRef = useRef<HTMLDivElement>(null);
const counterRef = useRef<HTMLSpanElement>(null);
const mirrorRef = useRef<HTMLTextAreaElement>(null);
const innerRef = useRef<HTMLTextAreaElement | null>(null);
const setRefs = useCallback(
(node: HTMLTextAreaElement | null) => {
innerRef.current = node;
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
},
[forwardedRef],
);
const hasError = Boolean(error);
const errorMessage = typeof error === "string" ? error : null;
const countVisible = showCount ?? maxLength !== undefined;
const count = value.length;
const ratio = maxLength ? count / maxLength : 0;
const atLimit = maxLength !== undefined && count >= maxLength;
const nearLimit = maxLength !== undefined && ratio >= warnAt && !atLimit;
// Measure the content with an invisible twin so the real field can
// transition between pixel heights (resetting it to `auto` would kill the
// transition). Height is this component's purpose, so it animates layout.
const measure = useCallback(() => {
const mirror = mirrorRef.current;
if (!mirror) return;
const style = getComputedStyle(mirror);
const lineHeight = Number.parseFloat(style.lineHeight) || 24;
const padY =
Number.parseFloat(style.paddingTop) +
Number.parseFloat(style.paddingBottom);
const min = lineHeight * minRows + padY;
const max = lineHeight * Math.max(minRows, maxRows) + padY;
const content = mirror.scrollHeight;
setHeight(Math.min(max, Math.max(min, content)));
setScrolls(content > max + 1);
}, [minRows, maxRows]);
useLayoutEffect(() => {
if (mirrorRef.current) mirrorRef.current.value = value || " ";
measure();
}, [value, measure]);
// Width changes rewrap the text, so re-measure on resize.
useEffect(() => {
const field = fieldRef.current;
if (!field || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => measure());
observer.observe(field);
return () => observer.disconnect();
}, [measure]);
// Shake the field when an error appears.
useEffect(() => {
if (!fieldRef.current || reduce || !hasError) return;
animate(fieldRef.current, SHAKE, { duration: 0.45 });
}, [hasError, reduce]);
const nudgeCounter = useCallback(() => {
if (!counterRef.current || reduce) return;
animate(
counterRef.current,
{ x: [0, -4, 4, -3, 3, 0] },
{ duration: 0.35 },
);
}, [reduce]);
// Typing or pasting past `maxLength` is blocked natively; catch the
// attempt first so the counter can shake. Native listener because React's
// onBeforeInput misses paste and line breaks.
useEffect(() => {
const el = innerRef.current;
if (!el || maxLength === undefined) return;
const onBeforeInput = (event: InputEvent) => {
if (!event.inputType.startsWith("insert")) return;
const data =
event.data ??
event.dataTransfer?.getData("text/plain") ??
(event.inputType === "insertLineBreak" ? "\n" : "");
const selected = el.selectionEnd - el.selectionStart;
if (el.value.length - selected + data.length > maxLength) {
nudgeCounter();
}
};
el.addEventListener("beforeinput", onBeforeInput);
return () => el.removeEventListener("beforeinput", onBeforeInput);
}, [maxLength, nudgeCounter]);
const handleChange = (next: string) => {
if (!controlled) setInternal(next);
onChange?.(next);
};
const describedBy =
[
description ? `${id}-description` : null,
countVisible ? `${id}-count` : null,
errorMessage ? `${id}-error` : null,
]
.filter(Boolean)
.join(" ") || undefined;
const sharedText =
"block w-full resize-none bg-transparent px-3.5 py-2.5 text-base leading-6";
return (
<div
className={cn("flex flex-col gap-1.5", className, classNames?.root)}
>
{label || description ? (
<div className="flex flex-col gap-0.5 px-1">
{label ? (
<label
htmlFor={id}
className={cn(
"text-sm font-medium text-foreground",
classNames?.label,
)}
>
{label}
</label>
) : null}
{description ? (
<p
id={`${id}-description`}
className={cn(
"text-xs text-muted-foreground",
classNames?.description,
)}
>
{description}
</p>
) : null}
</div>
) : null}
<div
ref={fieldRef}
data-state={hasError ? "error" : focused ? "focused" : "idle"}
className={cn(
"relative overflow-hidden rounded-2xl border transition-colors duration-200",
"border-border",
focused && !hasError && "border-foreground/40 ring-2 ring-ring/40",
hasError && "border-destructive ring-2 ring-destructive/25",
disabled && "opacity-60",
classNames?.field,
)}
>
<textarea
ref={mirrorRef}
aria-hidden="true"
tabIndex={-1}
readOnly
rows={1}
className={cn(
sharedText,
"pointer-events-none invisible absolute inset-x-0 top-0 h-0 overflow-hidden",
classNames?.textarea,
)}
/>
<textarea
ref={setRefs}
id={id}
rows={minRows}
value={value}
disabled={disabled}
maxLength={maxLength}
placeholder={placeholder}
aria-invalid={hasError || undefined}
aria-describedby={describedBy}
{...rest}
onChange={(e) => handleChange(e.target.value)}
onFocus={(event) => {
setFocused(true);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
style={{
height: height ?? undefined,
transition: reduce ? undefined : `height 160ms ${EASE_OUT_CSS}`,
...rest.style,
}}
className={cn(
sharedText,
"text-foreground caret-foreground outline-none",
"placeholder:text-muted-foreground/60",
scrolls
? "overflow-y-auto [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]"
: "overflow-y-hidden",
disabled && "cursor-not-allowed",
classNames?.textarea,
)}
/>
{countVisible ? (
<div className="flex justify-end px-3.5 pb-2">
<span
ref={counterRef}
id={`${id}-count`}
className={cn(
"inline-block text-xs tabular-nums text-muted-foreground transition-colors duration-200",
nearLimit && "text-warning",
atLimit && "text-destructive",
classNames?.counter,
)}
>
<motion.span
key={atLimit ? "limit" : "count"}
className="inline-block"
initial={reduce || !atLimit ? false : { scale: 1.2 }}
animate={{ scale: 1 }}
transition={SPRING_PRESS}
>
{maxLength !== undefined ? `${count}/${maxLength}` : count}
</motion.span>
<span className="sr-only">
{maxLength !== undefined
? ` characters used, ${maxLength - count} remaining`
: " characters"}
</span>
</span>
</div>
) : null}
</div>
<AnimatePresence initial={false}>
{errorMessage ? (
<motion.p
id={`${id}-error`}
role="alert"
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
transition={{ duration: 0.2 }}
className={cn(
"px-1 text-xs text-destructive",
classNames?.errorMessage,
)}
>
{errorMessage}
</motion.p>
) : null}
</AnimatePresence>
</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 { TOUCH_TARGET_CLASS } from "@/lib/touch";
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-primary/5",
outline:
"border border-border bg-transparent text-foreground hover:bg-primary/5",
};
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(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
// The ripple layer clips itself, so on a touch screen the button can
// stop clipping and let its enlarged hit area overhang.
ripple && "overflow-hidden pointer-coarse:overflow-visible",
TOUCH_TARGET_CLASS,
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(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
TOUCH_TARGET_CLASS,
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"use client";
import { forwardRef } from "react";
import { Magnetic } from "../magnetic";
import { Button, type ButtonProps } from "./base";
export interface MagneticButtonProps extends ButtonProps {
/** Magnetic pull strength. Default 0.25. */
strength?: number;
/** Class applied to the magnetic wrapper. */
magneticClassName?: string;
}
export const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(
{ strength = 0.25, magneticClassName, children, ...rest },
ref,
) {
return (
<Magnetic strength={strength} className={magneticClassName}>
<Button ref={ref} {...rest}>
{children}
</Button>
</Magnetic>
);
});
"use client";
import { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
state?: ButtonState;
children: ReactNode;
loadingText?: ReactNode;
successText?: ReactNode;
errorText?: ReactNode;
icon?: ReactNode;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText = "Loading",
successText = "Done",
errorText = "Try again",
icon,
disabled,
...rest
},
ref,
) {
const isBusy = state === "loading";
const stateText =
state === "loading"
? loadingText
: state === "success"
? successText
: state === "error"
? errorText
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
defaultValues?Partial<ContactValues>—onSubmit?((values: ContactValues) => void | Promise<void>)Called with valid values. Reject with a message to show it and shake the form.
—validate?((values: ContactValues) => Partial<Record<keyof ContactValues, string>>)—topics?ContactTopic[][
{ value: "sales", label: "Sales" },
{ value: "support", label: "Support" },
{ value: "partnership", label: "Partnership" },
{ value: "other", label: "Something else" },
]methods?ContactMethod[]Side panel rows. Pass `[]` to hide the panel.
[
{
id: "email",
icon: Mail,
label: "Email",
value: "hello@example.com",
href: "mailto:hello@example.com",
},
{ id: "chat", icon: MessagesSquare, label: "Live chat", value: "Mon–Fri, 9am–6pm" },
{ id: "office", icon: MapPin, label: "Office", value: "100 Example St, Springfield" },
{ id: "reply", icon: Clock, label: "Response time", value: "Within one business day" },
]maxLength?numberCharacter limit for the message (counter shows). Default 500.
500minLength?numberMinimum message length. Default 10.
10title?ReactNodeGet in touchdescription?ReactNodeTell us what you need and the right person will reply.className?string—Keep in mind
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated