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
Localize Rails admin country, currency, and locale display names (#14220)
Damian Legawiece4b9afa91bc6
diff --git a/spree/admin/app/controllers/spree/admin/base_controller.rb b/spree/admin/app/controllers/spree/admin/base_controller.rbindex 0a77e739c0..69120549dc 100644--- a/spree/admin/app/controllers/spree/admin/base_controller.rb+++ b/spree/admin/app/controllers/spree/admin/base_controller.rb@@ -12,6 +12,7 @@ module Spreehelper 'spree/admin/navigation'helper 'spree/locale'helper 'spree/currency'+ helper 'spree/localized_names'helper 'spree/addresses'helper 'spree/integrations'diff --git a/spree/admin/app/controllers/spree/admin/countries_controller.rb b/spree/admin/app/controllers/spree/admin/countries_controller.rbindex 6d28e8e6fe..44b9c08159 100644--- a/spree/admin/app/controllers/spree/admin/countries_controller.rb+++ b/spree/admin/app/controllers/spree/admin/countries_controller.rb@@ -1,12 +1,26 @@module Spreemodule Adminclass CountriesController < Spree::Admin::BaseController+ # Returns every accessible country, sorted by its localized name. The set+ # is small and fixed, so the admin autocomplete loads the full list once+ # and filters it client-side (in the admin UI locale) rather than querying+ # the server per keystroke.+ #+ # `name` is the underlying value used for filtering (the stored English+ # country name); `label` is the localized, flag-prefixed display string.def select_options- q = params[:q]- ransack_params = q.is_a?(String) ? { name_cont: q } : q- countries = Spree::Country.accessible_by(current_ability).ransack(ransack_params).result.order(:name).limit(50)+ countries = Spree::Country.accessible_by(current_ability, :show).+ sort_by { |country| Spree::LocalizedNames.country_name(country.iso, fallback: country.name) }- render json: countries.pluck(:id, :name).map { |id, name| { id: id, name: name } }+ options = countries.map do |country|+ {+ id: country.id,+ name: country.name,+ label: Spree::LocalizedNames.country_option_label(country)+ }+ end++ render json: optionsendendenddiff --git a/spree/admin/app/javascript/spree/admin/application.js b/spree/admin/app/javascript/spree/admin/application.jsindex ecd2cda730..53dfdb524e 100644--- a/spree/admin/app/javascript/spree/admin/application.js+++ b/spree/admin/app/javascript/spree/admin/application.js@@ -55,6 +55,7 @@ import CodeMirrorController from 'spree/admin/controllers/codemirror_controller'import ColorPaletteController from 'spree/admin/controllers/color_palette_controller'import ColumnSelectorController from 'spree/admin/controllers/column_selector_controller'import ColorPickerController from 'spree/admin/controllers/color_picker_controller'+import DisplayNameController from 'spree/admin/controllers/display_name_controller'import DropdownController from 'spree/admin/controllers/dropdown_controller'import FiltersController from 'spree/admin/controllers/filters_controller'import FontPickerController from 'spree/admin/controllers/font_picker_controller'@@ -120,6 +121,7 @@ application.register('codemirror', CodeMirrorController)application.register('color-palette', ColorPaletteController)application.register('color-picker', ColorPickerController)application.register('column-selector', ColumnSelectorController)+application.register('display-name', DisplayNameController)application.register('dialog', Dialog)application.register('drawer', Dialog)application.register('disable-submit-button', DisableSubmitButtonController)diff --git a/spree/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js b/spree/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.jsindex ca02292e7f..f9bd5f9e79 100644--- a/spree/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js+++ b/spree/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js@@ -1,11 +1,15 @@import { Controller } from "@hotwired/stimulus"import TomSelect from 'tom-select/dist/esm/tom-select.complete.js';+import { localizeSelectOptions } from 'spree/admin/helpers/display_names'// this is a very simple autocomplete select controller that uses TomSelect// by default it does not support remote data fetching or adding new options// that scenarios are handled in the more robust select_controller.jsexport default class extends Controller {connect() {+ const displayNamesType = this.element.dataset.displayNamesType+ if (displayNamesType) localizeSelectOptions(this.element, displayNamesType)+let selectedValue = this.element.valuelet plugins = []diff --git a/spree/admin/app/javascript/spree/admin/controllers/display_name_controller.js b/spree/admin/app/javascript/spree/admin/controllers/display_name_controller.jsnew file mode 100644index 0000000000..c4ba5fca32--- /dev/null+++ b/spree/admin/app/javascript/spree/admin/controllers/display_name_controller.js@@ -0,0 +1,18 @@+import { Controller } from '@hotwired/stimulus'+import { adminUiLocale, formatCodeName, intlDisplayName } from 'spree/admin/helpers/display_names'++/**+ * Upgrades a server-rendered code/name label to its `Intl.DisplayNames`+ * equivalent in the admin UI language once JS is available.+ */+export default class extends Controller {+ static values = {+ type: String,+ code: String+ }++ connect() {+ const name = intlDisplayName(this.typeValue, this.codeValue, adminUiLocale())+ if (name) this.element.textContent = formatCodeName(this.codeValue, name)+ }+}diff --git a/spree/admin/app/javascript/spree/admin/controllers/query_builder_controller.js b/spree/admin/app/javascript/spree/admin/controllers/query_builder_controller.jsindex a52143534b..7281d8562e 100644--- a/spree/admin/app/javascript/spree/admin/controllers/query_builder_controller.js+++ b/spree/admin/app/javascript/spree/admin/controllers/query_builder_controller.js@@ -355,8 +355,21 @@ export default class extends Controller {if (fieldConfig.search_url) {wrapper.dataset.selectUrlValue = fieldConfig.search_url- // Use remote search mode so it doesn't pre-fetch and overwrite our preloaded options- wrapper.dataset.selectRemoteSearchValue = "true"++ if (fieldConfig.preload_options) {+ // Small, fixed option set: load it once and filter client-side on+ // the localized `label` while submitting the underlying value.+ wrapper.dataset.selectLabelFieldValue = "label"+ wrapper.dataset.selectSearchFieldValue = "label"+ // Preserve the server's localized-name ordering. The label is+ // flag-prefixed, so sorting by it would order by flag codepoints+ // (ISO) instead of name; "$order" keeps the received order.+ wrapper.dataset.selectSortFieldValue = "$order"+ } else {+ // Remote search mode so it doesn't pre-fetch and overwrite our+ // preloaded options (datasets here are large / server-limited).+ wrapper.dataset.selectRemoteSearchValue = "true"+ }}// Use name as value field for tags (tags_name ransack attribute expects tag names)@@ -371,17 +384,27 @@ export default class extends Controller {input.dataset.selectTarget = "input"input.dataset.valueInput = "" // Mark as value input for serialization- // Restore existing values - we store as array of {id, name} objects- // Use remoteSearchActiveOption which properly preloads options and selects them+ // Restore existing values - we store as array of {id, name} objects.if (existingValue !== null && existingValue !== undefined && Array.isArray(existingValue) && existingValue.length > 0) {- const preloadedOptions = existingValue.map(item => {- if (typeof item === 'object') {- return { id: useNameAsValue ? item.name : item.id, name: item.name }- } else {- return { id: item, name: item }- }- })- wrapper.dataset.selectRemoteSearchActiveOptionValue = JSON.stringify(preloadedOptions)+ if (fieldConfig.preload_options) {+ // The full option list is preloaded, so we only need the selected+ // values; Tom Select resolves their labels from the loaded options.+ const selectedValues = existingValue.map(item =>+ String(typeof item === 'object' ? item.id : item)+ )+ wrapper.dataset.selectActiveOptionValue = JSON.stringify(selectedValues)+ } else {+ // Remote search: preload the selected options so they render with+ // their labels without first issuing a search.+ const preloadedOptions = existingValue.map(item => {+ if (typeof item === 'object') {+ return { id: useNameAsValue ? item.name : item.id, name: item.name }+ } else {+ return { id: item, name: item }+ }+ })+ wrapper.dataset.selectRemoteSearchActiveOptionValue = JSON.stringify(preloadedOptions)+ }}// Set up change listener on select element directlydiff --git a/spree/admin/app/javascript/spree/admin/helpers/display_names.js b/spree/admin/app/javascript/spree/admin/helpers/display_names.jsnew file mode 100644index 0000000000..c30fd34dda--- /dev/null+++ b/spree/admin/app/javascript/spree/admin/helpers/display_names.js@@ -0,0 +1,54 @@+/** Mirrors the React dashboard's `CODE — Localized Name` format. */+export function formatCodeName(code, name) {+ const upper = code.toUpperCase()+ if (!name || name.toUpperCase() === upper) return upper+ return `${upper} — ${name}`+}++// Intl.DisplayNames construction is the expensive part (locale resolution ++// table setup); .of() is cheap. Cache one formatter per (type, locale) so+// localizing a large select doesn't rebuild it for every option.+const formatterCache = new Map()++function displayNameFormatter(type, locale) {+ const key = `${type}:${locale}`+ if (formatterCache.has(key)) return formatterCache.get(key)++ let formatter+ try {+ formatter = new Intl.DisplayNames([locale, 'en'], { type })+ } catch {+ formatter = null+ }+ formatterCache.set(key, formatter)+ return formatter+}++/** Resolve a code via Intl.DisplayNames in the admin UI language. */+export function intlDisplayName(type, code, locale) {+ if (!code) return undefined++ const formatter = displayNameFormatter(type, locale)+ if (!formatter) return undefined++ try {+ return formatter.of(code)+ } catch {+ return undefined+ }+}++/** Returns the admin UI locale from `<html lang>`, defaulting to `en` when unset. */+export function adminUiLocale() {+ return document.documentElement.lang || 'en'+}++/** Rewrite <option> labels using Intl.DisplayNames before Tom Select init. */+export function localizeSelectOptions(select, type, locale = adminUiLocale()) {+ for (const option of select.options) {+ if (!option.value) continue++ const name = intlDisplayName(type, option.value, locale)+ if (name) option.textContent = formatCodeName(option.value, name)+ }+}diff --git a/spree/admin/app/models/spree/admin/table/column.rb b/spree/admin/app/models/spree/admin/table/column.rbindex 4747aae500..d4e60ec959 100644--- a/spree/admin/app/models/spree/admin/table/column.rb+++ b/spree/admin/app/models/spree/admin/table/column.rb@@ -44,6 +44,11 @@ module Spreeattribute :operators, default: -> { [] }attribute :value_optionsattribute :search_url+ # When true, the autocomplete filter loads the full option list from+ # `search_url` once and filters it client-side on each option's `label`+ # field (instead of querying the server per keystroke). Only suitable for+ # small, fixed option sets whose endpoint returns a `label` attribute.+ attribute :preload_options, :boolean, default: falseattribute :sort_scope_ascattribute :sort_scope_descdiff --git a/spree/admin/app/models/spree/admin/table/query_builder.rb b/spree/admin/app/models/spree/admin/table/query_builder.rbindex 1cf1e45be2..730911a44c 100644--- a/spree/admin/app/models/spree/admin/table/query_builder.rb+++ b/spree/admin/app/models/spree/admin/table/query_builder.rb@@ -80,7 +80,8 @@ module Spreetype: column.filter_type.to_s,operators: column.operators.map(&:to_s),value_options: format_value_options(column.value_options),- search_url: resolve_search_url(column.search_url, view_context)+ search_url: resolve_search_url(column.search_url, view_context),+ preload_options: column.preload_options}endenddiff --git a/spree/admin/app/views/spree/admin/markets/_form.html.erb b/spree/admin/app/views/spree/admin/markets/_form.html.erbindex 791cff22fb..f3a7aa344b 100644--- a/spree/admin/app/views/spree/admin/markets/_form.html.erb+++ b/spree/admin/app/views/spree/admin/markets/_form.html.erb@@ -8,17 +8,19 @@<div class="card-body"><%= f.spree_text_field :name, required: true %>- <%= f.spree_select :country_ids, @countries.map { |country| ["#{Spree::Country.iso_to_emoji_flag(country.iso)} #{country.name}", country.id] }, { include_blank: false, label: Spree.t(:countries), autocomplete: true, multiple: true } %>+ <%= f.spree_select :country_ids, country_select_options(@countries), { include_blank: false, label: Spree.t(:countries), autocomplete: true, multiple: true } %>- <%= f.spree_select :currency, currency_options(f.object.currency), { label: Spree.t(:currency), required: true, autocomplete: true } %>+ <%= f.spree_select :currency, currency_options(f.object.currency), { label: Spree.t(:currency), required: true, autocomplete: true }, { data: { display_names_type: 'currency' } } %><%= f.spree_select :default_locale,options_from_collection_for_select(translation_locales_options, :last, :first, f.object.default_locale || I18n.locale),- { required: true, autocomplete: true } %>+ { required: true, autocomplete: true },+ { data: { display_names_type: 'language' } } %><%= f.spree_select :supported_locales,options_from_collection_for_select(translation_locales_options, :last, :first, f.object.supported_locales&.split(',')),- { multiple: true, autocomplete: true, hint: Spree.t('admin.markets.supported_locales_hint') } %>+ { multiple: true, autocomplete: true, hint: Spree.t('admin.markets.supported_locales_hint') },+ { data: { display_names_type: 'language' } } %><hr class="my-6">diff --git a/spree/admin/app/views/spree/admin/promotion_rules/forms/_country.html.erb b/spree/admin/app/views/spree/admin/promotion_rules/forms/_country.html.erbindex 086633604e..52c7010dbe 100644--- a/spree/admin/app/views/spree/admin/promotion_rules/forms/_country.html.erb+++ b/spree/admin/app/views/spree/admin/promotion_rules/forms/_country.html.erb@@ -1,7 +1,7 @@<div class="form-group"><%= f.label :preferred_country_iso, Spree.t(:country) %><%= f.select :preferred_country_iso,- available_countries_iso.map { |iso| [Spree.t(iso, scope: 'country_names', default: iso), iso] },+ available_countries_iso.map { |iso| [Spree::LocalizedNames.country_name(iso, fallback: iso), iso] },{ selected: f.object.preferred_country_iso || current_store.default_market&.default_country&.iso },{ data: { controller: 'autocomplete-select' } } %></div>diff --git a/spree/admin/config/initializers/spree_admin_tables.rb b/spree/admin/config/initializers/spree_admin_tables.rbindex 19e70b4d5e..2d3f28fc75 100644--- a/spree/admin/config/initializers/spree_admin_tables.rb+++ b/spree/admin/config/initializers/spree_admin_tables.rb@@ -489,6 +489,7 @@ Rails.application.config.after_initialize doransack_attribute: 'addresses_country_name',operators: %i[eq],search_url: ->(view_context) { view_context.spree.select_options_admin_countries_path(format: :json) },+ preload_options: true,partial: 'spree/admin/tables/columns/user_location'# Number of orders@@ -1713,7 +1714,8 @@ Rails.application.config.after_initialize dotype: :string,sortable: true,default: true,- position: 30+ position: 30,+ format: 'locale_display_label'Spree.admin.tables.markets.add :default,label: :default,diff --git a/spree/admin/spec/controllers/spree/admin/countries_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/countries_controller_spec.rbindex 44803d15a4..5998c5d1ac 100644--- a/spree/admin/spec/controllers/spree/admin/countries_controller_spec.rb+++ b/spree/admin/spec/controllers/spree/admin/countries_controller_spec.rb@@ -10,44 +10,31 @@ RSpec.describe Spree::Admin::CountriesController, type: :controller dolet!(:germany) { create(:country, name: 'Germany', iso: 'DE') }let!(:france) { create(:country, name: 'France', iso: 'FR') }- it 'returns countries ordered by name' do+ it 'returns all countries with an English value and a localized label' doget :select_options, format: :jsonjson = JSON.parse(response.body)- names = json.map { |c| c['name'] }- expect(names).to include('France', 'Germany', 'Poland')- expect(names).to eq(names.sort)- end-- it 'filters countries by query string' do- get :select_options, params: { q: 'pol' }, format: :json-- json = JSON.parse(response.body)- expect(json.length).to eq(1)- expect(json.first['name']).to eq('Poland')+ france = json.find { |c| c['name'] == 'France' }+ expect(france).to be_present+ expect(france['label']).to include('France').and include('🇫🇷')end- it 'filters countries by ransack hash' do- get :select_options, params: { q: { name_cont: 'pol' } }, format: :json-- json = JSON.parse(response.body)- expect(json.length).to eq(1)- expect(json.first['name']).to eq('Poland')- end-- it 'returns empty array when no matches' do- get :select_options, params: { q: 'xyz' }, format: :json+ it 'sorts countries by localized name' do+ get :select_options, format: :jsonjson = JSON.parse(response.body)- expect(json).to be_empty+ # Labels carry a leading flag emoji whose codepoints sort by ISO code, not+ # by name — assert ordering on the name portion (after the flag prefix).+ country_names = json.map { |c| c['label'].split(' ', 2).last }+ expect(country_names).to eq(country_names.sort)end- it 'is case insensitive' do- get :select_options, params: { q: 'GERMANY' }, format: :json+ it 'returns the full list regardless of query (filtering is client-side)' do+ get :select_options, params: { q: 'pol' }, format: :jsonjson = JSON.parse(response.body)- expect(json.length).to eq(1)- expect(json.first['name']).to eq('Germany')+ names = json.map { |c| c['name'] }+ expect(names).to include('France', 'Germany', 'Poland')endendenddiff --git a/spree/admin/spec/features/spree/admin/markets_spec.rb b/spree/admin/spec/features/spree/admin/markets_spec.rbnew file mode 100644index 0000000000..d13cee56e5--- /dev/null+++ b/spree/admin/spec/features/spree/admin/markets_spec.rb@@ -0,0 +1,39 @@+require 'spec_helper'++RSpec.describe 'Markets', type: :feature do+ stub_authorization!++ let(:store) { @default_store }+ # @default_country is the seeded US country; reuse it so the flag/name are deterministic.+ let(:country) { @default_country }++ # Markets selects only offer countries with shipping coverage, so wire up a+ # shipping zone + method for the country first.+ before do+ zone = create(:zone, name: 'US Shipping Zone', kind: 'country')+ create(:zone_member, zone: zone, zoneable: country)+ create(:shipping_method, zones: [zone])+ end++ scenario 'index renders the default locale as a localized label' do+ create(:market, store: store, currency: 'USD', default_locale: 'en', countries: [country])++ visit spree.admin_markets_path++ # The default_locale column localizes "en" instead of rendering the raw code.+ expect(page).to have_content('EN — English')+ expect(page).not_to have_selector('td', exact_text: 'en')+ end++ scenario 'new form renders localized country, currency, and locale options' do+ visit spree.new_admin_market_path++ # Country option is prefixed with the flag emoji + localized name.+ expect(page).to have_select(Spree.t(:countries))+ expect(page).to have_content('🇺🇸')+ expect(page).to have_content('United States')++ expect(page).to have_select(Spree.t(:currency), with_options: ['EUR — Euro'])+ expect(page).to have_select('market_default_locale', with_options: ['EN — English'])+ end+enddiff --git a/spree/core/app/helpers/spree/base_helper.rb b/spree/core/app/helpers/spree/base_helper.rbindex 00da331174..ea55629dc7 100644--- a/spree/core/app/helpers/spree/base_helper.rb+++ b/spree/core/app/helpers/spree/base_helper.rb@@ -8,7 +8,7 @@ module Spreecountries = current_store.countries_available_for_checkoutcountries.collect do |country|- country.name = Spree.t(country.iso, scope: 'country_names', default: country.name)+ country.name = localized_country_name(country)countryend.sort_by { |c| c.name.parameterize }end@@ -17,7 +17,7 @@ module Spreecountries = Spree::Country.allcountries.collect do |country|- country.name = Spree.t(country.iso, scope: 'country_names', default: country.name)+ country.name = localized_country_name(country)countryend.sort_by { |c| c.name.parameterize }end@@ -112,6 +112,16 @@ module Spreeinline_svg "payment_icons/#{payment_method}.svg", optsend+ # @param country [Spree::Country]+ # @return [String]+ def localized_country_name(country)+ Spree.t(+ country.iso,+ scope: 'country_names',+ default: Spree::LocalizedNames.country_name(country.iso, fallback: country.name)+ )+ end+privateI18N_PLURAL_MANY_COUNT = 2.1diff --git a/spree/core/app/helpers/spree/currency_helper.rb b/spree/core/app/helpers/spree/currency_helper.rbindex dc820ea65e..ac1b7d0e5c 100644--- a/spree/core/app/helpers/spree/currency_helper.rb+++ b/spree/core/app/helpers/spree/currency_helper.rb@@ -36,10 +36,7 @@ module Spree# @param currency [String] the currency ISO code# @return [Array] the currency presentation and ISO codedef currency_presentation(currency)- currency_money = currency_money(currency)- label = "#{currency_money.name} (#{currency_money.iso_code})"-- [label, currency]+ [Spree::LocalizedNames.currency_label(currency), currency]enddef currency_money(currency = current_currency)diff --git a/spree/core/app/helpers/spree/locale_helper.rb b/spree/core/app/helpers/spree/locale_helper.rbindex 2e02dc3a13..033d5fc761 100644--- a/spree/core/app/helpers/spree/locale_helper.rb+++ b/spree/core/app/helpers/spree/locale_helper.rb@@ -32,15 +32,7 @@ module Spreeenddef locale_presentation(locale)- if I18n.exists?('spree.i18n.this_file_language', locale: locale, fallback: false)- [locale_full_name(locale), locale.to_s]- elsif defined?(SpreeI18n::Locale) && (language_name = SpreeI18n::Locale.local_language_name(locale))- ["#{language_name} (#{locale})", locale.to_s]- elsif locale.to_s == 'en'- ['English (US)', 'en']- else- [locale, locale.to_s]- end+ [Spree::LocalizedNames.locale_label(locale), locale.to_s]enddef locale_full_name(locale)diff --git a/spree/core/app/helpers/spree/localized_names_helper.rb b/spree/core/app/helpers/spree/localized_names_helper.rbnew file mode 100644index 0000000000..6696c7845a--- /dev/null+++ b/spree/core/app/helpers/spree/localized_names_helper.rb@@ -0,0 +1,25 @@+module Spree+ module LocalizedNamesHelper+ # @param code [String, Symbol]+ # @return [String]+ def locale_display_label(code)+ return if code.blank?++ content_tag(+ :span,+ Spree::LocalizedNames.locale_label(code),+ data: {+ controller: 'display-name',+ display_name_type_value: 'language',+ display_name_code_value: code+ }+ )+ end++ # @param countries [Enumerable<Spree::Country>]+ # @return [Array<Array>]+ def country_select_options(countries)+ countries.map { |country| [Spree::LocalizedNames.country_option_label(country), country.id] }+ end+ end+enddiff --git a/spree/core/app/models/spree/country.rb b/spree/core/app/models/spree/country.rbindex a8360e5ff4..8f10010cd4 100644--- a/spree/core/app/models/spree/country.rb+++ b/spree/core/app/models/spree/country.rb@@ -31,7 +31,7 @@ module Spreepluck(:name, :id, :iso).map do |name, id, iso|{id: id,- name: "#{iso_to_emoji_flag(iso)} #{name}"+ name: Spree::LocalizedNames.country_option_label(new(iso: iso, name: name))}end.as_jsonenddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 499cb27600..e40b140a4d 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -492,6 +492,7 @@ require 'spree/translation_migrations'require 'spree/core/engine'require 'spree/i18n'+require 'spree/localized_names'require 'spree/localized_number'require 'spree/money'require 'spree/permitted_attributes'diff --git a/spree/core/lib/spree/localized_names.rb b/spree/core/lib/spree/localized_names.rbnew file mode 100644index 0000000000..aba7106b28--- /dev/null+++ b/spree/core/lib/spree/localized_names.rb@@ -0,0 +1,110 @@+# frozen_string_literal: true++require 'countries'++module Spree+ # Localized display names for countries, currencies, and locales.+ #+ # Country names come from the +countries+ gem (CLDR translations) in the+ # current +I18n.locale+. Currency and language names use the Money gem and+ # Spree I18n bundles (not locale-aware server-side); the admin Stimulus+ # +display-name+ controller upgrades those labels client-side via+ # +Intl.DisplayNames+ when available — matching the React dashboard.+ module LocalizedNames+ module_function++ # @param code [String, Symbol]+ # @param name [String]+ # @return [String] e.g. "EN — English"+ def format_code_name(code, name)+ upper = code.to_s.upcase+ label = name.to_s+ return upper if label.blank? || label.casecmp?(code.to_s)++ "#{upper} — #{label}"+ end++ # @param iso [String]+ # @param locale [Symbol, String]+ # @param fallback [String, nil]+ # @return [String]+ def country_name(iso, locale: I18n.locale, fallback: nil)+ iso = iso.to_s.upcase+ fallback ||= iso++ data = ISO3166::Country[iso]+ return fallback unless data++ translation = data.translation(display_locale(locale)) || data.translation(:en)+ translation.presence || fallback+ end++ # @param country [Spree::Country]+ # @param locale [Symbol, String]+ # @return [String]+ def country_option_label(country, locale: I18n.locale)+ name = country_name(country.iso, locale: locale, fallback: country.name)+ "#{Spree::Country.iso_to_emoji_flag(country.iso)} #{name}"+ end++ # @param code [String]+ # @return [String]+ def currency_name(code)+ code = code.to_s.upcase+ # Fully-qualified: bare `Money` resolves to Spree::Money inside this module.+ # `find` returns nil (it does not raise) for unknown codes.+ ::Money::Currency.find(code)&.name || code+ end++ # @param code [String]+ # @return [String]+ def currency_label(code)+ format_code_name(code, currency_name(code))+ end++ # @param code [String, Symbol]+ # @return [String]+ def language_name(code)+ code = code.to_s++ if I18n.exists?('spree.i18n.this_file_language', locale: code, fallback: false)+ return normalize_language_name(Spree.t('i18n.this_file_language', locale: code))+ end++ if defined?(SpreeI18n::Locale) && (name = SpreeI18n::Locale.local_language_name(code))+ return normalize_language_name(name)+ end++ return 'English' if code == 'en'++ code+ end++ # @param code [String, Symbol]+ # @return [String]+ def locale_label(code)+ format_code_name(code, language_name(code))+ end++ # @param locale [Symbol, String]+ # @return [String]+ def display_locale(locale)+ locale.to_s.downcase.tr('_', '-').split('-').first+ end++ # Strip a trailing " (CODE)" suffix from Spree I18n locale labels.+ # Uses plain string ops rather than a regex to avoid polynomial+ # backtracking on adversarial input (ReDoS).+ # @param name [String]+ # @return [String]+ def normalize_language_name(name)+ name = name.to_s.rstrip+ return name unless name.end_with?(')')++ open_paren = name.rindex('(')+ return name unless open_paren++ name[0...open_paren].rstrip+ end+ end+enddiff --git a/spree/core/spec/helpers/currency_helper_spec.rb b/spree/core/spec/helpers/currency_helper_spec.rbindex 359e5f794e..27126088fd 100644--- a/spree/core/spec/helpers/currency_helper_spec.rb+++ b/spree/core/spec/helpers/currency_helper_spec.rb@@ -9,7 +9,7 @@ describe Spree::CurrencyHelper, type: :helper doenddescribe '#supported_currency_options' do- it { expect(supported_currency_options).to contain_exactly(['Polish Złoty (PLN)', 'PLN'], ['British Pound (GBP)', 'GBP'], ['Euro (EUR)', 'EUR']) }+ it { expect(supported_currency_options).to contain_exactly(['PLN — Polish Złoty', 'PLN'], ['GBP — British Pound', 'GBP'], ['EUR — Euro', 'EUR']) }enddescribe '#should_render_currency_dropdown?' do@@ -29,7 +29,7 @@ describe Spree::CurrencyHelper, type: :helper doenddescribe '#currency_presentation' do- it { expect(currency_presentation('EUR')).to eq(['Euro (EUR)', 'EUR']) }+ it { expect(currency_presentation('EUR')).to eq(['EUR — Euro', 'EUR']) }enddescribe '#currency_money' dodiff --git a/spree/core/spec/helpers/locale_helper_spec.rb b/spree/core/spec/helpers/locale_helper_spec.rbindex e1266519cc..2d0e69a02d 100644--- a/spree/core/spec/helpers/locale_helper_spec.rb+++ b/spree/core/spec/helpers/locale_helper_spec.rb@@ -22,7 +22,7 @@ describe Spree::LocaleHelper, type: :helper doenddescribe '#all_locales_options' do- it { expect(all_locales_options).to contain_exactly(['English (US)', 'en'], ['Deutsch (DE)', 'de'], ['Français (FR)', 'fr']) }+ it { expect(all_locales_options).to contain_exactly(['EN — English', 'en'], ['DE — Deutsch', 'de'], ['FR — Français', 'fr']) }enddescribe '#available_locales_options' do@@ -32,13 +32,13 @@ describe Spree::LocaleHelper, type: :helper doRails.cache.clearend- it { expect(available_locales_options).to contain_exactly(['English (US)', 'en'], ['Deutsch (DE)', 'de']) }+ it { expect(available_locales_options).to contain_exactly(['EN — English', 'en'], ['DE — Deutsch', 'de']) }enddescribe '#supported_locales_options' dolet(:current_store) { eu_store }- it { expect(supported_locales_options).to contain_exactly(['Deutsch (DE)', 'de'], ['Français (FR)', 'fr']) }+ it { expect(supported_locales_options).to contain_exactly(['DE — Deutsch', 'de'], ['FR — Français', 'fr']) }enddescribe '#translation_locales_options' do@@ -52,7 +52,7 @@ describe Spree::LocaleHelper, type: :helper doit 'returns [name, code] pairs suitable for a select' doexpect(subject).to all(be_an(Array).and(have_attributes(size: 2)))- expect(subject).to include(['Deutsch (DE)', 'de'], ['Français (FR)', 'fr'])+ expect(subject).to include(['DE — Deutsch', 'de'], ['FR — Français', 'fr'])endit 'offers regional variants a store may not yet use' do@@ -66,10 +66,10 @@ describe Spree::LocaleHelper, type: :helper doenddescribe '#locale_presentation' do- it { expect(locale_presentation(:fr)).to eq( ['Français (FR)', 'fr']) }+ it { expect(locale_presentation(:fr)).to eq(['FR — Français', 'fr']) }it 'returns the locale when no translation exists' do- expect(locale_presentation(:klingon)).to eq([:klingon, 'klingon'])+ expect(locale_presentation(:klingon)).to eq(['KLINGON', 'klingon'])endenddiff --git a/spree/core/spec/helpers/localized_names_helper_spec.rb b/spree/core/spec/helpers/localized_names_helper_spec.rbnew file mode 100644index 0000000000..5df0596fa9--- /dev/null+++ b/spree/core/spec/helpers/localized_names_helper_spec.rb@@ -0,0 +1,30 @@+require 'spec_helper'++describe Spree::LocalizedNamesHelper, type: :helper do+ describe '#locale_display_label' do+ it 'renders the localized label inside a display-name span' do+ html = helper.locale_display_label('en')++ expect(html).to have_css('span[data-controller="display-name"]', text: 'EN — English')+ expect(html).to have_css('span[data-display-name-type-value="language"]')+ expect(html).to have_css('span[data-display-name-code-value="en"]')+ end++ it 'returns nil for a blank code' do+ expect(helper.locale_display_label(nil)).to be_nil+ end+ end++ describe '#country_select_options' do+ let(:country) { build_stubbed(:country, iso: 'US', name: 'United States') }++ it 'returns [label, id] pairs with the localized country option label' do+ options = helper.country_select_options([country])++ expect(options.size).to eq(1)+ label, id = options.first+ expect(label).to include('United States')+ expect(id).to eq(country.id)+ end+ end+enddiff --git a/spree/core/spec/lib/spree/localized_names_spec.rb b/spree/core/spec/lib/spree/localized_names_spec.rbnew file mode 100644index 0000000000..b59a48341a--- /dev/null+++ b/spree/core/spec/lib/spree/localized_names_spec.rb@@ -0,0 +1,97 @@+require 'spec_helper'++describe Spree::LocalizedNames do+ describe '.format_code_name' do+ it 'formats code and name' do+ expect(described_class.format_code_name('en', 'English')).to eq('EN — English')+ end++ it 'returns uppercased code when name matches code' do+ expect(described_class.format_code_name('en', 'en')).to eq('EN')+ end+ end++ describe '.country_name' do+ it 'returns localized country name' do+ expect(described_class.country_name('US', locale: :en)).to include('United States')+ end++ it 'falls back to english then provided fallback' do+ expect(described_class.country_name('US', locale: :zz, fallback: 'Fallback')).to include('United States')+ end++ it 'returns the fallback for an unknown ISO code' do+ expect(described_class.country_name('ZZ', fallback: 'Nowhere')).to eq('Nowhere')+ end+ end++ describe '.country_option_label' do+ let(:country) { build(:country, iso: 'US', name: 'United States') }++ it 'prefixes the localized name with the flag emoji' do+ label = described_class.country_option_label(country, locale: :en)++ expect(label).to include('🇺🇸')+ expect(label).to include('United States')+ end+ end++ describe '.currency_name' do+ it 'returns the currency name for a known code' do+ expect(described_class.currency_name('EUR')).to eq('Euro')+ end++ it 'returns the upcased code for an unknown currency' do+ expect(described_class.currency_name('zzz')).to eq('ZZZ')+ end+ end++ describe '.currency_label' do+ it 'formats currency code and name' do+ expect(described_class.currency_label('EUR')).to eq('EUR — Euro')+ end++ it 'falls back to the bare code for an unknown currency' do+ expect(described_class.currency_label('zzz')).to eq('ZZZ')+ end+ end++ describe '.language_name' do+ it 'returns English for the en locale without a translation bundle' do+ expect(described_class.language_name('en')).to eq('English')+ end++ it 'returns the raw code when no language name is resolvable' do+ expect(described_class.language_name('klingon')).to eq('klingon')+ end+ end++ describe '.normalize_language_name' do+ it 'strips a trailing parenthetical suffix' do+ expect(described_class.normalize_language_name('Deutsch (DE)')).to eq('Deutsch')+ end++ it 'leaves a name without a parenthetical untouched' do+ expect(described_class.normalize_language_name('English')).to eq('English')+ end+ end++ describe '.locale_label' do+ before do+ I18n.backend.store_translations(:de,+ spree: {+ i18n: {+ this_file_language: 'Deutsch (DE)'+ }+ })+ end++ it 'formats locale code and language name' do+ expect(described_class.locale_label(:de)).to eq('DE — Deutsch')+ end++ it 'formats english locale' do+ expect(described_class.locale_label(:en)).to eq('EN — English')+ end+ end+end