Prediction Market Trade Ticket
Buy or sell an outcome with a rolling amount and quick add chips.
Preview
"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/trade-ticket
import { Banknote, ChevronDown } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
type CSSProperties,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { type ButtonState, StatefulButton } from "./button/stateful";
import { NumberTicker } from "./number-ticker";
import { Tabs, TabsList, TabsTrigger } from "./tabs";
export type PredictionMarketMode = "buy" | "sell";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const predictionMarketMessages = {
buy: "Buy",
sell: "Sell",
orderType: "Market",
amount: "Amount",
shares: "Shares",
max: "Max",
toWin: "To win",
toReceive: "To receive",
avgPrice: "Avg. Price {price}",
trade: "Trade",
trading: "Trading",
tradeFilled: "Trade filled",
connect: "Connect",
enterAmount: "Enter an amount",
minimum: "Minimum {amount}",
insufficientBalance: "Insufficient balance",
notEnoughShares: "Not enough shares",
};
export type PredictionMarketMessages = typeof predictionMarketMessages;
type Translate = (
key: keyof PredictionMarketMessages,
values?: Record<string, string | number>,
) => string;
export type PredictionMarketOutcome = {
/** Unique key, used as the order's `outcomeId` and the `positions` key. */
id: string;
/** Text on the outcome button. "No" and "Down" are styled red. */
label: string;
/** Price per share from 0 to 1, shown in cents. */
price: number;
};
export type PredictionMarketOrderValue = {
/** Whether the order buys or sells shares. */
mode: PredictionMarketMode;
/** The `id` of the selected outcome. */
outcomeId: string;
/** Raw input text: dollars when buying, shares when selling. */
amount: string;
};
export type PredictionMarketQuote = {
/** Whether the order can be placed. */
valid: boolean;
/** The parsed amount: dollars when buying, shares when selling. */
amount: number;
/** Price per share, clamped between 0.01 and 0.99. */
price: number;
/** Shares bought, or shares sold. */
shares: number;
/** Dollars won if the outcome resolves, or dollars received from a sale. */
payout: number;
/** Why the order is invalid, shown on the trade button. Absent when valid. */
error?: string;
};
export type PredictionMarketClassNames = {
/** Classes for the outer card. */
root?: string;
/** Classes for the top bar with the buy and sell tabs. */
header?: string;
/** Classes for the buy and sell tabs. */
tabs?: string;
/** Classes for the outcome buttons. */
outcomes?: string;
/** Classes for the amount panel with the input and chips. */
amount?: string;
/** Classes for the row of quick amount chips. */
chips?: string;
/** Classes for the footer with the payout and trade button. */
footer?: string;
/** Classes for the trade or connect button. */
action?: string;
};
export interface PredictionMarketProps {
/** Outcomes to trade, each with a price from 0 to 1. Default: Up and Down */
outcomes?: PredictionMarketOutcome[];
/** The order's mode, outcome and amount, for controlled use. */
value?: PredictionMarketOrderValue;
/** The initial order when uncontrolled. Missing fields start as buy, the first outcome and empty. */
defaultValue?: Partial<PredictionMarketOrderValue>;
/** Called with the full order when the mode, outcome or amount changes. */
onValueChange?: (value: PredictionMarketOrderValue) => void;
/** Called with the order and its quote once a valid trade fills. */
onTrade?: (
order: PredictionMarketOrderValue,
quote: PredictionMarketQuote,
) => void;
/** Called when the connect button is pressed while signed out. */
onSignIn?: () => void;
/** Whether the user is signed in. When false, a connect button replaces the trade footer. Default: true */
authenticated?: boolean;
/** Text beside the buy and sell tabs. Default: "Market" */
orderTypeLabel?: string;
/** Cash available to buy with, in dollars. Default: 500 */
balance?: number;
/** Shares held per outcome id, which caps how much can be sold. */
positions?: Record<string, number>;
/** Amounts the quick chips add to the input. Default: [10, 50, 100, 500] */
quickAmounts?: number[];
/** Smallest buy amount, in dollars. Default: 1 */
minTrade?: number;
/** Override any built-in string. `{price}` fills `avgPrice`, `{amount}` fills `minimum`. */
labels?: Partial<PredictionMarketMessages>;
/** Classes merged onto the root element. */
className?: string;
/** Classes for each inner part, keyed by slot. */
classNames?: PredictionMarketClassNames;
}
const DEFAULT_OUTCOMES: PredictionMarketOutcome[] = [
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
];
const MODES: PredictionMarketMode[] = ["buy", "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,
t,
}: {
order: PredictionMarketOrderValue;
outcome: PredictionMarketOutcome;
balance: number;
position: number;
minTrade: number;
t: Translate;
}): 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: t("enterAmount"),
};
}
if (order.mode === "buy" && amount < minTrade) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("minimum", { amount: formatCompactCurrency(minTrade) }),
};
}
if (order.mode === "buy" && amount > balance) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("insufficientBalance"),
};
}
if (order.mode === "sell" && amount > position) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("notEnoughShares"),
};
}
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,
label,
onChange,
}: {
id: string;
value: string;
mode: PredictionMarketMode;
inputSize: string;
disabled: boolean;
reduce: boolean;
label: string;
onChange: (value: string) => void;
}) {
const displayValue = value || "0";
const chars = keyedAmountChars(displayValue);
const inputStyle = {
"--amount-chars": String(chars.length),
} as AmountInputStyle;
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,
balance = 500,
positions = { up: 24, down: 16 },
quickAmounts = DEFAULT_QUICK_AMOUNTS,
minTrade = 1,
labels,
className,
classNames,
}: PredictionMarketProps) {
const t = useMessages("predictionMarket", predictionMarketMessages, labels);
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,
t,
}),
[balance, minTrade, order, position, selectedOutcome, t],
);
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;
const amountLabel = order.mode === "buy" ? t("amount") : t("shares");
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}
value={mode}
className="px-0 pb-3 pt-0 text-2xl font-medium"
indicatorClassName="h-0.5 bg-primary"
>
{t(mode)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<button
type="button"
disabled={status === "placing"}
className="mb-3 inline-flex items-center gap-2 text-xl font-medium text-foreground transition-opacity disabled:opacity-50"
>
{orderTypeLabel ?? t("orderType")}
<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-full px-0 py-0 text-base font-medium 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-2xl 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"
>
{amountLabel}
</label>
<div className="w-full min-w-0">
<AnimatedAmountInput
id={inputId}
mode={order.mode}
value={order.amount}
disabled={status === "placing"}
inputSize={inputSize}
reduce={reduce}
label={amountLabel}
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-full bg-background px-3.5 text-sm font-medium 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-full bg-background px-3.5 text-sm font-medium text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
{t("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-medium text-foreground">
{order.mode === "buy" ? t("toWin") : t("toReceive")}
<Banknote className="h-5 w-5 text-emerald-500" />
</div>
<p className="text-sm font-medium text-muted-foreground">
{t("avgPrice", { 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={t("trading")}
successText={t("tradeFilled")}
errorText={quote.error ?? t("enterAmount")}
className={cn(
"h-12 w-full rounded-full text-base font-medium",
classNames?.action,
)}
>
{t("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-full text-base font-medium",
classNames?.action,
)}
>
{t("connect")}
</StatefulButton>
</div>
)}
</div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] 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;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
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 {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import {
registerSoundSettings,
retainAudioContext,
type SoundSettingsEntry,
} from "@/lib/audio-context";
import type { PlayOptions, Sound } from "@/lib/sounds/engine";
export interface SoundSettings {
/** False mutes every beUI sound under the provider. */
enabled: boolean;
/** 0 to 1, scales every beUI sound. */
volume: number;
}
const SoundContext = createContext<SoundSettings & { depth: number }>({
enabled: true,
volume: 1,
depth: 0,
});
/**
* App-wide sound settings. `enabled={false}` mutes every beUI sound, from
* component `sound` props and `useSound` to the games, Wheel Picker and
* Bookshelf, and `volume` scales them all. Without a provider, sounds play at
* full volume. A nested provider overrides the one around it.
*/
export function SoundProvider({
enabled = true,
volume = 1,
children,
}: Partial<SoundSettings> & { children: ReactNode }) {
const depth = useContext(SoundContext).depth + 1;
const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);
// Module-level as well (lib/audio-context.ts), so players outside React
// and `sound.play()` obey it too.
const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });
const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);
useEffect(() => {
registration.current = registerSoundSettings(entry.current);
return () => {
registration.current?.release();
registration.current = null;
};
}, []);
useEffect(() => {
Object.assign(entry.current, { depth, enabled, volume });
registration.current?.update();
}, [depth, enabled, volume]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}
export function useSoundSettings(): SoundSettings {
return useContext(SoundContext);
}
export interface UseSoundOptions {
/** False makes `play` do nothing, for a component's `sound` prop. */
enabled?: boolean;
/** 0 to 1 for this sound, on top of the provider volume. */
volume?: number;
}
/**
* A stable `play()` for one sound. It does nothing while disabled or muted,
* and keeps the shared audio context warm only while it can play.
*/
export function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {
const settings = useSoundSettings();
const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;
// Read by the stable callback, so a caller's effects don't re-run when
// the settings change.
const latest = useRef({ on, volume, sound });
useLayoutEffect(() => {
latest.current = { on, volume, sound };
});
useEffect(() => {
if (!on) return;
return retainAudioContext();
}, [on]);
return useCallback((options?: PlayOptions) => {
const current = latest.current;
if (!current.on) return;
current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });
}, []);
}
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* 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";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// 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.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: 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" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"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;
},
}),
[],
);
}
import type { Ref } from "react";
/** Points a callback or object ref at `value`. */
export function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
/** One callback ref that sets every ref it is given. */
export function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) assignRef(ref, node);
};
}
import { defineSound } from "./engine";
/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */
export const pressSound = defineSound({
name: "Press",
duration: 0.1,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });
v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });
v.strike({ freq: 150, material: "wood", bend: 1.5, decay: 0.07, gain: 0.75 });
v.strike({ freq: 1250, material: "plastic", decay: 0.022, gain: 0.14 });
},
});
// One AudioContext for every synthesized sound on the page: the sounds
// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino
// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap
// concurrent contexts, and a page can show a date made of several WheelPickers
// next to a game, so they all share this one. It is created on first use and
// closed once every player is disposed.
//
// Every player connects to `audioOutput()` rather than the context's
// destination, so the page-wide volume and mute from `SoundProvider`
// (lib/sound.tsx) reach all of them in one place.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let master: GainNode | null = null;
let users = 0;
/** Settings one mounted `SoundProvider` asks for. */
export interface SoundSettingsEntry {
/** Nesting depth: the deepest provider decides. */
depth: number;
enabled: boolean;
volume: number;
}
// Mounted providers in mount order. Module state, so `sound.play()` called
// outside React obeys them too. The deepest provider wins; among equals, the
// one mounted last. Effects run child first, so this can't be "whoever ran
// last".
const providers = new Set<SoundSettingsEntry>();
let allowed = true;
let volume = 1;
function applySettings() {
let chosen: SoundSettingsEntry | undefined;
for (const entry of providers) {
if (!chosen || entry.depth >= chosen.depth) chosen = entry;
}
allowed = chosen?.enabled ?? true;
volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));
if (master) master.gain.value = volume;
}
/**
* Registers a provider's settings; call `update` after changing the entry and
* the returned release function when the provider unmounts.
*/
export function registerSoundSettings(entry: SoundSettingsEntry) {
providers.add(entry);
applySettings();
return {
update: applySettings,
release() {
providers.delete(entry);
applySettings();
},
};
}
/**
* Registers a sound player. Call the returned function when the player is
* disposed; the context closes after the last one.
*/
export function retainAudioContext() {
users++;
let released = false;
return () => {
if (released) return;
released = true;
users--;
if (users === 0 && context) {
void context.close();
context = null;
master = null;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR, in browsers without Web Audio, and while sounds are muted or at
* zero volume.
*/
export function getAudioContext(): AudioContext | null {
if (!allowed || volume <= 0) return null;
if (!context) {
if (typeof window === "undefined") return null;
const Ctor =
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
}
// Browsers may refuse outside a user gesture. Players call this from
// pointer and key handlers first, so a later call finds it running.
if (context.state === "suspended") void context.resume().catch(() => undefined);
return context;
}
/** The node every player connects to: the page-wide volume, then the speakers. */
export function audioOutput(ctx: AudioContext): AudioNode {
if (master?.context !== ctx) {
master = ctx.createGain();
master.gain.value = volume;
master.connect(ctx.destination);
}
return master;
}
const gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();
/**
* A player's own level, made once per context and routed into `audioOutput`.
* Players keep their mix this way without rebuilding nodes on every play, and
* a context closed and recreated gets fresh ones.
*/
export function playerGain(ctx: AudioContext, key: string, level: number): GainNode {
let byKey = gains.get(ctx);
if (!byKey) {
byKey = new Map();
gains.set(ctx, byKey);
}
let gain = byKey.get(key);
if (!gain) {
gain = ctx.createGain();
gain.gain.value = level;
gain.connect(audioOutput(ctx));
byKey.set(key, gain);
}
return gain;
}
import { audioOutput, getAudioContext } from "@/lib/audio-context";
// Every beUI sound is a short recipe played with Web Audio the moment it is
// asked for. Nothing is downloaded. Recipes are built the way a real tap
// sounds: a contact click (a millisecond of filtered noise), a body that
// rings at a few inharmonic partials of a material and settles in pitch, and
// a little of a small room behind it.
/** Options for one play of a sound. */
export interface PlayOptions {
/** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */
volume?: number;
/** Pitch multiplier; 1 is the designed pitch. */
pitch?: number;
}
/** Where a sound renders: the live context, or an offline one for drawing. */
export interface SoundTarget {
context: BaseAudioContext;
destination: AudioNode;
/** Start time on the context clock, in seconds. */
when: number;
volume: number;
pitch: number;
}
/** A plain oscillator with an attack, a decay and an optional glide. */
export interface ToneSpec {
type?: OscillatorType;
/** Start frequency in Hz. */
freq: number;
/** End frequency in Hz; glides from `freq` over `glide`. */
to?: number;
/** Glide time in seconds; defaults to the attack plus decay. */
glide?: number;
/** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** A burst of filtered white noise. */
export interface NoiseSpec {
filter?: BiquadFilterType;
/** Filter frequency in Hz. */
freq: number;
/** End filter frequency in Hz; sweeps from `freq` over the decay. */
to?: number;
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */
export interface ClickSpec {
/** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */
freq: number;
/** Band width; higher is narrower and more tonal. */
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time to fade to silence, in seconds. */
decay?: number;
gain: number;
}
/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */
export interface Material {
partials: readonly (readonly [ratio: number, level: number])[];
/** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */
damping: number;
}
// Partial ratios follow the modes of small struck objects: a free bar for
// wood and metal, a cup for glass, a tuned bar for the mallet.
export const MATERIALS = {
wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },
plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },
glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },
metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },
mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },
bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },
} satisfies Record<string, Material>;
/** A struck object: one partial per mode of its material, each with its own decay. */
export interface StrikeSpec {
/** Fundamental in Hz. */
freq: number;
/** A name from `MATERIALS` or your own partials. Default: "plastic". */
material?: keyof typeof MATERIALS | Material;
/** Starts this many times higher and settles in about 15 ms. Default: 1.01. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time for the fundamental to fade to silence, in seconds. */
decay: number;
gain: number;
}
export interface Voice {
tone(spec: ToneSpec): void;
noise(spec: NoiseSpec): void;
click(spec: ClickSpec): void;
strike(spec: StrikeSpec): void;
}
export interface Sound {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Plays the sound now. Silent during SSR and while sounds are muted. */
play(options?: PlayOptions): void;
/** Schedules the sound on any context; `play` uses the live one. */
render(target: SoundTarget): void;
}
export interface SoundRecipe {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */
vary?: number;
/** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */
room?: number;
/** Adds the sound's layers to the voice on each play. */
build: (voice: Voice) => void;
}
// Keeps a sum of voices well under clipping at volume 1.
const MASTER_GAIN = 0.16;
const SILENT = 0.0001;
// Time a strike or bend takes to settle onto its pitch.
const SETTLE = 0.015;
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
/** One second of white noise per context, shared by every noise voice. */
export function noiseBuffer(context: BaseAudioContext) {
let buffer = noiseBuffers.get(context);
if (!buffer) {
buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(context, buffer);
}
return buffer;
}
// A small, soft room: 8 early reflections, then a diffuse tail that falls
// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls
// absorb highs first. Generated once per context.
const ROOM_LENGTH = 0.3;
// The convolver's equal-power normalization leaves the room about 15 dB
// under the dry sound; this brings `room: 0.12` to a tail heard only as space.
const ROOM_GAIN = 6;
const roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function roomBuffer(context: BaseAudioContext) {
let buffer = roomBuffers.get(context);
if (!buffer) {
const rate = context.sampleRate;
const length = Math.ceil(ROOM_LENGTH * rate);
buffer = context.createBuffer(2, length, rate);
for (let channel = 0; channel < 2; channel++) {
const data = buffer.getChannelData(channel);
let smooth = 0;
for (let i = Math.floor(0.004 * rate); i < length; i++) {
const t = i / rate;
// One-pole low-pass whose cutoff closes over the tail.
const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;
smooth += brightness * (Math.random() * 2 - 1 - smooth);
data[i] = smooth * Math.exp(-t / 0.043);
}
for (let r = 0; r < 8; r++) {
const at = Math.floor((0.005 + Math.random() * 0.022) * rate);
data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);
}
}
roomBuffers.set(context, buffer);
}
return buffer;
}
// One convolver per output node, shared by every play: building one is the
// expensive part, sending to it is cheap.
const rooms = new WeakMap<AudioNode, ConvolverNode>();
function roomFor(context: BaseAudioContext, destination: AudioNode) {
let room = rooms.get(destination);
if (!room) {
room = context.createConvolver();
room.buffer = roomBuffer(context);
room.connect(destination);
rooms.set(destination, room);
}
return room;
}
/** A linear attack to `peak`, then an exponential fall to silence. */
function envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {
param.setValueAtTime(0, start);
param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);
param.exponentialRampToValueAtTime(SILENT, start + attack + decay);
}
function voiceFor(target: SoundTarget, output: AudioNode): Voice {
const { context, when, pitch } = target;
// Partials above this only add hiss on small speakers, or alias near Nyquist.
const ceiling = Math.min(12000, context.sampleRate * 0.45);
const tone: Voice["tone"] = ({ type = "sine", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const osc = context.createOscillator();
const amp = context.createGain();
osc.type = type;
const base = freq * pitch;
osc.frequency.setValueAtTime(base * (bend ?? 1), start);
if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);
if (to !== undefined) {
osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));
}
envelope(amp.gain, start, attack, decay, gain);
osc.connect(amp).connect(output);
osc.start(start);
osc.stop(start + attack + decay + 0.02);
};
const noise: Voice["noise"] = ({ filter = "bandpass", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const source = context.createBufferSource();
const shape = context.createBiquadFilter();
const amp = context.createGain();
source.buffer = noiseBuffer(context);
shape.type = filter;
shape.Q.value = q;
shape.frequency.setValueAtTime(freq * pitch, start);
if (to !== undefined) {
shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);
}
envelope(amp.gain, start, attack, decay, gain);
source.connect(shape).connect(amp).connect(output);
// A random offset into the buffer keeps each burst a little different.
source.start(start, Math.random() * 0.5);
source.stop(start + attack + decay + 0.02);
};
return {
tone,
noise,
click({ freq, q = 2, at = 0, decay = 0.005, gain }) {
// A little spread on the band, so no two contacts are identical.
noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });
},
strike({ freq, material = "plastic", bend = 1.01, at = 0, decay, gain }) {
const { partials, damping } = typeof material === "string" ? MATERIALS[material] : material;
for (const [ratio, level] of partials) {
if (freq * ratio * pitch * bend > ceiling) continue;
tone({
// Real objects are never perfectly tuned; a hair of detune per partial.
freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),
bend,
at,
attack: 0.001,
decay: decay / ratio ** damping,
gain: gain * level,
});
}
},
};
}
/** Turns a recipe into a playable sound. */
export function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {
const render = (target: SoundTarget) => {
const { context, destination } = target;
const output = context.createGain();
output.gain.value = MASTER_GAIN * target.volume;
output.connect(destination);
if (room > 0) {
const send = context.createGain();
send.gain.value = room * ROOM_GAIN;
output.connect(send).connect(roomFor(context, destination));
}
build(voiceFor(target, output));
};
return {
name,
duration,
render,
play({ volume = 1, pitch = 1 } = {}) {
const context = getAudioContext();
if (!context || volume <= 0) return;
const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;
render({
context,
// The page-wide volume is applied there.
destination: audioOutput(context),
when: context.currentTime + 0.005,
volume,
pitch: pitch * spread,
});
},
};
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
// 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;
Copy the source code
"use client";
// beui.dev/components/blocks/prediction-market/trade-ticket
import { Banknote, ChevronDown } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
type CSSProperties,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { type ButtonState, StatefulButton } from "./button/stateful";
import { NumberTicker } from "./number-ticker";
import { Tabs, TabsList, TabsTrigger } from "./tabs";
export type PredictionMarketMode = "buy" | "sell";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const predictionMarketMessages = {
buy: "Buy",
sell: "Sell",
orderType: "Market",
amount: "Amount",
shares: "Shares",
max: "Max",
toWin: "To win",
toReceive: "To receive",
avgPrice: "Avg. Price {price}",
trade: "Trade",
trading: "Trading",
tradeFilled: "Trade filled",
connect: "Connect",
enterAmount: "Enter an amount",
minimum: "Minimum {amount}",
insufficientBalance: "Insufficient balance",
notEnoughShares: "Not enough shares",
};
export type PredictionMarketMessages = typeof predictionMarketMessages;
type Translate = (
key: keyof PredictionMarketMessages,
values?: Record<string, string | number>,
) => string;
export type PredictionMarketOutcome = {
/** Unique key, used as the order's `outcomeId` and the `positions` key. */
id: string;
/** Text on the outcome button. "No" and "Down" are styled red. */
label: string;
/** Price per share from 0 to 1, shown in cents. */
price: number;
};
export type PredictionMarketOrderValue = {
/** Whether the order buys or sells shares. */
mode: PredictionMarketMode;
/** The `id` of the selected outcome. */
outcomeId: string;
/** Raw input text: dollars when buying, shares when selling. */
amount: string;
};
export type PredictionMarketQuote = {
/** Whether the order can be placed. */
valid: boolean;
/** The parsed amount: dollars when buying, shares when selling. */
amount: number;
/** Price per share, clamped between 0.01 and 0.99. */
price: number;
/** Shares bought, or shares sold. */
shares: number;
/** Dollars won if the outcome resolves, or dollars received from a sale. */
payout: number;
/** Why the order is invalid, shown on the trade button. Absent when valid. */
error?: string;
};
export type PredictionMarketClassNames = {
/** Classes for the outer card. */
root?: string;
/** Classes for the top bar with the buy and sell tabs. */
header?: string;
/** Classes for the buy and sell tabs. */
tabs?: string;
/** Classes for the outcome buttons. */
outcomes?: string;
/** Classes for the amount panel with the input and chips. */
amount?: string;
/** Classes for the row of quick amount chips. */
chips?: string;
/** Classes for the footer with the payout and trade button. */
footer?: string;
/** Classes for the trade or connect button. */
action?: string;
};
export interface PredictionMarketProps {
/** Outcomes to trade, each with a price from 0 to 1. Default: Up and Down */
outcomes?: PredictionMarketOutcome[];
/** The order's mode, outcome and amount, for controlled use. */
value?: PredictionMarketOrderValue;
/** The initial order when uncontrolled. Missing fields start as buy, the first outcome and empty. */
defaultValue?: Partial<PredictionMarketOrderValue>;
/** Called with the full order when the mode, outcome or amount changes. */
onValueChange?: (value: PredictionMarketOrderValue) => void;
/** Called with the order and its quote once a valid trade fills. */
onTrade?: (
order: PredictionMarketOrderValue,
quote: PredictionMarketQuote,
) => void;
/** Called when the connect button is pressed while signed out. */
onSignIn?: () => void;
/** Whether the user is signed in. When false, a connect button replaces the trade footer. Default: true */
authenticated?: boolean;
/** Text beside the buy and sell tabs. Default: "Market" */
orderTypeLabel?: string;
/** Cash available to buy with, in dollars. Default: 500 */
balance?: number;
/** Shares held per outcome id, which caps how much can be sold. */
positions?: Record<string, number>;
/** Amounts the quick chips add to the input. Default: [10, 50, 100, 500] */
quickAmounts?: number[];
/** Smallest buy amount, in dollars. Default: 1 */
minTrade?: number;
/** Override any built-in string. `{price}` fills `avgPrice`, `{amount}` fills `minimum`. */
labels?: Partial<PredictionMarketMessages>;
/** Classes merged onto the root element. */
className?: string;
/** Classes for each inner part, keyed by slot. */
classNames?: PredictionMarketClassNames;
}
const DEFAULT_OUTCOMES: PredictionMarketOutcome[] = [
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
];
const MODES: PredictionMarketMode[] = ["buy", "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,
t,
}: {
order: PredictionMarketOrderValue;
outcome: PredictionMarketOutcome;
balance: number;
position: number;
minTrade: number;
t: Translate;
}): 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: t("enterAmount"),
};
}
if (order.mode === "buy" && amount < minTrade) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("minimum", { amount: formatCompactCurrency(minTrade) }),
};
}
if (order.mode === "buy" && amount > balance) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("insufficientBalance"),
};
}
if (order.mode === "sell" && amount > position) {
return {
valid: false,
amount,
price,
shares,
payout,
error: t("notEnoughShares"),
};
}
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,
label,
onChange,
}: {
id: string;
value: string;
mode: PredictionMarketMode;
inputSize: string;
disabled: boolean;
reduce: boolean;
label: string;
onChange: (value: string) => void;
}) {
const displayValue = value || "0";
const chars = keyedAmountChars(displayValue);
const inputStyle = {
"--amount-chars": String(chars.length),
} as AmountInputStyle;
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,
balance = 500,
positions = { up: 24, down: 16 },
quickAmounts = DEFAULT_QUICK_AMOUNTS,
minTrade = 1,
labels,
className,
classNames,
}: PredictionMarketProps) {
const t = useMessages("predictionMarket", predictionMarketMessages, labels);
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,
t,
}),
[balance, minTrade, order, position, selectedOutcome, t],
);
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;
const amountLabel = order.mode === "buy" ? t("amount") : t("shares");
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}
value={mode}
className="px-0 pb-3 pt-0 text-2xl font-medium"
indicatorClassName="h-0.5 bg-primary"
>
{t(mode)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<button
type="button"
disabled={status === "placing"}
className="mb-3 inline-flex items-center gap-2 text-xl font-medium text-foreground transition-opacity disabled:opacity-50"
>
{orderTypeLabel ?? t("orderType")}
<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-full px-0 py-0 text-base font-medium 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-2xl 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"
>
{amountLabel}
</label>
<div className="w-full min-w-0">
<AnimatedAmountInput
id={inputId}
mode={order.mode}
value={order.amount}
disabled={status === "placing"}
inputSize={inputSize}
reduce={reduce}
label={amountLabel}
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-full bg-background px-3.5 text-sm font-medium 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-full bg-background px-3.5 text-sm font-medium text-foreground transition-[background-color,transform] duration-150 active:scale-95 disabled:pointer-events-none disabled:opacity-50"
>
{t("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-medium text-foreground">
{order.mode === "buy" ? t("toWin") : t("toReceive")}
<Banknote className="h-5 w-5 text-emerald-500" />
</div>
<p className="text-sm font-medium text-muted-foreground">
{t("avgPrice", { 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={t("trading")}
successText={t("tradeFilled")}
errorText={quote.error ?? t("enterAmount")}
className={cn(
"h-12 w-full rounded-full text-base font-medium",
classNames?.action,
)}
>
{t("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-full text-base font-medium",
classNames?.action,
)}
>
{t("connect")}
</StatefulButton>
</div>
)}
</div>
);
}
"use client";
// beui.dev/components/blocks/prediction-market/trade-ticket
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 { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { ActionSwapText } from "./action-swap";
import { Tooltip } from "./tooltip";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const predictionMarketCardMessages = {
payoutHint:
"Potential payout per $1 if this outcome wins, including your stake. Before fees; based on the displayed price.",
payoutFor: "Potential payout for {outcome}",
volume: "{volume} vol.",
bookmark: "Bookmark {title}",
trade: "Trade {outcome} at {percent}%",
percent: "{percent}%",
yes: "Yes",
no: "No",
};
export type PredictionMarketCardMessages = typeof predictionMarketCardMessages;
export interface PredictionMarketCardOutcome {
/** Unique key, sent back as `outcomeId` when the outcome is picked. */
id: string;
/** Outcome name shown in the row and the trade button's accessible name. */
label: string;
/** Probability between 0 and 1. */
probability: number;
/** Image or icon shown in a round frame before the label. */
icon?: ReactNode;
/** Optional team color for the compact probability line. */
color?: string;
}
export interface PredictionMarketCardSelection {
/** The `id` of the outcome that was picked. */
outcomeId: string;
/** The side picked. The card's outcome buttons always send "yes". */
side: "yes" | "no";
}
export interface PredictionMarketCardProps {
/** Market question shown as the card heading. */
title: string;
/** Image or icon shown in a round frame beside the title. */
icon?: ReactNode;
/** Category label shown under the title, after the status. */
category?: string;
/** Preformatted trading volume shown in the footer, e.g. "$2.4M". */
volume: string;
/** Chronological volume samples for the optional footer sparkline. */
volumeHistory?: number[];
/** A scheduled time or live match status. */
status?: string;
/** Show the status in red with a dot, for a match in progress. Default: false */
live?: boolean;
/** Outcomes listed with their probability, payout and trade button. */
outcomes: PredictionMarketCardOutcome[];
/** Called on each outcome CTA click; the card keeps no selected state. */
onOutcomeClick?: (value: PredictionMarketCardSelection) => void;
/** Whether the market is bookmarked, for controlled use. */
bookmarked?: boolean;
/** The initial bookmark state when uncontrolled. Default: false */
defaultBookmarked?: boolean;
/** Called with the new state when the bookmark button is pressed. */
onBookmarkChange?: (bookmarked: boolean) => void;
/** Override any built-in string. */
labels?: Partial<PredictionMarketCardMessages>;
/** Classes merged onto the root element. */
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,
labels,
className,
}: PredictionMarketCardProps) {
const t = useMessages(
"predictionMarketCard",
predictionMarketCardMessages,
labels,
);
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-2xl 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={t("payoutHint")}
className="w-44 whitespace-normal text-center leading-relaxed"
>
<button
type="button"
aria-label={t("payoutFor", { outcome: outcome.label })}
className="-mx-2 shrink-0 rounded-full px-2 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}
t={t}
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">{t("volume", { volume })}</span>
<motion.button
type="button"
aria-label={t("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-full 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,
t,
onClick,
}: {
outcome: PredictionMarketCardOutcome;
positive: boolean;
t: (
key: keyof PredictionMarketCardMessages,
values?: Record<string, string | number>,
) => string;
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={t("trade", { outcome: outcome.label, percent: 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-full border border-border bg-background px-3 text-sm font-medium 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
? t("yes")
: t("no")
: t("percent", { percent: 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 { useMessages } from "@/lib/i18n";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const statefulButtonMessages = {
loading: "Loading",
success: "Done",
error: "Try again",
};
export type StatefulButtonMessages = typeof statefulButtonMessages;
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
/** Which state to show. Loading also disables the button. Default: "idle" */
state?: ButtonState;
children: ReactNode;
/** Text shown while loading. Default: "Loading" */
loadingText?: ReactNode;
/** Text shown on success. Default: "Done" */
successText?: ReactNode;
/** Text shown on error. Default: "Try again" */
errorText?: ReactNode;
/** Trailing icon shown only while idle. */
icon?: ReactNode;
/** Override any built-in string. */
labels?: Partial<StatefulButtonMessages>;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText,
successText,
errorText,
icon,
labels,
disabled,
...rest
},
ref,
) {
const t = useMessages("statefulButton", statefulButtonMessages, labels);
const isBusy = state === "loading";
const stateText =
state === "loading"
? (loadingText ?? t("loading"))
: state === "success"
? (successText ?? t("success"))
: state === "error"
? (errorText ?? t("error"))
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...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 { useLocale } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export interface NumberTickerProps {
/** Number to show. Digits roll to it when it changes. */
value: number;
/** Digits to pad to (left). */
pad?: number;
/**
* Fraction digits to keep. The value is rounded to this many places before
* `format` runs (default 0, whole numbers).
*/
decimals?: number;
/** Per-digit roll duration in seconds. */
duration?: number;
/** Stagger between digits. */
stagger?: number;
/** Render only after the element enters the viewport. */
startOnView?: boolean;
/** Static text before the number, such as "$". */
prefix?: string;
/** Static text after the number, such as "%". */
suffix?: string;
/** Add a small blur during digit rolls. */
blur?: boolean;
/** Classes merged onto the root element. */
className?: string;
/** Classes merged onto each rolling digit. */
digitClassName?: string;
/**
* Insert locale group separators. `true` uses the `LocaleProvider` locale
* (or the runtime default without one); a BCP 47 tag such as `"de-DE"` pins it.
*/
locale?: boolean | string;
/** 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,
decimals = 0,
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);
const { locale: contextLocale } = useLocale();
useEffect(() => {
if (startOnView && inView) setArmed(true);
}, [startOnView, inView]);
const text = useMemo(() => {
const places = Math.max(0, Math.floor(decimals));
const factor = 10 ** places;
const rounded = Math.round(value * factor) / factor;
const formatted = format
? format(rounded)
: locale
? rounded.toLocaleString(typeof locale === "string" ? locale : contextLocale, {
minimumFractionDigits: places,
maximumFractionDigits: places,
})
: rounded.toFixed(places);
return pad ? formatted.padStart(pad, "0") : formatted;
}, [value, pad, decimals, format, locale, contextLocale]);
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-baseline tabular-nums", className)}
>
<span className="sr-only">{readableText}</span>
<span aria-hidden="true" className="inline-flex items-baseline">
{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 (
// The invisible in-flow digit gives the slot a real text baseline so it
// lines up with surrounding text; clip-path clips the rolling column
// without moving that baseline the way overflow: hidden would.
<span
className={cn(
"relative inline-block text-center [clip-path:inset(0)]",
className,
)}
style={{
height: `${DIGIT_HEIGHT_EM}em`,
lineHeight: `${DIGIT_HEIGHT_EM}em`,
width: "1ch",
}}
>
<span className="invisible">{digit}</span>
<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 { ChevronLeft, ChevronRight } from "lucide-react";
import { cancelFrame, frame, motion, MotionConfig, useReducedMotion, useSpring, type MotionValue, type Transition } from "motion/react";
import {
createContext,
useCallback,
useContext,
useId,
useLayoutEffect,
useRef,
useMemo,
useState,
type ButtonHTMLAttributes,
type HTMLAttributes,
type KeyboardEvent,
type ReactNode,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { useSound } from "@/lib/sound";
import { selectSound } from "@/lib/sounds/select";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const tabsMessages = {
scrollLeft: "Scroll tabs left",
scrollRight: "Scroll tabs right",
};
export type TabsMessages = typeof tabsMessages;
type Variant = "pill" | "underline" | "segment";
/** Whether trigger icons show on every tab or only on the selected one. */
type IconDisplay = "always" | "selected";
type Ctx = {
value: string;
setValue: (v: string) => void;
layoutId: string;
variant: Variant;
icons: IconDisplay;
/** The pill's box in the list, for tabs whose width changes as they're selected. */
track: Track;
/** Whether the tracked pill has been measured; until then CSS places it. */
placed: boolean;
setPlaced: (placed: boolean) => void;
/**
* The one tab Tab reaches: the selected tab, or the first enabled one when
* nothing enabled is selected. `null` until the triggers have registered,
* when every enabled tab stays reachable.
*/
tabStop: string | null;
registerTab: (value: string, disabled: boolean) => void;
unregisterTab: (value: string) => void;
/** Values with a mounted panel, so triggers only point at panels that exist. */
panels: ReadonlySet<string>;
registerPanel: (value: string) => void;
unregisterPanel: (value: string) => void;
tabId: (value: string) => string;
panelId: (value: string) => string;
t: (key: keyof TabsMessages) => string;
};
type Track = Record<"x" | "y" | "width" | "height", MotionValue<number>>;
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.
// Scale stiffness and damping together for a quicker glide with the same feel.
const transition: Transition = {
type: "spring",
stiffness: 245,
damping: 36,
mass: 1.2,
};
/**
* Pass a union of tab values as `T` (or let `value` infer it) and
* `onValueChange` receives that union. Every trigger's `value` must be one of
* them.
*/
export function Tabs<T extends string = string>({
defaultValue,
value,
onValueChange,
variant = "pill",
icons = "always",
labels,
sound = false,
children,
className,
}: {
/** The tab selected at first when uncontrolled. */
defaultValue?: T;
/** The selected tab's value, for controlled use. */
value?: T;
/** Called with the tab's value when a tab is picked. */
onValueChange?: (v: T) => void;
/** Selection style: "pill", "underline" or "segment". Default: "pill" */
variant?: Variant;
/**
* With "selected", a trigger's icon springs open only on the selected tab
* and folds away when another is chosen. Defaults to "always".
*/
icons?: IconDisplay;
/** Override any built-in string. */
labels?: Partial<TabsMessages>;
/** Play a soft tick when the user picks another tab. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
children: ReactNode;
className?: string;
}) {
const t = useMessages("tabs", tabsMessages, labels);
const [internal, setInternal] = useState<string>(defaultValue ?? "");
const layoutId = useId();
const reduce = useReducedMotion();
const controlled = value !== undefined;
const current = controlled ? value : internal;
const play = useSound(selectSound, { enabled: sound });
const setValue = useCallback(
(v: string) => {
if (v !== current) play();
if (!controlled) setInternal(v);
// Triggers only carry values from `T`, so the string is one of them.
onValueChange?.(v as T);
},
[controlled, onValueChange, current, play],
);
const x = useSpring(0, transition);
const y = useSpring(0, transition);
const width = useSpring(0, transition);
const height = useSpring(0, transition);
const track = useMemo(() => ({ x, y, width, height }), [x, y, width, height]);
const [placed, setPlaced] = useState(false);
const [tabs, setTabs] = useState<Map<string, boolean>>(new Map());
const registerTab = useCallback((tab: string, disabled: boolean) => {
setTabs((map) => (map.get(tab) === disabled ? map : new Map(map).set(tab, disabled)));
}, []);
const unregisterTab = useCallback((tab: string) => {
setTabs((map) => {
if (!map.has(tab)) return map;
const next = new Map(map);
next.delete(tab);
return next;
});
}, []);
const [panels, setPanels] = useState<ReadonlySet<string>>(new Set());
const registerPanel = useCallback((panel: string) => {
setPanels((set) => (set.has(panel) ? set : new Set(set).add(panel)));
}, []);
const unregisterPanel = useCallback((panel: string) => {
setPanels((set) => {
if (!set.has(panel)) return set;
const next = new Set(set);
next.delete(panel);
return next;
});
}, []);
// Resolved during render so the list has exactly one tab stop in the same
// commit that changes the selection or the tabs.
let tabStop: string | null = null;
if (tabs.size > 0) {
const enabled = Array.from(tabs).filter(([, disabled]) => !disabled);
tabStop = enabled.some(([tab]) => tab === current) ? current : (enabled[0]?.[0] ?? "");
}
const baseId = useId();
const tabId = useCallback((tab: string) => `${baseId}-tab-${tab.replace(/[^\w-]/g, "_")}`, [baseId]);
const panelId = useCallback((tab: string) => `${baseId}-panel-${tab.replace(/[^\w-]/g, "_")}`, [baseId]);
const contextValue = useMemo(
() => ({
value: current,
setValue,
layoutId,
variant,
icons,
track,
placed,
setPlaced,
tabStop,
registerTab,
unregisterTab,
panels,
registerPanel,
unregisterPanel,
tabId,
panelId,
t,
}),
[current, icons, layoutId, setValue, variant, track, placed, tabStop, registerTab, unregisterTab, panels, registerPanel, unregisterPanel, tabId, panelId, t],
);
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-full bg-card p-0.5",
};
export function TabsList({
children,
className,
wrapperClassName,
onKeyDown,
...props
}: {
wrapperClassName?: string;
} & HTMLAttributes<HTMLDivElement>) {
const { variant, value, icons, track, placed, setPlaced, t } = useTabs();
const reduce = useReducedMotion();
const tracked = icons === "selected" && variant !== "underline";
const rootRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const viewportId = useId();
const [edges, setEdges] = useState({ overflow: false, left: false, right: false });
const measure = useCallback(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
if (!root || !viewport) return;
// Overlay controls do not reduce the viewport or change its scroll range.
const overflow = viewport.scrollWidth > root.clientWidth + 1;
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
// Modern browsers expose negative scrollLeft in RTL. Clamp rubber-banding.
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
const next = { overflow, left: fromLeft > 1, right: fromLeft < max - 1 };
setEdges((previous) => previous.overflow === next.overflow && previous.left === next.left && previous.right === next.right ? previous : next);
}, []);
const reveal = useCallback((tab: HTMLElement | null) => {
const viewport = viewportRef.current;
if (!viewport || !tab) return;
const frame = viewport.getBoundingClientRect();
const item = tab.getBoundingClientRect();
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
// Keep the selected/focused label clear of the arrows over the faded edges.
const left = frame.left + (fromLeft > 1 ? 36 : 0);
const right = frame.right - (fromLeft < max - 1 ? 36 : 0);
const delta = item.left < left ? item.left - left : item.right > right ? item.right - right : 0;
// Scroll only this viewport; scrollIntoView can also move the whole page.
if (delta) viewport.scrollBy({ left: delta, behavior: reduce ? "instant" : "smooth" });
}, [reduce]);
useLayoutEffect(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
const list = listRef.current;
if (!root || !viewport || !list) return;
const update = () => {
measure();
reveal(list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'));
};
const observer = new ResizeObserver(update);
observer.observe(root);
observer.observe(viewport);
observer.observe(list);
viewport.addEventListener("scroll", measure, { passive: true });
update();
return () => {
observer.disconnect();
viewport.removeEventListener("scroll", measure);
};
}, [measure, reveal]);
useLayoutEffect(() => {
// Children may change without a resize; controlled selection must also reveal.
void children;
void value;
void edges.overflow;
measure();
reveal(listRef.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]') ?? null);
}, [children, value, edges.overflow, measure, reveal]);
useLayoutEffect(() => {
// With icons="selected" the chosen tab grows as its icon opens and the
// last one shrinks. A layout animation measures the tabs mid-change, so
// the pill would squeeze and catch up. Instead the pill springs straight
// to where the selected tab will settle, with every icon open or closed.
if (!tracked) return;
const list = listRef.current;
if (!list) return;
void children;
const place = () => {
const tabs = Array.from(list.querySelectorAll<HTMLElement>('[role="tab"]'));
const target = tabs.find((tab) => tab.dataset.tabsValue === value)?.parentElement;
if (!target) return;
// Measure the settled layout: open the selected icon and fold the rest
// for one synchronous read, then hand the styles back to Motion before
// anything paints. Exact in any layout, from flex rows to grids.
const icons = Array.from(list.querySelectorAll<HTMLElement>('[role="tab"] > [data-tabs-icon]'));
const saved = icons.map((icon) => [icon.style.width, icon.style.marginRight]);
for (const icon of icons) {
const open = icon.parentElement?.parentElement === target;
icon.style.width = open ? "auto" : "0px";
icon.style.marginRight = open ? `${ICON_GAP}px` : "0px";
}
const box = {
x: target.offsetLeft,
y: target.offsetTop,
// Fractional: a rounded width leaves the pill a hair off its tab.
width: target.getBoundingClientRect().width,
height: target.offsetHeight,
};
icons.forEach((icon, index) => {
[icon.style.width, icon.style.marginRight] = saved[index];
});
// A first measurement, or one after the list was hidden, lands in place.
const instant = reduce || track.width.get() === 0;
for (const key of ["x", "y", "width", "height"] as const) {
if (instant) track[key].jump(box[key]);
else track[key].set(box[key]);
}
// Hand over from the CSS pill once there's a real box, before paint.
if (box.width > 0) setPlaced(true);
};
place();
const observer = new ResizeObserver(place);
for (const tab of list.querySelectorAll('[role="tab"]')) if (tab.parentElement) observer.observe(tab.parentElement);
return () => observer.disconnect();
}, [tracked, value, children, reduce, track, setPlaced]);
useLayoutEffect(() => {
if (variant === "underline") return;
const list = listRef.current;
if (!list) return;
void children;
// `placed` swaps the indicator element, so measure the new one.
void placed;
const labels = Array.from(list.querySelectorAll<HTMLElement>("[data-tabs-label]"));
const indicator = list.querySelector<HTMLElement>("[data-tabs-indicator]");
const target = list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');
if (!indicator || !target || target.dataset.tabsValue !== value) {
for (const label of labels) label.style.clipPath = "inset(0 100% 0 0)";
return;
}
let frames = 0;
let stillFrames = 0;
let previous: { left: number; right: number } | undefined;
const syncClips = () => {
const pill = (reduce ? target : indicator).getBoundingClientRect();
// Read ALL geometry before writing ANY masks. A loop per tab interleaved
// reads and writes, forcing the browser to flush styles repeatedly.
const clips = labels.map((label) => {
const bounds = label.getBoundingClientRect();
const left = Math.max(0, Math.min(bounds.width, pill.left - bounds.left));
const right = Math.max(0, Math.min(bounds.width, bounds.right - pill.right));
return left + right >= bounds.width ? "inset(0 100% 0 0)" : `inset(0 ${right}px 0 ${left}px)`;
});
labels.forEach((label, index) => {
if (label.style.clipPath !== clips[index]) label.style.clipPath = clips[index];
});
frames += 1;
stillFrames = previous && Math.abs(pill.left - previous.left) < 0.01 && Math.abs(pill.right - previous.right) < 0.01 ? stillFrames + 1 : 0;
previous = { left: pill.left, right: pill.right };
if (reduce || (frames > 2 && stillFrames >= 2)) cancelFrame(syncClips);
};
// One shared pass after Motion paints the projected pill keeps every label
// in sync, including labels crossed during a long or interrupted glide.
frame.postRender(syncClips, true);
// A list measured while hidden (display: none, a closed panel, a
// breakpoint) gets every mask closed. Sync again once it has a size, or
// the selected label stays invisible until the value changes.
const resync = () => {
frames = 0;
stillFrames = 0;
previous = undefined;
cancelFrame(syncClips);
frame.postRender(syncClips, true);
};
const observer = new ResizeObserver(resync);
observer.observe(list);
return () => {
observer.disconnect();
cancelFrame(syncClips);
};
}, [value, children, variant, reduce, placed]);
// Arrow keys move along the list and select as focus arrives, wrapping at
// the ends; Home and End jump to the first and last enabled tab.
const onListKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const list = listRef.current;
if (!list || !(event.target instanceof HTMLElement)) return;
const tabs = Array.from(list.querySelectorAll<HTMLButtonElement>('[role="tab"]')).filter(
(tab) => !tab.disabled && tab.closest('[role="tablist"]') === list,
);
const at = tabs.indexOf(event.target as HTMLButtonElement);
if (at < 0) return;
const rtl = getComputedStyle(list).direction === "rtl";
const forward = rtl ? "ArrowLeft" : "ArrowRight";
const back = rtl ? "ArrowRight" : "ArrowLeft";
const next =
event.key === forward
? tabs[(at + 1) % tabs.length]
: event.key === back
? tabs[(at - 1 + tabs.length) % tabs.length]
: event.key === "Home"
? tabs[0]
: event.key === "End"
? tabs[tabs.length - 1]
: null;
if (!next) return;
event.preventDefault();
next.focus();
next.click();
};
const scroll = (direction: number) => {
const viewport = viewportRef.current;
if (viewport) viewport.scrollBy({ left: direction * viewport.clientWidth * 0.8, behavior: reduce ? "instant" : "smooth" });
};
const controlClass = "absolute inset-y-0 z-20 inline-flex w-9 items-center justify-center text-foreground transition-opacity hover:opacity-70 focus-visible:outline-2 focus-visible:-outline-offset-4 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-0";
const surfaceClass = variant === "pill" ? "rounded-full bg-card" : variant === "segment" ? "rounded-full bg-card" : "";
return (
<div ref={rootRef} className={cn("relative isolate flex w-full max-w-full min-w-0 items-center", edges.overflow && surfaceClass, wrapperClassName)}>
{edges.overflow && (
<button type="button" aria-label={t("scrollLeft")} aria-controls={viewportId} disabled={!edges.left} onClick={() => scroll(-1)} className={cn(controlClass, "left-0 rounded-l-full")}>
<ChevronLeft size={20} aria-hidden="true" />
</button>
)}
<motion.div
ref={viewportRef}
id={viewportId}
layoutScroll
className={cn("w-full min-w-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden", edges.overflow && "[border-radius:inherit]")}
style={edges.overflow ? {
maskImage: `linear-gradient(to right, ${edges.left ? "transparent, black 40px" : "black, black 0px"}, ${edges.right ? "black calc(100% - 40px), transparent" : "black 100%"})`,
} : undefined}
onFocusCapture={(event) => {
if (event.target instanceof HTMLElement && event.target.getAttribute("role") === "tab") reveal(event.target);
}}
>
<div {...props} ref={listRef} role="tablist" onKeyDown={onListKeyDown} className={cn(listClasses[variant], "w-max", tracked && "relative", className)}>
{children}
</div>
</motion.div>
{edges.overflow && edges.left && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 left-0 z-10 w-10 rounded-l-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_right,black,transparent)]" />
)}
{edges.overflow && edges.right && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 z-10 w-10 rounded-r-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_left,black,transparent)]" />
)}
{edges.overflow && (
<button type="button" aria-label={t("scrollRight")} aria-controls={viewportId} disabled={!edges.right} onClick={() => scroll(1)} className={cn(controlClass, "right-0 rounded-r-full")}>
<ChevronRight size={20} aria-hidden="true" />
</button>
)}
</div>
);
}
/** Space between a selected-only icon and its label, in pixels. */
const ICON_GAP = 6;
/**
* A trigger's icon before its label. Shown on every tab, or with
* `icons="selected"` springing open on the selected tab only.
*/
function TriggerIcon({ icon, active }: { icon: ReactNode; active: boolean }) {
const { icons } = useTabs();
const reduce = useReducedMotion();
if (icons === "always") {
return (
<span aria-hidden="true" className="mr-1.5 inline-flex shrink-0 items-center">
{icon}
</span>
);
}
return (
<motion.span
aria-hidden="true"
data-tabs-icon=""
initial={false}
animate={{
width: active ? "auto" : 0,
marginRight: active ? ICON_GAP : 0,
opacity: active ? 1 : 0,
scale: active ? 1 : 0.6,
}}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="inline-flex shrink-0 items-center justify-center overflow-hidden"
>
{icon}
</motion.span>
);
}
export function TabsTrigger({
value,
icon,
children,
className,
indicatorClassName,
onClick,
...props
}: {
value: string;
/** An icon before the label, such as a Lucide icon element. */
icon?: ReactNode;
indicatorClassName?: string;
} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value">) {
const {
value: current,
setValue,
layoutId,
variant,
icons,
track,
placed,
tabStop,
registerTab,
unregisterTab,
panels,
tabId,
panelId,
} = useTabs();
const active = current === value;
const disabled = Boolean(props.disabled);
useLayoutEffect(() => {
registerTab(value, disabled);
}, [registerTab, value, disabled]);
useLayoutEffect(() => () => unregisterTab(value), [unregisterTab, value]);
const a11y = {
id: tabId(value),
"aria-controls": panels.has(value) ? panelId(value) : undefined,
tabIndex: !disabled && (tabStop === null || tabStop === value) ? 0 : -1,
};
const content = icon ? (
<>
<TriggerIcon icon={icon} active={active} />
{children}
</>
) : (
children
);
// React owns the initial mask only; TabsList synchronizes subsequent masks.
const [initialClip] = useState(() => active ? "inset(0)" : "inset(0 100% 0 0)");
if (variant === "underline") {
return (
<button
// Consumer ids and wiring win, e.g. several tabs sharing one panel.
{...a11y}
{...props}
type="button"
role="tab"
aria-selected={active}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) 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 whitespace-nowrap shrink-0",
active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
className,
)}
>
{content}
{active ? (
<motion.span
layoutId={layoutId}
layout
className={cn(
"absolute bottom-0 left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
// Tracked pills are placed in the list, so this wrapper must not be their
// containing block. Server HTML can't measure, so until the first
// measurement the pill fills the selected tab with CSS, like the others.
const tracked = icons === "selected" && placed;
return (
<div className={cn("shrink-0", !tracked && "relative")}>
{/* Distinct keys: reused across the swap, the CSS pill's leftover
`transform: none` would hide the tracked pill's offset until the
next value change. */}
{active && tracked ? (
<motion.span
key="tracked"
data-tabs-indicator=""
style={{ ...track, borderRadius: 9999 }}
className={cn("absolute top-0 left-0 rounded-full bg-primary", indicatorClassName)}
/>
) : active ? (
<motion.span
key="layout"
data-tabs-indicator=""
layoutId={layoutId}
layout
style={{ borderRadius: 9999 }}
className={cn("absolute inset-0 rounded-full bg-primary", indicatorClassName)}
/>
) : null}
<button
// Consumer ids and wiring win, e.g. several tabs sharing one panel.
{...a11y}
{...props}
type="button"
role="tab"
aria-selected={active}
data-tabs-value={value}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) 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",
"text-muted-foreground hover:text-foreground rounded-full",
className,
)}
>
{content}
<span
data-tabs-label=""
aria-hidden="true"
inert
className="pointer-events-none absolute inset-0 inline-flex items-center justify-center text-primary-foreground [gap:inherit] [padding:inherit]"
style={{ clipPath: initialClip }}
>
{content}
</span>
</button>
</div>
);
}
export function TabsContent({
value,
children,
className,
}: {
/** The trigger value that shows this panel. */
value: string;
children: ReactNode;
className?: string;
}) {
const { value: current, registerPanel, unregisterPanel, tabId, panelId } = useTabs();
const reduce = useReducedMotion();
const active = current === value;
useLayoutEffect(() => {
registerPanel(value);
return () => unregisterPanel(value);
}, [registerPanel, unregisterPanel, value]);
const a11y = {
id: panelId(value),
role: "tabpanel",
"aria-labelledby": tabId(value),
} as const;
// 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 {...a11y} hidden className={className}>
{children}
</div>
);
}
return (
<motion.div
{...a11y}
// Reachable with Tab so a panel without controls can still be read.
tabIndex={0}
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 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 rounded-md", className)}
>
{children}
</motion.div>
);
}
"use client";
import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion, type Variants } from "motion/react";
import type { ReactNode } from "react";
import { useState } from "react";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ActionSwapItem = {
/** Unique key, used as the button's value. */
id: string;
/** Text shown on the button while this item is active. Hidden when `iconOnly`. */
label: ReactNode;
/** Icon shown before the label while this item is active. */
icon?: ReactNode;
/** Accessible name while active. Falls back to a string label when `iconOnly`. */
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"
> {
/** States the button steps through, each with a label and optional icon. */
items: ActionSwapItem[];
/** The id of the shown item, for controlled use. */
value?: string;
/** The initial item id when uncontrolled. Default: the first item. */
defaultValue?: string;
/** Called with the next item's id and the item when a press advances it. */
onValueChange?: (value: string, item: ActionSwapItem) => void;
/** Visual style of the button. Default: "secondary" */
variant?: ActionSwapButtonVariant;
/** Button height and padding. Default: "md" */
size?: ActionSwapButtonSize;
/** How the label and icon swap between items. Default: "blur" */
animation?: ActionSwapAnimation;
/** Show only the icon and use the label as the accessible name. Default: true for size "icon" */
iconOnly?: boolean;
/** Advance to the next item on each press, wrapping at the end. Default: true */
cycle?: boolean;
}
export interface ActionSwapTextProps {
/** Key for the current text; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old text leaves and the new text enters. Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
export interface ActionSwapIconProps {
/** Key for the current icon; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old icon leaves and the new one enters. "cascade" plays as "roll". Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
// The arriving layer springs in, so a second press mid-swap bends it toward
// the new target instead of restarting. The leaving layer is a little quicker,
// still long enough to cross the arrival so the swap reads as one morph.
const BLUR_TRANSITION = SPRING_SWAP;
const BLUR_EXIT_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;
const ROLL_TRANSITION = SPRING_SWAP;
const ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;
// A light blur softens the crossing without smearing small glyphs.
const SWAP_BLUR = "blur(2px)";
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.9, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.96,
filter: SWAP_BLUR,
transition: BLUR_EXIT_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_EXIT_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-muted/60",
ghost: "text-muted-foreground hover:bg-muted/60 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}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`${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,
style,
...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);
const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;
return (
<motion.button
type="button"
disabled={disabled}
// A label of a different length resizes the button: glide the width on
// the soft layout spring, and only when the value changes, so unrelated
// page reflow never animates the button.
layout
layoutDependency={activeItem.id}
whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
transition={{ ...SPRING_PRESS, layout: layoutTransition }}
// Layout animations only correct a radius set inline.
style={{ borderRadius: 9999, ...style }}
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}
>
{/* Position-only layout keeps the contents from stretching with the
button while its width glides. */}
{hasIcon ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex shrink-0"
>
<ActionSwapIcon value={activeItem.id} animation={animation} className="h-4 w-4">
{activeItem.icon ?? null}
</ActionSwapIcon>
</motion.span>
) : null}
{!iconOnly ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex min-w-0 max-w-full"
>
<ActionSwapText value={activeItem.id} animation={animation}>
{activeItem.label}
</ActionSwapText>
</motion.span>
) : null}
</motion.button>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
type ComponentProps,
type PointerEvent as ReactPointerEvent,
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { assignRef } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
import { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from "./tooltip/grace";
import { TooltipArrow, TooltipPositioner } from "./tooltip/positioner";
import {
type TooltipAlign,
type TooltipAnchor,
type TooltipPoint,
type TooltipSide,
useTooltipPointer,
} from "./tooltip/use-position";
export type { TooltipAlign, TooltipSide };
/* -------------------------------------------------------------------------- */
/* Provider */
/* -------------------------------------------------------------------------- */
interface TooltipTiming {
/** Delay before a hover opens a tooltip (ms). */
delay: number;
/** Delay before a tooltip closes once the pointer has left it (ms). */
closeDelay: number;
/** After one tooltip closes, others open instantly for this long (ms). */
skipDelay: number;
}
const TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });
export interface TooltipProviderProps extends Partial<TooltipTiming> {
children: ReactNode;
}
/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */
export function TooltipProvider({ children, ...timing }: TooltipProviderProps) {
const parent = useContext(TimingContext);
const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =
timing;
const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);
return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
// Moving along a toolbar should feel instant after the first label, and only
// one label may show at a time: a keyboard-focused control and a hovered one
// would otherwise both claim the screen.
let lastClosedAt = 0;
let current: { close: () => void } | null = null;
function isEmpty(content: ReactNode) {
return content == null || content === false || content === "";
}
interface TooltipContextValue {
open: boolean;
/** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */
instant: boolean;
contentId: string;
labelId: string;
asLabel: boolean;
empty: boolean;
followCursor: boolean;
anchor: TooltipAnchor | null;
/** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */
triggered: boolean;
floatingRef: RefObject<HTMLSpanElement | null>;
pointer: ReturnType<typeof useTooltipPointer>;
setTrigger: (element: TooltipAnchor | null) => void;
setEmpty: (empty: boolean) => void;
close: () => void;
onContentEnter: () => void;
onContentLeave: (event: ReactPointerEvent) => void;
}
const TooltipContext = createContext<TooltipContextValue | null>(null);
function useTooltipContext(part: string) {
const context = useContext(TooltipContext);
if (!context) throw new Error(`${part} must be used inside <Tooltip>`);
return context;
}
export interface TooltipRootProps {
children?: ReactNode;
/** Whether the tooltip is shown, for controlled use. */
open?: boolean;
/** Whether the tooltip starts shown when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the tooltip shows or hides. */
onOpenChange?: (open: boolean) => void;
/** Delay before showing on hover (ms). Keyboard focus shows immediately. */
delay?: number;
/** Delay before hiding once the pointer has left (ms). */
closeDelay?: number;
/** Never show, e.g. while the label it carries is already visible. */
disabled?: boolean;
/**
* Use the tooltip as the trigger's accessible name rather than its
* description. For icon-only controls whose only label is the tooltip.
*/
asLabel?: boolean;
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
/** Existing anchor for controlled integrations such as chart cells. */
anchorRef?: RefObject<TooltipAnchor | null>;
/** Id of the tooltip surface, for anchors that reference it themselves. */
id?: string;
}
function TooltipRoot({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delay: delayProp,
closeDelay: closeDelayProp,
disabled = false,
asLabel = false,
followCursor = false,
anchorRef,
id,
initialEmpty = false,
}: TooltipRootProps & { initialEmpty?: boolean }) {
const timing = useContext(TimingContext);
const delay = delayProp ?? timing.delay;
const closeDelay = closeDelayProp ?? timing.closeDelay;
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
// Keyboard focus and a warm toolbar show the label at once; animating
// something seen this often only makes it feel slow.
const [instant, setInstant] = useState(false);
const [empty, setEmpty] = useState(initialEmpty);
const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);
const [external, setExternal] = useState<TooltipAnchor | null>(null);
const anchor = anchorRef ? external : trigger;
const generatedId = useId();
const contentId = id ?? `${generatedId}-content`;
const labelId = `${generatedId}-label`;
const floatingRef = useRef<HTMLSpanElement | null>(null);
const anchorObject = useRef<TooltipAnchor | null>(null);
const pointer = useTooltipPointer(anchor, followCursor);
// An external ref can attach after this component renders; read it once it has.
useLayoutEffect(() => {
if (!anchorRef) return;
const element = anchorRef.current ?? null;
if (element !== external) setExternal(element);
});
// Everything the event listeners read, current without re-binding them.
const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });
useLayoutEffect(() => {
anchorObject.current = anchor;
latest.current = {
open,
delay,
closeDelay,
disabled,
empty,
onOpenChange,
controlled: controlledOpen !== undefined,
};
});
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const grace = useRef<(() => void) | null>(null);
const self = useRef<{ close: () => void }>({ close: () => {} });
const clearTimers = useCallback(() => {
if (openTimer.current) clearTimeout(openTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
openTimer.current = null;
closeTimer.current = null;
}, []);
const stopGrace = useCallback(() => {
grace.current?.();
grace.current = null;
}, []);
// Only a real change reaches the consumer: a pointer leaving a closed
// tooltip is not news.
const commit = useCallback((next: boolean) => {
if (latest.current.open === next) return;
if (!latest.current.controlled) setUncontrolledOpen(next);
latest.current.onOpenChange?.(next);
}, []);
const openNow = useCallback(
(now = false) => {
clearTimers();
stopGrace();
if (latest.current.disabled || latest.current.empty) return;
// The label being replaced leaves at once, so two never show together.
if (current && current !== self.current) current.close();
current = self.current;
setInstant(now);
commit(true);
},
[clearTimers, stopGrace, commit],
);
const finish = useCallback(
(now: boolean) => {
clearTimers();
stopGrace();
if (latest.current.open) lastClosedAt = Date.now();
if (current === self.current) current = null;
if (latest.current.open) setInstant(now);
commit(false);
},
[clearTimers, stopGrace, commit],
);
// Also a listener (window blur, outside press), so it takes no arguments.
const close = useCallback(() => finish(false), [finish]);
useLayoutEffect(() => {
self.current.close = () => finish(true);
}, [finish]);
const requestOpen = useCallback(() => {
clearTimers();
if (latest.current.open || latest.current.disabled || latest.current.empty) return;
// Warm: another label is still showing (the pointer is crossing to this
// one), or one closed a moment ago. Either way, skip the delay and the fade.
const warm =
(current !== null && current !== self.current) ||
Date.now() - lastClosedAt < timing.skipDelay;
if (warm) openNow(true);
else if (latest.current.delay <= 0) openNow();
else openTimer.current = setTimeout(() => openNow(), latest.current.delay);
}, [clearTimers, openNow, timing.skipDelay]);
const requestClose = useCallback(() => {
clearTimers();
if (latest.current.closeDelay > 0) {
closeTimer.current = setTimeout(close, latest.current.closeDelay);
} else close();
}, [clearTimers, close]);
// Hold the label open while the pointer crosses from one box toward the other.
const startGrace = useCallback(
(exit: TooltipPoint, from: Element, to: Element | null) => {
stopGrace();
if (!to) return requestClose();
const target = to.getBoundingClientRect();
const origin = from.getBoundingClientRect();
const corridor = graceArea(exit, target);
const onMove = (event: PointerEvent) => {
const point = { x: event.clientX, y: event.clientY };
if (inBox(point, target) || inBox(point, origin)) return;
if (!inPolygon(point, corridor)) requestClose();
};
document.addEventListener("pointermove", onMove);
grace.current = () => document.removeEventListener("pointermove", onMove);
},
[stopGrace, requestClose],
);
const hover = useHoverGesture();
const tap = useTapGesture<boolean>();
// Listeners go on the trigger itself rather than on cloned props, so a
// component that owns its own handlers keeps them, and no wrapper element
// sits between the control and its layout.
useEffect(() => {
if (anchorRef || !trigger) return;
watchModality();
// A mouse press dismisses the label and keeps it away until the pointer
// leaves; hovering a control you just clicked should not bring it back.
let suppressed = false;
// Focus that came from the keyboard holds the label open on its own.
let keyboardFocus = false;
const onEnter = (event: PointerEvent) => {
if (!hover.enter(event)) return;
stopGrace();
if (closeTimer.current) clearTimeout(closeTimer.current);
if (!suppressed) requestOpen();
};
const onLeave = (event: PointerEvent) => {
if (!hover.leave(event)) return;
suppressed = false;
if (keyboardFocus) return;
if (openTimer.current) {
clearTimers();
return;
}
if (latest.current.open && !followCursor) {
startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);
} else requestClose();
};
const onDown = (event: PointerEvent) => {
tap.start(event, latest.current.open);
if (event.pointerType === "mouse") {
suppressed = true;
close();
}
};
// A finger never hovers, and Safari does not focus a button on tap either,
// so the label is only reachable if the tap itself toggles it. The click
// carries no pointerType; the pointerdown before it says whether it was a
// tap, and keyboard activation has none at all.
const onClick = () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) close();
else openNow();
};
const onKey = () => tap.drop();
const onFocusIn = () => {
if (!focusFromKeyboard()) return;
keyboardFocus = true;
openNow(true);
};
const onFocusOut = (event: FocusEvent) => {
if (trigger.contains(event.relatedTarget as Node | null)) return;
const fromKeyboard = keyboardFocus;
keyboardFocus = false;
finish(fromKeyboard);
};
// Both element kinds dispatch the same events; one type keeps the listeners typed.
const el = trigger as HTMLElement;
el.addEventListener("pointerenter", onEnter);
el.addEventListener("pointerleave", onLeave);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointercancel", tap.drop);
el.addEventListener("click", onClick);
el.addEventListener("keydown", onKey);
el.addEventListener("focusin", onFocusIn);
el.addEventListener("focusout", onFocusOut);
return () => {
el.removeEventListener("pointerenter", onEnter);
el.removeEventListener("pointerleave", onLeave);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointercancel", tap.drop);
el.removeEventListener("click", onClick);
el.removeEventListener("keydown", onKey);
el.removeEventListener("focusin", onFocusIn);
el.removeEventListener("focusout", onFocusOut);
};
}, [
anchorRef,
trigger,
followCursor,
hover,
tap,
requestOpen,
requestClose,
openNow,
close,
finish,
clearTimers,
stopGrace,
startGrace,
]);
// While open, a trigger that turns disabled loses focus without a blur event,
// and a window that loses focus never reports the pointer leaving.
useEffect(() => {
if (!open || anchorRef || !trigger) return;
const observer = new MutationObserver(() => {
if (trigger.matches(":disabled, [aria-disabled='true']")) close();
});
observer.observe(trigger, { attributes: true, attributeFilter: ["disabled", "aria-disabled"] });
window.addEventListener("blur", close);
return () => {
observer.disconnect();
window.removeEventListener("blur", close);
};
}, [open, anchorRef, trigger, close]);
// A chart drives its own open state and swaps content as it goes; only a
// trigger-owned label closes itself for having nothing to say.
useEffect(() => {
if (disabled || (empty && !anchorRef)) close();
}, [disabled, empty, anchorRef, close]);
useEffect(
() => () => {
clearTimers();
stopGrace();
if (current === self.current) current = null;
},
[clearTimers, stopGrace],
);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// ...and closed by the next tap that lands somewhere else, or Escape. The
// label covers nothing interactive, so that tap passes through to what it hit.
// Escape is a key press, so the label goes at once.
const dismiss = useCallback((reason: DismissReason) => finish(reason === "escape"), [finish]);
useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });
const onContentEnter = useCallback(() => {
stopGrace();
clearTimers();
}, [stopGrace, clearTimers]);
const onContentLeave = useCallback(
(event: ReactPointerEvent) => {
const floating = floatingRef.current;
if (!floating) return;
if (anchorRef) {
// Bridge the small gap back onto a chart; it reopens on its own terms.
clearTimers();
closeTimer.current = setTimeout(close, 100);
return;
}
startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);
},
[anchorRef, clearTimers, close, startGrace],
);
const value = useMemo<TooltipContextValue>(
() => ({
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
triggered: !anchorRef,
floatingRef,
pointer,
setTrigger,
setEmpty,
close,
onContentEnter,
onContentLeave,
}),
[
open,
instant,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
anchorRef,
pointer,
close,
onContentEnter,
onContentLeave,
],
);
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
function mergeIds(...ids: unknown[]) {
return ids.filter((value) => typeof value === "string" && value).join(" ") || undefined;
}
export interface TooltipTriggerProps extends ComponentProps<"button"> {
/** Use the single child element as the trigger instead of rendering a button. */
asChild?: boolean;
}
export function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {
const { open, contentId, labelId, asLabel, empty, setTrigger } =
useTooltipContext("TooltipTrigger");
const child = asChild && isValidElement(children) ? children : null;
const childProps = (child?.props ?? props) as Record<string, unknown>;
const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;
const attached = useRef<TooltipAnchor | null>(null);
const setRef = useCallback(
(element: TooltipAnchor | null) => {
attached.current = element;
setTrigger(element);
assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);
},
[setTrigger, childRef, ref],
);
useEffect(() => {
if (process.env.NODE_ENV !== "production" && child && !attached.current) {
console.warn(
"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.",
);
}
}, [child]);
const aria = asLabel
? {
"aria-labelledby": empty
? (childProps["aria-labelledby"] as string | undefined)
: labelId,
}
: {
"aria-describedby": mergeIds(
childProps["aria-describedby"],
open && !empty ? contentId : undefined,
),
};
if (asChild) {
if (!child) return children;
return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });
}
return (
<button
type="button"
data-state={open ? "open" : "closed"}
{...props}
ref={setRef as Ref<HTMLButtonElement>}
{...aria}
>
{children}
</button>
);
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface TooltipContentProps {
children?: ReactNode;
/** Preferred side of the anchor. Flips when there is no room. Default: "top" */
side?: TooltipSide;
/** Alignment along the chosen side. Default: "center" */
align?: TooltipAlign;
/** Gap between anchor and tooltip (px). */
sideOffset?: number;
/** Draw an arrow pointing at the anchor. */
arrow?: boolean;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: TooltipPoint;
/** Classes merged onto the tooltip surface. */
className?: string;
}
export function TooltipContent({
children,
side = "top",
align = "center",
sideOffset,
arrow = false,
anchorPoint,
className,
}: TooltipContentProps) {
const {
open,
instant,
contentId,
labelId,
asLabel,
followCursor,
anchor,
floatingRef,
pointer,
setEmpty,
close,
onContentEnter,
onContentLeave,
} = useTooltipContext("TooltipContent");
const empty = isEmpty(children);
const arrowRef = useRef<SVGSVGElement | null>(null);
useLayoutEffect(() => {
setEmpty(empty);
}, [empty, setEmpty]);
if (typeof document === "undefined") return null;
return createPortal(
<>
{/* The name has to exist while the label is closed, so it lives apart from the surface. */}
{asLabel && !empty ? (
<span id={labelId} hidden>
{children}
</span>
) : null}
{/* `custom` reaches a surface that is already exiting, so a label closed
from the keyboard or replaced by a neighbour leaves without animating. */}
<AnimatePresence custom={instant}>
{open && !empty ? (
<TooltipPositioner
key="tooltip"
anchor={anchor}
floatingRef={floatingRef}
arrowRef={arrow ? arrowRef : undefined}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
align={align}
sideOffset={sideOffset}
onDismiss={close}
pointer={pointer}
>
{(positioned, isPresent, placedSide) => (
<TooltipSurface
id={asLabel ? undefined : contentId}
aria-hidden={asLabel || undefined}
ready={positioned}
instant={instant}
onPointerEnter={onContentEnter}
onPointerLeave={onContentLeave}
style={{ pointerEvents: isPresent && !followCursor ? "auto" : "none" }}
className={cn(
"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words",
arrow && "relative",
className,
)}
>
{children}
{arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>
</>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Tooltip (root, or one-line shorthand when given `content`) */
/* -------------------------------------------------------------------------- */
export interface TooltipProps
extends TooltipRootProps,
Omit<TooltipContentProps, "children" | "className"> {
/**
* Shorthand: the tooltip's content. With it, `children` is the trigger
* element; without it, compose `TooltipTrigger` and `TooltipContent`.
*/
content?: ReactNode;
/** Shorthand only: classes for the tooltip surface. */
className?: string;
}
export function Tooltip(props: TooltipProps) {
if (!("content" in props)) return <TooltipRoot {...props} />;
const {
content,
children,
side,
align,
sideOffset,
arrow,
anchorPoint,
className,
...root
} = props;
if (!root.anchorRef && !isValidElement(children)) return children ?? null;
return (
<TooltipRoot {...root} initialEmpty={isEmpty(content)}>
{isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}
<TooltipContent
side={side}
align={align}
sideOffset={sideOffset}
arrow={arrow}
anchorPoint={anchorPoint}
className={className}
>
{content}
</TooltipContent>
</TooltipRoot>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type MouseEvent,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useSound } from "@/lib/sound";
import { pressSound } from "@/lib/sounds/press";
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"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only button. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
/** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only link. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97. */
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-full",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.97,
ripple = false,
sound = false,
className,
children,
onPointerDown,
onClick,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const play = useSound(pressSound, { enabled: sound });
const handleClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
// `detail` is 0 for a click the keyboard made; a pointer press already sounded.
if (event.detail === 0) play();
onClick?.(event);
},
[play, onClick],
);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
play();
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, play],
);
return (
// Hover changes colour only: a hover scale blurs the label, and buttons
// are hovered far too often for movement to earn its place.
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
onClick={handleClick}
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: 0.8, 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.97,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
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>
);
},
);
type Point = { x: number; y: number };
type Box = { left: number; top: number; right: number; bottom: number };
/**
* The corridor a pointer may cross between the trigger and the open tooltip
* without closing it: the convex hull of where it left and the box it is
* heading for. A fixed timeout either cuts a slow diagonal move short or keeps
* the label alive after the pointer has plainly gone elsewhere; this follows
* the path itself.
*/
export function graceArea(exit: Point, target: Box): Point[] {
// A few pixels either side of the exit point give the corridor some width at
// its narrow end, so a hand that drifts sideways while it moves stays inside.
const pad = 5;
return hull([
{ x: exit.x - pad, y: exit.y - pad },
{ x: exit.x + pad, y: exit.y - pad },
{ x: exit.x - pad, y: exit.y + pad },
{ x: exit.x + pad, y: exit.y + pad },
{ x: target.left, y: target.top },
{ x: target.right, y: target.top },
{ x: target.right, y: target.bottom },
{ x: target.left, y: target.bottom },
]);
}
export function inBox(point: Point, box: Box) {
return (
point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom
);
}
export function inPolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
// Monotone chain; the corridor is always convex, so a hull is all it needs.
function hull(points: Point[]) {
const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Point, a: Point, b: Point) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Point[] = [];
for (const p of sorted) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper: Point[] = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const p = sorted[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
/**
* How the user last reached for the page. A focus that a mouse press caused is
* not a request to read the label: the pointer is already on the control and
* hovering showed it. A focus that followed a key — Tab, or a roving arrow key
* moving focus in script — is the only way a keyboard user sees it at all.
*/
let modality: "keyboard" | "pointer" = "keyboard";
let listening = false;
export function watchModality() {
if (listening || typeof window === "undefined") return;
listening = true;
window.addEventListener("keydown", () => (modality = "keyboard"), true);
window.addEventListener("pointerdown", () => (modality = "pointer"), true);
}
export function focusFromKeyboard() {
return modality === "keyboard";
}
"use client";
import { useIsPresent } from "motion/react";
import { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from "react";
import { type TooltipSide, useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const [side, setSide] = useState<TooltipSide>(position.side);
const onPosition = useCallback((placed: TooltipSide) => {
setReady(true);
setSide(placed);
}, []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present, side)}
</span>
);
}
// Each arrow is a 12px box whose base sits on the surface's inner border edge,
// so its fill covers the border beneath it and only the two outer edges stroke.
const ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {
top: { path: "M0 6L6 12L12 6", style: { top: "calc(100% - 6px)" } },
bottom: { path: "M0 6L6 0L12 6", style: { bottom: "calc(100% - 6px)" } },
left: { path: "M6 0L12 6L6 12", style: { left: "calc(100% - 6px)" } },
right: { path: "M6 0L0 6L6 12", style: { right: "calc(100% - 6px)" } },
};
export function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {
const { path, style } = ARROW[side];
return (
<svg
ref={ref}
aria-hidden="true"
width="12"
height="12"
viewBox="0 0 12 12"
className="pointer-events-none absolute overflow-visible"
style={style}
>
{/* Redrawn to fit the surface's edge once placed (see arrowShape). */}
<path data-arrow-fill="" d={`${path}Z`} style={{ fill: "var(--tooltip-arrow-fill, transparent)" }} />
<path
data-arrow-stroke=""
d={path}
fill="none"
strokeWidth="1"
style={{ stroke: "var(--tooltip-arrow-stroke, transparent)" }}
/>
</svg>
);
}
"use client";
import {
arrow as arrowMiddleware,
autoUpdate,
computePosition,
flip,
hide,
offset,
type Placement,
shift,
type VirtualElement,
} from "@floating-ui/dom";
import { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipAlign = "start" | "center" | "end";
export type TooltipPoint = {
/** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */
x: number;
/** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */
y: number;
};
export type TooltipAnchor = HTMLElement | SVGElement;
const ORIGIN: Record<TooltipSide, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */
function blend(top: string, bottom: string) {
const context = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
if (!context) return top;
context.fillStyle = bottom;
context.fillRect(0, 0, 1, 1);
context.fillStyle = top;
context.fillRect(0, 0, 1, 1);
const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;
// A see-through background has nothing solid to blend onto.
return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;
}
/** The arrow element's box, which the arrow middleware centres along the edge. */
const ARROW_SIZE = 12;
/** How far the tip reaches past the border's inner edge. */
const ARROW_REACH = 6;
/**
* How far a rounded edge has curved in from its straight line at `position`
* along an edge of `length`, with corners of `radius`. Zero on the straight
* stretch between the corners.
*/
function curveDepth(position: number, length: number, radius: number) {
const offset =
position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;
if (offset <= 0) return 0;
return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));
}
/**
* The arrow's two paths, in the surface's border-box coordinates. Each 45°
* side runs from the tip until it meets the middle of the surface's border,
* wherever that is: on a straight stretch, or partway round a pill's curved
* end. The stroke covers only those two sides, so the border flows straight
* into them. The fill closes a little inside the surface, hiding the stretch
* of border the arrow sits on.
*/
function arrowShape({
side,
center,
width,
height,
radius,
border,
}: {
side: TooltipSide;
center: number;
width: number;
height: number;
radius: number;
border: number;
}) {
const vertical = side === "top" || side === "bottom";
const length = vertical ? width : height;
// Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.
const tip = { depth: border - ARROW_REACH, along: center };
// The border's centre line: the stroke meets it there, so the two line up.
const line = border / 2;
// Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.
const curved =
curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||
curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;
const meet = (direction: -1 | 1) => {
// On a straight stretch the 45° side meets the border directly.
if (!curved) {
for (let t = 0; t <= ARROW_SIZE; t += 0.05) {
const along = center + direction * t;
const depth = tip.depth + t;
if (depth >= line) return { depth, along };
}
}
// On a pill's round end a 45° side passes outside the curve, or meets it
// at a kink. Run the side tangent to the curve instead, so the border
// flows into it without a corner.
const curve = radius - line;
const centre = { depth: radius, along: direction < 0 ? radius : length - radius };
const dx = tip.depth - centre.depth;
const dy = tip.along - centre.along;
const distance = Math.hypot(dx, dy);
if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };
const base = Math.atan2(dy, dx);
const spread = Math.acos(curve / distance);
const candidates = [base + spread, base - spread].map((angle) => ({
depth: centre.depth + curve * Math.cos(angle),
along: centre.along + curve * Math.sin(angle),
}));
// The tangent on this side of the tip.
return direction < 0
? candidates[0].along < candidates[1].along
? candidates[0]
: candidates[1]
: candidates[0].along > candidates[1].along
? candidates[0]
: candidates[1];
};
const start = meet(-1);
const end = meet(1);
const inside = Math.max(start.depth, end.depth) + border + 1;
const point = ({ depth, along }: { depth: number; along: number }) => {
const [x, y] =
side === "right"
? [depth, along]
: side === "left"
? [width - depth, along]
: side === "bottom"
? [along, depth]
: [along, height - depth];
return `${x.toFixed(2)} ${y.toFixed(2)}`;
};
return {
fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,
stroke: `M${point(start)}L${point(tip)}L${point(end)}`,
};
}
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchor,
floatingRef,
arrowRef,
anchorPoint,
followCursor,
side,
align,
sideOffset,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchor: TooltipAnchor | null;
floatingRef: RefObject<HTMLSpanElement | null>;
arrowRef?: RefObject<SVGSVGElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
align: TooltipAlign;
sideOffset?: number;
onDismiss: () => void;
onPosition: (side: TooltipSide) => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const preferred: Placement = align === "center" ? side : `${side}-${align}`;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? preferred : null;
}, [open, preferred]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;
const reference: Element | VirtualElement = virtual
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
const arrowElement = arrowRef?.current ?? null;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,
middleware: [
offset(sideOffset ?? (currentCursor ? 12 : 8)),
flip({ padding: 8 }),
shift({ padding: 8 }),
...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),
// A label left floating over whatever scrolled into its trigger's place
// describes nothing there. Points inside a chart move with the chart.
...(virtual ? [] : [hide({ strategy: "referenceHidden" })]),
],
}).then(({ x, y, placement, middlewareData }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const placedSide = placement.split("-")[0] as TooltipSide;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
floating.style.setProperty("--tooltip-origin", ORIGIN[placedSide]);
// A box with no size has no clipped state to report, only a missing layout.
const box = anchor.getBoundingClientRect();
const clipped =
Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);
floating.style.visibility = clipped ? "hidden" : "visible";
floating.dataset.placement = placement;
const surface = arrowElement?.parentElement;
if (arrowElement && surface) {
// The middleware centres the 12px arrow box along the edge; its
// centre is where the tip points. The paths are drawn in the
// surface's border-box coordinates, so the svg sits at its corner.
const { x: ax, y: ay } = middlewareData.arrow ?? {};
const vertical = placedSide === "top" || placedSide === "bottom";
const width = surface.offsetWidth;
const height = surface.offsetHeight;
const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;
const style = getComputedStyle(surface);
const shape = arrowShape({
side: placedSide,
center: along + ARROW_SIZE / 2,
width,
height,
// `rounded-full` resolves to a huge radius; the box clamps it to half its short side.
radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),
border: surface.clientLeft,
});
Object.assign(arrowElement.style, {
left: `${-surface.clientLeft}px`,
top: `${-surface.clientTop}px`,
right: "auto",
bottom: "auto",
});
arrowElement.querySelector("[data-arrow-fill]")?.setAttribute("d", shape.fill);
arrowElement.querySelector("[data-arrow-stroke]")?.setAttribute("d", shape.stroke);
// Paint with whatever the surface resolved to, so a restyled tooltip
// keeps a matching arrow without a second set of classes. A
// see-through border is drawn over the surface's own background, so
// the stroke takes that blended colour: half of it sits over the
// page, and it overlaps the border where the two meet.
arrowElement.style.setProperty("--tooltip-arrow-fill", style.backgroundColor);
arrowElement.style.setProperty(
"--tooltip-arrow-stroke",
blend(style.borderTopColor, style.backgroundColor),
);
}
onPosition(placedSide);
});
};
if (open) schedule();
}, [
open,
anchor,
floatingRef,
arrowRef,
followCursor,
pointX,
pointY,
preferred,
sideOffset,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the anchor, including the opening delay. */
export function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchor, followCursor]);
return useMemo(() => ({ cursor, onMove }), []);
}
"use client";
import { motion, useReducedMotion, type Variants } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
const ENTER = { duration: 0.18, ease: EASE_OUT };
const EXIT = { duration: 0.12, ease: EASE_OUT };
const INSTANT = { duration: 0 };
/**
* `custom` is the `instant` flag. An exiting surface reads it from its
* `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once
* even though it has already left the React tree.
*/
const variants = (reduce: boolean): Variants => ({
closed: (instant = false) => ({
opacity: 0,
scale: reduce ? 1 : 0.97,
transition: instant ? INSTANT : EXIT,
}),
open: (instant = false) => ({
opacity: 1,
scale: 1,
transition: instant ? INSTANT : ENTER,
}),
});
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
className,
ref,
ready = true,
instant = false,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
/**
* Appear and disappear without animating: a label opened from the keyboard,
* or one of a row of tooltips the pointer is moving along.
*/
instant?: boolean;
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.span
ref={ref}
role="tooltip"
custom={instant}
variants={variants(reduce)}
initial="closed"
animate={ready ? "open" : "closed"}
exit="closed"
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
outcomes?PredictionMarketOutcome[]Outcomes to trade, each with a price from 0 to 1. Default: Up and Down
[
{ id: "up", label: "Up", price: 0.09 },
{ id: "down", label: "Down", price: 0.91 },
]value?PredictionMarketOrderValueThe order's mode, outcome and amount, for controlled use.
—defaultValue?Partial<PredictionMarketOrderValue>The initial order when uncontrolled. Missing fields start as buy, the first outcome and empty.
—onValueChange?((value: PredictionMarketOrderValue) => void)Called with the full order when the mode, outcome or amount changes.
—onTrade?((order: PredictionMarketOrderValue, quote: PredictionMarketQuote) => void)Called with the order and its quote once a valid trade fills.
—onSignIn?(() => void)Called when the connect button is pressed while signed out.
—authenticated?booleanWhether the user is signed in. When false, a connect button replaces the trade footer. Default: true
trueorderTypeLabel?stringText beside the buy and sell tabs. Default: "Market"
—balance?numberCash available to buy with, in dollars. Default: 500
500positions?Record<string, number>Shares held per outcome id, which caps how much can be sold.
{ up: 24, down: 16 }quickAmounts?number[]Amounts the quick chips add to the input. Default: [10, 50, 100, 500]
[10, 50, 100, 500]minTrade?numberSmallest buy amount, in dollars. Default: 1
1labels?Partial<{ buy: string; sell: string; orderType: string; amount: string; shares: string; max: string; toWin: string; toReceive: string; avgPrice: string; trade: string; trading: string; tradeFilled: string; ... 4 more ...; notEnoughShares: string; }>Override any built-in string. `{price}` fills `avgPrice`, `{amount}` fills `minimum`.
—className?stringClasses merged onto the root element.
—classNames?PredictionMarketClassNamesClasses for each inner part, keyed by slot.
—Wallet Card
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.
Multi-chain Swap
Cross-chain swap widget with chain + token selectors, morphing views, animated flip and quote.
Card Dealer
A card table with a face-down deck, a fanned hand and a discard pile. Cards arc across the table between them and flip in flight, hop over each other when the hand is sorted, and lift on hover. Data-driven by each card's zone, with custom faces and backs, keyboard-playable hand cards and reduced-motion support.
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