Boston Celtics vs. Los Angeles Lakers
Sunday · 7:30 PMBasketball
Animated market listing cards with outcome CTAs, probabilities and bookmarks, plus a trade ticket with buy/sell modes and rolling amount entry.
prediction-market-card.tsxCompact market listings with consistent outcome rows, animated odds CTAs, payout multipliers and bookmarks. Odds CTAs use green/red backgrounds and roll into Yes/No labels on hover or keyboard focus. Use Update odds to preview animated price changes.
On the radar
Demo markets · simulated prices
Sunday · 7:30 PM·Basketball
Mid 6th·MLB
Dec 31·Economics
"use client";
import {
PredictionMarketCard,
type PredictionMarketCardSelection,
} from "@/components/motion/prediction-market-card";
export function PredictionMarketCardUsage({
onTrade,
}: {
onTrade: (selection: PredictionMarketCardSelection) => void;
}) {
return (
<PredictionMarketCard
title="Boston Celtics vs. Los Angeles Lakers"
category="Basketball"
status="Sunday · 7:30 PM"
volume="$2.4M"
volumeHistory={[12, 18, 15, 26, 20, 32, 29, 38]}
outcomes={[
{ id: "celtics", label: "Celtics", probability: 0.51, color: "#34d399" },
{ id: "lakers", label: "Lakers", probability: 0.49, color: "#fbbf24" },
]}
onOutcomeClick={onTrade}
/>
);
}
"use client";
// beui.dev/components/blocks/prediction-market
import { Bookmark } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useState } from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
import { ActionSwapText } from "./action-swap";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
export interface PredictionMarketCardOutcome {
id: string;
label: string;
/** Probability between 0 and 1. */
probability: number;
icon?: ReactNode;
/** Optional team color for the compact probability line. */
color?: string;
}
export interface PredictionMarketCardSelection {
outcomeId: string;
side: "yes" | "no";
}
export interface PredictionMarketCardProps {
title: string;
icon?: ReactNode;
category?: string;
volume: string;
/** Chronological volume samples for the optional footer sparkline. */
volumeHistory?: number[];
/** A scheduled time or live match status. */
status?: string;
live?: boolean;
outcomes: PredictionMarketCardOutcome[];
/** Called on each outcome CTA click; the card keeps no selected state. */
onOutcomeClick?: (value: PredictionMarketCardSelection) => void;
bookmarked?: boolean;
defaultBookmarked?: boolean;
onBookmarkChange?: (bookmarked: boolean) => void;
className?: string;
}
function probability(value: number) {
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
}
/** A listing surface with outcome CTAs and an independent bookmark toggle. */
export function PredictionMarketCard({
title,
icon,
category,
volume,
volumeHistory,
status,
live = false,
outcomes,
onOutcomeClick,
bookmarked,
defaultBookmarked = false,
onBookmarkChange,
className,
}: PredictionMarketCardProps) {
const titleId = useId();
const chartId = useId();
const samples = volumeHistory?.filter(Number.isFinite) ?? [];
const low = Math.min(...samples);
const range = Math.max(...samples) - low;
const chartPoints =
samples.length > 1
? samples
.map(
(sample, index) =>
`${2 + (index / (samples.length - 1)) * 44},${18 - (range ? (sample - low) / range : 0.5) * 14}`,
)
.join(" ")
: null;
const reduce = useReducedMotion();
const [internalBookmark, setInternalBookmark] = useState(defaultBookmarked);
const saved = bookmarked ?? internalBookmark;
return (
<article
aria-labelledby={titleId}
className={cn(
"flex h-full w-full min-w-0 flex-col overflow-hidden rounded-3xl bg-card text-foreground",
className,
)}
>
<header className="flex shrink-0 items-center gap-3 px-4 py-3">
{icon && (
<div
aria-hidden
className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-background text-foreground"
>
{icon}
</div>
)}
<div className="min-w-0 flex-1">
<h3
id={titleId}
className="break-words font-display text-base font-medium leading-snug tracking-tight"
>
{title}
</h3>
<p className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{status && (
<span
className={cn(
"inline-flex items-center gap-1.5",
live && "text-rose-500",
)}
>
{live && (
<span
aria-hidden
className="size-1.5 rounded-full bg-current"
/>
)}
{status}
</span>
)}
{status && category && <span aria-hidden>·</span>}
{category && <span>{category}</span>}
</p>
</div>
</header>
<div className="mx-2 mb-2 flex flex-1 flex-col rounded-3xl bg-background px-4 py-3">
<div className="flex flex-1 flex-col justify-center gap-3">
{outcomes.map((outcome, index) => (
<div key={outcome.id} className="space-y-1">
<div className="flex min-h-10 items-center gap-2">
{outcome.icon && (
<span
aria-hidden
className="flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted"
>
{outcome.icon}
</span>
)}
<span className="min-w-0 flex-1 break-words text-sm font-medium">
{outcome.label}
</span>
<Tooltip
content="Potential payout per $1 if this outcome wins, including your stake. Before fees; based on the displayed price."
wrapperClassName="shrink-0"
className="w-44 whitespace-normal text-center leading-relaxed"
>
<button
type="button"
aria-label={`Potential payout for ${outcome.label}`}
className="rounded-md py-2 text-sm tabular-nums text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring"
>
{probability(outcome.probability) > 0
? `${(1 / probability(outcome.probability)).toFixed(1)}×`
: "—"}
</button>
</Tooltip>
<MarketOddsButton
positive={index % 2 === 0}
outcome={outcome}
onClick={() =>
onOutcomeClick?.({ outcomeId: outcome.id, side: "yes" })
}
/>
</div>
<div
aria-hidden
className="h-0.5 w-24 overflow-hidden rounded-full"
>
<motion.div
initial={false}
animate={{ scaleX: probability(outcome.probability) }}
transition={
reduce
? { duration: 0 }
: { duration: 0.25, ease: EASE_OUT }
}
className="h-full origin-left rounded-full bg-emerald-300/70 dark:bg-emerald-400/40"
style={
outcome.color
? { backgroundColor: outcome.color }
: undefined
}
/>
</div>
</div>
))}
</div>
<footer className="mt-2 flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
{chartPoints && (
<svg
aria-hidden="true"
viewBox="0 0 48 22"
className="h-5 w-12 shrink-0 text-emerald-500 dark:text-emerald-400"
fill="none"
>
<defs>
<linearGradient id={chartId} x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor="currentColor"
stopOpacity="0.22"
/>
<stop
offset="100%"
stopColor="currentColor"
stopOpacity="0"
/>
</linearGradient>
</defs>
<polygon
points={`2,22 ${chartPoints} 46,22`}
fill={`url(#${chartId})`}
/>
<polyline
points={chartPoints}
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
<span className="shrink-0">{volume} vol.</span>
<motion.button
type="button"
aria-label={`Bookmark ${title}`}
aria-pressed={saved}
onClick={() => {
if (bookmarked === undefined) setInternalBookmark(!saved);
onBookmarkChange?.(!saved);
}}
whileTap={reduce ? undefined : { scale: 0.85 }}
transition={SPRING_PRESS}
className={cn(
"ml-auto flex size-9 shrink-0 items-center justify-center rounded-xl transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-ring",
saved && "text-foreground",
)}
>
<motion.span
animate={{ scale: saved && !reduce ? [1, 1.2, 1] : 1 }}
transition={{ duration: 0.22, ease: EASE_OUT }}
>
<Bookmark
aria-hidden
className={cn("size-4", saved && "fill-current")}
/>
</motion.span>
</motion.button>
</footer>
</div>
</article>
);
}
function MarketOddsButton({
positive,
outcome,
onClick,
}: {
outcome: PredictionMarketCardOutcome;
positive: boolean;
onClick: () => void;
}) {
const reduce = useReducedMotion();
const cents = Math.round(probability(outcome.probability) * 100);
const canHover = useHoverCapable();
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const showAction = (canHover && hovered) || focused;
return (
<motion.button
type="button"
aria-label={`Trade ${outcome.label} at ${cents}%`}
onClick={onClick}
onPointerEnter={(event) => {
if (event.pointerType !== "touch") setHovered(true);
}}
onPointerLeave={() => setHovered(false)}
onFocus={(event) =>
setFocused(event.currentTarget.matches(":focus-visible"))
}
onBlur={() => setFocused(false)}
whileTap={reduce ? undefined : { scale: 0.96 }}
transition={SPRING_PRESS}
className={cn(
"relative flex min-h-10 min-w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-background px-3 text-sm font-semibold text-foreground shadow-[0_3px_0] transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
positive &&
"shadow-emerald-500/20 border-emerald-500/25 bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-400",
!positive &&
"shadow-rose-500/20 border-rose-500/25 bg-rose-500/10 text-rose-700 hover:bg-rose-500/15 dark:text-rose-400",
)}
>
<ActionSwapText
value={showAction ? "action" : String(cents)}
animation="roll"
>
{showAction ? (positive ? "Yes" : "No") : `${cents}%`}
</ActionSwapText>
</motion.button>
);
}
shadcn init? You are set. Theme setupnpm i clsx lucide-react motion tailwind-merge// 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;
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
"use client";
// beui.dev/components/blocks/prediction-market
import { Bookmark } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useState } from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
import { ActionSwapText } from "./action-swap";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
export interface PredictionMarketCardOutcome {
id: string;
label: string;
/** Probability between 0 and 1. */
probability: number;
icon?: ReactNode;
/** Optional team color for the compact probability line. */
color?: string;
}
export interface PredictionMarketCardSelection {
outcomeId: string;
side: "yes" | "no";
}
export interface PredictionMarketCardProps {
title: string;
icon?: ReactNode;
category?: string;
volume: string;
/** Chronological volume samples for the optional footer sparkline. */
volumeHistory?: number[];
/** A scheduled time or live match status. */
status?: string;
live?: boolean;
outcomes: PredictionMarketCardOutcome[];
/** Called on each outcome CTA click; the card keeps no selected state. */
onOutcomeClick?: (value: PredictionMarketCardSelection) => void;
bookmarked?: boolean;
defaultBookmarked?: boolean;
onBookmarkChange?: (bookmarked: boolean) => void;
className?: string;
}
function probability(value: number) {
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
}
/** A listing surface with outcome CTAs and an independent bookmark toggle. */
export function PredictionMarketCard({
title,
icon,
category,
volume,
volumeHistory,
status,
live = false,
outcomes,
onOutcomeClick,
bookmarked,
defaultBookmarked = false,
onBookmarkChange,
className,
}: PredictionMarketCardProps) {
const titleId = useId();
const chartId = useId();
const samples = volumeHistory?.filter(Number.isFinite) ?? [];
const low = Math.min(...samples);
const range = Math.max(...samples) - low;
const chartPoints =
samples.length > 1
? samples
.map(
(sample, index) =>
`${2 + (index / (samples.length - 1)) * 44},${18 - (range ? (sample - low) / range : 0.5) * 14}`,
)
.join(" ")
: null;
const reduce = useReducedMotion();
const [internalBookmark, setInternalBookmark] = useState(defaultBookmarked);
const saved = bookmarked ?? internalBookmark;
return (
<article
aria-labelledby={titleId}
className={cn(
"flex h-full w-full min-w-0 flex-col overflow-hidden rounded-3xl bg-card text-foreground",
className,
)}
>
<header className="flex shrink-0 items-center gap-3 px-4 py-3">
{icon && (
<div
aria-hidden
className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-background text-foreground"
>
{icon}
</div>
)}
<div className="min-w-0 flex-1">
<h3
id={titleId}
className="break-words font-display text-base font-medium leading-snug tracking-tight"
>
{title}
</h3>
<p className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{status && (
<span
className={cn(
"inline-flex items-center gap-1.5",
live && "text-rose-500",
)}
>
{live && (
<span
aria-hidden
className="size-1.5 rounded-full bg-current"
/>
)}
{status}
</span>
)}
{status && category && <span aria-hidden>·</span>}
{category && <span>{category}</span>}
</p>
</div>
</header>
<div className="mx-2 mb-2 flex flex-1 flex-col rounded-3xl bg-background px-4 py-3">
<div className="flex flex-1 flex-col justify-center gap-3">
{outcomes.map((outcome, index) => (
<div key={outcome.id} className="space-y-1">
<div className="flex min-h-10 items-center gap-2">
{outcome.icon && (
<span
aria-hidden
className="flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted"
>
{outcome.icon}
</span>
)}
<span className="min-w-0 flex-1 break-words text-sm font-medium">
{outcome.label}
</span>
<Tooltip
content="Potential payout per $1 if this outcome wins, including your stake. Before fees; based on the displayed price."
wrapperClassName="shrink-0"
className="w-44 whitespace-normal text-center leading-relaxed"
>
<button
type="button"
aria-label={`Potential payout for ${outcome.label}`}
className="rounded-md py-2 text-sm tabular-nums text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring"
>
{probability(outcome.probability) > 0
? `${(1 / probability(outcome.probability)).toFixed(1)}×`
: "—"}
</button>
</Tooltip>
<MarketOddsButton
positive={index % 2 === 0}
outcome={outcome}
onClick={() =>
onOutcomeClick?.({ outcomeId: outcome.id, side: "yes" })
}
/>
</div>
<div
aria-hidden
className="h-0.5 w-24 overflow-hidden rounded-full"
>
<motion.div
initial={false}
animate={{ scaleX: probability(outcome.probability) }}
transition={
reduce
? { duration: 0 }
: { duration: 0.25, ease: EASE_OUT }
}
className="h-full origin-left rounded-full bg-emerald-300/70 dark:bg-emerald-400/40"
style={
outcome.color
? { backgroundColor: outcome.color }
: undefined
}
/>
</div>
</div>
))}
</div>
<footer className="mt-2 flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
{chartPoints && (
<svg
aria-hidden="true"
viewBox="0 0 48 22"
className="h-5 w-12 shrink-0 text-emerald-500 dark:text-emerald-400"
fill="none"
>
<defs>
<linearGradient id={chartId} x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor="currentColor"
stopOpacity="0.22"
/>
<stop
offset="100%"
stopColor="currentColor"
stopOpacity="0"
/>
</linearGradient>
</defs>
<polygon
points={`2,22 ${chartPoints} 46,22`}
fill={`url(#${chartId})`}
/>
<polyline
points={chartPoints}
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
<span className="shrink-0">{volume} vol.</span>
<motion.button
type="button"
aria-label={`Bookmark ${title}`}
aria-pressed={saved}
onClick={() => {
if (bookmarked === undefined) setInternalBookmark(!saved);
onBookmarkChange?.(!saved);
}}
whileTap={reduce ? undefined : { scale: 0.85 }}
transition={SPRING_PRESS}
className={cn(
"ml-auto flex size-9 shrink-0 items-center justify-center rounded-xl transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-ring",
saved && "text-foreground",
)}
>
<motion.span
animate={{ scale: saved && !reduce ? [1, 1.2, 1] : 1 }}
transition={{ duration: 0.22, ease: EASE_OUT }}
>
<Bookmark
aria-hidden
className={cn("size-4", saved && "fill-current")}
/>
</motion.span>
</motion.button>
</footer>
</div>
</article>
);
}
function MarketOddsButton({
positive,
outcome,
onClick,
}: {
outcome: PredictionMarketCardOutcome;
positive: boolean;
onClick: () => void;
}) {
const reduce = useReducedMotion();
const cents = Math.round(probability(outcome.probability) * 100);
const canHover = useHoverCapable();
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const showAction = (canHover && hovered) || focused;
return (
<motion.button
type="button"
aria-label={`Trade ${outcome.label} at ${cents}%`}
onClick={onClick}
onPointerEnter={(event) => {
if (event.pointerType !== "touch") setHovered(true);
}}
onPointerLeave={() => setHovered(false)}
onFocus={(event) =>
setFocused(event.currentTarget.matches(":focus-visible"))
}
onBlur={() => setFocused(false)}
whileTap={reduce ? undefined : { scale: 0.96 }}
transition={SPRING_PRESS}
className={cn(
"relative flex min-h-10 min-w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-background px-3 text-sm font-semibold text-foreground shadow-[0_3px_0] transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
positive &&
"shadow-emerald-500/20 border-emerald-500/25 bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-400",
!positive &&
"shadow-rose-500/20 border-rose-500/25 bg-rose-500/10 text-rose-700 hover:bg-rose-500/15 dark:text-rose-400",
)}
>
<ActionSwapText
value={showAction ? "action" : String(cents)}
animation="roll"
>
{showAction ? (positive ? "Yes" : "No") : `${cents}%`}
</ActionSwapText>
</motion.button>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion, type HTMLMotionProps, type Variants } from "motion/react";
import { useState } from "react";
import type { ReactNode } from "react";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ActionSwapItem = {
id: string;
label: ReactNode;
icon?: ReactNode;
ariaLabel?: string;
};
export type ActionSwapButtonVariant = "primary" | "secondary" | "outline" | "ghost";
export type ActionSwapButtonSize = "sm" | "md" | "lg" | "icon";
export type ActionSwapAnimation = "blur" | "roll" | "cascade";
/** Animations with a single-element variant set (cascade animates per letter). */
type CoreAnimation = "blur" | "roll";
export interface ActionSwapButtonProps extends Omit<
HTMLMotionProps<"button">,
"children" | "onChange"
> {
items: ActionSwapItem[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string, item: ActionSwapItem) => void;
variant?: ActionSwapButtonVariant;
size?: ActionSwapButtonSize;
animation?: ActionSwapAnimation;
iconOnly?: boolean;
cycle?: boolean;
}
export interface ActionSwapTextProps {
value: string;
children: ReactNode;
animation?: ActionSwapAnimation;
className?: string;
}
export interface ActionSwapIconProps {
value: string;
children: ReactNode;
animation?: ActionSwapAnimation;
className?: string;
}
const BLUR_TRANSITION = { duration: 0.2, ease: "easeInOut" } as const;
const ROLL_TRANSITION = SPRING_SWAP;
const ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;
const SWAP_BLUR = "blur(8px)";
const ROLL_BLUR = "blur(3px)";
// Cascade rolls the label one letter at a time, left to right. The leaving
// and landing strings overlap as independent layers (no shared cells), so
// proportional glyph widths never jitter. Exits cascade at half the enter
// stagger so the tail of the old label lingers briefly.
const CASCADE_STAGGER = 0.025;
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 TEXT_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.94, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.94,
filter: SWAP_BLUR,
transition: BLUR_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: "90%", filter: ROLL_BLUR },
animate: {
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: "-90%",
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const ICON_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.25, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.25,
filter: SWAP_BLUR,
transition: BLUR_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: 12, filter: ROLL_BLUR },
animate: {
opacity: 1,
y: 0,
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: -12,
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
outline: "border border-border bg-transparent text-foreground hover:bg-primary/5",
ghost: "text-muted-foreground hover:bg-primary/5 hover:text-foreground",
};
const SIZE_CLASS: Record<ActionSwapButtonSize, string> = {
sm: "h-8 gap-1.5 rounded-full px-3 text-xs",
md: "h-10 gap-2 rounded-full px-4 text-sm",
lg: "h-12 gap-2.5 rounded-full px-5 text-base",
icon: "h-10 w-10 rounded-full",
};
export function ActionSwapText({
value,
children,
animation = "blur",
className,
}: ActionSwapTextProps) {
const reduce = useReducedMotion();
// Cascade needs a plain string to split into letters; non-string content
// and reduced motion fall back to the closest single-element animation.
const label = typeof children === "string" ? children : null;
const cascade = animation === "cascade" && label !== null && !reduce;
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span
className={cn(
"relative -my-[0.08em] inline-block max-w-full whitespace-nowrap py-[0.08em] align-bottom",
className,
)}
style={{
clipPath: "inset(0 -999px)",
WebkitClipPath: "inset(0 -999px)",
}}
>
<span
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 ? (
<>
{/* Letters are decorative fragments; readers get the whole label. */}
<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.08em] inline-block whitespace-pre"
>
{label.split("").map((char, i) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity — the letter at a position is exactly what rolls.
key={i}
custom={i * 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={`${animation}-${value}`}
variants={TEXT_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
// Truncation lives on the layer that holds the text — the layer
// moves as a whole, so clipping it never eats the roll.
className="absolute left-0 top-[0.08em] inline-block max-w-full truncate will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</span>
);
}
export function ActionSwapIcon({
value,
children,
animation = "blur",
className,
}: ActionSwapIconProps) {
const reduce = useReducedMotion();
// Icons are single elements — cascade maps to its closest motion, roll.
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span className={cn("relative inline-grid shrink-0 place-items-center overflow-hidden", className)}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={`${animation}-${value}`}
aria-hidden
variants={ICON_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
className="col-start-1 row-start-1 inline-flex items-center justify-center will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
</span>
);
}
export function ActionSwapButton({
items,
value,
defaultValue,
onValueChange,
variant = "secondary",
size = "md",
animation = "blur",
iconOnly = size === "icon",
cycle = true,
className,
disabled,
onClick,
...rest
}: ActionSwapButtonProps) {
const reduce = useReducedMotion();
const [internalValue, setInternalValue] = useState(defaultValue ?? items[0]?.id);
const currentValue = value ?? internalValue;
const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentValue));
const activeItem = items[activeIndex] ?? items[0];
const hasIcon = items.some((item) => item.icon);
const nextItem = cycle && items.length > 0 ? items[(activeIndex + 1) % items.length] : undefined;
if (!activeItem) return null;
const accessibleLabel = activeItem.ariaLabel ?? (iconOnly && typeof activeItem.label === "string" ? activeItem.label : undefined);
return (
<motion.button
type="button"
disabled={disabled}
whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center overflow-hidden font-medium transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
aria-label={accessibleLabel}
onClick={(event) => {
onClick?.(event);
if (event.defaultPrevented || disabled || !cycle || !nextItem) return;
if (value === undefined) setInternalValue(nextItem.id);
onValueChange?.(nextItem.id, nextItem);
}}
{...rest}
>
{hasIcon ? (
<ActionSwapIcon value={activeItem.id} animation={animation} className="h-4 w-4">
{activeItem.icon ?? null}
</ActionSwapIcon>
) : null}
{!iconOnly ? (
<ActionSwapText value={activeItem.id} animation={animation}>
{activeItem.label}
</ActionSwapText>
) : null}
</motion.button>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
cloneElement,
isValidElement,
type PointerEvent,
type ReactElement,
type ReactNode,
type RefObject,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
export interface TooltipProps {
content: ReactNode;
children?: ReactElement;
/** Existing trigger for controlled integrations such as chart cells. */
anchorRef?: RefObject<HTMLElement | SVGElement | null>;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: { x: number; y: number };
open?: boolean;
onOpenChange?: (open: boolean) => void;
id?: string;
side?: Side;
/** Delay before showing (ms). Default 120. */
delay?: number;
className?: string;
/** Classes for the outer wrapper span. Use to fix baseline / fill parent. */
wrapperClassName?: string;
}
// Gap between trigger and tooltip, in px.
const GAP = 8;
// Centering transform for the fixed-positioned anchor point, per side.
const anchorTransform: Record<Side, string> = {
top: "translate(-50%, -100%)",
bottom: "translate(-50%, 0)",
left: "translate(-100%, -50%)",
right: "translate(0, -50%)",
};
const transformOrigin: Record<Side, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
// Once any tooltip has just closed, neighbouring tooltips open without the
// initial delay — moving along a toolbar feels instant after the first one.
const WARM_WINDOW_MS = 300;
let lastHiddenAt = 0;
export function Tooltip({
content,
children,
side = "top",
delay = 120,
className,
wrapperClassName,
anchorRef: externalAnchorRef,
anchorPoint,
open: controlledOpen,
onOpenChange,
id: providedId,
}: TooltipProps) {
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (controlledOpen === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[controlledOpen, onOpenChange],
);
const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
const generatedId = useId();
const id = providedId ?? generatedId;
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapperRef = useRef<HTMLSpanElement>(null);
const anchorRef = externalAnchorRef ?? wrapperRef;
const hover = useHoverGesture();
const surfaceRef = useRef<HTMLSpanElement>(null);
// Anchor point in viewport coords, on the edge of the trigger facing `side`.
// Position:fixed means these viewport coords place the tooltip directly, so
// it escapes every ancestor's stacking context and overflow.
const place = useCallback(() => {
const el = anchorRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
const cx = r.left + r.width * (anchorPoint?.x ?? 0.5);
const cy = r.top + r.height * (anchorPoint?.y ?? 0.5);
const point: Record<Side, { top: number; left: number }> = {
top: { top: (anchorPoint ? cy : r.top) - GAP, left: cx },
bottom: { top: (anchorPoint ? cy : r.bottom) + GAP, left: cx },
left: { top: cy, left: (anchorPoint ? cx : r.left) - GAP },
right: { top: cy, left: (anchorPoint ? cx : r.right) + GAP },
};
const next = point[side];
const width = surfaceRef.current?.offsetWidth ?? 0;
const height = surfaceRef.current?.offsetHeight ?? 0;
const dx = side === "left" ? width : side === "right" ? 0 : width / 2;
const dy = side === "top" ? height : side === "bottom" ? 0 : height / 2;
next.left = Math.max(GAP + dx, Math.min(next.left, window.innerWidth - GAP - width + dx));
next.top = Math.max(GAP + dy, Math.min(next.top, window.innerHeight - GAP - height + dy));
setCoords(previous => previous?.top === next.top && previous.left === next.left ? previous : next);
}, [side, anchorRef, anchorPoint]);
const positioned = coords !== null;
useLayoutEffect(() => {
if (!open) return;
place();
const observer = new ResizeObserver(place);
if (anchorRef.current) observer.observe(anchorRef.current);
if (positioned && surfaceRef.current) observer.observe(surfaceRef.current);
return () => observer.disconnect();
}, [open, place, anchorRef, positioned]);
const show = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
const warm = Date.now() - lastHiddenAt < WARM_WINDOW_MS;
timer.current = setTimeout(
() => {
place();
setOpen(true);
},
warm ? 0 : delay,
);
}, [delay, place, setOpen]);
const hide = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
if (open) lastHiddenAt = Date.now();
setOpen(false);
}, [open, setOpen]);
// A finger never hovers, and Safari does not focus a button on tap either, so
// the label is only reachable if the tap itself opens the tooltip. A click
// carries no pointerType, so the pointerdown that preceded it is what says
// whether this was a tap; keyboard activation arrives with no pointerdown at
// all, and focus has already shown the label there.
const tap = useTapGesture<boolean>();
const toggleOnTap = useCallback(() => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) {
hide();
return;
}
if (timer.current) clearTimeout(timer.current);
place();
setOpen(true);
}, [hide, place, tap, setOpen]);
// ...and closed again by the next tap that lands somewhere else. The label
// covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, hide, anchorRef);
// Keep the tooltip pinned to the trigger while it's open and the page scrolls
// or resizes (fixed coords are viewport-relative).
useEffect(() => {
if (!open) return;
const onMove = () => place();
window.addEventListener("scroll", onMove, true);
window.addEventListener("resize", onMove);
return () => {
window.removeEventListener("scroll", onMove, true);
window.removeEventListener("resize", onMove);
};
}, [open, place]);
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
if (!externalAnchorRef && !isValidElement(children)) return children;
// The label describes the trigger, so it has to name the trigger itself.
// Everything else the tooltip needs is read off the anchor below instead of
// cloned on: a handler written onto the child is the child's handler as far
// as that child can tell, and a component that owns its activation —
// hard-wiring onClick and spreading the rest of its props over it, as
// ThemeToggle does — then runs the tooltip's instead of its own. Composing
// with `props.onClick` cannot save it either, because a component element's
// props hold nothing the component does internally.
const trigger = isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, {
"aria-describedby": id,
})
: null;
return (
<>
{!externalAnchorRef ? (
// biome-ignore lint/a11y/noStaticElementInteractions: This wrapper observes bubbling trigger events without replacing the control's handlers.
<span
ref={wrapperRef}
className={cn("relative inline-flex align-middle", wrapperClassName)}
// Pointer events, not the mouse pair: a tap fires compatibility
// mouseenter/mouseleave that carry no pointerType, which raced the tap
// path into opening and closing the same label.
onPointerEnter={(event: PointerEvent) => {
if (hover.enter(event)) show();
}}
onPointerLeave={(event: PointerEvent) => {
if (hover.leave(event)) hide();
}}
onFocus={show}
onBlur={hide}
onPointerDown={(event: PointerEvent) => tap.start(event, open)}
// A gesture the platform took away sends no click, and a key press
// starts an activation that never had a pointer behind it. Either way
// the record has to go, or the next click reads a finger that has long
// since lifted.
onPointerCancel={tap.drop}
onKeyDown={tap.drop}
onClick={toggleOnTap}
>
{trigger}
</span>
) : null}
{typeof document !== "undefined"
? createPortal(
<AnimatePresence>
{open && coords ? (
<span
className="pointer-events-none fixed z-[9999]"
style={{
top: coords.top,
left: coords.left,
transform: anchorTransform[side],
}}
>
<TooltipSurface
ref={surfaceRef}
id={id}
side={side}
style={{ transformOrigin: transformOrigin[side], maxWidth: "calc(100vw - 16px)", whiteSpace: "normal" }}
className={className}
>
{content}
</TooltipSurface>
</span>
) : null}
</AnimatePresence>,
document.body,
)
: null}
</>
);
}
"use client";
import { motion, useReducedMotion, type Variants } from "motion/react";
import { useMemo, type ComponentProps, type ReactNode, type Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
// Offset is in the direction *away* from the trigger — content originates near
// the trigger and rises into resting position.
const offsetFrom: Record<Side, { x?: number; y?: number }> = {
top: { y: 8 },
bottom: { y: -8 },
left: { x: 8 },
right: { x: -8 },
};
// Small tooltip surfaces need the lighter spawn used by the original Tooltip.
const TOOLTIP_SPRING = { type: "spring", stiffness: 380, damping: 30, mass: 0.7 } as const;
function buildVariants(side: Side): Variants {
const o = offsetFrom[side];
return {
initial: {
opacity: 0,
scale: 0.9,
filter: "blur(5px)",
x: o.x ?? 0,
y: o.y ?? 0,
},
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
x: 0,
y: 0,
transition: {
...TOOLTIP_SPRING,
opacity: { duration: 0.14, ease: EASE_OUT },
filter: { duration: 0.18, ease: EASE_OUT },
},
},
exit: {
opacity: 0,
scale: 0.94,
filter: "blur(3px)",
x: (o.x ?? 0) * 0.6,
y: (o.y ?? 0) * 0.6,
transition: { duration: 0.12, ease: EASE_OUT },
},
};
}
const REDUCED_VARIANTS: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1, transition: { duration: 0.14, ease: EASE_OUT } },
exit: { opacity: 0, transition: { duration: 0.1, ease: EASE_OUT } },
};
/** The shared visual surface for trigger tooltips and chart readouts. Positioning belongs to the caller. */
export function TooltipSurface({
children,
side = "top",
className,
ref,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
side?: Side;
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion();
const variants = useMemo(() => reduce ? REDUCED_VARIANTS : buildVariants(side), [reduce, side]);
return (
<motion.span
ref={ref}
role="tooltip"
variants={variants}
initial="initial"
animate="animate"
exit="exit"
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
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-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(
"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}
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>
);
}
titlestring—icon?ReactNode—category?string—volumestring—volumeHistory?number[]Chronological volume samples for the optional footer sparkline.
—status?stringA scheduled time or live match status.
—live?booleanfalseoutcomesPredictionMarketCardOutcome[]—onOutcomeClick?((value: PredictionMarketCardSelection) => void)Called on each outcome CTA click; the card keeps no selected state.
—bookmarked?boolean—defaultBookmarked?booleanfalseonBookmarkChange?((bookmarked: boolean) => void)—className?string—prediction-market.tsxBuy and sell outcomes with rolling amount entry, quick add chips and trade states.
Avg. Price 16.7¢
"use client";
import { useState } from "react";
import {
PredictionMarket,
type PredictionMarketOrderValue,
} from "@/components/motion/prediction-market";
const outcomes = [
{
id: "yes",
label: "Yes",
price: 0.167,
},
{
id: "no",
label: "No",
price: 0.834,
},
];
export function PredictionMarketPreview() {
const [order, setOrder] = useState<PredictionMarketOrderValue>({
mode: "buy",
outcomeId: "yes",
amount: "115",
});
return (
<div className="flex w-full items-center justify-center">
<PredictionMarket
outcomes={outcomes}
value={order}
onValueChange={setOrder}
balance={500}
positions={{ yes: 125, no: 48 }}
quickAmounts={[1, 5, 10, 100]}
/>
</div>
);
}
"use client";
// beui.dev/components/blocks/prediction-market
import { Banknote, ChevronDown } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
type CSSProperties,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { StatefulButton, type ButtonState } from "./button/stateful";
import { NumberTicker } from "./number-ticker";
import { Tabs, TabsList, TabsTrigger } from "./tabs";
export type PredictionMarketMode = "buy" | "sell";
export type PredictionMarketOutcome = {
id: string;
label: string;
price: number;
};
export type PredictionMarketOrderValue = {
mode: PredictionMarketMode;
outcomeId: string;
amount: string;
};
export type PredictionMarketQuote = {
valid: boolean;
amount: number;
price: number;
shares: number;
payout: number;
error?: string;
};
export type PredictionMarketClassNames = {
root?: string;
header?: string;
tabs?: string;
outcomes?: string;
amount?: string;
chips?: string;
footer?: string;
action?: string;
};
export interface PredictionMarketProps {
outcomes?: PredictionMarketOutcome[];
value?: PredictionMarketOrderValue;
defaultValue?: Partial<PredictionMarketOrderValue>;
onValueChange?: (value: PredictionMarketOrderValue) => void;
onTrade?: (
order: PredictionMarketOrderValue,
quote: PredictionMarketQuote,
) => void;
onSignIn?: () => void;
authenticated?: boolean;
orderTypeLabel?: string;
balance?: number;
positions?: Record<string, number>;
quickAmounts?: number[];
minTrade?: number;
className?: string;
classNames?: PredictionMarketClassNames;
}
const DEFAULT_OUTCOMES: PredictionMarketOutcome[] = [
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
];
const MODES: { id: PredictionMarketMode; label: string }[] = [
{ id: "buy", label: "Buy" },
{ id: "sell", label: "Sell" },
];
const DEFAULT_QUICK_AMOUNTS = [10, 50, 100, 500];
const DIGIT_TRANSITION = { duration: 0.18, ease: EASE_OUT } as const;
type AmountInputStyle = CSSProperties & { "--amount-chars": string };
function useControllableOrder({
value,
defaultValue,
outcomes,
onValueChange,
}: {
value?: PredictionMarketOrderValue;
defaultValue?: Partial<PredictionMarketOrderValue>;
outcomes: PredictionMarketOutcome[];
onValueChange?: (value: PredictionMarketOrderValue) => void;
}) {
const initialValue: PredictionMarketOrderValue = {
mode: defaultValue?.mode ?? "buy",
outcomeId: defaultValue?.outcomeId ?? outcomes[0]?.id ?? "",
amount: defaultValue?.amount ?? "",
};
const [internalValue, setInternalValue] = useState(initialValue);
const controlled = value !== undefined;
const order = value ?? internalValue;
const setOrder = useCallback(
(next: PredictionMarketOrderValue) => {
if (!controlled) {
setInternalValue(next);
}
onValueChange?.(next);
},
[controlled, onValueChange],
);
return [order, setOrder] as const;
}
function sanitizeAmount(value: string) {
const normalized = value.replace(/[^\d.]/g, "");
const [whole, ...decimalParts] = normalized.split(".");
const decimal = decimalParts.join("");
if (decimalParts.length === 0) return whole;
return `${whole}.${decimal.slice(0, 2)}`;
}
function parseAmount(value: string) {
return Number(value) || 0;
}
function formatCurrency(value: number, maximumFractionDigits = 2) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits,
}).format(value);
}
function formatCompactCurrency(value: number) {
return value >= 100
? formatCurrency(value, 0)
: formatCurrency(value, value % 1 === 0 ? 0 : 2);
}
function formatCents(value: number) {
const cents = value * 100;
const precision = Number.isInteger(cents) ? 0 : 1;
return `${cents.toFixed(precision)}¢`;
}
function buildQuote({
order,
outcome,
balance,
position,
minTrade,
}: {
order: PredictionMarketOrderValue;
outcome: PredictionMarketOutcome;
balance: number;
position: number;
minTrade: number;
}): PredictionMarketQuote {
const amount = parseAmount(order.amount);
const price = Math.max(0.01, Math.min(0.99, outcome.price));
const shares = order.mode === "buy" ? amount / price : amount;
const payout = order.mode === "buy" ? shares : amount * price;
if (amount <= 0) {
return {
valid: false,
amount,
price,
shares: 0,
payout: 0,
error: "Enter an amount",
};
}
if (order.mode === "buy" && amount < minTrade) {
return {
valid: false,
amount,
price,
shares,
payout,
error: `Minimum ${formatCompactCurrency(minTrade)}`,
};
}
if (order.mode === "buy" && amount > balance) {
return {
valid: false,
amount,
price,
shares,
payout,
error: "Insufficient balance",
};
}
if (order.mode === "sell" && amount > position) {
return {
valid: false,
amount,
price,
shares,
payout,
error: "Not enough shares",
};
}
return {
valid: true,
amount,
price,
shares,
payout,
};
}
function keyedAmountChars(value: string) {
const seen = new Map<string, number>();
return value.split("").map((char) => {
const count = seen.get(char) ?? 0;
seen.set(char, count + 1);
return { id: `${char}-${count}`, char };
});
}
function amountInputSize(value: string) {
const length = value.replace(/\D/g, "").length;
if (length >= 10) return "text-3xl sm:text-4xl";
if (length >= 8) return "text-4xl sm:text-5xl";
if (length >= 6) return "text-[44px] sm:text-[56px]";
return "text-5xl sm:text-6xl";
}
function payoutTickerSize(value: number) {
const length = formatCurrency(value).length;
if (length >= 16) return "text-xl sm:text-2xl";
if (length >= 13) return "text-2xl";
if (length >= 10) return "text-3xl";
return "text-4xl";
}
function AnimatedAmountInput({
id,
value,
mode,
inputSize,
disabled,
reduce,
onChange,
}: {
id: string;
value: string;
mode: PredictionMarketMode;
inputSize: string;
disabled: boolean;
reduce: boolean;
onChange: (value: string) => void;
}) {
const displayValue = value || "0";
const chars = keyedAmountChars(displayValue);
const inputStyle = {
"--amount-chars": String(chars.length),
} as AmountInputStyle;
const label = mode === "buy" ? "Amount" : "Shares";
return (
<div className="flex min-w-0 items-center justify-center overflow-hidden">
{mode === "buy" ? (
<span
aria-hidden
className={cn(
"shrink-0 font-semibold leading-none tracking-normal text-muted-foreground/65 tabular-nums transition-[font-size] duration-200",
inputSize,
)}
>
$
</span>
) : null}
<div className="relative min-w-0 shrink">
<input
id={id}
value={value}
disabled={disabled}
onChange={(event) => onChange(sanitizeAmount(event.target.value))}
placeholder="0"
inputMode="decimal"
aria-label={label}
autoComplete="off"
className={cn(
"w-[calc((var(--amount-chars)+1)*0.62em)] min-w-[0.8em] max-w-[260px] bg-transparent text-left font-semibold leading-none tracking-normal text-transparent outline-none tabular-nums",
"caret-foreground transition-[font-size] duration-200 placeholder:text-transparent selection:bg-foreground/10 disabled:cursor-not-allowed",
inputSize,
)}
style={inputStyle}
/>
<div
aria-hidden
className={cn(
"pointer-events-none absolute inset-0 flex min-w-0 items-center justify-start overflow-hidden font-semibold leading-none tracking-normal text-foreground tabular-nums transition-[font-size] duration-200",
!value && "text-muted-foreground/55",
inputSize,
)}
style={inputStyle}
>
<AnimatePresence initial={false} mode="popLayout">
{chars.map(({ id: charId, char }) => (
<motion.span
key={charId}
layout={reduce ? false : "position"}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: 18, filter: "blur(10px)" }
}
animate={
reduce
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -14, filter: "blur(10px)" }
}
transition={DIGIT_TRANSITION}
className="inline-block min-w-[0.55em] text-center will-change-[transform,opacity,filter]"
>
{char}
</motion.span>
))}
</AnimatePresence>
</div>
</div>
</div>
);
}
export function PredictionMarket({
outcomes = DEFAULT_OUTCOMES,
value,
defaultValue,
onValueChange,
onTrade,
onSignIn,
authenticated = true,
orderTypeLabel = "Market",
balance = 500,
positions = { up: 24, down: 16 },
quickAmounts = DEFAULT_QUICK_AMOUNTS,
minTrade = 1,
className,
classNames,
}: PredictionMarketProps) {
const inputId = useId();
const reduce = useReducedMotion() ?? false;
const amountRef = useRef<HTMLDivElement>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [status, setStatus] = useState<"idle" | "placing" | "filled">("idle");
const [shakeKey, setShakeKey] = useState(0);
const [order, setOrder] = useControllableOrder({
value,
defaultValue,
outcomes,
onValueChange,
});
const selectedOutcome =
outcomes.find((outcome) => outcome.id === order.outcomeId) ?? outcomes[0];
const position = positions[selectedOutcome.id] ?? 0;
const quote = useMemo(
() =>
buildQuote({
order,
outcome: selectedOutcome,
balance,
position,
minTrade,
}),
[balance, minTrade, order, position, selectedOutcome],
);
const setOrderValue = useCallback(
(next: Partial<PredictionMarketOrderValue>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setStatus("idle");
setOrder({ ...order, ...next });
},
[order, setOrder],
);
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, []);
useEffect(() => {
if (shakeKey === 0 || reduce || !amountRef.current) return;
animate(
amountRef.current,
{ x: [0, -5, 5, -3, 3, -1, 0] },
{ duration: 0.38, ease: EASE_OUT },
);
}, [reduce, shakeKey]);
const addAmount = (increment: number) => {
const next = parseAmount(order.amount) + increment;
setOrderValue({ amount: String(next) });
};
const setMax = () => {
if (order.mode === "buy") {
setOrderValue({ amount: String(Math.floor(balance)) });
return;
}
setOrderValue({ amount: position.toFixed(position % 1 === 0 ? 0 : 2) });
};
const submit = () => {
if (!authenticated) {
onSignIn?.();
return;
}
if (!quote.valid) {
setShakeKey((key) => key + 1);
return;
}
setStatus("placing");
timeoutRef.current = setTimeout(() => {
setStatus("filled");
onTrade?.(order, quote);
}, 650);
};
const inputSize = amountInputSize(order.amount);
const payoutSize = payoutTickerSize(quote.payout);
const actionState: ButtonState =
status === "placing"
? "loading"
: status === "filled"
? "success"
: quote.valid
? "idle"
: "error";
const showFooter = authenticated;
return (
<div
className={cn(
"w-full max-w-[400px] overflow-hidden rounded-3xl border border-border bg-background",
className,
classNames?.root,
)}
>
<div
className={cn(
"border-b border-border/80 px-4 pt-4",
classNames?.header,
)}
>
<div className="flex items-end justify-between gap-4">
<Tabs
value={order.mode}
onValueChange={(mode) =>
setOrderValue({
mode: mode as PredictionMarketMode,
amount: "",
})
}
variant="underline"
className={cn("shrink-0", classNames?.tabs)}
>
<TabsList className="gap-5 border-b-0 bg-transparent p-0">
{MODES.map((mode) => (
<TabsTrigger
key={mode.id}
value={mode.id}
className="px-0 pb-3 pt-0 text-2xl font-semibold"
indicatorClassName="h-0.5 bg-foreground"
>
{mode.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<button
type="button"
disabled={status === "placing"}
className="mb-3 inline-flex items-center gap-2 text-xl font-semibold text-foreground transition-opacity disabled:opacity-50"
>
{orderTypeLabel}
<ChevronDown className="h-5 w-5" />
</button>
</div>
</div>
<div className="space-y-4 p-3">
<Tabs
value={selectedOutcome.id}
onValueChange={(outcomeId) => setOrderValue({ outcomeId })}
variant="pill"
className={classNames?.outcomes}
>
<TabsList className="grid w-full grid-cols-2 gap-2 p-1.5">
{outcomes.map((outcome) => {
const selected = outcome.id === selectedOutcome.id;
const isNo =
outcome.label.toLowerCase() === "no" ||
outcome.label.toLowerCase() === "down";
return (
<TabsTrigger
key={outcome.id}
value={outcome.id}
indicatorClassName={
isNo
? "bg-red-500/10 dark:bg-red-500/15"
: "bg-emerald-500/20"
}
className={cn(
"h-14 w-full rounded-[1.35rem] px-0 py-0 text-base font-semibold active:scale-[0.99]",
isNo
? selected
? "text-red-300 dark:text-red-300"
: "text-red-300/55 dark:text-red-300/50"
: selected
? "text-emerald-400 dark:text-emerald-300"
: "text-muted-foreground",
)}
>
{outcome.label} {formatCents(outcome.price)}
</TabsTrigger>
);
})}
</TabsList>
</Tabs>
<div
ref={amountRef}
className={cn("rounded-3xl bg-card p-4", classNames?.amount)}
>
<div className="flex min-h-24 flex-col items-center justify-center gap-5 text-center">
<label
htmlFor={inputId}
className="text-xl font-medium text-foreground mr-6"
>
{order.mode === "buy" ? "Amount" : "Shares"}
</label>
<div className="w-full min-w-0">
<AnimatedAmountInput
id={inputId}
mode={order.mode}
value={order.amount}
disabled={status === "placing"}
inputSize={inputSize}
reduce={reduce}
onChange={(amount) => setOrderValue({ amount })}
/>
</div>
</div>
<div
className={cn(
"mt-8 flex flex-wrap justify-center gap-2",
classNames?.chips,
)}
>
{quickAmounts.map((amount) => (
<button
key={amount}
type="button"
disabled={status === "placing"}
onClick={() => addAmount(amount)}
className="h-9 rounded-xl bg-background px-3.5 text-sm font-semibold text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
+{order.mode === "buy" ? formatCompactCurrency(amount) : amount}
</button>
))}
<button
type="button"
disabled={status === "placing"}
onClick={setMax}
className="h-9 rounded-xl bg-background px-3.5 text-sm font-semibold text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
Max
</button>
</div>
</div>
</div>
{showFooter ? (
<div
className={cn(
"border-t border-border/80 px-4 py-4",
classNames?.footer,
)}
>
<div className="mb-4 flex items-end justify-between gap-3">
<div className="min-w-0 shrink">
<div className="flex items-center gap-2 text-xl font-semibold text-foreground">
{order.mode === "buy" ? "To win" : "To receive"}
<Banknote className="h-5 w-5 text-emerald-500" />
</div>
<p className="text-sm font-medium text-muted-foreground">
Avg. Price {formatCents(quote.price)}
</p>
</div>
<NumberTicker
value={quote.payout * 100}
startOnView={false}
duration={0.45}
stagger={0}
blur
className={cn(
"ml-auto min-w-0 shrink-0 justify-end whitespace-nowrap text-right font-semibold leading-none tracking-tight text-emerald-500 tabular-nums transition-[font-size] duration-200",
payoutSize,
)}
format={(cents) => formatCurrency(cents / 100)}
/>
</div>
<StatefulButton
state={actionState}
variant="primary"
size="lg"
pressScale={0.98}
onClick={submit}
loadingText="Trading"
successText="Trade filled"
errorText={quote.error ?? "Enter an amount"}
className={cn(
"h-12 w-full rounded-2xl text-base font-semibold",
classNames?.action,
)}
>
Trade
</StatefulButton>
</div>
) : (
<div className="px-4 pb-5">
<StatefulButton
state="idle"
variant="primary"
size="lg"
pressScale={0.98}
onClick={submit}
className={cn(
"h-14 w-full rounded-2xl text-base font-semibold",
classNames?.action,
)}
>
Connect
</StatefulButton>
</div>
)}
</div>
);
}
shadcn init? You are set. Theme setupnpm i clsx lucide-react motion tailwind-merge// 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;
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
"use client";
// beui.dev/components/blocks/prediction-market
import { Banknote, ChevronDown } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
type CSSProperties,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { StatefulButton, type ButtonState } from "./button/stateful";
import { NumberTicker } from "./number-ticker";
import { Tabs, TabsList, TabsTrigger } from "./tabs";
export type PredictionMarketMode = "buy" | "sell";
export type PredictionMarketOutcome = {
id: string;
label: string;
price: number;
};
export type PredictionMarketOrderValue = {
mode: PredictionMarketMode;
outcomeId: string;
amount: string;
};
export type PredictionMarketQuote = {
valid: boolean;
amount: number;
price: number;
shares: number;
payout: number;
error?: string;
};
export type PredictionMarketClassNames = {
root?: string;
header?: string;
tabs?: string;
outcomes?: string;
amount?: string;
chips?: string;
footer?: string;
action?: string;
};
export interface PredictionMarketProps {
outcomes?: PredictionMarketOutcome[];
value?: PredictionMarketOrderValue;
defaultValue?: Partial<PredictionMarketOrderValue>;
onValueChange?: (value: PredictionMarketOrderValue) => void;
onTrade?: (
order: PredictionMarketOrderValue,
quote: PredictionMarketQuote,
) => void;
onSignIn?: () => void;
authenticated?: boolean;
orderTypeLabel?: string;
balance?: number;
positions?: Record<string, number>;
quickAmounts?: number[];
minTrade?: number;
className?: string;
classNames?: PredictionMarketClassNames;
}
const DEFAULT_OUTCOMES: PredictionMarketOutcome[] = [
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
];
const MODES: { id: PredictionMarketMode; label: string }[] = [
{ id: "buy", label: "Buy" },
{ id: "sell", label: "Sell" },
];
const DEFAULT_QUICK_AMOUNTS = [10, 50, 100, 500];
const DIGIT_TRANSITION = { duration: 0.18, ease: EASE_OUT } as const;
type AmountInputStyle = CSSProperties & { "--amount-chars": string };
function useControllableOrder({
value,
defaultValue,
outcomes,
onValueChange,
}: {
value?: PredictionMarketOrderValue;
defaultValue?: Partial<PredictionMarketOrderValue>;
outcomes: PredictionMarketOutcome[];
onValueChange?: (value: PredictionMarketOrderValue) => void;
}) {
const initialValue: PredictionMarketOrderValue = {
mode: defaultValue?.mode ?? "buy",
outcomeId: defaultValue?.outcomeId ?? outcomes[0]?.id ?? "",
amount: defaultValue?.amount ?? "",
};
const [internalValue, setInternalValue] = useState(initialValue);
const controlled = value !== undefined;
const order = value ?? internalValue;
const setOrder = useCallback(
(next: PredictionMarketOrderValue) => {
if (!controlled) {
setInternalValue(next);
}
onValueChange?.(next);
},
[controlled, onValueChange],
);
return [order, setOrder] as const;
}
function sanitizeAmount(value: string) {
const normalized = value.replace(/[^\d.]/g, "");
const [whole, ...decimalParts] = normalized.split(".");
const decimal = decimalParts.join("");
if (decimalParts.length === 0) return whole;
return `${whole}.${decimal.slice(0, 2)}`;
}
function parseAmount(value: string) {
return Number(value) || 0;
}
function formatCurrency(value: number, maximumFractionDigits = 2) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits,
}).format(value);
}
function formatCompactCurrency(value: number) {
return value >= 100
? formatCurrency(value, 0)
: formatCurrency(value, value % 1 === 0 ? 0 : 2);
}
function formatCents(value: number) {
const cents = value * 100;
const precision = Number.isInteger(cents) ? 0 : 1;
return `${cents.toFixed(precision)}¢`;
}
function buildQuote({
order,
outcome,
balance,
position,
minTrade,
}: {
order: PredictionMarketOrderValue;
outcome: PredictionMarketOutcome;
balance: number;
position: number;
minTrade: number;
}): PredictionMarketQuote {
const amount = parseAmount(order.amount);
const price = Math.max(0.01, Math.min(0.99, outcome.price));
const shares = order.mode === "buy" ? amount / price : amount;
const payout = order.mode === "buy" ? shares : amount * price;
if (amount <= 0) {
return {
valid: false,
amount,
price,
shares: 0,
payout: 0,
error: "Enter an amount",
};
}
if (order.mode === "buy" && amount < minTrade) {
return {
valid: false,
amount,
price,
shares,
payout,
error: `Minimum ${formatCompactCurrency(minTrade)}`,
};
}
if (order.mode === "buy" && amount > balance) {
return {
valid: false,
amount,
price,
shares,
payout,
error: "Insufficient balance",
};
}
if (order.mode === "sell" && amount > position) {
return {
valid: false,
amount,
price,
shares,
payout,
error: "Not enough shares",
};
}
return {
valid: true,
amount,
price,
shares,
payout,
};
}
function keyedAmountChars(value: string) {
const seen = new Map<string, number>();
return value.split("").map((char) => {
const count = seen.get(char) ?? 0;
seen.set(char, count + 1);
return { id: `${char}-${count}`, char };
});
}
function amountInputSize(value: string) {
const length = value.replace(/\D/g, "").length;
if (length >= 10) return "text-3xl sm:text-4xl";
if (length >= 8) return "text-4xl sm:text-5xl";
if (length >= 6) return "text-[44px] sm:text-[56px]";
return "text-5xl sm:text-6xl";
}
function payoutTickerSize(value: number) {
const length = formatCurrency(value).length;
if (length >= 16) return "text-xl sm:text-2xl";
if (length >= 13) return "text-2xl";
if (length >= 10) return "text-3xl";
return "text-4xl";
}
function AnimatedAmountInput({
id,
value,
mode,
inputSize,
disabled,
reduce,
onChange,
}: {
id: string;
value: string;
mode: PredictionMarketMode;
inputSize: string;
disabled: boolean;
reduce: boolean;
onChange: (value: string) => void;
}) {
const displayValue = value || "0";
const chars = keyedAmountChars(displayValue);
const inputStyle = {
"--amount-chars": String(chars.length),
} as AmountInputStyle;
const label = mode === "buy" ? "Amount" : "Shares";
return (
<div className="flex min-w-0 items-center justify-center overflow-hidden">
{mode === "buy" ? (
<span
aria-hidden
className={cn(
"shrink-0 font-semibold leading-none tracking-normal text-muted-foreground/65 tabular-nums transition-[font-size] duration-200",
inputSize,
)}
>
$
</span>
) : null}
<div className="relative min-w-0 shrink">
<input
id={id}
value={value}
disabled={disabled}
onChange={(event) => onChange(sanitizeAmount(event.target.value))}
placeholder="0"
inputMode="decimal"
aria-label={label}
autoComplete="off"
className={cn(
"w-[calc((var(--amount-chars)+1)*0.62em)] min-w-[0.8em] max-w-[260px] bg-transparent text-left font-semibold leading-none tracking-normal text-transparent outline-none tabular-nums",
"caret-foreground transition-[font-size] duration-200 placeholder:text-transparent selection:bg-foreground/10 disabled:cursor-not-allowed",
inputSize,
)}
style={inputStyle}
/>
<div
aria-hidden
className={cn(
"pointer-events-none absolute inset-0 flex min-w-0 items-center justify-start overflow-hidden font-semibold leading-none tracking-normal text-foreground tabular-nums transition-[font-size] duration-200",
!value && "text-muted-foreground/55",
inputSize,
)}
style={inputStyle}
>
<AnimatePresence initial={false} mode="popLayout">
{chars.map(({ id: charId, char }) => (
<motion.span
key={charId}
layout={reduce ? false : "position"}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: 18, filter: "blur(10px)" }
}
animate={
reduce
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -14, filter: "blur(10px)" }
}
transition={DIGIT_TRANSITION}
className="inline-block min-w-[0.55em] text-center will-change-[transform,opacity,filter]"
>
{char}
</motion.span>
))}
</AnimatePresence>
</div>
</div>
</div>
);
}
export function PredictionMarket({
outcomes = DEFAULT_OUTCOMES,
value,
defaultValue,
onValueChange,
onTrade,
onSignIn,
authenticated = true,
orderTypeLabel = "Market",
balance = 500,
positions = { up: 24, down: 16 },
quickAmounts = DEFAULT_QUICK_AMOUNTS,
minTrade = 1,
className,
classNames,
}: PredictionMarketProps) {
const inputId = useId();
const reduce = useReducedMotion() ?? false;
const amountRef = useRef<HTMLDivElement>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [status, setStatus] = useState<"idle" | "placing" | "filled">("idle");
const [shakeKey, setShakeKey] = useState(0);
const [order, setOrder] = useControllableOrder({
value,
defaultValue,
outcomes,
onValueChange,
});
const selectedOutcome =
outcomes.find((outcome) => outcome.id === order.outcomeId) ?? outcomes[0];
const position = positions[selectedOutcome.id] ?? 0;
const quote = useMemo(
() =>
buildQuote({
order,
outcome: selectedOutcome,
balance,
position,
minTrade,
}),
[balance, minTrade, order, position, selectedOutcome],
);
const setOrderValue = useCallback(
(next: Partial<PredictionMarketOrderValue>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setStatus("idle");
setOrder({ ...order, ...next });
},
[order, setOrder],
);
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, []);
useEffect(() => {
if (shakeKey === 0 || reduce || !amountRef.current) return;
animate(
amountRef.current,
{ x: [0, -5, 5, -3, 3, -1, 0] },
{ duration: 0.38, ease: EASE_OUT },
);
}, [reduce, shakeKey]);
const addAmount = (increment: number) => {
const next = parseAmount(order.amount) + increment;
setOrderValue({ amount: String(next) });
};
const setMax = () => {
if (order.mode === "buy") {
setOrderValue({ amount: String(Math.floor(balance)) });
return;
}
setOrderValue({ amount: position.toFixed(position % 1 === 0 ? 0 : 2) });
};
const submit = () => {
if (!authenticated) {
onSignIn?.();
return;
}
if (!quote.valid) {
setShakeKey((key) => key + 1);
return;
}
setStatus("placing");
timeoutRef.current = setTimeout(() => {
setStatus("filled");
onTrade?.(order, quote);
}, 650);
};
const inputSize = amountInputSize(order.amount);
const payoutSize = payoutTickerSize(quote.payout);
const actionState: ButtonState =
status === "placing"
? "loading"
: status === "filled"
? "success"
: quote.valid
? "idle"
: "error";
const showFooter = authenticated;
return (
<div
className={cn(
"w-full max-w-[400px] overflow-hidden rounded-3xl border border-border bg-background",
className,
classNames?.root,
)}
>
<div
className={cn(
"border-b border-border/80 px-4 pt-4",
classNames?.header,
)}
>
<div className="flex items-end justify-between gap-4">
<Tabs
value={order.mode}
onValueChange={(mode) =>
setOrderValue({
mode: mode as PredictionMarketMode,
amount: "",
})
}
variant="underline"
className={cn("shrink-0", classNames?.tabs)}
>
<TabsList className="gap-5 border-b-0 bg-transparent p-0">
{MODES.map((mode) => (
<TabsTrigger
key={mode.id}
value={mode.id}
className="px-0 pb-3 pt-0 text-2xl font-semibold"
indicatorClassName="h-0.5 bg-foreground"
>
{mode.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<button
type="button"
disabled={status === "placing"}
className="mb-3 inline-flex items-center gap-2 text-xl font-semibold text-foreground transition-opacity disabled:opacity-50"
>
{orderTypeLabel}
<ChevronDown className="h-5 w-5" />
</button>
</div>
</div>
<div className="space-y-4 p-3">
<Tabs
value={selectedOutcome.id}
onValueChange={(outcomeId) => setOrderValue({ outcomeId })}
variant="pill"
className={classNames?.outcomes}
>
<TabsList className="grid w-full grid-cols-2 gap-2 p-1.5">
{outcomes.map((outcome) => {
const selected = outcome.id === selectedOutcome.id;
const isNo =
outcome.label.toLowerCase() === "no" ||
outcome.label.toLowerCase() === "down";
return (
<TabsTrigger
key={outcome.id}
value={outcome.id}
indicatorClassName={
isNo
? "bg-red-500/10 dark:bg-red-500/15"
: "bg-emerald-500/20"
}
className={cn(
"h-14 w-full rounded-[1.35rem] px-0 py-0 text-base font-semibold active:scale-[0.99]",
isNo
? selected
? "text-red-300 dark:text-red-300"
: "text-red-300/55 dark:text-red-300/50"
: selected
? "text-emerald-400 dark:text-emerald-300"
: "text-muted-foreground",
)}
>
{outcome.label} {formatCents(outcome.price)}
</TabsTrigger>
);
})}
</TabsList>
</Tabs>
<div
ref={amountRef}
className={cn("rounded-3xl bg-card p-4", classNames?.amount)}
>
<div className="flex min-h-24 flex-col items-center justify-center gap-5 text-center">
<label
htmlFor={inputId}
className="text-xl font-medium text-foreground mr-6"
>
{order.mode === "buy" ? "Amount" : "Shares"}
</label>
<div className="w-full min-w-0">
<AnimatedAmountInput
id={inputId}
mode={order.mode}
value={order.amount}
disabled={status === "placing"}
inputSize={inputSize}
reduce={reduce}
onChange={(amount) => setOrderValue({ amount })}
/>
</div>
</div>
<div
className={cn(
"mt-8 flex flex-wrap justify-center gap-2",
classNames?.chips,
)}
>
{quickAmounts.map((amount) => (
<button
key={amount}
type="button"
disabled={status === "placing"}
onClick={() => addAmount(amount)}
className="h-9 rounded-xl bg-background px-3.5 text-sm font-semibold text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
+{order.mode === "buy" ? formatCompactCurrency(amount) : amount}
</button>
))}
<button
type="button"
disabled={status === "placing"}
onClick={setMax}
className="h-9 rounded-xl bg-background px-3.5 text-sm font-semibold text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
Max
</button>
</div>
</div>
</div>
{showFooter ? (
<div
className={cn(
"border-t border-border/80 px-4 py-4",
classNames?.footer,
)}
>
<div className="mb-4 flex items-end justify-between gap-3">
<div className="min-w-0 shrink">
<div className="flex items-center gap-2 text-xl font-semibold text-foreground">
{order.mode === "buy" ? "To win" : "To receive"}
<Banknote className="h-5 w-5 text-emerald-500" />
</div>
<p className="text-sm font-medium text-muted-foreground">
Avg. Price {formatCents(quote.price)}
</p>
</div>
<NumberTicker
value={quote.payout * 100}
startOnView={false}
duration={0.45}
stagger={0}
blur
className={cn(
"ml-auto min-w-0 shrink-0 justify-end whitespace-nowrap text-right font-semibold leading-none tracking-tight text-emerald-500 tabular-nums transition-[font-size] duration-200",
payoutSize,
)}
format={(cents) => formatCurrency(cents / 100)}
/>
</div>
<StatefulButton
state={actionState}
variant="primary"
size="lg"
pressScale={0.98}
onClick={submit}
loadingText="Trading"
successText="Trade filled"
errorText={quote.error ?? "Enter an amount"}
className={cn(
"h-12 w-full rounded-2xl text-base font-semibold",
classNames?.action,
)}
>
Trade
</StatefulButton>
</div>
) : (
<div className="px-4 pb-5">
<StatefulButton
state="idle"
variant="primary"
size="lg"
pressScale={0.98}
onClick={submit}
className={cn(
"h-14 w-full rounded-2xl text-base font-semibold",
classNames?.action,
)}
>
Connect
</StatefulButton>
</div>
)}
</div>
);
}
"use client";
// beui.dev/components/blocks/prediction-market
import { Bookmark } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import { type ReactNode, useId, useState } from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
import { ActionSwapText } from "./action-swap";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
export interface PredictionMarketCardOutcome {
id: string;
label: string;
/** Probability between 0 and 1. */
probability: number;
icon?: ReactNode;
/** Optional team color for the compact probability line. */
color?: string;
}
export interface PredictionMarketCardSelection {
outcomeId: string;
side: "yes" | "no";
}
export interface PredictionMarketCardProps {
title: string;
icon?: ReactNode;
category?: string;
volume: string;
/** Chronological volume samples for the optional footer sparkline. */
volumeHistory?: number[];
/** A scheduled time or live match status. */
status?: string;
live?: boolean;
outcomes: PredictionMarketCardOutcome[];
/** Called on each outcome CTA click; the card keeps no selected state. */
onOutcomeClick?: (value: PredictionMarketCardSelection) => void;
bookmarked?: boolean;
defaultBookmarked?: boolean;
onBookmarkChange?: (bookmarked: boolean) => void;
className?: string;
}
function probability(value: number) {
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
}
/** A listing surface with outcome CTAs and an independent bookmark toggle. */
export function PredictionMarketCard({
title,
icon,
category,
volume,
volumeHistory,
status,
live = false,
outcomes,
onOutcomeClick,
bookmarked,
defaultBookmarked = false,
onBookmarkChange,
className,
}: PredictionMarketCardProps) {
const titleId = useId();
const chartId = useId();
const samples = volumeHistory?.filter(Number.isFinite) ?? [];
const low = Math.min(...samples);
const range = Math.max(...samples) - low;
const chartPoints =
samples.length > 1
? samples
.map(
(sample, index) =>
`${2 + (index / (samples.length - 1)) * 44},${18 - (range ? (sample - low) / range : 0.5) * 14}`,
)
.join(" ")
: null;
const reduce = useReducedMotion();
const [internalBookmark, setInternalBookmark] = useState(defaultBookmarked);
const saved = bookmarked ?? internalBookmark;
return (
<article
aria-labelledby={titleId}
className={cn(
"flex h-full w-full min-w-0 flex-col overflow-hidden rounded-3xl bg-card text-foreground",
className,
)}
>
<header className="flex shrink-0 items-center gap-3 px-4 py-3">
{icon && (
<div
aria-hidden
className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-background text-foreground"
>
{icon}
</div>
)}
<div className="min-w-0 flex-1">
<h3
id={titleId}
className="break-words font-display text-base font-medium leading-snug tracking-tight"
>
{title}
</h3>
<p className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{status && (
<span
className={cn(
"inline-flex items-center gap-1.5",
live && "text-rose-500",
)}
>
{live && (
<span
aria-hidden
className="size-1.5 rounded-full bg-current"
/>
)}
{status}
</span>
)}
{status && category && <span aria-hidden>·</span>}
{category && <span>{category}</span>}
</p>
</div>
</header>
<div className="mx-2 mb-2 flex flex-1 flex-col rounded-3xl bg-background px-4 py-3">
<div className="flex flex-1 flex-col justify-center gap-3">
{outcomes.map((outcome, index) => (
<div key={outcome.id} className="space-y-1">
<div className="flex min-h-10 items-center gap-2">
{outcome.icon && (
<span
aria-hidden
className="flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted"
>
{outcome.icon}
</span>
)}
<span className="min-w-0 flex-1 break-words text-sm font-medium">
{outcome.label}
</span>
<Tooltip
content="Potential payout per $1 if this outcome wins, including your stake. Before fees; based on the displayed price."
wrapperClassName="shrink-0"
className="w-44 whitespace-normal text-center leading-relaxed"
>
<button
type="button"
aria-label={`Potential payout for ${outcome.label}`}
className="rounded-md py-2 text-sm tabular-nums text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring"
>
{probability(outcome.probability) > 0
? `${(1 / probability(outcome.probability)).toFixed(1)}×`
: "—"}
</button>
</Tooltip>
<MarketOddsButton
positive={index % 2 === 0}
outcome={outcome}
onClick={() =>
onOutcomeClick?.({ outcomeId: outcome.id, side: "yes" })
}
/>
</div>
<div
aria-hidden
className="h-0.5 w-24 overflow-hidden rounded-full"
>
<motion.div
initial={false}
animate={{ scaleX: probability(outcome.probability) }}
transition={
reduce
? { duration: 0 }
: { duration: 0.25, ease: EASE_OUT }
}
className="h-full origin-left rounded-full bg-emerald-300/70 dark:bg-emerald-400/40"
style={
outcome.color
? { backgroundColor: outcome.color }
: undefined
}
/>
</div>
</div>
))}
</div>
<footer className="mt-2 flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
{chartPoints && (
<svg
aria-hidden="true"
viewBox="0 0 48 22"
className="h-5 w-12 shrink-0 text-emerald-500 dark:text-emerald-400"
fill="none"
>
<defs>
<linearGradient id={chartId} x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor="currentColor"
stopOpacity="0.22"
/>
<stop
offset="100%"
stopColor="currentColor"
stopOpacity="0"
/>
</linearGradient>
</defs>
<polygon
points={`2,22 ${chartPoints} 46,22`}
fill={`url(#${chartId})`}
/>
<polyline
points={chartPoints}
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
<span className="shrink-0">{volume} vol.</span>
<motion.button
type="button"
aria-label={`Bookmark ${title}`}
aria-pressed={saved}
onClick={() => {
if (bookmarked === undefined) setInternalBookmark(!saved);
onBookmarkChange?.(!saved);
}}
whileTap={reduce ? undefined : { scale: 0.85 }}
transition={SPRING_PRESS}
className={cn(
"ml-auto flex size-9 shrink-0 items-center justify-center rounded-xl transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-ring",
saved && "text-foreground",
)}
>
<motion.span
animate={{ scale: saved && !reduce ? [1, 1.2, 1] : 1 }}
transition={{ duration: 0.22, ease: EASE_OUT }}
>
<Bookmark
aria-hidden
className={cn("size-4", saved && "fill-current")}
/>
</motion.span>
</motion.button>
</footer>
</div>
</article>
);
}
function MarketOddsButton({
positive,
outcome,
onClick,
}: {
outcome: PredictionMarketCardOutcome;
positive: boolean;
onClick: () => void;
}) {
const reduce = useReducedMotion();
const cents = Math.round(probability(outcome.probability) * 100);
const canHover = useHoverCapable();
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const showAction = (canHover && hovered) || focused;
return (
<motion.button
type="button"
aria-label={`Trade ${outcome.label} at ${cents}%`}
onClick={onClick}
onPointerEnter={(event) => {
if (event.pointerType !== "touch") setHovered(true);
}}
onPointerLeave={() => setHovered(false)}
onFocus={(event) =>
setFocused(event.currentTarget.matches(":focus-visible"))
}
onBlur={() => setFocused(false)}
whileTap={reduce ? undefined : { scale: 0.96 }}
transition={SPRING_PRESS}
className={cn(
"relative flex min-h-10 min-w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-background px-3 text-sm font-semibold text-foreground shadow-[0_3px_0] transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
positive &&
"shadow-emerald-500/20 border-emerald-500/25 bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-400",
!positive &&
"shadow-rose-500/20 border-rose-500/25 bg-rose-500/10 text-rose-700 hover:bg-rose-500/15 dark:text-rose-400",
)}
>
<ActionSwapText
value={showAction ? "action" : String(cents)}
animation="roll"
>
{showAction ? (positive ? "Yes" : "No") : `${cents}%`}
</ActionSwapText>
</motion.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}
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 { animate, motion, useInView, useReducedMotion } from "motion/react";
import { useEffect, useMemo, useRef, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface NumberTickerProps {
value: number;
/** Digits to pad to (left). */
pad?: number;
/** Per-digit roll duration in seconds. */
duration?: number;
/** Stagger between digits. */
stagger?: number;
/** Render only after the element enters the viewport. */
startOnView?: boolean;
prefix?: string;
suffix?: string;
/** Add a small blur during digit rolls. */
blur?: boolean;
className?: string;
digitClassName?: string;
/** Insert locale group separators (commas). Server-component safe. */
locale?: boolean;
/** Custom formatter. Client-only — server components must use `locale` instead. */
format?: (value: number) => string;
}
const DIGIT_HEIGHT_EM = 1.1;
const DIGITS = Array.from({ length: 10 }, (_, n) => n);
export function NumberTicker({
value,
pad,
duration = 0.9,
stagger = 0.04,
startOnView = true,
prefix,
suffix,
blur = false,
className,
digitClassName,
locale,
format,
}: NumberTickerProps) {
const containerRef = useRef<HTMLSpanElement>(null);
const inView = useInView(containerRef, { once: true, amount: 0.6 });
const [armed, setArmed] = useState(!startOnView);
useEffect(() => {
if (startOnView && inView) setArmed(true);
}, [startOnView, inView]);
const text = useMemo(() => {
const rounded = Math.round(value);
const formatted = format
? format(rounded)
: locale
? rounded.toLocaleString()
: rounded.toString();
return pad ? formatted.padStart(pad, "0") : formatted;
}, [value, pad, format, locale]);
const glyphs = useMemo(() => {
const chars = text.split("");
// Key by place value (position from the right): a changing digit keeps its
// identity and rolls to the new value instead of remounting and replaying
// from 0. Growing numbers add glyphs on the left without re-keying the
// ones, tens, hundreds already on screen.
return chars.map((char, i) => ({ char, id: `g-${chars.length - 1 - i}` }));
}, [text]);
const readableText = `${prefix ?? ""}${text}${suffix ?? ""}`;
// Stagger is an entrance flourish. Once the reveal has played, value
// changes roll every digit immediately — a per-digit delay on live updates
// reads as lag.
const [entered, setEntered] = useState(false);
useEffect(() => {
if (!armed || entered) return;
const total = (duration + glyphs.length * stagger) * 1000;
const t = window.setTimeout(() => setEntered(true), total);
return () => window.clearTimeout(t);
}, [armed, entered, duration, stagger, glyphs.length]);
return (
<span
ref={containerRef}
className={cn("inline-flex items-center tabular-nums", className)}
>
<span className="sr-only">{readableText}</span>
<span aria-hidden="true" className="inline-flex items-center">
{prefix ? <span>{prefix}</span> : null}
{glyphs.map(({ char, id }, i) => {
const isDigit = /\d/.test(char);
if (!isDigit) {
return (
<span key={id} className="inline-block">
{char}
</span>
);
}
const digit = Number(char);
return (
<Digit
key={id}
digit={armed ? digit : 0}
delay={entered ? 0 : i * stagger}
duration={duration}
blur={blur}
className={digitClassName}
/>
);
})}
{suffix ? <span>{suffix}</span> : null}
</span>
</span>
);
}
function Digit({
digit,
delay,
duration,
blur,
className,
}: {
digit: number;
delay: number;
duration: number;
blur: boolean;
className?: string;
}) {
const reduce = useReducedMotion();
const columnRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (reduce || !blur || !columnRef.current || !Number.isFinite(digit)) {
return;
}
const node = columnRef.current;
const controls = animate(
node,
{ filter: ["blur(10px)", "blur(0px)"] },
{
duration: Math.min(duration * 0.75, 0.32),
delay,
ease: EASE_OUT,
},
);
return () => {
controls.stop();
node.style.filter = "blur(0px)";
};
}, [blur, delay, digit, duration, reduce]);
return (
<span
className={cn("relative inline-block overflow-hidden", className)}
style={{ height: `${DIGIT_HEIGHT_EM}em`, width: "1ch" }}
>
<motion.span
ref={columnRef}
initial={{ y: 0 }}
animate={{ y: `-${digit * DIGIT_HEIGHT_EM}em` }}
transition={
reduce
? { duration: 0 }
: { duration, delay, ease: EASE_OUT }
}
className="absolute inset-x-0 top-0 flex flex-col items-center will-change-[transform,filter]"
>
{DIGITS.map((n) => (
<span
key={n}
className="flex h-[1.1em] items-center justify-center leading-none"
>
{n}
</span>
))}
</motion.span>
</span>
);
}
"use client";
import { motion, MotionConfig, useReducedMotion, type Transition } from "motion/react";
import {
createContext,
useCallback,
useContext,
useId,
useMemo,
useState,
type ReactNode,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Variant = "pill" | "underline" | "segment";
type Ctx = {
value: string;
setValue: (v: string) => void;
layoutId: string;
variant: Variant;
};
const TabsCtx = createContext<Ctx | null>(null);
function useTabs() {
const ctx = useContext(TabsCtx);
if (!ctx) throw new Error("Tabs.* must be used inside <Tabs>");
return ctx;
}
// Settle without overshoot: a scrollable tab list would turn even a small
// overshoot into a transient scrollbar and layout shift.
const transition: Transition = {
type: "spring",
stiffness: 170,
damping: 30,
mass: 1.2,
};
export function Tabs({
defaultValue,
value,
onValueChange,
variant = "pill",
children,
className,
}: {
defaultValue?: string;
value?: string;
onValueChange?: (v: string) => void;
variant?: Variant;
children: ReactNode;
className?: string;
}) {
const [internal, setInternal] = useState(defaultValue ?? "");
const layoutId = useId();
const reduce = useReducedMotion();
const controlled = value !== undefined;
const current = controlled ? value : internal;
const setValue = useCallback(
(v: string) => {
if (!controlled) setInternal(v);
onValueChange?.(v);
},
[controlled, onValueChange],
);
const contextValue = useMemo(
() => ({ value: current, setValue, layoutId, variant }),
[current, layoutId, setValue, variant],
);
return (
<MotionConfig transition={reduce ? { duration: 0 } : transition}>
<TabsCtx.Provider value={contextValue}>
{/* layoutRoot: the indicator's layoutId measures in page coordinates, so
inside fixed/scrolled containers it would replay scroll offsets as
movement. The pill only ever travels within the list, so scoping
projection to the Tabs wrapper is always correct. */}
<motion.div layoutRoot className={className}>
{children}
</motion.div>
</TabsCtx.Provider>
</MotionConfig>
);
}
const listClasses: Record<Variant, string> = {
pill: "inline-flex items-center gap-1 rounded-full bg-card p-1",
underline: "inline-flex items-center gap-1 border-b border-border",
segment: "inline-flex items-center gap-0 rounded-lg bg-card p-0.5",
};
export function TabsList({ children, className }: { children: ReactNode; className?: string }) {
const { variant } = useTabs();
return (
<div role="tablist" className={cn(listClasses[variant], className)}>
{children}
</div>
);
}
export function TabsTrigger({
value,
children,
className,
indicatorClassName,
}: {
value: string;
children: ReactNode;
className?: string;
indicatorClassName?: string;
}) {
const { value: current, setValue, layoutId, variant } = useTabs();
const active = current === value;
if (variant === "underline") {
return (
<button
type="button"
role="tab"
aria-selected={active}
onClick={() => setValue(value)}
className={cn(
"relative isolate px-3 pb-2.5 pt-1 -mb-px text-sm font-medium transition-colors min-h-[44px] inline-flex items-center",
active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
className,
)}
>
{children}
{active ? (
<motion.span
layoutId={layoutId}
layout="position"
className={cn(
"absolute -bottom-px left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
const radius = variant === "pill" ? "rounded-full" : "rounded-md";
return (
<div className="relative">
{active ? (
<motion.span
layoutId={layoutId}
layout="position"
style={{ borderRadius: variant === "pill" ? 9999 : 8 }}
className={cn(
"absolute inset-0 bg-primary",
radius,
indicatorClassName,
)}
/>
) : null}
<button
type="button"
role="tab"
aria-selected={active}
onClick={() => setValue(value)}
className={cn(
"relative z-10 inline-flex items-center justify-center whitespace-nowrap bg-transparent px-3.5 py-1.5 text-sm font-medium outline-none",
"transition-colors",
active
? "text-primary-foreground"
: "text-muted-foreground hover:text-foreground",
radius,
className,
)}
>
{children}
</button>
</div>
);
}
export function TabsContent({ value, children, className }: { value: string; children: ReactNode; className?: string }) {
const { value: current } = useTabs();
const reduce = useReducedMotion();
const active = current === value;
// Inactive panels stay mounted but hidden, so their content (e.g. source
// code) is present in the server-rendered HTML for crawlers and assistive
// tech, instead of being dropped from the DOM.
if (!active) {
return (
<div hidden className={className}>
{children}
</div>
);
}
return (
<motion.div
key={value}
initial={{ opacity: 0, y: reduce ? 0 : 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18, ease: EASE_OUT }}
className={cn("mt-4", className)}
>
{children}
</motion.div>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion, type HTMLMotionProps, type Variants } from "motion/react";
import { useState } from "react";
import type { ReactNode } from "react";
import { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ActionSwapItem = {
id: string;
label: ReactNode;
icon?: ReactNode;
ariaLabel?: string;
};
export type ActionSwapButtonVariant = "primary" | "secondary" | "outline" | "ghost";
export type ActionSwapButtonSize = "sm" | "md" | "lg" | "icon";
export type ActionSwapAnimation = "blur" | "roll" | "cascade";
/** Animations with a single-element variant set (cascade animates per letter). */
type CoreAnimation = "blur" | "roll";
export interface ActionSwapButtonProps extends Omit<
HTMLMotionProps<"button">,
"children" | "onChange"
> {
items: ActionSwapItem[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string, item: ActionSwapItem) => void;
variant?: ActionSwapButtonVariant;
size?: ActionSwapButtonSize;
animation?: ActionSwapAnimation;
iconOnly?: boolean;
cycle?: boolean;
}
export interface ActionSwapTextProps {
value: string;
children: ReactNode;
animation?: ActionSwapAnimation;
className?: string;
}
export interface ActionSwapIconProps {
value: string;
children: ReactNode;
animation?: ActionSwapAnimation;
className?: string;
}
const BLUR_TRANSITION = { duration: 0.2, ease: "easeInOut" } as const;
const ROLL_TRANSITION = SPRING_SWAP;
const ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;
const SWAP_BLUR = "blur(8px)";
const ROLL_BLUR = "blur(3px)";
// Cascade rolls the label one letter at a time, left to right. The leaving
// and landing strings overlap as independent layers (no shared cells), so
// proportional glyph widths never jitter. Exits cascade at half the enter
// stagger so the tail of the old label lingers briefly.
const CASCADE_STAGGER = 0.025;
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 TEXT_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.94, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.94,
filter: SWAP_BLUR,
transition: BLUR_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: "90%", filter: ROLL_BLUR },
animate: {
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: "-90%",
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const ICON_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.25, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.25,
filter: SWAP_BLUR,
transition: BLUR_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: 12, filter: ROLL_BLUR },
animate: {
opacity: 1,
y: 0,
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: -12,
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
outline: "border border-border bg-transparent text-foreground hover:bg-primary/5",
ghost: "text-muted-foreground hover:bg-primary/5 hover:text-foreground",
};
const SIZE_CLASS: Record<ActionSwapButtonSize, string> = {
sm: "h-8 gap-1.5 rounded-full px-3 text-xs",
md: "h-10 gap-2 rounded-full px-4 text-sm",
lg: "h-12 gap-2.5 rounded-full px-5 text-base",
icon: "h-10 w-10 rounded-full",
};
export function ActionSwapText({
value,
children,
animation = "blur",
className,
}: ActionSwapTextProps) {
const reduce = useReducedMotion();
// Cascade needs a plain string to split into letters; non-string content
// and reduced motion fall back to the closest single-element animation.
const label = typeof children === "string" ? children : null;
const cascade = animation === "cascade" && label !== null && !reduce;
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span
className={cn(
"relative -my-[0.08em] inline-block max-w-full whitespace-nowrap py-[0.08em] align-bottom",
className,
)}
style={{
clipPath: "inset(0 -999px)",
WebkitClipPath: "inset(0 -999px)",
}}
>
<span
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 ? (
<>
{/* Letters are decorative fragments; readers get the whole label. */}
<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.08em] inline-block whitespace-pre"
>
{label.split("").map((char, i) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity — the letter at a position is exactly what rolls.
key={i}
custom={i * 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={`${animation}-${value}`}
variants={TEXT_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
// Truncation lives on the layer that holds the text — the layer
// moves as a whole, so clipping it never eats the roll.
className="absolute left-0 top-[0.08em] inline-block max-w-full truncate will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</span>
);
}
export function ActionSwapIcon({
value,
children,
animation = "blur",
className,
}: ActionSwapIconProps) {
const reduce = useReducedMotion();
// Icons are single elements — cascade maps to its closest motion, roll.
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span className={cn("relative inline-grid shrink-0 place-items-center overflow-hidden", className)}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={`${animation}-${value}`}
aria-hidden
variants={ICON_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
className="col-start-1 row-start-1 inline-flex items-center justify-center will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
</span>
);
}
export function ActionSwapButton({
items,
value,
defaultValue,
onValueChange,
variant = "secondary",
size = "md",
animation = "blur",
iconOnly = size === "icon",
cycle = true,
className,
disabled,
onClick,
...rest
}: ActionSwapButtonProps) {
const reduce = useReducedMotion();
const [internalValue, setInternalValue] = useState(defaultValue ?? items[0]?.id);
const currentValue = value ?? internalValue;
const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentValue));
const activeItem = items[activeIndex] ?? items[0];
const hasIcon = items.some((item) => item.icon);
const nextItem = cycle && items.length > 0 ? items[(activeIndex + 1) % items.length] : undefined;
if (!activeItem) return null;
const accessibleLabel = activeItem.ariaLabel ?? (iconOnly && typeof activeItem.label === "string" ? activeItem.label : undefined);
return (
<motion.button
type="button"
disabled={disabled}
whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center overflow-hidden font-medium transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
aria-label={accessibleLabel}
onClick={(event) => {
onClick?.(event);
if (event.defaultPrevented || disabled || !cycle || !nextItem) return;
if (value === undefined) setInternalValue(nextItem.id);
onValueChange?.(nextItem.id, nextItem);
}}
{...rest}
>
{hasIcon ? (
<ActionSwapIcon value={activeItem.id} animation={animation} className="h-4 w-4">
{activeItem.icon ?? null}
</ActionSwapIcon>
) : null}
{!iconOnly ? (
<ActionSwapText value={activeItem.id} animation={animation}>
{activeItem.label}
</ActionSwapText>
) : null}
</motion.button>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
cloneElement,
isValidElement,
type PointerEvent,
type ReactElement,
type ReactNode,
type RefObject,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
export interface TooltipProps {
content: ReactNode;
children?: ReactElement;
/** Existing trigger for controlled integrations such as chart cells. */
anchorRef?: RefObject<HTMLElement | SVGElement | null>;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: { x: number; y: number };
open?: boolean;
onOpenChange?: (open: boolean) => void;
id?: string;
side?: Side;
/** Delay before showing (ms). Default 120. */
delay?: number;
className?: string;
/** Classes for the outer wrapper span. Use to fix baseline / fill parent. */
wrapperClassName?: string;
}
// Gap between trigger and tooltip, in px.
const GAP = 8;
// Centering transform for the fixed-positioned anchor point, per side.
const anchorTransform: Record<Side, string> = {
top: "translate(-50%, -100%)",
bottom: "translate(-50%, 0)",
left: "translate(-100%, -50%)",
right: "translate(0, -50%)",
};
const transformOrigin: Record<Side, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
// Once any tooltip has just closed, neighbouring tooltips open without the
// initial delay — moving along a toolbar feels instant after the first one.
const WARM_WINDOW_MS = 300;
let lastHiddenAt = 0;
export function Tooltip({
content,
children,
side = "top",
delay = 120,
className,
wrapperClassName,
anchorRef: externalAnchorRef,
anchorPoint,
open: controlledOpen,
onOpenChange,
id: providedId,
}: TooltipProps) {
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (controlledOpen === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[controlledOpen, onOpenChange],
);
const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
const generatedId = useId();
const id = providedId ?? generatedId;
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapperRef = useRef<HTMLSpanElement>(null);
const anchorRef = externalAnchorRef ?? wrapperRef;
const hover = useHoverGesture();
const surfaceRef = useRef<HTMLSpanElement>(null);
// Anchor point in viewport coords, on the edge of the trigger facing `side`.
// Position:fixed means these viewport coords place the tooltip directly, so
// it escapes every ancestor's stacking context and overflow.
const place = useCallback(() => {
const el = anchorRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
const cx = r.left + r.width * (anchorPoint?.x ?? 0.5);
const cy = r.top + r.height * (anchorPoint?.y ?? 0.5);
const point: Record<Side, { top: number; left: number }> = {
top: { top: (anchorPoint ? cy : r.top) - GAP, left: cx },
bottom: { top: (anchorPoint ? cy : r.bottom) + GAP, left: cx },
left: { top: cy, left: (anchorPoint ? cx : r.left) - GAP },
right: { top: cy, left: (anchorPoint ? cx : r.right) + GAP },
};
const next = point[side];
const width = surfaceRef.current?.offsetWidth ?? 0;
const height = surfaceRef.current?.offsetHeight ?? 0;
const dx = side === "left" ? width : side === "right" ? 0 : width / 2;
const dy = side === "top" ? height : side === "bottom" ? 0 : height / 2;
next.left = Math.max(GAP + dx, Math.min(next.left, window.innerWidth - GAP - width + dx));
next.top = Math.max(GAP + dy, Math.min(next.top, window.innerHeight - GAP - height + dy));
setCoords(previous => previous?.top === next.top && previous.left === next.left ? previous : next);
}, [side, anchorRef, anchorPoint]);
const positioned = coords !== null;
useLayoutEffect(() => {
if (!open) return;
place();
const observer = new ResizeObserver(place);
if (anchorRef.current) observer.observe(anchorRef.current);
if (positioned && surfaceRef.current) observer.observe(surfaceRef.current);
return () => observer.disconnect();
}, [open, place, anchorRef, positioned]);
const show = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
const warm = Date.now() - lastHiddenAt < WARM_WINDOW_MS;
timer.current = setTimeout(
() => {
place();
setOpen(true);
},
warm ? 0 : delay,
);
}, [delay, place, setOpen]);
const hide = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
if (open) lastHiddenAt = Date.now();
setOpen(false);
}, [open, setOpen]);
// A finger never hovers, and Safari does not focus a button on tap either, so
// the label is only reachable if the tap itself opens the tooltip. A click
// carries no pointerType, so the pointerdown that preceded it is what says
// whether this was a tap; keyboard activation arrives with no pointerdown at
// all, and focus has already shown the label there.
const tap = useTapGesture<boolean>();
const toggleOnTap = useCallback(() => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) {
hide();
return;
}
if (timer.current) clearTimeout(timer.current);
place();
setOpen(true);
}, [hide, place, tap, setOpen]);
// ...and closed again by the next tap that lands somewhere else. The label
// covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, hide, anchorRef);
// Keep the tooltip pinned to the trigger while it's open and the page scrolls
// or resizes (fixed coords are viewport-relative).
useEffect(() => {
if (!open) return;
const onMove = () => place();
window.addEventListener("scroll", onMove, true);
window.addEventListener("resize", onMove);
return () => {
window.removeEventListener("scroll", onMove, true);
window.removeEventListener("resize", onMove);
};
}, [open, place]);
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
if (!externalAnchorRef && !isValidElement(children)) return children;
// The label describes the trigger, so it has to name the trigger itself.
// Everything else the tooltip needs is read off the anchor below instead of
// cloned on: a handler written onto the child is the child's handler as far
// as that child can tell, and a component that owns its activation —
// hard-wiring onClick and spreading the rest of its props over it, as
// ThemeToggle does — then runs the tooltip's instead of its own. Composing
// with `props.onClick` cannot save it either, because a component element's
// props hold nothing the component does internally.
const trigger = isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, {
"aria-describedby": id,
})
: null;
return (
<>
{!externalAnchorRef ? (
// biome-ignore lint/a11y/noStaticElementInteractions: This wrapper observes bubbling trigger events without replacing the control's handlers.
<span
ref={wrapperRef}
className={cn("relative inline-flex align-middle", wrapperClassName)}
// Pointer events, not the mouse pair: a tap fires compatibility
// mouseenter/mouseleave that carry no pointerType, which raced the tap
// path into opening and closing the same label.
onPointerEnter={(event: PointerEvent) => {
if (hover.enter(event)) show();
}}
onPointerLeave={(event: PointerEvent) => {
if (hover.leave(event)) hide();
}}
onFocus={show}
onBlur={hide}
onPointerDown={(event: PointerEvent) => tap.start(event, open)}
// A gesture the platform took away sends no click, and a key press
// starts an activation that never had a pointer behind it. Either way
// the record has to go, or the next click reads a finger that has long
// since lifted.
onPointerCancel={tap.drop}
onKeyDown={tap.drop}
onClick={toggleOnTap}
>
{trigger}
</span>
) : null}
{typeof document !== "undefined"
? createPortal(
<AnimatePresence>
{open && coords ? (
<span
className="pointer-events-none fixed z-[9999]"
style={{
top: coords.top,
left: coords.left,
transform: anchorTransform[side],
}}
>
<TooltipSurface
ref={surfaceRef}
id={id}
side={side}
style={{ transformOrigin: transformOrigin[side], maxWidth: "calc(100vw - 16px)", whiteSpace: "normal" }}
className={className}
>
{content}
</TooltipSurface>
</span>
) : null}
</AnimatePresence>,
document.body,
)
: null}
</>
);
}
"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-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(
"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 { motion, useReducedMotion, type Variants } from "motion/react";
import { useMemo, type ComponentProps, type ReactNode, type Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
// Offset is in the direction *away* from the trigger — content originates near
// the trigger and rises into resting position.
const offsetFrom: Record<Side, { x?: number; y?: number }> = {
top: { y: 8 },
bottom: { y: -8 },
left: { x: 8 },
right: { x: -8 },
};
// Small tooltip surfaces need the lighter spawn used by the original Tooltip.
const TOOLTIP_SPRING = { type: "spring", stiffness: 380, damping: 30, mass: 0.7 } as const;
function buildVariants(side: Side): Variants {
const o = offsetFrom[side];
return {
initial: {
opacity: 0,
scale: 0.9,
filter: "blur(5px)",
x: o.x ?? 0,
y: o.y ?? 0,
},
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
x: 0,
y: 0,
transition: {
...TOOLTIP_SPRING,
opacity: { duration: 0.14, ease: EASE_OUT },
filter: { duration: 0.18, ease: EASE_OUT },
},
},
exit: {
opacity: 0,
scale: 0.94,
filter: "blur(3px)",
x: (o.x ?? 0) * 0.6,
y: (o.y ?? 0) * 0.6,
transition: { duration: 0.12, ease: EASE_OUT },
},
};
}
const REDUCED_VARIANTS: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1, transition: { duration: 0.14, ease: EASE_OUT } },
exit: { opacity: 0, transition: { duration: 0.1, ease: EASE_OUT } },
};
/** The shared visual surface for trigger tooltips and chart readouts. Positioning belongs to the caller. */
export function TooltipSurface({
children,
side = "top",
className,
ref,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
side?: Side;
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion();
const variants = useMemo(() => reduce ? REDUCED_VARIANTS : buildVariants(side), [reduce, side]);
return (
<motion.span
ref={ref}
role="tooltip"
variants={variants}
initial="initial"
animate="animate"
exit="exit"
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
outcomes?PredictionMarketOutcome[][
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
]value?PredictionMarketOrderValue—defaultValue?Partial<PredictionMarketOrderValue>—onValueChange?((value: PredictionMarketOrderValue) => void)—onTrade?((order: PredictionMarketOrderValue, quote: PredictionMarketQuote) => void)—onSignIn?(() => void)—authenticated?booleantrueorderTypeLabel?stringMarketbalance?number500positions?Record<string, number>{ up: 24, down: 16 }quickAmounts?number[][10, 50, 100, 500]minTrade?number1className?string—classNames?PredictionMarketClassNames—Wallet overview card with an account switcher and search that morph open from their triggers, a cascading balance with a live change pill and privacy toggle, copy-address, and Send / Deposit / Swap / Buy actions.
Cross-chain swap widget with chain + token selectors, morphing views, animated flip and quote.
Corner trigger that morphs open into a feedback popup with message entry and animated sending, success and retry states.
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