import { ChevronDown, Loader2 } from 'lucide-react' import { Button, ButtonProps } from '@/components/ui/button' import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, } from '@/components/ui/command' import { Drawer, DrawerContent, DrawerTrigger } from '@/components/ui/drawer' import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover' import { Currency } from '@/lib/currency' import { useMediaQuery } from '@/lib/hooks' import { useTranslations } from 'next-intl' import { forwardRef, useEffect, useState } from 'react' type Props = { currencies: Currency[] onValueChange: (currencyCode: Currency['code']) => void /** Currency code to be selected by default. Overwriting this value will update current selection, too. */ defaultValue: Currency['code'] isLoading: boolean } export function CurrencySelector({ currencies, onValueChange, defaultValue, isLoading, }: Props) { const [open, setOpen] = useState(false) const [value, setValue] = useState(defaultValue) const isDesktop = useMediaQuery('(min-width: 768px)') // allow overwriting currently selected currency from outside useEffect(() => { setValue(defaultValue) onValueChange(defaultValue) }, [defaultValue]) const selectedCurrency = currencies.find((currency) => (currency.code ?? '') === value) ?? currencies[0] if (isDesktop) { return ( { setValue(code) onValueChange(code) setOpen(false) }} /> ) } return ( { setValue(id) onValueChange(id) setOpen(false) }} /> ) } function CurrencyCommand({ currencies, onValueChange, }: { currencies: Currency[] onValueChange: (currencyId: Currency['code']) => void }) { const currencyGroup = (currency: Currency) => { switch (currency.code) { case 'USD': case 'EUR': case 'JPY': case 'GBP': case 'CNY': return 'common' default: if (currency.code === '') return 'custom' return 'other' } } const t = useTranslations('Currencies') const currenciesByGroup = currencies.reduce>( (acc, currency) => ({ ...acc, [currencyGroup(currency)]: (acc[currencyGroup(currency)] ?? []).concat([ currency, ]), }), {}, ) return ( {t('noCurrency')}
{Object.entries(currenciesByGroup).map( ([group, groupCurrencies], index) => ( {groupCurrencies.map((currency) => ( { onValueChange(currency.code) }} > ))} ), )}
) } type CurrencyButtonProps = { currency: Currency open: boolean isLoading: boolean } const CurrencyButton = forwardRef( ( { currency, open, isLoading, ...props }: ButtonProps & CurrencyButtonProps, ref, ) => { const iconClassName = 'ml-2 h-4 w-4 shrink-0 opacity-50' return ( ) }, ) CurrencyButton.displayName = 'CurrencyButton' function CurrencyLabel({ currency }: { currency: Currency }) { const flagUrl = `https://flagcdn.com/h24/${ currency?.code.length ? currency.code.slice(0, 2).toLowerCase() : 'un' }.png` return (
{currency.name} {currency.code ? ` (${currency.code})` : ''}
) }