54 lines
1.7 KiB
TypeScript
54 lines
1.7 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import { useCurrency } from '@/lib/CurrencyContext';
|
|
import { CURRENCIES } from '@/lib/currency';
|
|
|
|
export default function CurrencySelector() {
|
|
const { currency, setCurrency } = useCurrency();
|
|
const [open, setOpen] = useState(false);
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
|
|
useEffect(() => {
|
|
const onClickOutside = (e: MouseEvent) => {
|
|
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
|
};
|
|
document.addEventListener('mousedown', onClickOutside);
|
|
return () => document.removeEventListener('mousedown', onClickOutside);
|
|
}, []);
|
|
|
|
const active = CURRENCIES.find((c) => c.code === currency) ?? CURRENCIES[0];
|
|
|
|
return (
|
|
<div ref={ref} className="relative hidden md:block">
|
|
<button
|
|
onClick={() => setOpen((o) => !o)}
|
|
aria-expanded={open}
|
|
className="tag-label flex items-center gap-1 hover:text-ink"
|
|
>
|
|
{active.symbol} {active.code}
|
|
<span className={`inline-block transition-transform ${open ? 'rotate-180' : ''}`}>▾</span>
|
|
</button>
|
|
|
|
{open && (
|
|
<div className="absolute right-0 top-full mt-2 w-44 border border-line bg-paper shadow-sm">
|
|
{CURRENCIES.map((c) => (
|
|
<button
|
|
key={c.code}
|
|
onClick={() => {
|
|
setCurrency(c.code);
|
|
setOpen(false);
|
|
}}
|
|
className={`block w-full px-4 py-3 text-left text-sm hover:bg-surface ${
|
|
c.code === currency ? 'text-clay' : ''
|
|
}`}
|
|
>
|
|
{c.symbol} {c.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|