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.

9.8 KB
Raw Blame
import {
  Combobox,
  ComboboxButtonTrigger,
  ComboboxChip,
  ComboboxChips,
  ComboboxChipsInput,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxItem,
  ComboboxList,
  ComboboxSearch,
  ComboboxTriggerPlaceholder,
  ComboboxValue,
  useComboboxAnchor,
} from '@spree/dashboard-ui'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDisplayName } from '../hooks/use-display-name'
import { useStore } from '../providers/store-provider'

interface BaseProps {
  /** Locale codes to pick from. Defaults to the languages of the current store's markets. */
  options?: string[]
  /** Locale to filter out (e.g. the default locale when picking additional supported ones). */
  excludeCode?: string
  /**
   * 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
  placeholder?: string
  /** ID for the trigger / chips input — paired with the parent `<FieldLabel htmlFor>`. */
  id?: string
}

/**
 * Single-select only, by design — the multi-select deliberately does not
 * support these. Its search box is the chips input itself rather than a box
 * inside the popup, and its validity is a property of the whole selection
 * rather than of one control. Declaring them here rather than on `BaseProps`
 * makes passing them to a `multiple` picker a compile error instead of a prop
 * that is silently dropped.
 */
interface SingleProps extends BaseProps {
  multiple?: false
  value: string | null | undefined
  onChange: (locale: string) => void
  /** 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
}

interface MultiProps extends BaseProps {
  multiple: true
  value: string[]
  onChange: (locales: string[]) => void
}

type LocaleSelectProps = SingleProps | MultiProps

/**
 * Mirrors `CurrencySelect`'s row format: `CODE — Localized Name`. Codes the
 * runtime cannot name (`Intl.DisplayNames` returns the code back, as it does
 * for `dz`) render as the bare upper-cased code rather than `DZ — dz`.
 */
function formatOption(code: string, name: string) {
  const upper = code.toUpperCase()
  return !name || name.toLowerCase() === code.toLowerCase() ? upper : `${upper} — ${name}`
}

/**
 * Combobox `filter` factory shared by the single- and multi-select pickers:
 * case-insensitive match on both the raw code and the localized `CODE — Name`
 * label, so typing "pt", "BR", or "Portuguese" all find `pt-BR`.
 */
function localeFilter(labelFor: (locale: string) => string) {
  return (locale: string, query: string) => {
    const q = query.trim().toLowerCase()
    if (!q) return true
    return locale.toLowerCase().includes(q) || labelFor(locale).toLowerCase().includes(q)
  }
}

/**
 * Returns a function that labels a locale code the way the dashboard shows
 * locales everywhere: `EN — English`, named in the admin UI language. For
 * plain-text contexts (option lists, search); render `LocaleLabel` in JSX.
 */
export function useLocaleLabel() {
  const displayName = useDisplayName('language')
  return useCallback((code: string) => formatOption(code, displayName(code) ?? code), [displayName])
}

/**
 * Static text label for a locale code: `EN — English`. Use this in tables
 * and read-only contexts where the picker isn't needed but the same
 * formatting is. Falls back to the upper-cased code when `Intl.DisplayNames`
 * has no entry.
 */
export function LocaleLabel({ code }: { code: string }) {
  const labelFor = useLocaleLabel()
  if (!code) return null
  return <>{labelFor(code)}</>
}

/**
 * Picker for one of the languages the current store's markets offer.
 * Single-select by default; pass `multiple` for a chips multi-select. Each
 * option reads `CODE — Localized Name` (e.g. `EN — English`), named in the
 * admin UI language via the browser's `Intl.DisplayNames`. Use this anywhere
 * the merchant is choosing a storefront language (market default, supported
 * locales list, customer preference, etc.).
 *
 * The single-select field is a button showing the current locale, with the
 * search box inside the dropdown; it is always searchable, whatever the list
 * length, so the field behaves the same on a store with three locales as on
 * one offering the full translatable set.
 */
export function LocaleSelect(props: LocaleSelectProps) {
  const { t } = useTranslation()
  const { locales: storeLocales } = useStore()
  const localeLabel = useLocaleLabel()

  // Union of `props.options` (everything the picker should show) and the
  // currently selected values — so editing an existing record doesn't
  // silently drop chips when the store's locale list later narrows.
  // An empty `options` (store not loaded yet, or a backend that omits
  // `available_locales`) falls back to the store's configured locales rather
  // than rendering an empty picker — matching `CurrencySelect`.
  const items = useMemo(() => {
    const base = props.options?.length ? props.options : storeLocales
    const selected = props.multiple ? props.value : props.value ? [props.value] : []
    const merged = Array.from(new Set([...base, ...selected]))
    return props.excludeCode ? merged.filter((l) => l !== props.excludeCode) : merged
  }, [props.options, props.excludeCode, props.multiple, props.value, storeLocales])

  // Precompute each option's `CODE — Name` label once. The searchable combobox
  // below runs `renderOption` across every item on each keystroke (filter +
  // render), so resolving `Intl.DisplayNames` per call would repeat ~N lookups
  // per character; a lookup map keeps it to a single pass per list change.
  const labels = useMemo(() => {
    const map = new Map<string, string>()
    for (const locale of items) map.set(locale, localeLabel(locale))
    return map
  }, [items, localeLabel])

  // `CODE — Name` label for a locale, from the precomputed map (falls back to a
  // direct lookup for a value not in the current option list, e.g. a selected
  // chip the list later dropped).
  const labelFor = (locale: string) => labels.get(locale) ?? localeLabel(locale)

  if (props.multiple) {
    return (
      <MultiLocalePicker
        id={props.id}
        items={items}
        value={props.value}
        onChange={props.onChange}
        labelFor={labelFor}
        placeholder={props.placeholder ?? t('admin.components.locale_select.multi_placeholder')}
        emptyText={t('admin.components.locale_select.empty')}
        disabled={props.disabled}
      />
    )
  }

  const value = props.value ?? ''
  const placeholder = props.placeholder ?? t('admin.components.locale_select.placeholder')

  return (
    <Combobox
      items={items}
      value={value}
      onValueChange={(next: string | null) => props.onChange(next ?? '')}
      itemToStringLabel={(locale: string | null) => (locale ? labelFor(locale) : '')}
      itemToStringValue={(locale: string | null) => locale ?? ''}
      filter={localeFilter(labelFor)}
      disabled={props.disabled}
    >
      <ComboboxButtonTrigger
        id={props.id}
        onBlur={props.onBlur}
        disabled={props.disabled}
        aria-required={props.required}
        aria-invalid={props.invalid || undefined}
      >
        {value ? (
          <span className="truncate">{labelFor(value)}</span>
        ) : (
          <ComboboxTriggerPlaceholder>{placeholder}</ComboboxTriggerPlaceholder>
        )}
      </ComboboxButtonTrigger>
      <ComboboxContent>
        <ComboboxSearch
          placeholder={
            props.searchPlaceholder ?? t('admin.components.locale_select.search_placeholder')
          }
        />
        <ComboboxEmpty>{t('admin.components.locale_select.empty')}</ComboboxEmpty>
        <ComboboxList>
          {(locale: string) => (
            <ComboboxItem key={locale} value={locale}>
              {labelFor(locale)}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  )
}

function MultiLocalePicker({
  id,
  items,
  value,
  onChange,
  labelFor,
  placeholder,
  emptyText,
  disabled,
}: {
  id?: string
  items: string[]
  value: string[]
  onChange: (locales: string[]) => void
  labelFor: (code: string) => string
  placeholder: string
  emptyText: string
  disabled?: boolean
}) {
  const anchorRef = useComboboxAnchor()
  const [inputValue, setInputValue] = useState('')

  return (
    <Combobox
      multiple
      items={items}
      value={value}
      onValueChange={(next: string[]) => {
        onChange(next)
        setInputValue('')
      }}
      // Search the same `CODE — Name` labels as the single-select picker — the
      // canonical locale list is too long to scan by raw code alone.
      itemToStringLabel={(locale: string | null) => (locale ? labelFor(locale) : '')}
      itemToStringValue={(locale: string | null) => locale ?? ''}
      filter={localeFilter(labelFor)}
      disabled={disabled}
    >
      <ComboboxChips ref={anchorRef}>
        <ComboboxValue>
          {(selectedLocales: string[]) =>
            selectedLocales.map((l) => <ComboboxChip key={l}>{labelFor(l)}</ComboboxChip>)
          }
        </ComboboxValue>
        <ComboboxChipsInput
          id={id}
          placeholder={placeholder}
          value={inputValue}
          onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}
        />
      </ComboboxChips>
      <ComboboxContent anchor={anchorRef}>
        <ComboboxEmpty>{emptyText}</ComboboxEmpty>
        <ComboboxList>
          {(locale: string) => (
            <ComboboxItem key={locale} value={locale}>
              {labelFor(locale)}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  )
}