CTA Section
Closing call-to-action section in a centered layout (large headline, two CTAs and a reassurance checklist inside a card) or a split layout (copy beside a visual or an email capture with a stateful submit), with a word-by-word headline reveal on scroll, a rotating gradient beam on the card border or a soft dotted field, and a layout that adapts to its own container width.
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))
}
"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;
}
// 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;
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/blocks/cta-section
import { Check, Send } from "lucide-react";
import { motion, type Transition, useReducedMotion } from "motion/react";
import {
type ElementType,
type FormEvent,
type ReactNode,
useEffect,
useId,
useRef,
useState,
} from "react";
import {
Button,
ButtonLink,
type ButtonState,
StatefulButton,
} from "@/components/motion/button";
import { TextReveal } from "@/components/motion/text-reveal";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface CtaAction {
label: ReactNode;
href?: string;
onClick?: () => void;
/** Trailing icon. */
icon?: ReactNode;
}
export interface CtaEmailCapture {
/** Resolve to show success; reject to show the retry state. */
onSubscribe: (email: string) => Promise<void> | void;
placeholder?: string;
buttonLabel?: ReactNode;
successMessage?: ReactNode;
/** Small print under the field, e.g. "Unsubscribe any time." */
note?: ReactNode;
}
export interface CtaSectionProps {
/** "centered" stacks everything in one card; "split" puts copy left and a visual or email capture right. */
variant?: "centered" | "split";
eyebrow?: ReactNode;
/** Revealed word by word when the section scrolls into view. */
headline: string | string[];
description?: ReactNode;
primaryAction?: CtaAction;
secondaryAction?: CtaAction;
/** Short reassurance list ("No credit card", "Cancel any time"). */
checklist?: ReactNode[];
/** Email field with a stateful submit button. */
emailCapture?: CtaEmailCapture;
/** Right column for `variant="split"` (mock UI, illustration). When omitted, the email capture takes that slot. */
visual?: ReactNode;
/** Card decoration: rotating gradient beam on the border, a dotted field, or nothing. Default "beam". */
background?: "beam" | "dots" | "none";
/** Heading element for the headline. Default "h2". */
headingAs?: ElementType;
className?: string;
cardClassName?: string;
}
const WORD_STAGGER = 0.05;
const ENTER: Transition = { duration: 0.5, ease: EASE_OUT };
// Beam sweep: decorative and slow so the border never pulls focus from the
// copy; linear so the light travels at a constant speed around the card.
const BEAM_TRANSITION: Transition = {
duration: 8,
ease: "linear",
repeat: Number.POSITIVE_INFINITY,
};
function isEmail(value: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}
function wordCount(text: string | string[]) {
return (Array.isArray(text) ? text.join(" ") : text)
.split(/\s+/)
.filter(Boolean).length;
}
function ActionButton({
action,
variant,
}: {
action: CtaAction;
variant: "primary" | "secondary";
}) {
const content = (
<>
{action.label}
{action.icon ?? null}
</>
);
return action.href ? (
<ButtonLink href={action.href} onClick={action.onClick} variant={variant}>
{content}
</ButtonLink>
) : (
<Button onClick={action.onClick} variant={variant}>
{content}
</Button>
);
}
function EmailCapture({
capture,
align,
}: {
capture: CtaEmailCapture;
align: "center" | "left";
}) {
const id = useId();
const [email, setEmail] = useState("");
const [state, setState] = useState<ButtonState>("idle");
const [error, setError] = useState<string | null>(null);
const timer = useRef<number | undefined>(undefined);
useEffect(
() => () => {
if (timer.current) window.clearTimeout(timer.current);
},
[],
);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (state === "loading" || state === "success") return;
if (!isEmail(email)) {
setError("Enter a valid email address.");
return;
}
setError(null);
setState("loading");
try {
await capture.onSubscribe(email.trim());
setState("success");
} catch {
setState("error");
setError("Something went wrong. Try again.");
timer.current = window.setTimeout(() => setState("idle"), 2400);
}
};
const done = state === "success";
return (
<form
noValidate
onSubmit={submit}
className={cn(
"flex w-full max-w-md flex-col gap-2",
align === "center" && "mx-auto",
)}
>
<div className="flex flex-col gap-2 @sm:flex-row @sm:items-center">
<label htmlFor={`${id}-email`} className="sr-only">
Email address
</label>
<input
id={`${id}-email`}
type="email"
inputMode="email"
autoComplete="email"
value={email}
disabled={done}
aria-invalid={error ? true : undefined}
aria-describedby={`${id}-status`}
onChange={(event) => {
setEmail(event.target.value);
if (error && isEmail(event.target.value)) setError(null);
}}
placeholder={capture.placeholder ?? "you@company.com"}
className={cn(
"h-10 min-w-0 flex-1 rounded-full border bg-background px-4 text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground focus-visible:ring-2 disabled:opacity-60",
error
? "border-destructive focus-visible:ring-destructive/30"
: "border-border focus-visible:border-border-strong focus-visible:ring-ring/40",
)}
/>
<StatefulButton
type="submit"
state={state}
loadingText="Sending"
successText="You're in"
errorText="Retry"
icon={<Send aria-hidden className="size-3.5" />}
className="shrink-0"
>
{capture.buttonLabel ?? "Get started"}
</StatefulButton>
</div>
<p
id={`${id}-status`}
aria-live="polite"
className={cn(
"min-h-5 text-xs",
align === "center" && "text-center",
error ? "text-destructive" : "text-muted-foreground",
)}
>
{error ??
(done
? (capture.successMessage ?? "Thanks! Check your inbox.")
: (capture.note ?? ""))}
</p>
</form>
);
}
function CardBackground({
background,
reduce,
}: {
background: "beam" | "dots" | "none";
reduce: boolean | null;
}) {
if (background === "none") return null;
if (background === "dots") {
return (
<div
aria-hidden
className="pointer-events-none absolute inset-0 bg-[radial-gradient(var(--border-strong)_1px,transparent_1px)] bg-[size:18px_18px] [mask-image:radial-gradient(ellipse_70%_70%_at_50%_40%,black,transparent)]"
/>
);
}
// Beam: an oversized conic gradient spins behind the card; the card body
// sits 1px inside it, so only a moving sliver shows along the border.
return (
<motion.div
aria-hidden
className="pointer-events-none absolute top-1/2 left-1/2 aspect-square w-[max(200%,40rem)] bg-[conic-gradient(from_0deg,transparent_0deg,transparent_250deg,var(--chart-1)_300deg,var(--chart-2)_330deg,transparent_360deg)]"
style={{ x: "-50%", y: "-50%" }}
initial={{ rotate: 0 }}
animate={reduce ? { rotate: 0 } : { rotate: 360 }}
transition={reduce ? { duration: 0 } : BEAM_TRANSITION}
/>
);
}
/**
* Closing call-to-action band. `centered` puts a large headline, supporting
* copy, two CTAs and an optional reassurance checklist inside one card;
* `split` sets the copy beside a visual or an email capture. The headline
* reveals word by word on view and the rest follows. The card can carry a
* rotating gradient beam along its border or a soft dotted field. Layout
* reads the section's own container width.
*/
export function CtaSection({
variant = "centered",
eyebrow,
headline,
description,
primaryAction,
secondaryAction,
checklist,
emailCapture,
visual,
background = "beam",
headingAs = "h2",
className,
cardClassName,
}: CtaSectionProps) {
const reduce = useReducedMotion();
const centered = variant === "centered";
const align = centered ? "center" : "left";
const after = Math.min(1, 0.15 + wordCount(headline) * WORD_STAGGER);
const enter = (delay: number) => ({
initial: reduce ? { opacity: 0 } : { opacity: 0, y: 12 },
whileInView: reduce ? { opacity: 1 } : { opacity: 1, y: 0 },
viewport: { once: true, amount: 0.4 },
transition: { ...ENTER, delay },
});
// In split mode the email capture fills the right column unless a visual
// claims it; then it moves under the copy.
const captureInAside = !centered && !visual && Boolean(emailCapture);
const copy = (
<div
className={cn(
"relative flex flex-col gap-4",
centered ? "items-center text-center" : "items-start text-left",
)}
>
{eyebrow ? (
<motion.p
{...enter(0)}
className="text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground"
>
{eyebrow}
</motion.p>
) : null}
<TextReveal
as={headingAs}
text={headline}
whileInView
stagger={WORD_STAGGER}
delay={0.05}
blur={8}
yOffset="30%"
className={cn(
"text-balance font-display font-semibold leading-[1.1] tracking-tight text-foreground",
centered
? "text-3xl @lg:text-4xl @3xl:text-5xl"
: "text-2xl @lg:text-3xl @3xl:text-4xl",
)}
/>
{description ? (
<motion.p
{...enter(after)}
className="max-w-xl text-pretty text-sm leading-6 text-muted-foreground @md:text-base @md:leading-7"
>
{description}
</motion.p>
) : null}
{primaryAction || secondaryAction ? (
<motion.div
{...enter(after + 0.08)}
className={cn(
"mt-1 flex flex-wrap items-center gap-3",
centered && "justify-center",
)}
>
{primaryAction ? (
<ActionButton action={primaryAction} variant="primary" />
) : null}
{secondaryAction ? (
<ActionButton action={secondaryAction} variant="secondary" />
) : null}
</motion.div>
) : null}
{emailCapture && !captureInAside ? (
<motion.div {...enter(after + 0.12)} className="mt-1 w-full">
<EmailCapture capture={emailCapture} align={align} />
</motion.div>
) : null}
{checklist?.length ? (
<motion.ul
initial="hidden"
whileInView="show"
viewport={{ once: true, amount: 0.4 }}
variants={{
show: {
transition: { staggerChildren: 0.06, delayChildren: after + 0.16 },
},
}}
className={cn(
"flex flex-wrap gap-x-5 gap-y-2 text-xs text-muted-foreground @md:text-sm",
centered && "justify-center",
)}
>
{checklist.map((item, index) => (
<motion.li
// biome-ignore lint/suspicious/noArrayIndexKey: checklist is a static positional list.
key={index}
variants={{
hidden: reduce ? { opacity: 0 } : { opacity: 0, y: 6 },
show: { opacity: 1, y: 0, transition: ENTER },
}}
className="inline-flex items-center gap-1.5"
>
<span className="grid size-4 place-items-center rounded-full bg-primary/10 text-primary">
<Check aria-hidden className="size-3" strokeWidth={3} />
</span>
{item}
</motion.li>
))}
</motion.ul>
) : null}
</div>
);
return (
<section className={cn("@container w-full", className)}>
<div
className={cn(
"relative isolate overflow-hidden rounded-3xl",
background === "beam"
? "bg-border p-px"
: "border border-border bg-card",
cardClassName,
)}
>
<CardBackground background={background} reduce={reduce} />
<div
className={cn(
"relative overflow-hidden",
background === "beam" && "rounded-[calc(var(--radius-3xl)-1px)] bg-card",
centered
? "px-6 py-12 @3xl:px-12 @3xl:py-16"
: "grid items-center gap-8 p-6 @2xl:grid-cols-[1.15fr_1fr] @3xl:p-10",
)}
>
{/* Soft top glow so the card reads as lit from the beam side. */}
<div
aria-hidden
className="pointer-events-none absolute inset-x-0 top-0 h-2/3 bg-[radial-gradient(50%_60%_at_50%_0%,color-mix(in_oklab,var(--foreground)_6%,transparent),transparent)]"
/>
{copy}
{!centered && (visual || captureInAside) ? (
<motion.div
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16, scale: 0.98 }}
whileInView={reduce ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
viewport={{ once: true, amount: 0.3 }}
transition={{ ...ENTER, delay: 0.2 }}
className="relative @container"
>
{visual ??
(emailCapture ? (
<div className="rounded-2xl border border-border bg-background/60 p-5 shadow-sm">
<EmailCapture capture={emailCapture} align="left" />
</div>
) : null)}
</motion.div>
) : null}
</div>
</div>
</section>
);
}
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 { motion, type Transition, useInView, useReducedMotion } from "motion/react";
import { useRef, type ElementType, type ReactNode } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type SplitMode = "word" | "char";
export interface TextRevealProps {
text: string | string[];
as?: ElementType;
className?: string;
split?: SplitMode;
stagger?: number;
delay?: number;
blur?: number;
yOffset?: string | number;
spring?: { stiffness?: number; damping?: number; mass?: number };
once?: boolean;
whileInView?: boolean;
children?: ReactNode;
}
const DEFAULT_SPRING = { stiffness: 140, damping: 26, mass: 1.2 };
type WordGroup = { text: string; trailing: string };
/**
* One tokenizer for both modes: a line becomes the words it is made of, each
* carrying the whitespace that follows it. Word mode animates a group at a
* time, char mode the characters inside one — so the two can't drift apart on
* what counts as a word or where a space belongs. Runs of whitespace and tabs
* survive as their own group rather than collapsing.
*/
function toWordGroups(line: string): WordGroup[] {
const chunks = line.match(/\S+\s*|\s+/g) ?? [];
return chunks.map((chunk) => {
const text = chunk.replace(/\s+$/, "");
return { text, trailing: chunk.slice(text.length) };
});
}
export function TextReveal({
text,
as: Comp = "span",
className,
split = "word",
stagger = 0.09,
delay = 0,
blur = 12,
yOffset = "40%",
spring,
once = true,
whileInView = false,
children,
}: TextRevealProps) {
const ref = useRef<HTMLElement>(null);
const inView = useInView(ref, { once, amount: 0.4 });
const reduce = useReducedMotion();
const shouldAnimate = whileInView ? inView : true;
const lines = Array.isArray(text) ? text : [text];
const s = { ...DEFAULT_SPRING, ...spring };
let unitIndex = 0;
const lineCounts = new Map<string, number>();
return (
<Comp ref={ref} className={cn("block", className)}>
{lines.map((line) => {
const lineCount = lineCounts.get(line) ?? 0;
lineCounts.set(line, lineCount + 1);
const lineKey = `${line}-${lineCount}`;
const unitCounts = new Map<string, number>();
const renderUnit = (unit: string) => {
const d = delay + unitIndex * stagger;
unitIndex += 1;
const unitCount = unitCounts.get(unit) ?? 0;
unitCounts.set(unit, unitCount + 1);
const unitKey = `${unit}-${unitCount}`;
const initial = reduce
? { opacity: 0 }
: { y: yOffset, opacity: 0, filter: `blur(${blur}px)` };
const animate = shouldAnimate
? reduce
? { opacity: 1 }
: { y: 0, opacity: 1, filter: "blur(0px)" }
: initial;
const transition: Transition = reduce
? { opacity: { duration: 0.25, ease: EASE_OUT, delay: d * 0.3 } }
: {
y: { type: "spring" as const, ...s, delay: d },
opacity: { duration: 0.7, ease: EASE_OUT, delay: d },
filter: { duration: 0.9, ease: EASE_OUT, delay: d },
};
return (
<motion.span
key={unitKey}
initial={initial}
animate={animate}
transition={transition}
// `whitespace-pre` is load-bearing: a unit's trailing space is
// inside an inline-block and would otherwise collapse to zero
// width, running every word together.
className="inline-block whitespace-pre will-change-transform"
>
{unit}
</motion.span>
);
};
const groups = toWordGroups(line);
const groupCounts = new Map<string, number>();
return (
<span key={lineKey} className="block">
{groups.map((group) => {
const whole = group.text + group.trailing;
// Characters animate one at a time, but each word (plus the
// space that follows it) sits in its own inline-block so a long
// line wraps between words instead of mid-word.
if (split !== "char") return renderUnit(whole);
const groupCount = groupCounts.get(whole) ?? 0;
groupCounts.set(whole, groupCount + 1);
return (
<span
key={`${whole}-${groupCount}`}
className="inline-block whitespace-pre"
>
{Array.from(whole).map((char) => renderUnit(char))}
</span>
);
})}
</span>
);
})}
{children}
</Comp>
);
}
"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
variant?"split" | "centered""centered" stacks everything in one card; "split" puts copy left and a visual or email capture right.
centeredeyebrow?ReactNode—headlinestring | string[]Revealed word by word when the section scrolls into view.
—description?ReactNode—primaryAction?CtaAction—secondaryAction?CtaAction—checklist?ReactNode[]Short reassurance list ("No credit card", "Cancel any time").
—emailCapture?CtaEmailCaptureEmail field with a stateful submit button.
—visual?ReactNodeRight column for `variant="split"` (mock UI, illustration). When omitted, the email capture takes that slot.
—background?"none" | "dots" | "beam"Card decoration: rotating gradient beam on the border, a dotted field, or nothing. Default "beam".
beamheadingAs?ElementTypeHeading element for the headline. Default "h2".
h2className?string—cardClassName?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