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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fixed country pickers in admin spa
Damian Legawiec7b3e19af31cc
diff --git a/packages/admin/src/components/spree/address-form-dialog.tsx b/packages/admin/src/components/spree/address-form-dialog.tsxindex 1708eb4139..f913c2a895 100644--- a/packages/admin/src/components/spree/address-form-dialog.tsx+++ b/packages/admin/src/components/spree/address-form-dialog.tsx@@ -1,10 +1,7 @@import type { Address } from '@spree/admin-sdk'import { type FormEvent, useCallback, useState } from 'react'-import {- CountryCombobox,- StateCombobox,- useCountryStates,-} from '@/components/spree/country-state-fields'+import { CountryCombobox } from '@/components/spree/country-combobox'+import { StateCombobox, useCountryStates } from '@/components/spree/country-state-fields'import { Button } from '@/components/ui/button'import { Checkbox } from '@/components/ui/checkbox'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'diff --git a/packages/admin/src/components/spree/country-combobox.tsx b/packages/admin/src/components/spree/country-combobox.tsxnew file mode 100644index 0000000000..cc532c1fc0--- /dev/null+++ b/packages/admin/src/components/spree/country-combobox.tsx@@ -0,0 +1,201 @@+import { useMemo, useState } from 'react'+import { CountryFlag } from '@/components/spree/country-flag'+import {+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxValue,+ useComboboxAnchor,+} from '@/components/ui/combobox'+import { InputGroupAddon } from '@/components/ui/input-group'+import { useCountries } from '@/hooks/use-countries'+import { useTranslation } from '@/lib/i18n'++export type CountryOption = { iso: string; iso3: string; name: string }++/**+ * Case-insensitive substring match against name, iso, and iso3 so the user+ * can find a country by typing "United States", "US", or "USA". Both pickers+ * filter the cached `useCountries()` list client-side — countries are a+ * ~250-row static set, so there's no remote search. Mirrors the server-side+ * `search` Ransack scope (`Spree::Country.search`).+ */+export function countryFilter(item: CountryOption, query: string): boolean {+ const q = query.trim().toLowerCase()+ if (!q) return true+ return (+ item.name.toLowerCase().includes(q) ||+ item.iso.toLowerCase().includes(q) ||+ item.iso3.toLowerCase().includes(q)+ )+}++/**+ * Shared dropdown row used by both pickers — flag + name + ISO code in a+ * muted suffix. The ISO code makes ISO-based matches (typing "US"/"USA")+ * comprehensible and keeps the two pickers visually consistent.+ */+function CountryRow({ country }: { country: CountryOption }) {+ return (+ <>+ <CountryFlag iso={country.iso} />+ <span>{country.name}</span>+ {country.iso && <span className="text-xs text-muted-foreground">({country.iso})</span>}+ </>+ )+}++/**+ * Searchable single-select country picker. Value is the 2-letter ISO code+ * (so the field round-trips cleanly with the Spree API). Renders the country+ * name + flag in the trigger and `<CountryRow>` in the dropdown.+ */+export function CountryCombobox({+ value,+ onValueChange,+ placeholder = 'Search countries...',+ disabled = false,+}: {+ value: string | null | undefined+ onValueChange: (iso: string) => void+ placeholder?: string+ disabled?: boolean+}) {+ const { countries } = useCountries()++ const items: CountryOption[] = useMemo(+ () => countries.map((c) => ({ iso: c.iso, iso3: c.iso3, name: c.name })),+ [countries],+ )++ // The Combobox holds the selected object internally; we adapt to a flat ISO+ // string at the boundary so callers don't have to thread the option shape.+ const selected = useMemo(() => items.find((c) => c.iso === value) ?? null, [items, value])++ return (+ <Combobox+ items={items}+ value={selected}+ onValueChange={(c: CountryOption | null) => onValueChange(c?.iso ?? '')}+ itemToStringLabel={(c: CountryOption | null) => c?.name ?? ''}+ itemToStringValue={(c: CountryOption | null) => c?.iso ?? ''}+ // Default filter matches name only via `itemToStringLabel`. Widen it so+ // typing the ISO code ("US", "USA") also matches.+ filter={countryFilter}+ >+ <ComboboxInput placeholder={placeholder} disabled={disabled}>+ {/* When a country is picked the InputGroup gets a leading flag —+ mirrors the dropdown items so the trigger shows the same shape.+ Hidden while empty so the input doesn't lurch when typing a new+ search query. */}+ {selected?.iso && (+ <InputGroupAddon align="inline-start">+ <CountryFlag iso={selected.iso} />+ </InputGroupAddon>+ )}+ </ComboboxInput>+ <ComboboxContent>+ <ComboboxEmpty>No countries found</ComboboxEmpty>+ <ComboboxList>+ {(country: CountryOption) => (+ <ComboboxItem key={country.iso} value={country}>+ <CountryRow country={country} />+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+}++/**+ * Searchable multi-select country picker. Value is an array of 2-letter ISO+ * codes. Renders a flag + name per chip and `<CountryRow>` per dropdown row;+ * filters the cached `useCountries()` list client-side via `countryFilter`+ * (name + both ISO codes). Reused anywhere the admin picks multiple+ * countries (promotion Country rule, market/zone editors, …).+ */+export function CountryMultiCombobox({+ value,+ onValueChange,+ placeholder,+ emptyText,+ disabled = false,+}: {+ /** Selected 2-letter ISO codes. */+ value: string[]+ /** Fires with the next array of ISO codes. */+ onValueChange: (isos: string[]) => void+ placeholder?: string+ emptyText?: string+ disabled?: boolean+}) {+ const { t } = useTranslation()+ const { countries } = useCountries()+ const anchorRef = useComboboxAnchor()+ const [inputValue, setInputValue] = useState('')++ const items: CountryOption[] = useMemo(+ () => countries.map((c) => ({ iso: c.iso, iso3: c.iso3, name: c.name })),+ [countries],+ )++ // The Combobox holds full option objects; selection round-trips as ISO+ // strings. Selected ISOs not yet present in `items` (list still loading)+ // fall back to a stub so chips don't vanish on first render.+ const selected = useMemo<CountryOption[]>(+ () => value.map((iso) => items.find((c) => c.iso === iso) ?? { iso, iso3: '', name: iso }),+ [value, items],+ )++ return (+ <Combobox+ multiple+ items={items}+ value={selected}+ onValueChange={(next: CountryOption[]) => {+ onValueChange(next.map((c) => c.iso))+ setInputValue('')+ }}+ itemToStringLabel={(c: CountryOption | null) => c?.name ?? ''}+ itemToStringValue={(c: CountryOption | null) => c?.iso ?? ''}+ isItemEqualToValue={(a: CountryOption, b: CountryOption) => a.iso === b.iso}+ filter={countryFilter}+ disabled={disabled}+ >+ <ComboboxChips ref={anchorRef}>+ <ComboboxValue>+ {(selectedCountries: CountryOption[]) =>+ selectedCountries.map((c) => (+ <ComboboxChip key={c.iso}>+ {c.iso && <CountryFlag iso={c.iso} />}+ {c.name}+ </ComboboxChip>+ ))+ }+ </ComboboxValue>+ <ComboboxChipsInput+ placeholder={placeholder ?? t('admin.promotions.rules.country.search_placeholder')}+ value={inputValue}+ onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}+ />+ </ComboboxChips>+ <ComboboxContent anchor={anchorRef}>+ <ComboboxEmpty>{emptyText ?? t('admin.promotions.rules.country.empty')}</ComboboxEmpty>+ <ComboboxList>+ {(country: CountryOption) => (+ <ComboboxItem key={country.iso} value={country}>+ <CountryRow country={country} />+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+}diff --git a/packages/admin/src/components/spree/country-state-fields.tsx b/packages/admin/src/components/spree/country-state-fields.tsxindex 7784c82f01..d1522c90d0 100644--- a/packages/admin/src/components/spree/country-state-fields.tsx+++ b/packages/admin/src/components/spree/country-state-fields.tsx@@ -1,6 +1,5 @@import type { State } from '@spree/admin-sdk'import { useMemo } from 'react'-import { CountryFlag } from '@/components/spree/country-flag'import {Combobox,ComboboxContent,@@ -9,10 +8,8 @@ import {ComboboxItem,ComboboxList,} from '@/components/ui/combobox'-import { InputGroupAddon } from '@/components/ui/input-group'import { useCountries } from '@/hooks/use-countries'-type CountryOption = { iso: string; name: string }type StateOption = { abbr: string; name: string }/**@@ -32,75 +29,6 @@ export function useCountryStates(countryIso: string | null | undefined) {}}-// ----------------------------------------------------------------------------// CountryCombobox-// -----------------------------------------------------------------------------/**- * Searchable country picker. Value is the 2-letter ISO code (so the field- * round-trips cleanly with the Spree API). Renders the country name + flag in- * the trigger and dropdown.- */-export function CountryCombobox({- value,- onValueChange,- placeholder = 'Search countries...',- disabled = false,-}: {- value: string | null | undefined- onValueChange: (iso: string) => void- placeholder?: string- disabled?: boolean-}) {- const { countries } = useCountries()-- const items: CountryOption[] = useMemo(- () => countries.map((c) => ({ iso: c.iso, name: c.name })),- [countries],- )-- // The Combobox holds the selected object internally; we adapt to a flat ISO- // string at the boundary so callers don't have to thread the option shape.- const selected = useMemo(() => items.find((c) => c.iso === value) ?? null, [items, value])-- return (- <Combobox- items={items}- value={selected}- onValueChange={(c: CountryOption | null) => onValueChange(c?.iso ?? '')}- itemToStringLabel={(c: CountryOption | null) => c?.name ?? ''}- itemToStringValue={(c: CountryOption | null) => c?.iso ?? ''}- >- <ComboboxInput placeholder={placeholder} disabled={disabled}>- {/* When a country is picked the InputGroup gets a leading flag —- mirrors the dropdown items so the trigger shows the same shape.- Hidden while empty so the input doesn't lurch when typing a new- search query. */}- {selected?.iso && (- <InputGroupAddon align="inline-start">- <CountryFlag iso={selected.iso} />- </InputGroupAddon>- )}- </ComboboxInput>- <ComboboxContent>- <ComboboxEmpty>No countries found</ComboboxEmpty>- <ComboboxList>- {(country: CountryOption) => (- <ComboboxItem key={country.iso} value={country}>- <CountryFlag iso={country.iso} />- {country.name}- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- )-}--// ----------------------------------------------------------------------------// StateCombobox-// ----------------------------------------------------------------------------/*** Searchable state/province picker for a given country. Value is the state* abbreviation (e.g. "CA"). Callers should hide this and render a free-textdiff --git a/packages/admin/src/components/spree/promotion-editors/rule-country.tsx b/packages/admin/src/components/spree/promotion-editors/rule-country.tsxindex 576a2a4b3d..6975ce7b23 100644--- a/packages/admin/src/components/spree/promotion-editors/rule-country.tsx+++ b/packages/admin/src/components/spree/promotion-editors/rule-country.tsx@@ -1,28 +1,45 @@import type { Country } from '@spree/admin-sdk'-import { useState } from 'react'-import { adminClient } from '@/client'-import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { useMemo, useState } from 'react'+import { CountryMultiCombobox } from '@/components/spree/country-combobox'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { useCountries } from '@/hooks/use-countries'+import { useTranslation } from '@/lib/i18n'import { EditorShell } from './editor-shell'import type { PromotionRuleEditorContext } from './types'/**+ * Multi-select country picker for the promotion Country rule.+ ** Stores ISO codes — the `Country` resource has no numeric id, so its- * primary key is `iso`. The autocomplete contract requires `{id: string}`,- * so we project ISO onto `id` for the picker and round-trip it through- * the rule's `country_isos` preference.+ * primary key is `iso`. The rule's `country_isos` preference and the+ * display-only `countries` records are both derived from the selected+ * ISO set on save. The picker UI lives in the shared+ * `<CountryMultiCombobox>` so it stays consistent with the address-form+ * country pickers.*/export function CountryRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const { t } = useTranslation()+ const { countries } = useCountries()+const [countryIsos, setCountryIsos] = useState<string[]>(() =>((draft.preferences?.country_isos ?? []) as string[]).map((s) => s.toUpperCase()),)- const [countries, setCountries] = useState<Country[]>(draft.countries ?? [])++ // Display-only `countries` records for the rule summary — derived from the+ // cached list, stripped at payload time.+ const selectedCountries = useMemo<Country[]>(+ () =>+ countryIsos+ .map((iso) => countries.find((c) => c.iso === iso))+ .filter((c): c is Country => Boolean(c)),+ [countryIsos, countries],+ )function handleSave() {onSave({...draft,preferences: { ...draft.preferences, country_isos: countryIsos },- countries,+ countries: selectedCountries,})onClose()}@@ -31,43 +48,10 @@ export function CountryRuleEditor({ draft, onSave, onClose }: PromotionRuleEdito<EditorShell onSave={handleSave} onCancel={onClose} pending={false}><FieldGroup><Field>- <FieldLabel>Countries</FieldLabel>- <ResourceMultiAutocomplete<CountryOption>- queryKey="promotion-rule-countries"- value={countryIsos}- onChange={setCountryIsos}- onResolvedOptionsChange={(options) => setCountries(options.map(fromOption))}- search={async (q) => {- const result = await adminClient.countries.list({- name_cont: q,- limit: 20,- sort: 'name',- })- return { data: result.data.map(toOption) }- }}- hydrate={async (isos) => {- const result = await adminClient.countries.list({- iso_in: isos,- limit: isos.length,- })- return { data: result.data.map(toOption) }- }}- getOptionLabel={(c) => `${c.name} (${c.id})`}- placeholder="Search countries…"- emptyText="No countries match"- />+ <FieldLabel>{t('admin.promotions.rules.country.label')}</FieldLabel>+ <CountryMultiCombobox value={countryIsos} onValueChange={setCountryIsos} /></Field></FieldGroup></EditorShell>)}--type CountryOption = { id: string; name: string; raw: Country }--function toOption(country: Country): CountryOption {- return { id: country.iso, name: country.name, raw: country }-}--function fromOption(option: CountryOption): Country {- return option.raw-}diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsxindex 93b31e0fe4..98b9ce0493 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx@@ -13,11 +13,8 @@ import { z } from 'zod/v4'import { adminClient } from '@/client'import { Can } from '@/components/spree/can'import { useConfirm } from '@/components/spree/confirm-dialog'-import {- CountryCombobox,- StateCombobox,- useCountryStates,-} from '@/components/spree/country-state-fields'+import { CountryCombobox } from '@/components/spree/country-combobox'+import { StateCombobox, useCountryStates } from '@/components/spree/country-state-fields'import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'import { useRowClickBridge } from '@/components/spree/row-click-bridge'import { Button } from '@/components/ui/button'diff --git a/spree/core/app/models/spree/country.rb b/spree/core/app/models/spree/country.rbindex 954f465f68..a8360e5ff4 100644--- a/spree/core/app/models/spree/country.rb+++ b/spree/core/app/models/spree/country.rb@@ -1,6 +1,6 @@module Spreeclass Country < Spree.base_class- self.whitelisted_ransackable_attributes = %w[iso iso3 iso_name]+ self.whitelisted_ransackable_attributes = %w[iso iso3 iso_name name]has_many :addresses, dependent: :restrict_with_errorhas_many :states,