refactor(converter): split converter card into modular section components

This commit is contained in:
2026-03-30 19:26:18 +02:00
parent a45393ac00
commit 24f21d25bc
11 changed files with 1075 additions and 755 deletions

View File

@@ -0,0 +1,82 @@
"use client";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
interface ConverterCardAmountInputProps {
amountInput: string;
amountPrefix?: string;
amountInputPaddingLeft?: string;
amountError: string | null;
quickAmounts: readonly number[];
activeQuickAmount: number | null;
onAmountChange: (nextValue: string) => void;
onQuickAmountSelect: (value: number) => void;
}
export function ConverterCardAmountInput({
amountInput,
amountPrefix,
amountInputPaddingLeft,
amountError,
quickAmounts,
activeQuickAmount,
onAmountChange,
onQuickAmountSelect,
}: ConverterCardAmountInputProps) {
return (
<div className="space-y-2">
<label
htmlFor="amount"
className="text-xs uppercase tracking-[0.14em] text-muted-foreground"
>
Amount
</label>
<div className="relative">
{amountPrefix ? (
<span className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-sm text-muted-foreground/80">
{amountPrefix}
</span>
) : null}
<Input
id="amount"
type="text"
inputMode="decimal"
value={amountInput}
onChange={(event) => onAmountChange(event.target.value)}
placeholder="Enter amount"
className="h-14 rounded-xl bg-background/70 px-4 text-lg"
style={amountInputPaddingLeft ? { paddingLeft: amountInputPaddingLeft } : undefined}
aria-invalid={Boolean(amountError)}
aria-describedby={amountError ? "amount-error" : undefined}
/>
</div>
<div className="flex flex-wrap items-center gap-2 pt-1">
{quickAmounts.map((quickAmount) => (
<Button
key={quickAmount}
type="button"
variant="outline"
size="sm"
onClick={() => onQuickAmountSelect(quickAmount)}
className={cn(
"h-7 rounded-full border-border/70 px-3 text-xs text-muted-foreground transition-colors hover:text-foreground",
activeQuickAmount === quickAmount
? "border-cyan-300/50 bg-cyan-500/15 text-cyan-100"
: "",
)}
aria-label={`Set amount to ${quickAmount}`}
>
{quickAmount}
</Button>
))}
</div>
{amountError ? (
<p id="amount-error" className="text-sm text-red-300">
{amountError}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,142 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { Check, Copy, Link2 } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { Button } from "@/components/ui/button";
import type { RateAsset } from "@/lib/rates";
interface ConverterCardConvertedValueProps {
shouldReduceMotion: boolean;
fromAsset?: RateAsset;
toAsset?: RateAsset;
pairTransitionKey: string;
convertedDisplay: string;
forAmountDisplay: string;
isShareLinkCopied: boolean;
isCopied: boolean;
canCopyConvertedValue: boolean;
onCopyShareLink: () => void;
onCopyConvertedValue: () => void;
}
export function ConverterCardConvertedValue({
shouldReduceMotion,
fromAsset,
toAsset,
pairTransitionKey,
convertedDisplay,
forAmountDisplay,
isShareLinkCopied,
isCopied,
canCopyConvertedValue,
onCopyShareLink,
onCopyConvertedValue,
}: ConverterCardConvertedValueProps) {
return (
<div className="rounded-xl border border-border/70 bg-background/50 p-4">
<div className="flex items-center justify-between gap-2">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Converted value
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="icon"
onClick={onCopyShareLink}
className="h-7 w-7 text-muted-foreground hover:text-foreground"
aria-label={isShareLinkCopied ? "Share link copied" : "Copy share link"}
>
{isShareLinkCopied ? (
<Check className="h-3.5 w-3.5 text-cyan-200" />
) : (
<Link2 className="h-3.5 w-3.5" />
)}
</Button>
<Button
type="button"
variant="ghost"
size="icon"
onClick={onCopyConvertedValue}
disabled={!canCopyConvertedValue}
className="h-7 w-7 text-muted-foreground hover:text-foreground"
aria-label={
isCopied
? "Converted value copied"
: "Copy converted value to clipboard"
}
>
{isCopied ? (
<Check className="h-3.5 w-3.5 text-cyan-200" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</Button>
</div>
</div>
{fromAsset && toAsset ? (
<AnimatePresence initial={false} mode="wait">
<motion.div
key={pairTransitionKey}
className="mt-2 flex items-center gap-2 text-xs text-muted-foreground"
initial={
shouldReduceMotion ? false : { opacity: 0, y: 4, filter: "blur(2px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion ? { opacity: 0 } : { opacity: 0, y: -4, filter: "blur(2px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.16 }}
>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon
code={fromAsset.code}
type={fromAsset.type}
size="sm"
/>
{fromAsset.code}
</span>
<span>to</span>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon code={toAsset.code} type={toAsset.type} size="sm" />
{toAsset.code}
</span>
</motion.div>
</AnimatePresence>
) : null}
<p className="mt-2 break-all text-3xl font-semibold tracking-tight text-foreground sm:text-4xl">
<AnimatePresence initial={false} mode="wait">
<motion.span
key={convertedDisplay}
className="inline-block"
initial={
shouldReduceMotion ? false : { opacity: 0, y: 6, filter: "blur(2px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion ? { opacity: 0 } : { opacity: 0, y: -6, filter: "blur(2px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.18 }}
>
{convertedDisplay}
</motion.span>
</AnimatePresence>
</p>
{fromAsset ? (
<p className="mt-2 text-sm text-muted-foreground">
for {forAmountDisplay} {fromAsset.code}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,71 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
export function ConverterCardHeader({
fiatSource,
cryptoSource,
}: {
fiatSource: string;
cryptoSource: string;
}) {
return (
<CardHeader className="relative isolate z-10 overflow-hidden rounded-t-2xl border-b border-white/5 bg-[linear-gradient(115deg,rgba(16,39,62,0.9)_0%,rgba(14,32,50,0.95)_46%,rgba(14,50,54,0.88)_100%)] pb-4 sm:pb-5 before:pointer-events-none before:absolute before:inset-0 before:bg-[radial-gradient(140%_120%_at_0%_0%,rgba(56,189,248,0.12)_0%,rgba(56,189,248,0)_45%),radial-gradient(120%_100%_at_100%_0%,rgba(16,185,129,0.1)_0%,rgba(16,185,129,0)_45%)] after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-white/10">
<div className="flex flex-wrap items-center justify-between gap-2">
<CardTitle className="text-2xl font-semibold tracking-tight">
Currency Converter
</CardTitle>
<Badge
variant="outline"
className="max-w-full border-border/70 bg-background/50 text-[11px] sm:text-xs"
>
<span className="inline-flex items-center gap-1 whitespace-nowrap sm:hidden">
<span className="text-muted-foreground">Data sources:</span>
<a
href="https://frankfurter.dev/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{fiatSource}
</a>
<span className="text-muted-foreground"></span>
<a
href="https://www.coingecko.com/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{cryptoSource}
</a>
</span>
<span className="hidden items-center gap-1 whitespace-nowrap sm:inline-flex">
<span className="text-muted-foreground">Data sources:</span>
<a
href="https://frankfurter.dev/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{fiatSource}
</a>
<span className="text-muted-foreground"></span>
<a
href="https://www.coingecko.com/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{cryptoSource}
</a>
</span>
</Badge>
</div>
<CardDescription className="pr-1 text-base/7 sm:text-sm">
Convert fiat currencies and cryptocurrencies using live exchange rates.
</CardDescription>
</CardHeader>
);
}

View File

@@ -0,0 +1,150 @@
"use client";
import { BarChart3 } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { PriceSparkline } from "@/components/converter/price-sparkline";
import { Button } from "@/components/ui/button";
import { type CryptoMarketResponse, MARKET_CHART_RANGES, type MarketChartRange } from "@/lib/market";
import { formatSignedPercent, formatTimestamp, formatUsdCompact, formatUsdPrice } from "@/lib/format";
import type { RateAsset } from "@/lib/rates";
import { cn } from "@/lib/utils";
interface ConverterCardMarketDataProps {
marketAsset: RateAsset | null;
marketData: CryptoMarketResponse | null;
marketError: string | null;
isMarketLoading: boolean;
marketRange: MarketChartRange;
marketRangeLabels: Record<MarketChartRange, string>;
marketRangeChangePct: number | null;
onMarketRangeChange: (range: MarketChartRange) => void;
}
export function ConverterCardMarketData({
marketAsset,
marketData,
marketError,
isMarketLoading,
marketRange,
marketRangeLabels,
marketRangeChangePct,
onMarketRangeChange,
}: ConverterCardMarketDataProps) {
if (!marketAsset) {
return null;
}
return (
<div className="rounded-xl border border-border/70 bg-background/40 p-4">
<div className="flex items-center justify-between gap-2">
<p className="inline-flex items-center gap-1.5 text-xs uppercase tracking-[0.12em] text-muted-foreground">
<BarChart3 className="h-3.5 w-3.5" />
Market data
</p>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/70 px-2 py-1 text-xs text-foreground">
<CurrencyIcon
code={marketAsset.code}
type={marketAsset.type}
size="sm"
/>
{marketAsset.code}
</span>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
{MARKET_CHART_RANGES.map((range) => {
const isActive = marketRange === range;
return (
<Button
key={range}
type="button"
variant="outline"
size="sm"
onClick={() => onMarketRangeChange(range)}
className={cn(
"h-7 rounded-full border-border/70 px-3 text-xs text-muted-foreground hover:text-foreground",
isActive ? "border-cyan-300/50 bg-cyan-500/15 text-cyan-100" : "",
)}
aria-pressed={isActive}
aria-label={`Show ${marketRangeLabels[range]} chart`}
>
{marketRangeLabels[range]}
</Button>
);
})}
</div>
{marketError && !marketData ? (
<p className="mt-3 text-xs text-red-300/90">
Unable to load market data right now.
</p>
) : null}
<PriceSparkline
points={marketData?.priceHistory ?? []}
rangeLabel={marketRangeLabels[marketRange]}
isLoading={isMarketLoading && !marketData}
className="mt-3"
/>
<div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Price
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdPrice(marketData.priceUsd) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
{marketRangeLabels[marketRange]}
</p>
<p
className={cn(
"mt-1 text-base font-medium text-foreground",
marketRangeChangePct !== null
? marketRangeChangePct > 0
? "text-emerald-300"
: marketRangeChangePct < 0
? "text-red-300"
: "text-foreground"
: "text-foreground",
)}
>
{marketData ? formatSignedPercent(marketRangeChangePct) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Market cap
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdCompact(marketData.marketCapUsd) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Volume (24h)
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdCompact(marketData.volume24hUsd) : "-"}
</p>
</div>
</div>
<div className="mt-3 flex min-h-4 items-center justify-between gap-2 text-xs text-muted-foreground">
<span>
{marketData
? `Updated ${formatTimestamp(marketData.updatedAt)}`
: isMarketLoading
? "Updating market data..."
: ""}
</span>
{marketData ? <span>Source: {marketData.source}</span> : null}
</div>
</div>
);
}

View File

@@ -0,0 +1,107 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { Loader2 } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { formatAmount } from "@/lib/format";
import type { RateAsset } from "@/lib/rates";
type AmountValidationResult =
| { ok: true; value: number }
| { ok: false; error: string };
interface MultiConversionItem {
asset: RateAsset;
value: number;
}
interface ConverterCardMultiConversionProps {
shouldReduceMotion: boolean;
debouncedValidation: AmountValidationResult;
fromAsset?: RateAsset;
multiConversions: MultiConversionItem[];
isRatesLoading: boolean;
}
export function ConverterCardMultiConversion({
shouldReduceMotion,
debouncedValidation,
fromAsset,
multiConversions,
isRatesLoading,
}: ConverterCardMultiConversionProps) {
return (
<div className="rounded-xl border border-border/70 bg-background/40 p-4">
<div className="flex items-center justify-between gap-2">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Multi conversion
</p>
{fromAsset && debouncedValidation.ok ? (
<span className="text-xs text-muted-foreground">
for {formatAmount(debouncedValidation.value, fromAsset)} {fromAsset.code}
</span>
) : null}
</div>
{!debouncedValidation.ok ? (
<p className="mt-3 text-sm text-red-300">{debouncedValidation.error}</p>
) : null}
{debouncedValidation.ok && multiConversions.length === 0 ? (
<p className="mt-3 text-sm text-muted-foreground">
No additional assets available for multi conversion.
</p>
) : null}
{debouncedValidation.ok && multiConversions.length > 0 ? (
<div className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
{multiConversions.map(({ asset, value }) => (
<div
key={asset.code}
className="rounded-lg border border-border/60 bg-background/60 p-3"
>
<div className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<CurrencyIcon code={asset.code} type={asset.type} size="sm" />
{asset.code}
</div>
<p className="mt-1 text-base font-medium text-foreground">
<AnimatePresence initial={false} mode="wait">
<motion.span
key={`${asset.code}-${formatAmount(value, asset)}`}
className="inline-block"
initial={
shouldReduceMotion
? false
: { opacity: 0, y: 4, filter: "blur(1px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(1px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.15 }}
>
{formatAmount(value, asset)} {asset.code}
</motion.span>
</AnimatePresence>
</p>
</div>
))}
</div>
) : null}
{isRatesLoading ? (
<div className="mt-3 inline-flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Updating multi conversion...
</div>
) : null}
</div>
);
}

View File

@@ -0,0 +1,76 @@
"use client";
import { motion } from "framer-motion";
import { ArrowUpDown } from "lucide-react";
import { CurrencySelect } from "@/components/converter/currency-select";
import { Button } from "@/components/ui/button";
import type { RateAsset } from "@/lib/rates";
interface ConverterCardPairSelectionProps {
assets: RateAsset[];
fromCode: string;
toCode: string;
shouldReduceMotion: boolean;
swapAnimationStep: number;
onFromChange: (code: string) => void;
onToChange: (code: string) => void;
onSwap: () => void;
}
export function ConverterCardPairSelection({
assets,
fromCode,
toCode,
shouldReduceMotion,
swapAnimationStep,
onFromChange,
onToChange,
onSwap,
}: ConverterCardPairSelectionProps) {
return (
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
<CurrencySelect
label="From"
value={fromCode}
onChange={onFromChange}
assets={assets}
/>
<Button
type="button"
size="icon"
variant="outline"
className="mx-auto mb-0.5 rounded-full border-border/70 bg-background/50"
onClick={onSwap}
aria-label="Swap currencies"
>
<motion.span
className="inline-flex"
animate={
shouldReduceMotion
? { scale: 1 }
: { rotate: swapAnimationStep * 180, scale: [1, 1.08, 1] }
}
transition={{
rotate: {
duration: shouldReduceMotion ? 0.01 : 0.28,
ease: [0.22, 1, 0.36, 1],
},
scale: {
duration: shouldReduceMotion ? 0.01 : 0.22,
times: [0, 0.35, 1],
},
}}
>
<ArrowUpDown className="h-4 w-4" />
</motion.span>
</Button>
<CurrencySelect
label="To"
value={toCode}
onChange={onToChange}
assets={assets}
/>
</div>
);
}

View File

@@ -0,0 +1,175 @@
"use client";
import { motion } from "framer-motion";
import { MoveRight, Star, X } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { Button } from "@/components/ui/button";
import { type PinnedPair } from "@/hooks/use-pinned-pairs";
import type { RateAsset } from "@/lib/rates";
import { cn } from "@/lib/utils";
interface PinnedPairItem {
pair: PinnedPair;
fromAsset: RateAsset;
toAsset: RateAsset;
}
interface ConverterCardPinnedPairsProps {
shouldReduceMotion: boolean;
isCurrentPairPinned: boolean;
hasReachedPinnedPairsLimit: boolean;
pinStarAnimationStep: number;
pinnedPairItems: PinnedPairItem[];
fromCode: string;
toCode: string;
isPinnedPairsReady: boolean;
maxPinnedPairs: number;
onTogglePinnedCurrentPair: () => void;
onSelectPinnedPair: (pair: PinnedPair) => void;
onRemovePinnedPair: (pair: PinnedPair) => void;
}
export function ConverterCardPinnedPairs({
shouldReduceMotion,
isCurrentPairPinned,
hasReachedPinnedPairsLimit,
pinStarAnimationStep,
pinnedPairItems,
fromCode,
toCode,
isPinnedPairsReady,
maxPinnedPairs,
onTogglePinnedCurrentPair,
onSelectPinnedPair,
onRemovePinnedPair,
}: ConverterCardPinnedPairsProps) {
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Pinned pairs
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={onTogglePinnedCurrentPair}
disabled={hasReachedPinnedPairsLimit}
aria-pressed={isCurrentPairPinned}
aria-label={
isCurrentPairPinned
? "Remove current pair from pinned pairs"
: "Add current pair to pinned pairs"
}
className={cn(
"h-8 rounded-full border-border/70 px-3 text-xs transition-colors",
isCurrentPairPinned
? "border-amber-300/50 bg-amber-400/10 text-amber-100 hover:border-amber-300/60 hover:bg-amber-400/15"
: "text-muted-foreground hover:text-foreground",
)}
>
<motion.span
key={`${pinStarAnimationStep}-${isCurrentPairPinned ? "on" : "off"}`}
className="mr-1.5 inline-flex"
initial={
shouldReduceMotion
? false
: { scale: 0.95, rotate: 0, opacity: 0.9 }
}
animate={
shouldReduceMotion
? { scale: 1, rotate: 0, opacity: 1 }
: {
scale: [1, 1.18, 1],
rotate: isCurrentPairPinned ? [0, -12, 8, 0] : [0, 12, -8, 0],
opacity: [1, 1, 1],
}
}
transition={{
duration: shouldReduceMotion ? 0.01 : 0.24,
ease: [0.22, 1, 0.36, 1],
}}
>
<Star
className={cn(
"h-3.5 w-3.5",
isCurrentPairPinned ? "fill-amber-300 text-amber-300" : "",
)}
/>
</motion.span>
{isCurrentPairPinned ? "Pinned" : "Pin current pair"}
</Button>
</div>
{pinnedPairItems.length > 0 ? (
<div className="flex flex-wrap gap-2">
{pinnedPairItems.map(({ pair, fromAsset, toAsset }) => {
const isActive = pair.fromCode === fromCode && pair.toCode === toCode;
return (
<div
key={`${pair.fromCode}-${pair.toCode}`}
className={cn(
"inline-flex items-center rounded-full border border-border/70 bg-background/45 pr-0.5",
isActive ? "border-cyan-300/40 bg-cyan-500/10" : "",
)}
>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => onSelectPinnedPair(pair)}
className={cn(
"h-8 rounded-full px-2.5 text-xs text-muted-foreground hover:text-foreground",
isActive ? "text-cyan-100 hover:text-cyan-100" : "",
)}
aria-label={`Set pair ${pair.fromCode} to ${pair.toCode}`}
>
<span className="inline-flex items-center gap-1.5">
<CurrencyIcon
code={fromAsset.code}
type={fromAsset.type}
size="sm"
/>
<span>{pair.fromCode}</span>
<MoveRight className="h-3.5 w-3.5 text-cyan-300/90" />
<CurrencyIcon
code={toAsset.code}
type={toAsset.type}
size="sm"
/>
<span>{pair.toCode}</span>
</span>
</Button>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => onRemovePinnedPair(pair)}
className="h-7 w-7 rounded-full text-muted-foreground hover:text-red-300 focus-visible:text-red-200"
aria-label={`Remove pinned pair ${pair.fromCode} to ${pair.toCode}`}
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
);
})}
</div>
) : null}
{isPinnedPairsReady && pinnedPairItems.length === 0 ? (
<p className="text-xs text-muted-foreground">
Pin your most-used pairs for one-click access.
</p>
) : null}
{hasReachedPinnedPairsLimit ? (
<p className="text-xs text-amber-200/90">
Pinned pairs limit reached ({maxPinnedPairs}). Remove one to add a new
pair.
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,45 @@
"use client";
import { formatTimestamp } from "@/lib/format";
import type { RateAsset } from "@/lib/rates";
interface ConverterCardRatesSummaryProps {
fromAsset?: RateAsset;
toAsset?: RateAsset;
currentRate: string | null;
inverseRate: string | null;
updatedAt: string;
}
export function ConverterCardRatesSummary({
fromAsset,
toAsset,
currentRate,
inverseRate,
updatedAt,
}: ConverterCardRatesSummaryProps) {
return (
<div className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-3">
<div>
<p className="text-xs uppercase tracking-[0.12em]">Current rate</p>
<p className="mt-1 text-sm text-foreground">
{fromAsset && toAsset && currentRate
? `1 ${fromAsset.code} = ${currentRate} ${toAsset.code}`
: "-"}
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Inverse rate</p>
<p className="mt-1 text-sm text-foreground">
{fromAsset && toAsset && inverseRate
? `1 ${toAsset.code} = ${inverseRate} ${fromAsset.code}`
: "-"}
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Last updated</p>
<p className="mt-1 text-sm text-foreground">{formatTimestamp(updatedAt)}</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,74 @@
"use client";
import { AlertTriangle, RefreshCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
export function ConverterSkeleton() {
return (
<Card className="border-border/70">
<CardHeader>
<Skeleton className="h-6 w-40" />
<Skeleton className="h-4 w-72" />
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-14 w-full rounded-xl" />
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
<Skeleton className="h-20 w-full rounded-xl" />
<Skeleton className="mx-auto h-10 w-10 rounded-full" />
<Skeleton className="h-20 w-full rounded-xl" />
</div>
<Skeleton className="h-28 w-full rounded-xl" />
</CardContent>
</Card>
);
}
export function ConverterErrorState({
message,
onRetry,
}: {
message: string;
onRetry: () => void;
}) {
return (
<Card className="border-red-500/30 bg-red-500/5">
<CardContent className="flex flex-col gap-4 p-6">
<div className="flex items-start gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 text-red-300" />
<div>
<p className="text-sm font-medium text-red-200">
Unable to load market rates
</p>
<p className="mt-1 text-sm text-red-200/80">{message}</p>
</div>
</div>
<Button
variant="outline"
onClick={onRetry}
className="w-fit border-red-300/30"
>
<RefreshCcw className="mr-2 h-4 w-4" />
Retry
</Button>
</CardContent>
</Card>
);
}
export function ConverterEmptyState() {
return (
<Card className="border-border/70">
<CardContent className="p-6">
<p className="text-sm text-muted-foreground">
No assets are currently available. Please try again shortly.
</p>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,22 @@
import type { MarketChartRange } from "@/lib/market";
export const DEFAULT_FROM = "USD";
export const DEFAULT_TO = "BTC";
export const QUICK_AMOUNTS = [10, 50, 100, 500, 1000] as const;
export const DEFAULT_MULTI_CONVERSION_CODES = [
"USD",
"EUR",
"BTC",
"ETH",
"SOL",
] as const;
export const MAX_MULTI_CONVERSIONS = 4;
export const MAX_PINNED_PAIRS = 6;
export const MARKET_RANGE_LABELS: Record<MarketChartRange, string> = {
"24h": "24h",
"7d": "7d",
"30d": "30d",
"1y": "1y",
all: "all",
};

View File

@@ -1,73 +1,45 @@
"use client"; "use client";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { useReducedMotion } from "framer-motion";
import { import { AlertTriangle, Loader2, RefreshCcw } from "lucide-react";
AlertTriangle,
ArrowUpDown,
BarChart3,
Check,
Copy,
Link2,
Loader2,
MoveRight,
RefreshCcw,
Star,
X,
} from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon"; import { ConverterCardAmountInput } from "@/components/converter/converter-card-amount-input";
import { PriceSparkline } from "@/components/converter/price-sparkline"; import { ConverterCardConvertedValue } from "@/components/converter/converter-card-converted-value";
import { CurrencySelect } from "@/components/converter/currency-select"; import { ConverterCardHeader } from "@/components/converter/converter-card-header";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { import {
Card, DEFAULT_FROM,
CardContent, DEFAULT_MULTI_CONVERSION_CODES,
CardDescription, DEFAULT_TO,
CardHeader, MARKET_RANGE_LABELS,
CardTitle, MAX_MULTI_CONVERSIONS,
} from "@/components/ui/card"; MAX_PINNED_PAIRS,
import { Input } from "@/components/ui/input"; QUICK_AMOUNTS,
} from "@/components/converter/converter-card.constants";
import { ConverterCardMarketData } from "@/components/converter/converter-card-market-data";
import { ConverterCardMultiConversion } from "@/components/converter/converter-card-multi-conversion";
import { ConverterCardPairSelection } from "@/components/converter/converter-card-pair-selection";
import { ConverterCardPinnedPairs } from "@/components/converter/converter-card-pinned-pairs";
import { ConverterCardRatesSummary } from "@/components/converter/converter-card-rates-summary";
import {
ConverterEmptyState,
ConverterErrorState,
ConverterSkeleton,
} from "@/components/converter/converter-card-states";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { useCryptoMarket } from "@/hooks/use-crypto-market"; import { useCryptoMarket } from "@/hooks/use-crypto-market";
import { useDebouncedValue } from "@/hooks/use-debounced-value"; import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { usePinnedPairs } from "@/hooks/use-pinned-pairs"; import { type PinnedPair, usePinnedPairs } from "@/hooks/use-pinned-pairs";
import { getDisplaySymbol } from "@/lib/currency-display";
import {
MARKET_CHART_RANGES,
type MarketChartRange,
} from "@/lib/market";
import { useMarketRates } from "@/hooks/use-market-rates"; import { useMarketRates } from "@/hooks/use-market-rates";
import { import { getDisplaySymbol } from "@/lib/currency-display";
formatAmount, import { formatAmount, formatInverseRate, formatRate } from "@/lib/format";
formatInverseRate, import { type MarketChartRange } from "@/lib/market";
formatRate,
formatSignedPercent,
formatTimestamp,
formatUsdCompact,
formatUsdPrice,
} from "@/lib/format";
import { buildRateMap, convertAmount } from "@/lib/rates"; import { buildRateMap, convertAmount } from "@/lib/rates";
import { buildConversionShareUrl } from "@/lib/share-link"; import { buildConversionShareUrl } from "@/lib/share-link";
import { cn } from "@/lib/utils";
import { validateAmount } from "@/lib/validation"; import { validateAmount } from "@/lib/validation";
const DEFAULT_FROM = "USD";
const DEFAULT_TO = "BTC";
const QUICK_AMOUNTS = [10, 50, 100, 500, 1000] as const;
const DEFAULT_MULTI_CONVERSION_CODES = ["USD", "EUR", "BTC", "ETH", "SOL"] as const;
const MAX_MULTI_CONVERSIONS = 4;
const MAX_PINNED_PAIRS = 6;
const MARKET_RANGE_LABELS: Record<MarketChartRange, string> = {
"24h": "24h",
"7d": "7d",
"30d": "30d",
"1y": "1y",
all: "all",
};
interface ConverterCardProps { interface ConverterCardProps {
forcedFromCode?: string; forcedFromCode?: string;
forcedToCode?: string; forcedToCode?: string;
@@ -108,73 +80,6 @@ async function copyTextToClipboard(text: string): Promise<boolean> {
} }
} }
function ConverterSkeleton() {
return (
<Card className="border-border/70">
<CardHeader>
<Skeleton className="h-6 w-40" />
<Skeleton className="h-4 w-72" />
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-14 w-full rounded-xl" />
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
<Skeleton className="h-20 w-full rounded-xl" />
<Skeleton className="mx-auto h-10 w-10 rounded-full" />
<Skeleton className="h-20 w-full rounded-xl" />
</div>
<Skeleton className="h-28 w-full rounded-xl" />
</CardContent>
</Card>
);
}
function ErrorState({
message,
onRetry,
}: {
message: string;
onRetry: () => void;
}) {
return (
<Card className="border-red-500/30 bg-red-500/5">
<CardContent className="flex flex-col gap-4 p-6">
<div className="flex items-start gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 text-red-300" />
<div>
<p className="text-sm font-medium text-red-200">
Unable to load market rates
</p>
<p className="mt-1 text-sm text-red-200/80">{message}</p>
</div>
</div>
<Button
variant="outline"
onClick={onRetry}
className="w-fit border-red-300/30"
>
<RefreshCcw className="mr-2 h-4 w-4" />
Retry
</Button>
</CardContent>
</Card>
);
}
function EmptyState() {
return (
<Card className="border-border/70">
<CardContent className="p-6">
<p className="text-sm text-muted-foreground">
No assets are currently available. Please try again shortly.
</p>
</CardContent>
</Card>
);
}
export function ConverterCard({ export function ConverterCard({
forcedFromCode, forcedFromCode,
forcedToCode, forcedToCode,
@@ -183,6 +88,7 @@ export function ConverterCard({
multiConversionCodes, multiConversionCodes,
}: ConverterCardProps) { }: ConverterCardProps) {
const shouldReduceMotion = useReducedMotion(); const shouldReduceMotion = useReducedMotion();
const prefersReducedMotion = shouldReduceMotion ?? false;
const { data, error, isLoading, refresh } = useMarketRates(); const { data, error, isLoading, refresh } = useMarketRates();
const [amountInput, setAmountInput] = useState("1"); const [amountInput, setAmountInput] = useState("1");
@@ -193,6 +99,7 @@ export function ConverterCard({
const [marketRange, setMarketRange] = useState<MarketChartRange>("24h"); const [marketRange, setMarketRange] = useState<MarketChartRange>("24h");
const [swapAnimationStep, setSwapAnimationStep] = useState(0); const [swapAnimationStep, setSwapAnimationStep] = useState(0);
const [pinStarAnimationStep, setPinStarAnimationStep] = useState(0); const [pinStarAnimationStep, setPinStarAnimationStep] = useState(0);
const { const {
pinnedPairs, pinnedPairs,
isReady: isPinnedPairsReady, isReady: isPinnedPairsReady,
@@ -219,8 +126,7 @@ export function ConverterCard({
if (!rateMap.has(toCode)) { if (!rateMap.has(toCode)) {
const fallback = rateMap.has(DEFAULT_TO) const fallback = rateMap.has(DEFAULT_TO)
? DEFAULT_TO ? DEFAULT_TO
: (assets.find((asset) => asset.code !== fromCode)?.code ?? : (assets.find((asset) => asset.code !== fromCode)?.code ?? assets[0].code);
assets[0].code);
setToCode(fallback); setToCode(fallback);
} }
@@ -428,17 +334,25 @@ export function ConverterCard({
}, [marketData, marketRange]); }, [marketData, marketRange]);
const amountPrefix = getDisplaySymbol(fromAsset); const amountPrefix = getDisplaySymbol(fromAsset);
const currentPair = useMemo( const amountInputPaddingLeft = useMemo(() => {
() => ({ fromCode, toCode }), if (!amountPrefix) {
[fromCode, toCode], return undefined;
); }
const prefixWidthCh = Math.max(amountPrefix.length, 1);
return `calc(1rem + ${prefixWidthCh}ch + 0.85rem)`;
}, [amountPrefix]);
const currentPair = useMemo(() => ({ fromCode, toCode }), [fromCode, toCode]);
const isCurrentPairPinned = isPinnedPair(currentPair); const isCurrentPairPinned = isPinnedPair(currentPair);
const hasReachedPinnedPairsLimit = const hasReachedPinnedPairsLimit =
isPinnedPairsLimitReached && !isCurrentPairPinned; isPinnedPairsLimitReached && !isCurrentPairPinned;
const handleTogglePinnedCurrentPair = () => { const handleTogglePinnedCurrentPair = () => {
setPinStarAnimationStep((current) => current + 1); setPinStarAnimationStep((current) => current + 1);
togglePinnedPair(currentPair); togglePinnedPair(currentPair);
}; };
const pinnedPairItems = useMemo( const pinnedPairItems = useMemo(
() => () =>
pinnedPairs pinnedPairs
@@ -460,32 +374,24 @@ export function ConverterCard({
( (
item, item,
): item is { ): item is {
pair: { fromCode: string; toCode: string }; pair: PinnedPair;
fromAsset: (typeof assets)[number]; fromAsset: (typeof assets)[number];
toAsset: (typeof assets)[number]; toAsset: (typeof assets)[number];
} => Boolean(item), } => Boolean(item),
), ),
[pinnedPairs, rateMap], [pinnedPairs, rateMap],
); );
const amountInputPaddingLeft = useMemo(() => {
if (!amountPrefix) {
return undefined;
}
const prefixWidthCh = Math.max(amountPrefix.length, 1);
return `calc(1rem + ${prefixWidthCh}ch + 0.85rem)`;
}, [amountPrefix]);
if (isLoading && !data) { if (isLoading && !data) {
return <ConverterSkeleton />; return <ConverterSkeleton />;
} }
if (!data && error) { if (!data && error) {
return <ErrorState message={error} onRetry={() => void refresh()} />; return <ConverterErrorState message={error} onRetry={() => void refresh()} />;
} }
if (!data || assets.length === 0) { if (!data || assets.length === 0) {
return <EmptyState />; return <ConverterEmptyState />;
} }
const convertedDisplay = const convertedDisplay =
@@ -494,641 +400,111 @@ export function ConverterCard({
: "--"; : "--";
const amountError = inputValidation.ok ? null : inputValidation.error; const amountError = inputValidation.ok ? null : inputValidation.error;
const activeQuickAmount = inputValidation.ok ? inputValidation.value : null;
const forAmountDisplay =
fromAsset && inputValidation.ok
? formatAmount(inputValidation.value, fromAsset)
: "-";
const pairTransitionKey = const pairTransitionKey =
fromAsset && toAsset ? `${fromAsset.code}-${toAsset.code}` : "empty"; fromAsset && toAsset ? `${fromAsset.code}-${toAsset.code}` : "empty";
return ( return (
<Card className="relative overflow-hidden border-border/70 bg-card/90"> <Card className="relative overflow-hidden border-border/70 bg-card/90">
<CardHeader className="relative isolate z-10 overflow-hidden rounded-t-2xl border-b border-white/5 bg-[linear-gradient(115deg,rgba(16,39,62,0.9)_0%,rgba(14,32,50,0.95)_46%,rgba(14,50,54,0.88)_100%)] pb-4 sm:pb-5 before:pointer-events-none before:absolute before:inset-0 before:bg-[radial-gradient(140%_120%_at_0%_0%,rgba(56,189,248,0.12)_0%,rgba(56,189,248,0)_45%),radial-gradient(120%_100%_at_100%_0%,rgba(16,185,129,0.1)_0%,rgba(16,185,129,0)_45%)] after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-white/10"> <ConverterCardHeader
<div className="flex flex-wrap items-center justify-between gap-2"> fiatSource={data.sources.fiat}
<CardTitle className="text-2xl font-semibold tracking-tight"> cryptoSource={data.sources.crypto}
Currency Converter />
</CardTitle>
<Badge
variant="outline"
className="max-w-full border-border/70 bg-background/50 text-[11px] sm:text-xs"
>
<span className="inline-flex items-center gap-1 whitespace-nowrap sm:hidden">
<span className="text-muted-foreground">Data sources:</span>
<a
href="https://frankfurter.dev/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{data.sources.fiat}
</a>
<span className="text-muted-foreground"></span>
<a
href="https://www.coingecko.com/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{data.sources.crypto}
</a>
</span>
<span className="hidden items-center gap-1 whitespace-nowrap sm:inline-flex">
<span className="text-muted-foreground">Data sources:</span>
<a
href="https://frankfurter.dev/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{data.sources.fiat}
</a>
<span className="text-muted-foreground"></span>
<a
href="https://www.coingecko.com/"
target="_blank"
rel="noreferrer"
className="text-foreground transition-colors hover:text-cyan-100"
>
{data.sources.crypto}
</a>
</span>
</Badge>
</div>
<CardDescription className="pr-1 text-base/7 sm:text-sm">
Convert fiat currencies and cryptocurrencies using live exchange
rates.
</CardDescription>
</CardHeader>
<CardContent className="relative z-10 space-y-5 pt-4 sm:pt-5"> <CardContent className="relative z-10 space-y-5 pt-4 sm:pt-5">
{error ? ( {error ? (
<div className="flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-200"> <div className="flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-200">
<AlertTriangle className="h-4 w-4" /> <AlertTriangle className="h-4 w-4" />
<span> <span>Using last successful data. Latest refresh failed: {error}</span>
Using last successful data. Latest refresh failed: {error}
</span>
</div> </div>
) : null} ) : null}
<div className="space-y-2"> <ConverterCardAmountInput
<label amountInput={amountInput}
htmlFor="amount" amountPrefix={amountPrefix}
className="text-xs uppercase tracking-[0.14em] text-muted-foreground" amountInputPaddingLeft={amountInputPaddingLeft}
> amountError={amountError}
Amount quickAmounts={QUICK_AMOUNTS}
</label> activeQuickAmount={activeQuickAmount}
<div className="relative"> onAmountChange={setAmountInput}
{amountPrefix ? ( onQuickAmountSelect={(value) => setAmountInput(String(value))}
<span className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-sm text-muted-foreground/80"> />
{amountPrefix}
</span>
) : null}
<Input
id="amount"
type="text"
inputMode="decimal"
value={amountInput}
onChange={(event) => setAmountInput(event.target.value)}
placeholder="Enter amount"
className="h-14 rounded-xl bg-background/70 px-4 text-lg"
style={amountInputPaddingLeft ? { paddingLeft: amountInputPaddingLeft } : undefined}
aria-invalid={Boolean(amountError)}
aria-describedby={amountError ? "amount-error" : undefined}
/>
</div>
<div className="flex flex-wrap items-center gap-2 pt-1">
{QUICK_AMOUNTS.map((quickAmount) => {
const isActive =
inputValidation.ok && inputValidation.value === quickAmount;
return ( <ConverterCardPairSelection
<Button assets={assets}
key={quickAmount} fromCode={fromCode}
type="button" toCode={toCode}
variant="outline" shouldReduceMotion={prefersReducedMotion}
size="sm" swapAnimationStep={swapAnimationStep}
onClick={() => setAmountInput(String(quickAmount))} onFromChange={setFromCode}
className={cn( onToChange={setToCode}
"h-7 rounded-full border-border/70 px-3 text-xs text-muted-foreground transition-colors hover:text-foreground", onSwap={handleSwap}
isActive ? "border-cyan-300/50 bg-cyan-500/15 text-cyan-100" : "" />
)}
aria-label={`Set amount to ${quickAmount}`}
>
{quickAmount}
</Button>
);
})}
</div>
{amountError ? (
<p id="amount-error" className="text-sm text-red-300">
{amountError}
</p>
) : null}
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end"> <ConverterCardPinnedPairs
<CurrencySelect shouldReduceMotion={prefersReducedMotion}
label="From" isCurrentPairPinned={isCurrentPairPinned}
value={fromCode} hasReachedPinnedPairsLimit={hasReachedPinnedPairsLimit}
onChange={setFromCode} pinStarAnimationStep={pinStarAnimationStep}
assets={assets} pinnedPairItems={pinnedPairItems}
/> fromCode={fromCode}
<Button toCode={toCode}
type="button" isPinnedPairsReady={isPinnedPairsReady}
size="icon" maxPinnedPairs={MAX_PINNED_PAIRS}
variant="outline" onTogglePinnedCurrentPair={handleTogglePinnedCurrentPair}
className="mx-auto mb-0.5 rounded-full border-border/70 bg-background/50" onSelectPinnedPair={(pair) => {
onClick={handleSwap} setFromCode(pair.fromCode);
aria-label="Swap currencies" setToCode(pair.toCode);
> }}
<motion.span onRemovePinnedPair={removePinnedPair}
className="inline-flex" />
animate={
shouldReduceMotion
? { scale: 1 }
: { rotate: swapAnimationStep * 180, scale: [1, 1.08, 1] }
}
transition={{
rotate: {
duration: shouldReduceMotion ? 0.01 : 0.28,
ease: [0.22, 1, 0.36, 1],
},
scale: {
duration: shouldReduceMotion ? 0.01 : 0.22,
times: [0, 0.35, 1],
},
}}
>
<ArrowUpDown className="h-4 w-4" />
</motion.span>
</Button>
<CurrencySelect
label="To"
value={toCode}
onChange={setToCode}
assets={assets}
/>
</div>
<div className="space-y-2"> <ConverterCardConvertedValue
<div className="flex flex-wrap items-center justify-between gap-2"> shouldReduceMotion={prefersReducedMotion}
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground"> fromAsset={fromAsset}
Pinned pairs toAsset={toAsset}
</p> pairTransitionKey={pairTransitionKey}
<Button convertedDisplay={convertedDisplay}
type="button" forAmountDisplay={forAmountDisplay}
variant="outline" isShareLinkCopied={isShareLinkCopied}
size="sm" isCopied={isCopied}
onClick={handleTogglePinnedCurrentPair} canCopyConvertedValue={convertedValue !== null && Boolean(toAsset)}
disabled={hasReachedPinnedPairsLimit} onCopyShareLink={() => void handleCopyShareLink()}
aria-pressed={isCurrentPairPinned} onCopyConvertedValue={() => void handleCopyConvertedValue()}
aria-label={ />
isCurrentPairPinned
? "Remove current pair from pinned pairs"
: "Add current pair to pinned pairs"
}
className={cn(
"h-8 rounded-full border-border/70 px-3 text-xs transition-colors",
isCurrentPairPinned
? "border-amber-300/50 bg-amber-400/10 text-amber-100 hover:border-amber-300/60 hover:bg-amber-400/15"
: "text-muted-foreground hover:text-foreground",
)}
>
<motion.span
key={`${pinStarAnimationStep}-${isCurrentPairPinned ? "on" : "off"}`}
className="mr-1.5 inline-flex"
initial={
shouldReduceMotion
? false
: { scale: 0.95, rotate: 0, opacity: 0.9 }
}
animate={
shouldReduceMotion
? { scale: 1, rotate: 0, opacity: 1 }
: {
scale: [1, 1.18, 1],
rotate: isCurrentPairPinned ? [0, -12, 8, 0] : [0, 12, -8, 0],
opacity: [1, 1, 1],
}
}
transition={{
duration: shouldReduceMotion ? 0.01 : 0.24,
ease: [0.22, 1, 0.36, 1],
}}
>
<Star
className={cn(
"h-3.5 w-3.5",
isCurrentPairPinned ? "fill-amber-300 text-amber-300" : "",
)}
/>
</motion.span>
{isCurrentPairPinned ? "Pinned" : "Pin current pair"}
</Button>
</div>
{pinnedPairItems.length > 0 ? ( <ConverterCardMultiConversion
<div className="flex flex-wrap gap-2"> shouldReduceMotion={prefersReducedMotion}
{pinnedPairItems.map(({ pair, fromAsset, toAsset }) => { debouncedValidation={debouncedValidation}
const isActive = fromAsset={fromAsset}
pair.fromCode === fromCode && pair.toCode === toCode; multiConversions={multiConversions}
isRatesLoading={isLoading}
return ( />
<div
key={`${pair.fromCode}-${pair.toCode}`}
className={cn(
"inline-flex items-center rounded-full border border-border/70 bg-background/45 pr-0.5",
isActive ? "border-cyan-300/40 bg-cyan-500/10" : "",
)}
>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setFromCode(pair.fromCode);
setToCode(pair.toCode);
}}
className={cn(
"h-8 rounded-full px-2.5 text-xs text-muted-foreground hover:text-foreground",
isActive ? "text-cyan-100 hover:text-cyan-100" : "",
)}
aria-label={`Set pair ${pair.fromCode} to ${pair.toCode}`}
>
<span className="inline-flex items-center gap-1.5">
<CurrencyIcon
code={fromAsset.code}
type={fromAsset.type}
size="sm"
/>
<span>{pair.fromCode}</span>
<MoveRight className="h-3.5 w-3.5 text-cyan-300/90" />
<CurrencyIcon
code={toAsset.code}
type={toAsset.type}
size="sm"
/>
<span>{pair.toCode}</span>
</span>
</Button>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removePinnedPair(pair)}
className="h-7 w-7 rounded-full text-muted-foreground hover:text-red-300 focus-visible:text-red-200"
aria-label={`Remove pinned pair ${pair.fromCode} to ${pair.toCode}`}
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
);
})}
</div>
) : null}
{isPinnedPairsReady && pinnedPairItems.length === 0 ? (
<p className="text-xs text-muted-foreground">
Pin your most-used pairs for one-click access.
</p>
) : null}
{hasReachedPinnedPairsLimit ? (
<p className="text-xs text-amber-200/90">
Pinned pairs limit reached ({MAX_PINNED_PAIRS}). Remove one to add a new pair.
</p>
) : null}
</div>
<div className="rounded-xl border border-border/70 bg-background/50 p-4">
<div className="flex items-center justify-between gap-2">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Converted value
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => void handleCopyShareLink()}
className="h-7 w-7 text-muted-foreground hover:text-foreground"
aria-label={
isShareLinkCopied ? "Share link copied" : "Copy share link"
}
>
{isShareLinkCopied ? (
<Check className="h-3.5 w-3.5 text-cyan-200" />
) : (
<Link2 className="h-3.5 w-3.5" />
)}
</Button>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => void handleCopyConvertedValue()}
disabled={convertedValue === null || !toAsset}
className="h-7 w-7 text-muted-foreground hover:text-foreground"
aria-label={
isCopied
? "Converted value copied"
: "Copy converted value to clipboard"
}
>
{isCopied ? (
<Check className="h-3.5 w-3.5 text-cyan-200" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</Button>
</div>
</div>
{fromAsset && toAsset ? (
<AnimatePresence initial={false} mode="wait">
<motion.div
key={pairTransitionKey}
className="mt-2 flex items-center gap-2 text-xs text-muted-foreground"
initial={
shouldReduceMotion
? false
: { opacity: 0, y: 4, filter: "blur(2px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(2px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.16 }}
>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon
code={fromAsset.code}
type={fromAsset.type}
size="sm"
/>
{fromAsset.code}
</span>
<span>to</span>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon
code={toAsset.code}
type={toAsset.type}
size="sm"
/>
{toAsset.code}
</span>
</motion.div>
</AnimatePresence>
) : null}
<p className="mt-2 break-all text-3xl font-semibold tracking-tight text-foreground sm:text-4xl">
<AnimatePresence initial={false} mode="wait">
<motion.span
key={convertedDisplay}
className="inline-block"
initial={
shouldReduceMotion
? false
: { opacity: 0, y: 6, filter: "blur(2px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion
? { opacity: 0 }
: { opacity: 0, y: -6, filter: "blur(2px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.18 }}
>
{convertedDisplay}
</motion.span>
</AnimatePresence>
</p>
{fromAsset ? (
<p className="mt-2 text-sm text-muted-foreground">
for{" "}
{inputValidation.ok
? formatAmount(inputValidation.value, fromAsset)
: "-"}{" "}
{fromAsset.code}
</p>
) : null}
</div>
<div className="rounded-xl border border-border/70 bg-background/40 p-4">
<div className="flex items-center justify-between gap-2">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Multi conversion
</p>
{fromAsset && debouncedValidation.ok ? (
<span className="text-xs text-muted-foreground">
for {formatAmount(debouncedValidation.value, fromAsset)} {fromAsset.code}
</span>
) : null}
</div>
{!debouncedValidation.ok ? (
<p className="mt-3 text-sm text-red-300">{debouncedValidation.error}</p>
) : null}
{debouncedValidation.ok && multiConversions.length === 0 ? (
<p className="mt-3 text-sm text-muted-foreground">
No additional assets available for multi conversion.
</p>
) : null}
{debouncedValidation.ok && multiConversions.length > 0 ? (
<div className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
{multiConversions.map(({ asset, value }) => (
<div
key={asset.code}
className="rounded-lg border border-border/60 bg-background/60 p-3"
>
<div className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<CurrencyIcon code={asset.code} type={asset.type} size="sm" />
{asset.code}
</div>
<p className="mt-1 text-base font-medium text-foreground">
<AnimatePresence initial={false} mode="wait">
<motion.span
key={`${asset.code}-${formatAmount(value, asset)}`}
className="inline-block"
initial={
shouldReduceMotion
? false
: { opacity: 0, y: 4, filter: "blur(1px)" }
}
animate={
shouldReduceMotion
? { opacity: 1 }
: { opacity: 1, y: 0, filter: "blur(0px)" }
}
exit={
shouldReduceMotion
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(1px)" }
}
transition={{ duration: shouldReduceMotion ? 0.01 : 0.15 }}
>
{formatAmount(value, asset)} {asset.code}
</motion.span>
</AnimatePresence>
</p>
</div>
))}
</div>
) : null}
{isLoading ? (
<div className="mt-3 inline-flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Updating multi conversion...
</div>
) : null}
</div>
<Separator className="bg-border/70" /> <Separator className="bg-border/70" />
<div className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-3"> <ConverterCardRatesSummary
<div> fromAsset={fromAsset}
<p className="text-xs uppercase tracking-[0.12em]">Current rate</p> toAsset={toAsset}
<p className="mt-1 text-sm text-foreground"> currentRate={currentRate}
{fromAsset && toAsset && currentRate inverseRate={inverseRate}
? `1 ${fromAsset.code} = ${currentRate} ${toAsset.code}` updatedAt={displayUpdatedAt ?? data.updatedAt}
: "-"} />
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Inverse rate</p>
<p className="mt-1 text-sm text-foreground">
{fromAsset && toAsset && inverseRate
? `1 ${toAsset.code} = ${inverseRate} ${fromAsset.code}`
: "-"}
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Last updated</p>
<p className="mt-1 text-sm text-foreground">
{formatTimestamp(displayUpdatedAt ?? data.updatedAt)}
</p>
</div>
</div>
{marketAsset ? ( <ConverterCardMarketData
<div className="rounded-xl border border-border/70 bg-background/40 p-4"> marketAsset={marketAsset}
<div className="flex items-center justify-between gap-2"> marketData={marketData}
<p className="inline-flex items-center gap-1.5 text-xs uppercase tracking-[0.12em] text-muted-foreground"> marketError={marketError}
<BarChart3 className="h-3.5 w-3.5" /> isMarketLoading={isMarketLoading}
Market data marketRange={marketRange}
</p> marketRangeLabels={MARKET_RANGE_LABELS}
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/70 px-2 py-1 text-xs text-foreground"> marketRangeChangePct={marketRangeChangePct}
<CurrencyIcon onMarketRangeChange={setMarketRange}
code={marketAsset.code} />
type={marketAsset.type}
size="sm"
/>
{marketAsset.code}
</span>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
{MARKET_CHART_RANGES.map((range) => {
const isActive = marketRange === range;
return (
<Button
key={range}
type="button"
variant="outline"
size="sm"
onClick={() => setMarketRange(range)}
className={cn(
"h-7 rounded-full border-border/70 px-3 text-xs text-muted-foreground hover:text-foreground",
isActive ? "border-cyan-300/50 bg-cyan-500/15 text-cyan-100" : "",
)}
aria-pressed={isActive}
aria-label={`Show ${MARKET_RANGE_LABELS[range]} chart`}
>
{MARKET_RANGE_LABELS[range]}
</Button>
);
})}
</div>
{marketError && !marketData ? (
<p className="mt-3 text-xs text-red-300/90">
Unable to load market data right now.
</p>
) : null}
<PriceSparkline
points={marketData?.priceHistory ?? []}
rangeLabel={MARKET_RANGE_LABELS[marketRange]}
isLoading={isMarketLoading && !marketData}
className="mt-3"
/>
<div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Price
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdPrice(marketData.priceUsd) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
{MARKET_RANGE_LABELS[marketRange]}
</p>
<p
className={cn(
"mt-1 text-base font-medium text-foreground",
marketRangeChangePct !== null
? marketRangeChangePct > 0
? "text-emerald-300"
: marketRangeChangePct < 0
? "text-red-300"
: "text-foreground"
: "text-foreground",
)}
>
{marketData ? formatSignedPercent(marketRangeChangePct) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Market cap
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdCompact(marketData.marketCapUsd) : "-"}
</p>
</div>
<div className="rounded-lg border border-border/60 bg-background/60 p-3">
<p className="text-xs uppercase tracking-[0.1em] text-muted-foreground">
Volume (24h)
</p>
<p className="mt-1 text-base font-medium text-foreground">
{marketData ? formatUsdCompact(marketData.volume24hUsd) : "-"}
</p>
</div>
</div>
<div className="mt-3 flex min-h-4 items-center justify-between gap-2 text-xs text-muted-foreground">
<span>
{marketData
? `Updated ${formatTimestamp(marketData.updatedAt)}`
: isMarketLoading
? "Updating market data..."
: ""}
</span>
{marketData ? <span>Source: {marketData.source}</span> : null}
</div>
</div>
) : null}
<div className="flex items-center justify-end"> <div className="flex items-center justify-end">
<Button <Button