Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

7.2 KB
Raw Blame
import { type CurrencyCode, isCurrencyCode } from '@spree/core'
import {
  Combobox,
  ComboboxButtonTrigger,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxItem,
  ComboboxList,
  ComboboxSearch,
  ComboboxTriggerPlaceholder,
} from '@spree/dashboard-ui'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDisplayName } from '../hooks/use-display-name'
import { useOptionalStore } from '../providers/store-provider'

export { ACTIVE_CURRENCY_CODES as ALL_CURRENCY_CODES } from '@spree/core'

interface CurrencySelectProps {
  /** Classes for the trigger — used to match a neighbouring control's height. */
  triggerClassName?: string
  /** `sm` matches the toolbar controls beside it — see `SelectTrigger`. */
  triggerSize?: 'sm' | 'default'
  /** ID for the trigger — paired with the parent `<FieldLabel htmlFor>`. */
  id?: string
  /** Submit name — a hidden input mirrors the value so plain `FormData` works. */
  name?: string
  /** Initial selection. Falls back to the store's default currency. */
  defaultValue?: string
  /** Controlled value. Pair with `onChange` to lift state out. */
  value?: string
  /** Fires on every selection change. */
  onChange?: (currency: CurrencyCode) => void
  /**
   * Currency codes to pick from. Defaults to the currencies of the current
   * store's markets. Pass `ALL_CURRENCY_CODES` (or any custom list) for
   * contexts where the merchant chooses a currency the store doesn't yet
   * support — e.g. a market's currency.
   */
  options?: readonly CurrencyCode[]
  /**
   * Announces the field as required to assistive technology (`aria-required`).
   * It does not enforce anything: the trigger is a button, so there is no
   * native constraint validation behind it. The consuming form owns
   * enforcement.
   */
  required?: boolean
  disabled?: boolean
  /** Text in the dropdown's search box. */
  searchPlaceholder?: string
  invalid?: boolean
  /** Forwarded to the trigger so RHF's `<Controller>` can track touched state. */
  onBlur?: () => void
}

/**
 * Picker for a currency code. Defaults to the currencies of the
 * current store's markets (the default market's first), so callers
 * choosing among already-configured currencies don't have to wire anything up.
 * Pass `options` (e.g. `ALL_CURRENCY_CODES`) when the merchant may pick any
 * currency, such as a market's currency. Each option reads `CODE — Full Name`
 * (e.g. `USD — US Dollar`), with the name localized to the admin UI language.
 *
 * Always searchable, whatever the list length. The picker used to fall back to
 * a plain `<Select>` under a dozen options, which meant the same field behaved
 * differently from one store to the next — typing to filter worked on a store
 * with many currencies and did nothing on a store with three.
 */
export function CurrencySelect({
  id,
  name,
  defaultValue,
  value: controlledValue,
  onChange,
  options,
  required,
  disabled,
  searchPlaceholder,
  invalid,
  onBlur,
  triggerClassName,
  triggerSize,
}: CurrencySelectProps) {
  const { t } = useTranslation()
  // Optional: the operator's dashboard always has a store, the seller panel
  // has none — its tenant is a seller and the store is derived server-side.
  // Without one the picker renders from the `options` its caller passes,
  // rather than refusing to render at all. It deliberately does NOT fall back
  // to every ISO code: a currency the store does not trade in saves fine and
  // then quotes nothing.
  const store = useOptionalStore()
  const currencies = store?.currencies ?? []
  const defaultCurrency = store?.defaultCurrency ?? ''
  const [internalValue, setInternalValue] = useState(defaultValue ?? defaultCurrency)
  const isControlled = controlledValue !== undefined
  // Controlled callers that pass an empty value still see the store default
  // in the dropdown. Derive it here without emitting onChange — committing the
  // fallback during render dirties forms and re-triggers effects. The caller
  // gets the real value the first time the merchant interacts.
  const value = isControlled ? controlledValue || defaultCurrency : internalValue
  const displayNameFor = useDisplayName('currency')

  // Union of the option list and the current value so editing a record whose
  // currency isn't in the list (a store-supported list that later narrowed)
  // never silently drops the selection. An empty `options` falls back to the
  // store's currencies rather than an empty picker.
  const items = useMemo(() => {
    const base = options?.length ? options : currencies
    return isCurrencyCode(value) && !base.includes(value) ? [value, ...base] : base
  }, [options, currencies, value])

  const handleChange = (next: CurrencyCode) => {
    if (!isControlled) setInternalValue(next)
    onChange?.(next)
  }

  const renderOption = (code: string) => {
    const currencyName = displayNameFor(code)
    // Avoid `USD — USD` when the resolver falls back to the code itself.
    return currencyName && currencyName !== code ? `${code} — ${currencyName}` : code
  }

  // Case-insensitive match against the code and its localized name so typing
  // "EUR" or "Euro" both find it.
  const filter = (code: CurrencyCode, query: string) => {
    const q = query.trim().toLowerCase()
    if (!q) return true
    return code.toLowerCase().includes(q) || renderOption(code).toLowerCase().includes(q)
  }

  const hiddenInput = name ? <input type="hidden" name={name} value={value} /> : null

  return (
    <>
      {/* Hidden input keeps the parent `<form>` submit / FormData path working
          without each caller having to thread the value through state. */}
      {hiddenInput}
      <Combobox
        items={items}
        value={isCurrencyCode(value) ? value : null}
        // Nothing on the picker clears it, so a null selection is not a choice
        // to report.
        onValueChange={(next: CurrencyCode | null) => {
          if (next) handleChange(next)
        }}
        itemToStringLabel={(code: CurrencyCode | null) => (code ? renderOption(code) : '')}
        itemToStringValue={(code: CurrencyCode | null) => code ?? ''}
        filter={filter}
        disabled={disabled}
      >
        <ComboboxButtonTrigger
          id={id}
          size={triggerSize}
          className={triggerClassName}
          onBlur={onBlur}
          disabled={disabled}
          aria-required={required}
          aria-invalid={invalid || undefined}
        >
          {value ? (
            <span className="truncate">{renderOption(value)}</span>
          ) : (
            <ComboboxTriggerPlaceholder>
              {t('admin.components.currency_select.placeholder')}
            </ComboboxTriggerPlaceholder>
          )}
        </ComboboxButtonTrigger>
        <ComboboxContent>
          <ComboboxSearch
            placeholder={
              searchPlaceholder ?? t('admin.components.currency_select.search_placeholder')
            }
          />
          <ComboboxEmpty>{t('admin.components.currency_select.empty')}</ComboboxEmpty>
          <ComboboxList>
            {(code: CurrencyCode) => (
              <ComboboxItem key={code} value={code}>
                {renderOption(code)}
              </ComboboxItem>
            )}
          </ComboboxList>
        </ComboboxContent>
      </Combobox>
    </>
  )
}