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
When swiching Locale via UI append locale to routes
Damian Legawieca5f1ad54db61
diff --git a/.eslintrc b/.eslintrcindex c6b5e5c2ce..ec4972afd1 100644--- a/.eslintrc+++ b/.eslintrc@@ -16,6 +16,8 @@ globals:Turbolinks: trueADDRESS_FIELDS: trueAUTH_TOKEN: true+ SPREE_LOCALE: true+ SPREE_CURRENCY: trueupdate_state: trueenv:diff --git a/core/app/assets/javascripts/spree.js b/core/app/assets/javascripts/spree.jsindex 70b876fcc2..26fd681ad8 100644--- a/core/app/assets/javascripts/spree.js+++ b/core/app/assets/javascripts/spree.js@@ -17,9 +17,25 @@ Spree.adminPath = function () {Spree.pathFor = function (path) {var locationOrigin = (window.location.protocol + '//' + window.location.hostname) + (window.location.port ? ':' + window.location.port : '')+return this.url('' + locationOrigin + (this.mountedAt()) + path, this.url_params).toString()}+Spree.localizedPathFor = function(path) {+ if (typeof (SPREE_LOCALE) !== 'undefined') {+ if (path.match(/api\/v/)) {+ if (path.match(/\?/)) {+ path = path + '&locale=' + SPREE_LOCALE+ } else {+ path = path + '?locale=' + SPREE_LOCALE+ }+ } else {+ path = SPREE_LOCALE + '/' + path+ }+ }+ return Spree.pathFor(path)+}+Spree.adminPathFor = function (path) {return this.pathFor('' + (this.adminPath()) + path)}diff --git a/core/app/helpers/spree/base_helper.rb b/core/app/helpers/spree/base_helper.rbindex cdeb95998e..141a30d5d5 100644--- a/core/app/helpers/spree/base_helper.rb+++ b/core/app/helpers/spree/base_helper.rb@@ -134,7 +134,8 @@ module Spree[I18n.l(date.to_date, format: :long)].join(' ')end- def seo_url(taxon, options = nil)+ def seo_url(taxon, options = {})+ options.merge(locale: locale_param)spree.nested_taxons_path(taxon.permalink, options)enddiff --git a/core/app/services/spree/build_localized_url.rb b/core/app/services/spree/build_localized_url.rbnew file mode 100644index 0000000000..68b2670cb5--- /dev/null+++ b/core/app/services/spree/build_localized_url.rb@@ -0,0 +1,39 @@+module Spree+ class BuildLocalizedUrl+ prepend Spree::ServiceModule::Base++ LOCALE_REGEX = /^\/[A-Za-z]{2}\/|^\/[A-Za-z]{2}$/++ def call(url:, locale:, default_locale: nil)+ run :initialize_url_object+ run :generate_new_path+ run :build_url+ end++ protected++ def initialize_url_object(url:, locale:, default_locale:)+ success(url: URI(url), locale: locale, default_locale: default_locale)+ end++ def generate_new_path(url:, locale:, default_locale:)+ match = url.path.match(LOCALE_REGEX)[0].gsub('/', '') if url.path.match(LOCALE_REGEX)++ # we've found previously used locale in the URL, so we need to replace it+ # or if it's the default store locale remove it completely++ new_path = if default_locale.present? && default_locale.to_s == locale.to_s+ match.present? ? url.path.gsub(LOCALE_REGEX, '/') : url.path+ else+ match.present? ? url.path.gsub(LOCALE_REGEX, "/#{locale}/") : "/#{locale}#{url.path}"+ end+ success(url: url, path: new_path.chomp('/').gsub('//', '/'))+ end++ def build_url(url:, path:)+ builder_class = url.scheme == 'http' ? URI::HTTP : URI::HTTPS+ localized_url = builder_class.build(host: url.host, port: url.port, path: path, query: url.query).to_s+ success(localized_url)+ end+ end+enddiff --git a/core/spec/services/spree/build_localized_url_spec.rb b/core/spec/services/spree/build_localized_url_spec.rbnew file mode 100644index 0000000000..f7c858cf4b--- /dev/null+++ b/core/spec/services/spree/build_localized_url_spec.rb@@ -0,0 +1,118 @@+require 'spec_helper'++module Spree+ describe BuildLocalizedUrl do+ subject { described_class.call(url: url, locale: locale, default_locale: default_locale) }++ let(:result) { subject.value }+ let(:default_locale) { 'en' }++ context 'root path' do+ context 'default locale' do+ let(:locale) { 'en' }++ context 'http with port' do+ let(:url) { 'http://example.com:3000/' }++ it { expect(result).to eq('http://example.com:3000') }+ end++ context 'https with no trailing slash' do+ let(:url) { 'https://example.com' }++ it { expect(result).to eq('https://example.com') }+ end++ context 'with parameters and port' do+ let(:url) { 'https://example.com:3000/?utm_source=google' }++ it { expect(result).to eq('https://example.com:3000?utm_source=google') }+ end+ end++ context 'non-default locale' do+ let(:locale) { 'de' }++ context 'http with port' do+ let(:url) { 'http://example.com:3000/' }++ it { expect(result).to eq('http://example.com:3000/de') }+ end++ context 'https with no trailing slash' do+ let(:url) { 'https://example.com' }++ it { expect(result).to eq('https://example.com/de') }+ end++ context 'with parameters and port' do+ let(:url) { 'https://example.com:3000/?utm_source=google' }++ it { expect(result).to eq('https://example.com:3000/de?utm_source=google') }+ end+ end+ end++ context 'localized path' do+ context 'default locale' do+ let(:locale) { 'en' }++ context 'http with port' do+ let(:url) { 'http://example.com:3000/fr/products/some-product' }++ it { expect(result).to eq('http://example.com:3000/products/some-product') }+ end++ context 'https with no trailing slash' do+ let(:url) { 'https://example.com/fr/products/some-product' }++ it { expect(result).to eq('https://example.com/products/some-product') }+ end++ context 'with parameters and port' do+ let(:url) { 'https://example.com:3000/fr/products/some-product?taxon_id=1&utm_source=google' }++ it { expect(result).to eq('https://example.com:3000/products/some-product?taxon_id=1&utm_source=google') }+ end+ end++ context 'non-default locale' do+ let(:locale) { 'de' }++ context 'http with port' do+ let(:url) { 'http://example.com:3000/fr/products/some-product' }++ it { expect(result).to eq('http://example.com:3000/de/products/some-product') }+ end++ context 'https with no trailing slash' do+ let(:url) { 'https://example.com/fr/products/some-product' }++ it { expect(result).to eq('https://example.com/de/products/some-product') }+ end++ context 'with parameters and port' do+ let(:url) { 'https://example.com:3000/fr/products/some-product?taxon_id=1&utm_source=google' }++ it { expect(result).to eq('https://example.com:3000/de/products/some-product?taxon_id=1&utm_source=google') }+ end+ end+ end++ context 'default_locale is nil' do+ let(:default_locale) { nil }+ let(:locale) { 'de' }+ let(:url) { 'http://example.com:3000/products' }++ it { expect { subject }.not_to raise_error }+ it { expect { result }.not_to raise_error }+ end++ context 'subdomain as host' do+ let(:locale) { 'de' }+ let(:url) { 'http://subdomain.example.com:3000/products' }++ it { expect(result).to eq('http://subdomain.example.com:3000/de/products') }+ end+ end+enddiff --git a/frontend/app/assets/javascripts/spree/frontend/account.js b/frontend/app/assets/javascripts/spree/frontend/account.jsindex ae5b652ba7..0e00d8eaf1 100644--- a/frontend/app/assets/javascripts/spree/frontend/account.js+++ b/frontend/app/assets/javascripts/spree/frontend/account.js@@ -1,6 +1,6 @@Spree.fetchAccount = function () {return $.ajax({- url: Spree.pathFor('account_link')+ url: Spree.localizedPathFor('account_link')}).done(function (data) {Spree.accountFetched = truereturn $('#link-to-account').html(data)diff --git a/frontend/app/assets/javascripts/spree/frontend/cart.js b/frontend/app/assets/javascripts/spree/frontend/cart.jsindex b0691959cf..d84c4423de 100644--- a/frontend/app/assets/javascripts/spree/frontend/cart.js+++ b/frontend/app/assets/javascripts/spree/frontend/cart.js@@ -123,7 +123,7 @@ Spree.ready(function ($) {Spree.fetchCart = function () {return $.ajax({- url: Spree.pathFor('cart_link')+ url: Spree.localizedPathFor('cart_link')}).done(function (data) {Spree.cartFetched = truereturn $('#link-to-cart').html(data)diff --git a/frontend/app/assets/javascripts/spree/frontend/checkout/address.js b/frontend/app/assets/javascripts/spree/frontend/checkout/address.jsindex 05298f108b..8ede4895a4 100644--- a/frontend/app/assets/javascripts/spree/frontend/checkout/address.js+++ b/frontend/app/assets/javascripts/spree/frontend/checkout/address.js@@ -8,7 +8,7 @@ Spree.ready(function($) {$.ajax({async: false,method: 'GET',- url: Spree.pathFor('/api/v2/storefront/countries/' + countryId + '?include=checkout_zone_applicable_states'),+ url: Spree.localizedPathFor('/api/v2/storefront/countries/' + countryId + '?include=checkout_zone_applicable_states'),dataType: 'json'}).done(function(data) {var json = data.included;diff --git a/frontend/app/assets/javascripts/spree/frontend/coupon_manager.js b/frontend/app/assets/javascripts/spree/frontend/coupon_manager.jsindex c1a2907dd6..69f5f3c50b 100644--- a/frontend/app/assets/javascripts/spree/frontend/coupon_manager.js+++ b/frontend/app/assets/javascripts/spree/frontend/coupon_manager.js@@ -49,7 +49,7 @@ CouponManager.prototype.sendRequest = function () {return $.ajax({async: false,method: 'PATCH',- url: Spree.routes.api_v2_storefront_cart_apply_coupon_code,+ url: Spree.routes.api_v2_storefront_cart_apply_coupon_code + '?locale=' + SPREE_LOCALE,dataType: 'json',headers: {'X-Spree-Order-Token': SpreeAPI.orderToken@@ -74,7 +74,7 @@ CouponManager.prototype.sendRemoveRequest = function () {return $.ajax({async: false,method: 'DELETE',- url: Spree.routes.api_v2_storefront_cart_remove_coupon_code + '/' + this.couponCode,+ url: Spree.routes.api_v2_storefront_cart_remove_coupon_code + '/' + this.couponCode + '?locale=' + SPREE_LOCALE,dataType: 'json',headers: {'X-Spree-Order-Token': SpreeAPI.orderTokendiff --git a/frontend/app/controllers/spree/checkout_controller.rb b/frontend/app/controllers/spree/checkout_controller.rbindex 0109b9d1d0..17436af507 100644--- a/frontend/app/controllers/spree/checkout_controller.rb+++ b/frontend/app/controllers/spree/checkout_controller.rb@@ -129,8 +129,8 @@ module Spreeend# Provides a route to redirect after order completion- def completion_route(custom_params = nil)- spree.order_path(@order, custom_params)+ def completion_route(custom_params = {})+ spree.order_path(@order, custom_params.merge(locale: locale_param))enddef setup_for_current_statediff --git a/frontend/app/controllers/spree/locale_controller.rb b/frontend/app/controllers/spree/locale_controller.rbindex 6a4aa7926d..665fb02034 100644--- a/frontend/app/controllers/spree/locale_controller.rb+++ b/frontend/app/controllers/spree/locale_controller.rb@@ -1,3 +1,5 @@+require 'uri'+module Spreeclass LocaleController < Spree::StoreControllerdef index@@ -5,12 +7,21 @@ module Spreeenddef set- new_locale = params[:switch_to_locale] || params[:locale]+ new_locale = (params[:switch_to_locale] || params[:locale]).to_sif new_locale.present? && supported_locale?(new_locale)- session[:locale] = new_locale+ if request.env['HTTP_REFERER'].present? && request.env['HTTP_REFERER'] != request.env['REQUEST_URI']+ redirect_to BuildLocalizedUrl.call(+ url: request.env['HTTP_REFERER'],+ locale: new_locale,+ default_locale: current_store.default_locale+ ).value+ else+ redirect_to root_path(locale: new_locale)+ end+ else+ redirect_to root_pathend- redirect_back_or_default(root_path(locale: new_locale))endendenddiff --git a/frontend/app/views/spree/shared/_head.html.erb b/frontend/app/views/spree/shared/_head.html.erbindex 5f998ae60a..42193d4f84 100644--- a/frontend/app/views/spree/shared/_head.html.erb+++ b/frontend/app/views/spree/shared/_head.html.erb@@ -8,5 +8,9 @@<%= stylesheet_link_tag 'spree/frontend/all', media: 'screen', 'data-turbolinks-track': 'reload' %><%= csrf_meta_tags %><%= render 'spree/shared/paths' %>+<script>+ var SPREE_LOCALE = '<%= I18n.locale %>'+ var SPREE_CURRENCY = '<%= current_currency %>'+</script><%= javascript_include_tag 'spree/frontend/all', defer: true, 'data-turbolinks-track': 'reload' %><%= yield :head %>diff --git a/frontend/spec/features/locale_spec.rb b/frontend/spec/features/locale_spec.rbindex f7c3e8d460..de176bdfbd 100644--- a/frontend/spec/features/locale_spec.rb+++ b/frontend/spec/features/locale_spec.rb@@ -1,21 +1,12 @@require 'spec_helper'-describe 'setting locale', type: :feature do+describe 'setting locale', type: :feature, js: true dolet(:store) { Spree::Store.default }let(:locale) { :fr }before do- I18n.backend.store_translations(:fr,- spree: {- added_to_cart: 'Ajouté au panier avec succès!',- cart_page: {- header: 'Votre panier',- empty_info: 'Votre panier est vide'- },- i18n: {- this_file_language: 'Français (FR)'- }- })+ store.update(default_locale: 'en', supported_locales: 'en,fr')+ add_french_localesendcontext 'checkout form validation messages' do@@ -38,15 +29,33 @@ describe 'setting locale', type: :feature doshared_examples 'translates cart page' doit 'is in french' do- visit spree.cart_pathexpect(page).to have_content('Votre panier')expect(page).to have_content('Votre panier est vide')endend- context 'with store locale set' do+ shared_examples 'translates UI' do+ context 'locale dropdown' do+ before { open_i18n_menu }++ it { expect(page).to have_select('switch_to_locale', selected: 'Français (FR)') }+ end++ it { expect(page.evaluate_script('SPREE_LOCALE')).to eq('fr') }+ end++ shared_examples 'generates proper URLs' do+ it 'has localized links' do+ expect(page).to have_link(store.name, href: '/fr')+ expect(page).to have_selector('#link-to-cart a[href="/fr/cart"]')+ expect(page).to have_link('Femmes', href: '/fr/t/women')+ end+ end++ context 'with default store locale set' dobefore dostore.update(default_locale: locale)+ visit spree.cart_pathendafter do@@ -55,12 +64,14 @@ describe 'setting locale', type: :feature doendit_behaves_like 'translates cart page'+ it_behaves_like 'translates UI'endcontext 'without store locale set' dobefore doI18n.locale = localeSpree::Frontend::Config[:locale] = locale+ visit spree.cart_pathendafter do@@ -73,8 +84,8 @@ describe 'setting locale', type: :feature docontext 'via set_locale endpoint' dobefore do- store.update(default_locale: 'en', supported_locales: 'en,fr')visit spree.set_locale_path(switch_to_locale: 'fr')+ first('a.cart-icon').clickendafter do@@ -84,9 +95,8 @@ describe 'setting locale', type: :feature doit_behaves_like 'translates cart page'end- context 'locales list endpoint' do+ context 'locales list endpoint', js: false dobefore do- store.update(default_locale: 'en', supported_locales: 'en,fr')visit spree.locales_pathend@@ -98,13 +108,83 @@ describe 'setting locale', type: :feature doendend- context 'via UI', :js do+ context 'via UI' dobefore do- store.update(default_locale: 'en', supported_locales: 'en,fr')visit spree.cart_pathswitch_to_locale('Français (FR)')end+ it { expect(page).to have_current_path('/fr/cart') }++ it_behaves_like 'translates UI'it_behaves_like 'translates cart page'+ it_behaves_like 'generates proper URLs'+ end++ context 'via URL' do+ let!(:taxon) { create(:taxon) }+ let!(:product) { create(:product_in_stock, taxons: [taxon]) }++ context 'cart page' do+ before do+ visit spree.cart_path(locale: 'fr')+ end++ it { expect(page).to have_current_path('/fr/cart') }++ it_behaves_like 'translates UI'+ it_behaves_like 'translates cart page'+ it_behaves_like 'generates proper URLs'+ end++ context 'products page' do+ before do+ visit spree.products_path(locale: 'fr')+ end++ it { expect(page).to have_current_path('/fr/products') }++ it_behaves_like 'translates UI'+ it_behaves_like 'generates proper URLs'++ it { expect(page).to have_link(product.name, href: spree.product_path(product, locale: 'fr')) }+ end++ context 'taxon page' do+ before do+ visit spree.nested_taxons_path(taxon, locale: 'fr')+ end++ it { expect(page).to have_current_path("/fr/t/#{taxon.permalink}") }++ it_behaves_like 'translates UI'+ it_behaves_like 'generates proper URLs'++ it { expect(page).to have_link(product.name, href: spree.product_path(product, locale: 'fr', taxon_id: taxon.id)) }+ end++ context 'product page' do+ before do+ visit spree.product_path(product, locale: 'fr')+ end++ it { expect(page).to have_current_path("/fr/products/#{product.slug}") }++ it_behaves_like 'translates UI'+ it_behaves_like 'generates proper URLs'++ it { expect(page).to have_link(taxon.name, href: spree.nested_taxons_path(taxon, locale: 'fr')) }+ end++ context 'home page' do+ before do+ visit spree.root_path(locale: 'fr')+ end++ it { expect(page).to have_current_path('/fr') }++ it_behaves_like 'translates UI'+ it_behaves_like 'generates proper URLs'+ endendenddiff --git a/frontend/spec/support/internationalization.rb b/frontend/spec/support/internationalization.rbindex 6223c3c7cd..3f1c4e5704 100644--- a/frontend/spec/support/internationalization.rb+++ b/frontend/spec/support/internationalization.rb@@ -1,3 +1,49 @@+def add_french_locales+ I18n.backend.store_translations(:fr,+ spree: {+ added_to_cart: 'Ajouté au panier avec succès!',+ continue_shopping: 'Continuer vos achats',+ choose_currency: 'Choisir la devise',+ internationalization: 'Internationalisation',+ i18n: {+ language: 'Langue',+ this_file_language: 'Français (FR)'+ },+ cart_page: {+ header: 'Votre panier',+ empty_info: 'Votre panier est vide',+ add_promo_code: 'AJOUTER UN CODE PROMOTIONNEL',+ checkout: 'Passer la commande',+ product: 'articles',+ quantity: 'quantité',+ title: 'Panier',+ change_quantity: 'Changer la quantité',+ remove_from_cart: 'Retirer du panier'+ },+ shopping_cart: 'Panier',+ cart: 'Panier',+ close: 'Fermer',+ search: 'Rechercher',+ home: 'Accueil',+ nav_bar: {+ admin_panel: "Panneau d'administration",+ close_menu: 'Fermer le menu',+ go_to_previous_menu: 'Vers le menu précédent',+ log_in: 'SE CONNECTER',+ log_out: 'DÉCONNEXION',+ my_account: 'MON COMPTE',+ my_orders: 'MES COMMANDES',+ show_menu: 'Afficher le menu',+ show_search: 'Afficher la recherche',+ show_user_menu: 'Afficher le menu utilisateur',+ sign_up: 'ENREGISTRER',+ change_country: 'Changer de pays',+ desktop: 'Navigation sur le bureau',+ mobile: 'Navigation mobile'+ }+ })+end+def open_i18n_menufind('#header #internationalization-button-desktop').clickend