Candlestick Chart
Live OHLC candles with volume, a last-price line, and a crosshair readout.
Preview
- Candle
- 15:55
- O
- 2,360.34
- H
- 2,369.93
- L
- 2,351.12
- C
- 2,368.44
- Vol
- 151.2
- +0.34%
"use client";
import {
type Candle,
CandlestickChart,
CandlestickChartLegend,
CandlestickChartPlot,
} from "@/components/charts/candlestick-chart";
/** Pass candles oldest first with stable ids. Update the last candle as trades
* print and append a new one when its interval opens. */
export function CandlestickChartExample({
candles,
lastPrice,
}: {
candles: readonly Candle[];
lastPrice?: number;
}) {
return (
<CandlestickChart
candles={candles}
lastPrice={lastPrice}
label="ETH / USD, 5 minute candles"
formatPrice={(value) => value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
>
<CandlestickChartLegend />
<CandlestickChartPlot height={320} className="mt-4" />
</CandlestickChart>
);
}
"use client";
// beui.dev/charts/candlestick-chart
import { cn } from "@/lib/utils";
import {
type CandlestickChartProps,
CandlestickContext,
useCandlestickModel,
} from "./candlestick-chart/context";
import { CandlestickChartLegend } from "./candlestick-chart/legend";
import { CandlestickChartPlot } from "./candlestick-chart/plot";
/**
* OHLC candles with volume, a last-price line, and a crosshair readout.
*
* ```tsx
* <CandlestickChart candles={candles} lastPrice={last} formatPrice={usd}>
* <CandlestickChartLegend />
* <CandlestickChartPlot height={360} />
* </CandlestickChart>
* ```
*/
export function CandlestickChart({
className,
children,
...props
}: CandlestickChartProps) {
const model = useCandlestickModel(props);
return (
<CandlestickContext.Provider value={model}>
<div className={cn("w-full", className)}>
{children ?? (
<div className="grid gap-3">
<CandlestickChartLegend />
<CandlestickChartPlot />
</div>
)}
</div>
</CandlestickContext.Provider>
);
}
export {
type Candle,
type CandlestickChartProps,
useCandlestickChart,
} from "./candlestick-chart/context";
export {
CandlestickChartLegend,
type CandlestickChartLegendProps,
} from "./candlestick-chart/legend";
export {
CandlestickChartPlot,
type CandlestickChartPlotProps,
} from "./candlestick-chart/plot";
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
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// 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;
"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";
// beui.dev/charts/candlestick-chart
import { cn } from "@/lib/utils";
import {
type CandlestickChartProps,
CandlestickContext,
useCandlestickModel,
} from "./candlestick-chart/context";
import { CandlestickChartLegend } from "./candlestick-chart/legend";
import { CandlestickChartPlot } from "./candlestick-chart/plot";
/**
* OHLC candles with volume, a last-price line, and a crosshair readout.
*
* ```tsx
* <CandlestickChart candles={candles} lastPrice={last} formatPrice={usd}>
* <CandlestickChartLegend />
* <CandlestickChartPlot height={360} />
* </CandlestickChart>
* ```
*/
export function CandlestickChart({
className,
children,
...props
}: CandlestickChartProps) {
const model = useCandlestickModel(props);
return (
<CandlestickContext.Provider value={model}>
<div className={cn("w-full", className)}>
{children ?? (
<div className="grid gap-3">
<CandlestickChartLegend />
<CandlestickChartPlot />
</div>
)}
</div>
</CandlestickContext.Provider>
);
}
export {
type Candle,
type CandlestickChartProps,
useCandlestickChart,
} from "./candlestick-chart/context";
export {
CandlestickChartLegend,
type CandlestickChartLegendProps,
} from "./candlestick-chart/legend";
export {
CandlestickChartPlot,
type CandlestickChartPlotProps,
} from "./candlestick-chart/plot";
"use client";
import { useReducedMotion } from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
export type Candle = {
/** Stable id, such as the open timestamp. */
id: string;
/** Axis and readout label, such as "14:05". */
label: string;
open: number;
high: number;
low: number;
close: number;
volume: number;
};
export interface CandlestickChartProps {
candles: readonly Candle[];
/** Draws a dashed line and tag at this price, usually the last trade. */
lastPrice?: number;
/**
* Controlled crosshair candle, by `id`, so it stays on the same candle as
* new ones arrive. Pair with `onActiveIdChange`.
*/
activeId?: string | null;
defaultActiveId?: string | null;
onActiveIdChange?: (id: string | null) => void;
formatPrice?: (value: number) => string;
formatVolume?: (value: number) => string;
/** Accessible name for the chart. */
label?: string;
className?: string;
children?: ReactNode;
}
const defaultPrice = (value: number) =>
value.toLocaleString("en-US", { maximumFractionDigits: 2 });
const defaultVolume = (value: number) =>
new Intl.NumberFormat("en-US", {
notation: "compact",
maximumFractionDigits: 1,
}).format(value);
export function useCandlestickModel({
candles,
lastPrice,
activeId,
defaultActiveId = null,
onActiveIdChange,
formatPrice = defaultPrice,
formatVolume = defaultVolume,
label = "Candlestick chart",
}: CandlestickChartProps) {
const reduce = useReducedMotion() ?? false;
const [internalActive, setInternalActive] = useState(defaultActiveId);
const rawActive = activeId === undefined ? internalActive : activeId;
// Resolve the crosshair during render by id; a candle that scrolled out of
// the window clears it rather than landing on a neighbour.
const index = rawActive === null ? -1 : candles.findIndex((candle) => candle.id === rawActive);
const active = index >= 0 ? index : null;
// Stable setter that reads the latest candles and callback from a ref.
const latest = useRef({ candles, controlled: activeId !== undefined, onActiveIdChange });
useLayoutEffect(() => {
latest.current = { candles, controlled: activeId !== undefined, onActiveIdChange };
});
const setActive = useCallback((next: number | null) => {
const id = next === null ? null : (latest.current.candles[next]?.id ?? null);
if (!latest.current.controlled) setInternalActive(id);
latest.current.onActiveIdChange?.(id);
}, []);
const scale = useMemo(() => {
const lows = candles.map((candle) => candle.low);
const highs = candles.map((candle) => candle.high);
if (lastPrice !== undefined) {
lows.push(lastPrice);
highs.push(lastPrice);
}
const min = lows.length ? Math.min(...lows) : 0;
const max = highs.length ? Math.max(...highs) : 1;
const pad = Math.max((max - min) * 0.08, max * 0.0005, 0.0001);
const volumeMax = Math.max(1, ...candles.map((candle) => candle.volume));
return { min: min - pad, max: max + pad, volumeMax };
}, [candles, lastPrice]);
return {
candles,
lastPrice,
active,
setActive,
scale,
formatPrice,
formatVolume,
label,
reduce,
};
}
export type CandlestickModel = ReturnType<typeof useCandlestickModel>;
export const CandlestickContext = createContext<CandlestickModel | null>(null);
export function useCandlestickChart() {
const model = useContext(CandlestickContext);
if (!model)
throw new Error(
"CandlestickChart parts must be used inside <CandlestickChart>",
);
return model;
}
"use client";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
import { type Candle, useCandlestickChart } from "./context";
export type CandlestickChartLegendProps = {
/** Custom readout. Receives the crosshair candle, or the latest one. */
children?: (candle: Candle, change: number) => ReactNode;
className?: string;
};
/** OHLC and volume readout that follows the crosshair. */
export function CandlestickChartLegend({
children,
className,
}: CandlestickChartLegendProps) {
const { candles, active, formatPrice, formatVolume } = useCandlestickChart();
const candle = active !== null ? candles[active] : candles.at(-1);
if (!candle) return null;
const change = candle.open
? ((candle.close - candle.open) / candle.open) * 100
: 0;
if (children) return <>{children(candle, change)}</>;
const tone =
change >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-rose-600 dark:text-rose-400";
const items: [string, string][] = [
["O", formatPrice(candle.open)],
["H", formatPrice(candle.high)],
["L", formatPrice(candle.low)],
["C", formatPrice(candle.close)],
["Vol", formatVolume(candle.volume)],
];
return (
<dl
className={cn(
"flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-xs tabular-nums",
className,
)}
>
<dt className="sr-only">Candle</dt>
<dd className="text-muted-foreground">{candle.label}</dd>
{items.map(([term, value]) => (
<div key={term} className="flex gap-1">
<dt className="text-muted-foreground">{term}</dt>
<dd className={term === "Vol" ? undefined : tone}>{value}</dd>
</div>
))}
<dd className={tone}>
{change >= 0 ? "+" : "−"}
{Math.abs(change).toFixed(2)}%
</dd>
</dl>
);
}
"use client";
/* Candles fade up 12ms apart on first draw. The live candle's body, wick, and
* volume bar spring to new values as trades print, and the last-price line
* follows. Pointer or arrow keys move a crosshair with a price tag on the
* axis. Every moving shape is drawn at unit height and placed with
* translateY and scaleY, so updates animate transforms only. Reduced motion:
* no fade or spring; values update in place. */
import { motion, type Transition } from "motion/react";
import {
type KeyboardEvent,
type PointerEvent,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { useCandlestickChart } from "./context";
/** Right gutter reserved for price labels, in px. */
const AXIS = 64;
const VOLUME_SHARE = 0.18;
const GAP = 8;
/** Scale from the shape's own top edge rather than its centre. */
const TOP_ORIGIN = { originX: 0, originY: 0 } as const;
export type CandlestickChartPlotProps = {
/** Plot height in px. */
height?: number;
className?: string;
};
export function CandlestickChartPlot({
height = 320,
className,
}: CandlestickChartPlotProps) {
const { candles, lastPrice, active, setActive, scale, formatPrice, label, reduce } =
useCandlestickChart();
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [pointerY, setPointerY] = useState<number | null>(null);
useLayoutEffect(() => {
const node = ref.current;
if (!node) return;
const update = () => setWidth(node.clientWidth);
update();
const observer = new ResizeObserver(update);
observer.observe(node);
return () => observer.disconnect();
}, []);
const plotWidth = Math.max(0, width - AXIS);
const priceHeight = height * (1 - VOLUME_SHARE) - GAP;
const slot = candles.length ? plotWidth / candles.length : 0;
const body = Math.max(1, slot * 0.62);
const y = (price: number) => ((scale.max - price) / (scale.max - scale.min || 1)) * priceHeight;
const priceAt = (py: number) => scale.max - (py / priceHeight) * (scale.max - scale.min);
const ticks = Array.from(
{ length: 5 },
(_, i) => scale.max - ((scale.max - scale.min) * (i + 0.5)) / 5,
);
const spring: Transition = reduce ? { duration: 0 } : SPRING_LAYOUT;
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
const x = event.clientX - rect.left;
const py = event.clientY - rect.top;
if (x > plotWidth || !slot) return;
setActive(Math.min(candles.length - 1, Math.max(0, Math.floor(x / slot))));
setPointerY(py <= priceHeight ? py : null);
};
const onKeyDown = (event: KeyboardEvent) => {
const current = active ?? candles.length - 1;
let next: number | null = current;
if (event.key === "ArrowLeft") next = Math.max(0, current - 1);
else if (event.key === "ArrowRight") next = Math.min(candles.length - 1, current + 1);
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = candles.length - 1;
else if (event.key === "Escape") next = null;
else return;
event.preventDefault();
setPointerY(null);
setActive(next);
};
const focus = active !== null ? candles[active] : candles.at(-1);
const crossX = active !== null ? active * slot + slot / 2 : null;
return (
<div
ref={ref}
role="slider"
tabIndex={0}
aria-label={label}
aria-valuemin={0}
aria-valuemax={Math.max(0, candles.length - 1)}
aria-valuenow={active ?? Math.max(0, candles.length - 1)}
aria-valuetext={
focus
? `${focus.label}: open ${formatPrice(focus.open)}, high ${formatPrice(focus.high)}, low ${formatPrice(focus.low)}, close ${formatPrice(focus.close)}`
: undefined
}
onPointerMove={onPointerMove}
onPointerLeave={() => {
setActive(null);
setPointerY(null);
}}
onKeyDown={onKeyDown}
onBlur={() => setActive(null)}
className={cn(
"relative w-full cursor-crosshair touch-pan-y select-none rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
style={{ height }}
>
{width > 0 ? (
<svg
width={width}
height={height}
className="absolute inset-0 overflow-visible"
aria-hidden="true"
>
{ticks.map((tick) => (
<line
key={tick}
x1={0}
x2={plotWidth}
y1={y(tick)}
y2={y(tick)}
stroke="var(--border)"
strokeDasharray="2 6"
/>
))}
{candles.map((candle, index) => {
const up = candle.close >= candle.open;
const cx = index * slot + slot / 2;
const top = y(Math.max(candle.open, candle.close));
const bodyHeight = Math.max(1, Math.abs(y(candle.open) - y(candle.close)));
const wickTop = y(candle.high);
const wickHeight = Math.max(1, y(candle.low) - wickTop);
const volumeHeight = Math.max(
0.5,
(candle.volume / scale.volumeMax) * height * VOLUME_SHARE,
);
const dimmed = active !== null && active !== index;
return (
<motion.g
key={candle.id}
className={
up ? "fill-emerald-500 stroke-emerald-500" : "fill-rose-500 stroke-rose-500"
}
initial={reduce ? false : { opacity: 0 }}
animate={{ opacity: dimmed ? 0.45 : 1 }}
transition={{
duration: 0.3,
ease: EASE_OUT,
delay: reduce ? 0 : Math.min(index * 0.012, 0.6),
}}
>
<motion.line
x1={cx}
x2={cx}
y1={0}
y2={1}
vectorEffect="non-scaling-stroke"
strokeWidth={1}
style={TOP_ORIGIN}
initial={false}
animate={{ y: wickTop, scaleY: wickHeight }}
transition={spring}
/>
<motion.rect
x={cx - body / 2}
y={0}
width={body}
height={1}
strokeWidth={0}
style={TOP_ORIGIN}
initial={false}
animate={{ y: top, scaleY: bodyHeight }}
transition={spring}
/>
<motion.rect
x={cx - body / 2}
y={0}
width={body}
height={1}
strokeWidth={0}
opacity={0.28}
style={TOP_ORIGIN}
initial={false}
animate={{ y: height - volumeHeight, scaleY: volumeHeight }}
transition={spring}
/>
</motion.g>
);
})}
{lastPrice !== undefined ? (
<motion.line
x1={0}
x2={plotWidth}
y1={0}
y2={0}
initial={false}
animate={{ y: y(lastPrice) }}
transition={spring}
stroke="var(--foreground)"
strokeOpacity={0.45}
strokeDasharray="3 4"
/>
) : null}
{crossX !== null ? (
<line
x1={crossX}
x2={crossX}
y1={0}
y2={height}
stroke="var(--foreground)"
strokeOpacity={0.3}
/>
) : null}
{pointerY !== null ? (
<line
x1={0}
x2={plotWidth}
y1={pointerY}
y2={pointerY}
stroke="var(--foreground)"
strokeOpacity={0.3}
/>
) : null}
</svg>
) : null}
{width > 0
? ticks.map((tick) => (
<span
key={tick}
className="pointer-events-none absolute right-0 -translate-y-1/2 pr-1 font-mono text-xs text-muted-foreground tabular-nums"
style={{ top: y(tick) }}
>
{formatPrice(tick)}
</span>
))
: null}
{width > 0 && lastPrice !== undefined ? (
<motion.div
className="pointer-events-none absolute top-0 right-0"
initial={false}
animate={{ y: y(lastPrice) }}
transition={spring}
>
<span className="block -translate-y-1/2 rounded-md bg-foreground px-1.5 py-0.5 font-mono text-xs text-background tabular-nums">
{formatPrice(lastPrice)}
</span>
</motion.div>
) : null}
{width > 0 && pointerY !== null ? (
<span
className="pointer-events-none absolute right-0 -translate-y-1/2 rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground tabular-nums"
style={{ top: pointerY }}
>
{formatPrice(priceAt(pointerY))}
</span>
) : null}
</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 { MetallicButtonProps } from "./metallic";
export { MetallicButton } from "./metallic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
ripple && "relative overflow-hidden",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"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 { motion, useReducedMotion } from "motion/react";
import { forwardRef, useState } from "react";
import { EASE_IN_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Button, type ButtonProps } from "./base";
export interface MetallicButtonProps extends Omit<
ButtonProps,
"ripple" | "variant"
> {
/** Stops the traveling reflection while preserving the chrome rim. */
paused?: boolean;
}
// The rim and highlight drift separately so the material stays quiet and reflective.
const SILVER_DRIFT = {
duration: 8,
ease: EASE_IN_OUT,
repeat: Infinity,
};
const CHROME_SHIMMER = {
duration: 2.4,
ease: EASE_IN_OUT,
};
export const MetallicButton = forwardRef<
HTMLButtonElement,
MetallicButtonProps
>(function MetallicButton(
{
size = "md",
paused = false,
className,
children,
onHoverStart,
onHoverEnd,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const still = paused || Boolean(reduce);
const [hovered, setHovered] = useState(false);
return (
<Button
ref={ref}
variant="ghost"
size={size}
onHoverStart={(event, info) => {
setHovered(true);
onHoverStart?.(event, info);
}}
onHoverEnd={(event, info) => {
setHovered(false);
onHoverEnd?.(event, info);
}}
className={cn(
"group relative isolate overflow-hidden border-0 bg-transparent text-foreground",
"hover:bg-transparent hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"shadow-[0_8px_22px_rgba(0,0,0,0.16)]",
size === "icon" && "rounded-full",
className,
)}
{...rest}
>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]"
animate={still ? undefined : { x: ["0%", "13%", "0%"] }}
transition={still ? undefined : SILVER_DRIFT}
/>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen"
animate={still ? undefined : { x: hovered ? "310%" : "0%" }}
transition={still ? undefined : CHROME_SHIMMER}
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]"
/>
<span className="relative z-10 inline-flex items-center justify-center gap-2">
{children}
</span>
</Button>
);
});
"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}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
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>
);
}
API Reference
CandlestickChart
candlesreadonly Candle[]—lastPrice?numberDraws a dashed line and tag at this price, usually the last trade.
—activeId?string | nullControlled crosshair candle, by `id`, so it stays on the same candle as new ones arrive. Pair with `onActiveIdChange`.
—defaultActiveId?string | null—onActiveIdChange?((id: string | null) => void)—formatPrice?((value: number) => string)—formatVolume?((value: number) => string)—label?stringAccessible name for the chart.
—className?string—CandlestickChartLegend
children?((candle: Candle, change: number) => ReactNode)Custom readout. Receives the crosshair candle, or the latest one.
—className?string—CandlestickChartPlot
height?numberPlot height in px.
320className?string—Related components
Volume Profile
Animated volume by price, with point of control and value area highlights.
Price Target Fan
Composable price target chart with Header, Plot, SVG, Axes, History, Targets, Now, Cursor, and Tooltip parts. Supply dated price history and targets; scrub with a pointer or keyboard and customize the active readout.
Order Book
Animated order book with bid and ask depth, spread, and volume balance.
Updated