Hero Section
Landing hero with a New pill badge, a headline revealed word by word with a spring blur-in, supporting copy that follows, primary and secondary CTAs, an install command chip with an animated copy button, an optional media slot that tilts up into place on view, and a CSS-gradient grid background with sweeping beams, centered or left aligned.
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/hero-section
import { ArrowRight } from "lucide-react";
import { motion, type Transition, useReducedMotion } from "motion/react";
import type { ElementType, ReactNode } from "react";
import { Button, ButtonLink } from "@/components/motion/button";
import { CopyButton } from "@/components/motion/copy-button";
import { TextReveal } from "@/components/motion/text-reveal";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface HeroAction {
label: ReactNode;
href?: string;
onClick?: () => void;
/** Trailing icon. */
icon?: ReactNode;
}
export interface HeroBadge {
label: ReactNode;
/** Pill before the label. Default "New"; null hides it. */
pill?: ReactNode;
href?: string;
onClick?: () => void;
}
export interface HeroSectionProps {
/** Revealed word by word with a blur-in. */
headline: string | string[];
description?: ReactNode;
badge?: HeroBadge;
primaryAction?: HeroAction;
secondaryAction?: HeroAction;
/** Shell command shown in a chip with a copy button. */
installCommand?: string;
/** Screenshot, video or mock UI below the copy. Tilts in on view. */
media?: ReactNode;
align?: "center" | "left";
/** CSS-only animated grid with sweeping beams, or nothing. Default "grid". */
background?: "grid" | "none";
/** Heading element for the headline. Default "h1". */
headingAs?: ElementType;
className?: string;
mediaClassName?: string;
}
const WORD_STAGGER = 0.06;
const ENTER: Transition = { duration: 0.5, ease: EASE_OUT };
// Media tilt-in: a heavier, slower spring than the UI tokens because it moves
// a large surface through a 3D tilt; the snappier tokens read as a jolt here.
const MEDIA_SPRING: Transition = {
type: "spring",
stiffness: 110,
damping: 22,
mass: 1,
};
// Beam sweep: decorative, slow and linear so the eye never locks onto it.
const BEAM_TRANSITION: Transition = {
duration: 7,
ease: "linear",
repeat: Number.POSITIVE_INFINITY,
repeatDelay: 2,
};
function wordCount(text: string | string[]) {
return (Array.isArray(text) ? text.join(" ") : text)
.split(/\s+/)
.filter(Boolean).length;
}
function ActionButton({
action,
variant,
}: {
action: HeroAction;
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 HeroBackground({ reduce }: { reduce: boolean | null }) {
return (
<div
aria-hidden
className="pointer-events-none absolute inset-0 overflow-hidden [mask-image:radial-gradient(ellipse_70%_60%_at_50%_0%,black_40%,transparent_100%)]"
>
{/* 40px grid drawn with two repeating hairline gradients. */}
<div className="absolute inset-0 bg-[linear-gradient(to_right,var(--border-strong)_1px,transparent_1px),linear-gradient(to_bottom,var(--border-strong)_1px,transparent_1px)] bg-[size:40px_40px]" />
{/* Soft glow at the top. */}
<div className="absolute inset-x-0 top-0 h-2/3 bg-[radial-gradient(50%_60%_at_50%_0%,color-mix(in_oklab,var(--foreground)_9%,transparent),transparent)]" />
{reduce ? null : (
<>
{/* Beams ride grid lines (multiples of 40px) and only translate. */}
<motion.div
className="absolute top-[120px] left-0 h-px w-1/3 bg-[linear-gradient(to_right,transparent,var(--foreground),transparent)] opacity-40"
initial={{ x: "-100%" }}
animate={{ x: "300%" }}
transition={BEAM_TRANSITION}
/>
<motion.div
className="absolute top-0 left-[calc(50%+80px)] h-1/2 w-px bg-[linear-gradient(to_bottom,transparent,var(--foreground),transparent)] opacity-30"
initial={{ y: "-100%" }}
animate={{ y: "200%" }}
transition={{ ...BEAM_TRANSITION, delay: 3 }}
/>
</>
)}
</div>
);
}
/**
* Landing hero: an eyebrow badge with a "New" pill, a headline revealed word
* by word with a blur-in, supporting copy, primary/secondary CTAs, an optional
* install command with copy, and an optional media slot that tilts up into
* place on view, over a CSS-only animated grid. Type scales with the
* section's own container width.
*/
export function HeroSection({
headline,
description,
badge,
primaryAction,
secondaryAction,
installCommand,
media,
align = "center",
background = "grid",
headingAs = "h1",
className,
mediaClassName,
}: HeroSectionProps) {
const reduce = useReducedMotion();
const centered = align === "center";
// Supporting content enters as the headline finishes.
const after = Math.min(1.2, 0.15 + wordCount(headline) * WORD_STAGGER);
const enter = (delay: number) => ({
initial: reduce ? { opacity: 0 } : { opacity: 0, y: 12 },
animate: reduce ? { opacity: 1 } : { opacity: 1, y: 0 },
transition: { ...ENTER, delay },
});
const badgeInner = badge ? (
<>
{badge.pill === null ? null : (
<span className="rounded-full bg-primary px-2 py-0.5 text-[11px] font-semibold text-primary-foreground">
{badge.pill ?? "New"}
</span>
)}
<span className="truncate">{badge.label}</span>
<ArrowRight
aria-hidden
className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
/>
</>
) : null;
const badgeClass =
"group inline-flex max-w-full items-center gap-2 rounded-full border border-border bg-card/80 py-1 pr-3 pl-1 text-xs font-medium text-foreground shadow-xs backdrop-blur transition-colors hover:border-border-strong outline-none focus-visible:ring-2 focus-visible:ring-ring/50";
return (
<section
className={cn(
"@container relative isolate w-full overflow-hidden",
className,
)}
>
{background === "grid" ? <HeroBackground reduce={reduce} /> : null}
<div
className={cn(
"relative mx-auto flex max-w-3xl flex-col gap-5 px-5 pt-12 pb-10 @3xl:pt-20",
centered ? "items-center text-center" : "items-start text-left",
!centered && "mx-0 max-w-2xl",
)}
>
{badge ? (
<motion.div {...enter(0)}>
{badge.href ? (
<a href={badge.href} onClick={badge.onClick} className={badgeClass}>
{badgeInner}
</a>
) : badge.onClick ? (
<button type="button" onClick={badge.onClick} className={badgeClass}>
{badgeInner}
</button>
) : (
<span className={badgeClass}>{badgeInner}</span>
)}
</motion.div>
) : null}
<TextReveal
as={headingAs}
text={headline}
stagger={WORD_STAGGER}
delay={0.1}
blur={8}
yOffset="30%"
className="text-balance text-3xl font-semibold leading-[1.1] tracking-tight text-foreground @md:text-4xl @3xl:text-5xl @5xl:text-6xl"
/>
{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(
"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}
{installCommand ? (
<motion.div
{...enter(after + 0.16)}
className="inline-flex h-10 max-w-full items-center gap-2 rounded-full border border-border bg-card/80 pr-1 pl-4 font-mono text-xs text-foreground backdrop-blur @md:text-sm"
>
<span aria-hidden className="select-none text-muted-foreground">
$
</span>
<code className="min-w-0 truncate">{installCommand}</code>
<CopyButton
value={installCommand}
variant="ghost"
labels={{ idle: "Copy install command" }}
className="rounded-full"
/>
</motion.div>
) : null}
</div>
{media ? (
<div className="relative px-5 [perspective:1200px]">
<motion.div
initial={
reduce
? { opacity: 0 }
: { opacity: 0, rotateX: 22, y: 40, scale: 0.96 }
}
whileInView={
reduce
? { opacity: 1 }
: { opacity: 1, rotateX: 0, y: 0, scale: 1 }
}
viewport={{ once: true, amount: 0.2 }}
transition={
reduce
? { duration: 0.3, ease: EASE_OUT }
: { ...MEDIA_SPRING, opacity: { duration: 0.5, ease: EASE_OUT } }
}
style={{ transformOrigin: "50% 0%" }}
className={cn(
"mx-auto w-full max-w-4xl overflow-hidden rounded-2xl border border-border bg-card shadow-2xl shadow-foreground/5",
mediaClassName,
)}
>
{media}
</motion.div>
</div>
) : null}
</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 { Check, Copy, X } from "lucide-react";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type CopyButtonStatus = "idle" | "copied" | "error";
export type CopyButtonVariant = "secondary" | "ghost" | "outline" | "primary";
export type CopyButtonSize = "sm" | "md" | "icon";
export interface CopyButtonLabels {
idle: string;
copied: string;
error: string;
}
export interface CopyButtonProps
extends Omit<
HTMLMotionProps<"button">,
"value" | "children" | "onCopy" | "onError" | "onClick"
> {
/** Text to copy, or a (possibly async) getter evaluated on click. */
value: string | (() => string | Promise<string>);
/** Show a text label next to the icon that swaps with the status. */
showLabel?: boolean;
/** Label text per status. Also used for the accessible name and announcement. */
labels?: Partial<CopyButtonLabels>;
/** How long the copied/error state lingers before resetting, in ms. */
timeout?: number;
variant?: CopyButtonVariant;
size?: CopyButtonSize;
/** Override the idle / copied / error icons. */
icons?: Partial<Record<CopyButtonStatus, ReactNode>>;
onCopy?: (text: string) => void;
onCopyError?: (error: unknown) => void;
onStatusChange?: (status: CopyButtonStatus) => void;
}
const DEFAULT_LABELS: CopyButtonLabels = {
idle: "Copy",
copied: "Copied",
error: "Failed",
};
const VARIANT_CLASS: Record<CopyButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary:
"border border-border bg-card text-muted-foreground hover:text-foreground",
ghost: "text-muted-foreground hover:bg-primary/5 hover:text-foreground",
outline:
"border border-border bg-transparent text-muted-foreground hover:bg-primary/5 hover:text-foreground",
};
const SIZE_CLASS: Record<CopyButtonSize, string> = {
sm: "h-8 gap-1.5 rounded-full px-3 text-xs",
md: "h-10 gap-2 rounded-full px-4 text-sm",
icon: "size-8 rounded-lg",
};
const SWAP_BLUR = "blur(6px)";
const ICON_VARIANTS: Variants = {
initial: { opacity: 0, scale: 0.3, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
scale: 0.3,
filter: SWAP_BLUR,
transition: { duration: 0.12, ease: EASE_OUT },
},
};
const LABEL_VARIANTS: Variants = {
initial: { opacity: 0, y: "60%", filter: SWAP_BLUR },
animate: {
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
y: "-60%",
filter: SWAP_BLUR,
transition: { duration: 0.12, ease: EASE_OUT },
},
};
const FADE_VARIANTS: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1, transition: { duration: 0.15 } },
exit: { opacity: 0, transition: { duration: 0.1 } },
};
/** `document.execCommand("copy")` fallback for insecure contexts and old browsers. */
function legacyCopy(text: string) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.top = "0";
textarea.style.left = "0";
textarea.style.opacity = "0";
textarea.style.pointerEvents = "none";
document.body.appendChild(textarea);
const selection = document.getSelection();
const previous =
selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
textarea.select();
let ok = false;
try {
ok = document.execCommand("copy");
} finally {
document.body.removeChild(textarea);
if (previous && selection) {
selection.removeAllRanges();
selection.addRange(previous);
}
}
if (!ok) throw new Error("Copy command was rejected");
}
/** Copy text with the async Clipboard API, falling back to execCommand. */
export async function copyToClipboard(text: string) {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return;
} catch {
// Permission denied or insecure context — try the legacy path.
}
}
legacyCopy(text);
}
export function CopyButton({
value,
showLabel = false,
labels,
timeout = 1600,
variant = "secondary",
size,
icons,
onCopy,
onCopyError,
onStatusChange,
className,
disabled,
type = "button",
...props
}: CopyButtonProps) {
const reduce = useReducedMotion() ?? false;
const [status, setStatus] = useState<CopyButtonStatus>("idle");
const timer = useRef<number | undefined>(undefined);
const text = { ...DEFAULT_LABELS, ...labels };
const resolvedSize = size ?? (showLabel ? "sm" : "icon");
useEffect(
() => () => {
if (timer.current) window.clearTimeout(timer.current);
},
[],
);
const update = useCallback(
(next: CopyButtonStatus) => {
setStatus(next);
onStatusChange?.(next);
},
[onStatusChange],
);
const handleClick = async () => {
if (timer.current) window.clearTimeout(timer.current);
try {
const resolved = typeof value === "function" ? await value() : value;
await copyToClipboard(resolved);
update("copied");
onCopy?.(resolved);
} catch (error) {
update("error");
onCopyError?.(error);
}
timer.current = window.setTimeout(() => update("idle"), timeout);
};
const iconNode: Record<CopyButtonStatus, ReactNode> = {
idle: icons?.idle ?? <Copy />,
copied: icons?.copied ?? <Check className="text-(--color-success)" />,
error: icons?.error ?? <X className="text-destructive" />,
};
const iconVariants = reduce ? FADE_VARIANTS : ICON_VARIANTS;
const labelVariants = reduce ? FADE_VARIANTS : LABEL_VARIANTS;
return (
<>
<motion.button
type={type}
disabled={disabled}
onClick={handleClick}
whileTap={reduce || disabled ? undefined : { scale: 0.9 }}
transition={SPRING_PRESS}
aria-label={showLabel ? undefined : text[status]}
data-status={status}
className={cn(
"relative inline-flex shrink-0 select-none items-center justify-center font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
TOUCH_TARGET_CLASS,
VARIANT_CLASS[variant],
SIZE_CLASS[resolvedSize],
className,
)}
{...props}
>
<span aria-hidden="true" className="relative grid size-3.5 place-items-center [&_svg]:size-3.5">
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={status}
variants={iconVariants}
initial="initial"
animate="animate"
exit="exit"
className="col-start-1 row-start-1 grid place-items-center"
>
{iconNode[status]}
</motion.span>
</AnimatePresence>
</span>
{showLabel ? (
<span className="relative grid overflow-hidden">
{/* Every label sits invisibly in the same cell so the button keeps
the width of the longest one and never reflows mid-swap. */}
{(Object.keys(text) as CopyButtonStatus[]).map((key) => (
<span
key={key}
aria-hidden="true"
className="invisible col-start-1 row-start-1 whitespace-nowrap"
>
{text[key]}
</span>
))}
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={status}
variants={labelVariants}
initial="initial"
animate="animate"
exit="exit"
className="col-start-1 row-start-1 whitespace-nowrap text-left"
>
{text[status]}
</motion.span>
</AnimatePresence>
</span>
) : null}
</motion.button>
{/* Outside the button so the announcement never joins its accessible name. */}
<span aria-live="polite" className="sr-only">
{status === "copied"
? `${text.copied} to clipboard`
: status === "error"
? `${text.error} to copy`
: ""}
</span>
</>
);
}
"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
headlinestring | string[]Revealed word by word with a blur-in.
—description?ReactNode—badge?HeroBadge—primaryAction?HeroAction—secondaryAction?HeroAction—installCommand?stringShell command shown in a chip with a copy button.
—media?ReactNodeScreenshot, video or mock UI below the copy. Tilts in on view.
—align?"left" | "center"centerbackground?"grid" | "none"CSS-only animated grid with sweeping beams, or nothing. Default "grid".
gridheadingAs?ElementTypeHeading element for the headline. Default "h1".
h1className?string—mediaClassName?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