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.

Fixed setting store locale in react dashboard (#14208)

Damian Legawieca6b3b25bc185
diff --git a/packages/dashboard-core/src/components/top-bar.tsx b/packages/dashboard-core/src/components/top-bar.tsx
index 0ecd13d000..9483afdab5 100644
--- a/packages/dashboard-core/src/components/top-bar.tsx
+++ b/packages/dashboard-core/src/components/top-bar.tsx
@@ -22,12 +22,11 @@ import {
UserIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
-import { adminClient } from '../client'
import { useAuth } from '../hooks/use-auth'
import { useCommandPalette } from '../hooks/use-command-palette'
+import { useSwitchAdminLocale } from '../hooks/use-switch-admin-locale'
import { getInitials } from '../lib/formatters'
-import { i18n, switchLocale } from '../lib/i18n'
+import { i18n } from '../lib/i18n'
import { useStore } from '../providers/store-provider'
const IS_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform ?? '')
@@ -119,22 +118,16 @@ function TopBarUser({ uiLocales }: { uiLocales: ReadonlyArray<{ code: string; na
const { t } = useTranslation()
const { user, logout } = useAuth()
const { store } = useStore()
+ const switchAdminLocale = useSwitchAdminLocale()
if (!user) return null
const initials = getInitials(user.full_name, user.email)
- // Persist the chosen language to the account (PATCH /me) before reloading.
- // This must update the account — not just localStorage — otherwise the
- // auth provider, which treats the account's saved `selected_locale` as the
- // source of truth, would revert the switch on the next page load. Only
- // switch on success: reloading after a failed PATCH would desync localStorage
- // from the server and bounce the locale back on the next session bootstrap.
+ // Switching the admin UI language persists to the account, mirrors it into
+ // the auth context, and reloads — see useSwitchAdminLocale for why all three
+ // steps are required.
const handleSelectLocale = (code: string) => {
- if (code === i18n.language) return
- void adminClient.me.update({ selected_locale: code }).then(
- () => switchLocale(code),
- () => toast.error(t('admin.account.language.update_failed')),
- )
+ void switchAdminLocale(code)
}
return (
diff --git a/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts b/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts
new file mode 100644
index 0000000000..ad6e4b84eb
--- /dev/null
+++ b/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts
@@ -0,0 +1,55 @@
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { adminClient } from '../client'
+import { i18n, markGenuineLocaleChoice, switchLocale } from '../lib/i18n'
+import { useAuth } from './use-auth'
+
+/**
+ * Returns a function that switches the admin UI language and makes it stick.
+ *
+ * Switching the UI language is a three-step operation that every entry point
+ * (top-bar switcher, profile form, store settings) must perform identically:
+ *
+ * 1. Persist `selected_locale` to the ACCOUNT (`PATCH /me`) — not just
+ * localStorage. The auth provider treats the account's `selected_locale`
+ * as the cross-device source of truth and reverts a localStorage-only
+ * switch on the next session bootstrap.
+ * 2. Mirror the change into the auth context so the in-memory user (top-bar,
+ * etc.) reflects it immediately instead of waiting for the next refresh.
+ * 3. `switchLocale` persists the choice and reloads so every module-load
+ * `i18n.t(...)` label re-resolves in the new language.
+ *
+ * A failed PATCH leaves localStorage and the page untouched (no desync) and
+ * surfaces an error toast. Fully a no-op only when the account ALREADY records
+ * `code` and the UI is already displaying it — otherwise the account is brought
+ * in sync even if the UI happens to match (e.g. the language was applied via the
+ * store-default fallback, which writes localStorage but leaves the account
+ * `selected_locale` null), and the page reloads only when the displayed language
+ * actually changes.
+ *
+ * @returns an async `switchAdminLocale(code)` performing the full sequence
+ */
+export function useSwitchAdminLocale() {
+ const { t } = useTranslation()
+ const { user, updateUser } = useAuth()
+
+ return async (code: string): Promise<void> => {
+ // Already adopted on the account AND on screen — nothing to do.
+ if (code === user?.selected_locale && code === i18n.language) return
+ try {
+ const { user: updated } = await adminClient.me.update({ selected_locale: code })
+ updateUser(updated)
+ if (code !== i18n.language) {
+ // Displayed language changes — persist the genuine choice + reload.
+ switchLocale(code)
+ } else {
+ // Already on screen: no reload, but still record it as a GENUINE choice
+ // (clearing any store-default auto-marker) so a later store switch can't
+ // override what the admin explicitly picked.
+ markGenuineLocaleChoice(code)
+ }
+ } catch {
+ toast.error(t('admin.account.language.update_failed'))
+ }
+ }
+}
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index 8f02208c45..2fe5282064 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -50,6 +50,7 @@ export * from './hooks/use-display-name'
export * from './hooks/use-export'
export * from './hooks/use-global-search'
export * from './hooks/use-resource-mutation'
+export * from './hooks/use-switch-admin-locale'
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
diff --git a/packages/dashboard-core/src/lib/i18n.ts b/packages/dashboard-core/src/lib/i18n.ts
index a6039e8a58..32504c4000 100644
--- a/packages/dashboard-core/src/lib/i18n.ts
+++ b/packages/dashboard-core/src/lib/i18n.ts
@@ -9,9 +9,110 @@ import en from '../locales/en.json'
// made anywhere is honored on the next paint.
export const ADMIN_LOCALE_STORAGE_KEY = 'spree-admin-locale'
+// Marks the locale key as auto-applied from a store's `preferred_admin_locale`
+// (vs an explicit choice). Holds the storeId whose default is currently in
+// effect, so crossing into a different store can re-apply that store's default
+// while a genuine choice (switcher/profile/login) still wins everywhere. Mirrors
+// legacy Rails: the `spree_admin_locale` cookie only ever held an explicit
+// login-screen pick; the store default was re-derived per request, never stored.
+const ADMIN_LOCALE_AUTO_STORE_KEY = 'spree-admin-locale-auto-store'
+
+function readStorage(key: string): string | null {
+ try {
+ if (typeof localStorage === 'undefined') return null
+ return localStorage.getItem(key)
+ } catch {
+ return null
+ }
+}
+
+function writeStorage(key: string, value: string): void {
+ try {
+ if (typeof localStorage !== 'undefined') localStorage.setItem(key, value)
+ } catch {
+ // Restricted-storage contexts (Safari private mode, sandboxed iframes) throw
+ // on write; the choice still applies for this session via the booted `lng`.
+ }
+}
+
+function clearStorage(key: string): void {
+ try {
+ if (typeof localStorage !== 'undefined') localStorage.removeItem(key)
+ } catch {
+ // Ignore — see writeStorage.
+ }
+}
+
+// A full reload is deliberate for a language change: many labels (table columns,
+// nav, registry titles) are resolved with `i18n.t(...)` at module-load time and
+// don't react to a live `changeLanguage`. Reloading re-runs those at boot in the
+// new language (read from localStorage by `init`). Deferred to the next macrotask
+// so a pending React state flush (e.g. a just-saved form clearing its dirty
+// state) completes first — otherwise a still-armed `beforeunload` dirty-guard
+// would trigger the browser's "unsaved changes" prompt.
+function reloadSoon(): void {
+ if (typeof window !== 'undefined') {
+ setTimeout(() => window.location.reload(), 0)
+ }
+}
+
+// Read the stored locale, tolerating restricted-storage contexts where
+// `localStorage` access throws. Returns `null` when there is no stored choice
+// so callers can distinguish "no choice yet" from an explicit value.
+function storedLocale(): string | null {
+ return readStorage(ADMIN_LOCALE_STORAGE_KEY)
+}
+
function readStoredLocale(): string {
- if (typeof localStorage === 'undefined') return 'en'
- return localStorage.getItem(ADMIN_LOCALE_STORAGE_KEY) || 'en'
+ return storedLocale() || 'en'
+}
+
+/**
+ * Reconcile the admin UI language against a store's `preferred_admin_locale`
+ * fallback (legacy `base_controller` parity), for an admin with no genuine
+ * personal choice. Encodes the precedence:
+ * account selected_locale > genuine stored choice > store preferred_admin_locale > 'en'
+ *
+ * No-op when a higher tier owns the language (an account locale, or a genuine
+ * stored choice — locale key set without an auto-marker). Otherwise drives the
+ * stored language to this store's current default:
+ * - a supported default → adopt it (auto-marked to this store);
+ * - a blank/cleared/unsupported default → revert to 'en' IF the prior value was
+ * auto-applied (a stale auto-default from this or another store is dropped);
+ * - already matching → nothing changes.
+ * Reloads (via the boot path) only when the displayed language actually changes.
+ *
+ * @param code the store's current `preferred_admin_locale`
+ * @param storeId the store being entered
+ * @param accountLocale the account's `selected_locale` (null when unset)
+ * @param supported locale codes the dashboard ships a bundle for
+ */
+export function reconcileStoreDefaultLocale(
+ code: string | null | undefined,
+ storeId: string,
+ accountLocale: string | null,
+ supported: string[],
+): void {
+ if (accountLocale) return
+ const auto = readStorage(ADMIN_LOCALE_AUTO_STORE_KEY)
+ const stored = storedLocale()
+ // A genuine choice (locale key set, no auto-marker) outranks any store default.
+ if (stored != null && auto == null) return
+
+ const target = code && supported.includes(code) ? code : null
+ const current = i18n.resolvedLanguage ?? i18n.language
+
+ if (target) {
+ writeStorage(ADMIN_LOCALE_STORAGE_KEY, target)
+ writeStorage(ADMIN_LOCALE_AUTO_STORE_KEY, storeId)
+ if (target !== current) reloadSoon()
+ } else if (auto != null) {
+ // Store has no usable default and the current language was auto-applied —
+ // drop it so the UI reverts to the app default ('en').
+ clearStorage(ADMIN_LOCALE_STORAGE_KEY)
+ clearStorage(ADMIN_LOCALE_AUTO_STORE_KEY)
+ if (current !== 'en') reloadSoon()
+ }
}
// All non-English core bundles, imported EAGERLY so the active language has its
@@ -22,25 +123,32 @@ const coreLocales = import.meta.glob<{ default: Record<string, unknown> }>(
{ eager: true },
)
-// Switch the admin UI language. Persists the choice and reloads the page.
-//
-// A full reload is deliberate: many labels (table columns, nav, registry
-// titles) are resolved with `i18n.t(...)` at module-load time and don't react
-// to a live `changeLanguage`. Reloading re-runs those at boot in the new
-// language (read from localStorage by `init` below), so every string switches
-// — not just the components currently subscribed to i18next.
-//
-// The reload is deferred to the next macrotask so any pending React state flush
-// (e.g. a just-saved form resetting its dirty state) completes first — otherwise
-// a still-armed `beforeunload` dirty-guard would trigger the browser's
-// "unsaved changes" prompt.
+/** Admin-UI locale codes the framework ships a bundle for (including `en`). */
+export function coreLocaleCodes(): string[] {
+ return [
+ 'en',
+ ...Object.keys(coreLocales).map((p) => p.replace('../locales/', '').replace('.json', '')),
+ ]
+}
+
+/**
+ * Record an explicit, genuine UI-language choice (top-bar switcher, profile,
+ * login, settings-save) WITHOUT reloading. Persists the locale and clears any
+ * store-default marker, so the choice now outranks every store default and
+ * won't be superseded on store switches. Use this when the UI already displays
+ * `code` (no reload needed) but the choice must still be marked as genuine.
+ */
+export function markGenuineLocaleChoice(code: string): void {
+ writeStorage(ADMIN_LOCALE_STORAGE_KEY, code)
+ clearStorage(ADMIN_LOCALE_AUTO_STORE_KEY)
+}
+
+// Switch the admin UI language from an explicit, genuine choice. Marks it as
+// genuine (see `markGenuineLocaleChoice`) and reloads (see `reloadSoon`) so
+// every module-load label re-resolves in the new language.
export function switchLocale(code: string): void {
- if (typeof localStorage !== 'undefined') {
- localStorage.setItem(ADMIN_LOCALE_STORAGE_KEY, code)
- }
- if (typeof window !== 'undefined') {
- setTimeout(() => window.location.reload(), 0)
- }
+ markGenuineLocaleChoice(code)
+ reloadSoon()
}
// Bootstrap i18next with the framework's base translation namespace. Side-effect
diff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsx
index eb1a33a011..6afcbbcdd3 100644
--- a/packages/dashboard-core/src/providers/store-provider.tsx
+++ b/packages/dashboard-core/src/providers/store-provider.tsx
@@ -1,6 +1,16 @@
import type { Store } from '@spree/admin-sdk'
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useState } from 'react'
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react'
import { adminClient } from '../client'
+import { useAuth } from '../hooks/use-auth'
+import { coreLocaleCodes, reconcileStoreDefaultLocale } from '../lib/i18n'
interface StoreContextValue {
store: Store | null
@@ -21,20 +31,61 @@ const StoreContext = createContext<StoreContextValue | null>(null)
export function StoreProvider({ storeId, children }: { storeId: string; children: ReactNode }) {
const [store, setStore] = useState<Store | null>(null)
const [isLoading, setIsLoading] = useState(true)
+ const { user } = useAuth()
+
+ // Read the account locale through a ref so a `user` identity change (frequent —
+ // every auth update) doesn't re-key `fetchStore` and refetch the store.
+ const accountLocaleRef = useRef<string | null>(user?.selected_locale ?? null)
+ accountLocaleRef.current = user?.selected_locale ?? null
+ // Run the store-default fallback only on the FIRST store load. A later refetch
+ // (e.g. after saving store settings) must not re-apply it: that path already
+ // owns the locale via `switchAdminLocale`, and re-applying would race that
+ // PATCH and could reload before it lands. Re-armed per store (effect below) so
+ // a multi-store admin still inherits each store's preferred_admin_locale.
+ const localeFallbackDoneRef = useRef(false)
+ // Latest requested storeId, so a slow in-flight fetch that resolves after the
+ // route already moved to another store is dropped instead of clobbering the
+ // current store's state and one-shot locale fallback.
+ const latestStoreIdRef = useRef(storeId)
+ latestStoreIdRef.current = storeId
- // biome-ignore lint/correctness/useExhaustiveDependencies: adminClient resolves the store from the route's storeId, so we must refetch when it changes
const fetchStore = useCallback(async () => {
setIsLoading(true)
+ let data: Store | null = null
try {
- const data = await adminClient.store.get()
+ const result = await adminClient.store.get()
+ // Drop a stale response: the route moved on while this was in flight.
+ if (latestStoreIdRef.current !== storeId) return
+ data = result
setStore(data)
} catch {
+ if (latestStoreIdRef.current !== storeId) return
setStore(null)
} finally {
- setIsLoading(false)
+ if (latestStoreIdRef.current === storeId) setIsLoading(false)
+ }
+ // Outside the try: a thrown storage write in the locale fallback must not be
+ // mistaken for a failed fetch and null a store that loaded successfully.
+ // Reconcile the admin language against this store's default — adopting it,
+ // or dropping a now-stale auto-applied default — only when no account locale
+ // or genuine personal choice owns it (legacy base_controller parity).
+ if (data && !localeFallbackDoneRef.current) {
+ localeFallbackDoneRef.current = true
+ reconcileStoreDefaultLocale(
+ data.preferred_admin_locale,
+ storeId,
+ accountLocaleRef.current,
+ coreLocaleCodes(),
+ )
}
}, [storeId])
+ // Re-arm the one-shot fallback for each store the admin switches into.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-arm on store boundary only
+ useEffect(() => {
+ localeFallbackDoneRef.current = false
+ }, [storeId])
+
useEffect(() => {
fetchStore()
}, [fetchStore])
diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.ts
index 2d02ca2bc5..335e5f9b03 100644
--- a/packages/dashboard/e2e/store-settings.spec.ts
+++ b/packages/dashboard/e2e/store-settings.spec.ts
@@ -43,6 +43,96 @@ test.describe('store settings — general', () => {
await page.getByRole('button', { name: /^save$/i }).click()
await expect(page.locator('#store-name')).toHaveValue(creds.store_name)
})
+
+ test('setting the store admin language switches the dashboard UI', async ({ page }) => {
+ const creds = await login(page)
+
+ // Normalize the store's admin language to English while the UI is still
+ // English, so the Polish selection below is always a real change regardless
+ // of any value left by a prior run (the suite shares one seeded DB). A
+ // concrete language (not the blank "use default") is used because clearing
+ // the override sends `undefined`, which the backend treats as "unchanged".
+ // Save only when this actually dirties the form.
+ await page.goto(STORE_PATH(creds.store_id))
+ await expect(page.locator('#store-admin-locale')).toBeVisible({ timeout: 15_000 })
+ await page.locator('#store-admin-locale').click()
+ await page.getByRole('option', { name: /^english$/i }).click()
+ const saveEn = page.getByRole('button', { name: /^save$/i })
+ if (await saveEn.isEnabled()) {
+ await saveEn.click()
+ await expect(saveEn).toBeDisabled({ timeout: 15_000 })
+ }
+
+ // Precondition: give the admin an explicit personal language that DIFFERS
+ // from the one we'll set via store settings. This persists `selected_locale`
+ // on the account, which the auth provider treats as the cross-device source
+ // of truth. Without a saved personal language the store-locale switch passes
+ // trivially on a fresh account (selected_locale = null → nothing to revert
+ // it) while still being broken for a real user who has one — the auth
+ // provider reverts a localStorage-only switch back to the saved language on
+ // the next session bootstrap. German here; the store switch to Polish below
+ // must win over it and survive a reload.
+ await page.goto(`/${creds.store_id}/settings/profile`)
+ await expect(page.locator('#profile-language')).toBeVisible({ timeout: 15_000 })
+ await page.locator('#profile-language').click()
+ await page.getByRole('option', { name: /^deutsch$/i }).click()
+ // Save only if the selection dirtied the form — a prior run may have already
+ // left the account on German, in which case the button stays disabled.
+ const saveProfile = page.getByRole('button', { name: /^(save|speichern)$/i })
+ if (await saveProfile.isEnabled()) await saveProfile.click()
+ // Saving a new language reloads into it; the profile heading is now German.
+ await expect(page.getByText('Persönliche Daten', { exact: true })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ await page.goto(STORE_PATH(creds.store_id))
+ await expect(page.locator('#store-admin-locale')).toBeVisible({ timeout: 15_000 })
+
+ // Pick Polish (endonym shown in the picker) and save. The page is currently
+ // in German (the precondition above), so the Save button reads "Speichern".
+ // Saving persists preferred_admin_locale AND switches the dashboard into
+ // Polish, reloading so every module-load `i18n.t(...)` label re-resolves.
+ await page.locator('#store-admin-locale').click()
+ await page.getByRole('option', { name: /polski/i }).click()
+ await page.getByRole('button', { name: /^speichern$/i }).click()
+
+ // Whole UI re-renders in Polish: the "Standards and formats" card title →
+ // "Standardy i formaty", and the nav "Products" → "Produkty" (proves the
+ // switch drives boot-time labels across nav/tables, not just this form).
+ await expect(page.getByText('Standardy i formaty', { exact: true })).toBeVisible({
+ timeout: 15_000,
+ })
+ await expect(page.getByRole('link', { name: /produkty/i })).toBeVisible()
+
+ // The crux: survives a reload. The switch must have been adopted as the
+ // admin's own `selected_locale` (PATCH /me), not just written to
+ // localStorage — otherwise the auth provider reverts to the previously
+ // saved German on the next session bootstrap and the UI bounces back.
+ await page.reload()
+ await expect(page.getByText('Standardy i formaty', { exact: true })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ // Saving an UNRELATED field (the store name) must NOT touch the admin's UI
+ // language: only an actual change to the admin-locale field switches it.
+ // The UI stays Polish — no surprise reload back to a different language.
+ await page.locator('#store-name').fill(`${creds.store_name} ${Date.now()}`)
+ await page.getByRole('button', { name: /^zapisz$/i }).click()
+ await expect(page.getByText('Standardy i formaty', { exact: true })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ // Reset to English + restore the store name so later tests/specs run
+ // against clean English chrome. The page is now in Polish: the admin-locale
+ // field and the save button read "Zapisz".
+ await page.locator('#store-name').fill(creds.store_name)
+ await page.locator('#store-admin-locale').click()
+ await page.getByRole('option', { name: /^english$/i }).click()
+ await page.getByRole('button', { name: /^zapisz$/i }).click()
+ await expect(page.getByText('Standards and formats', { exact: true })).toBeVisible({
+ timeout: 15_000,
+ })
+ })
})
test.describe('store settings — emails', () => {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
index 464de9e24c..ac0efeeffe 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
@@ -1,6 +1,13 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { SpreeError, type Store } from '@spree/admin-sdk'
-import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'
+import {
+ mapSpreeErrorsToForm,
+ PageHeader,
+ reconcileStoreDefaultLocale,
+ useAuth,
+ useStore,
+ useSwitchAdminLocale,
+} from '@spree/dashboard-core'
import {
Card,
CardContent,
@@ -34,8 +41,8 @@ import {
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { useStoreSettings, useUpdateStoreSettings } from '@/hooks/use-store-settings'
+import { getAvailableUiLocales } from '@/i18n-setup'
import {
- ADMIN_LOCALE_OPTIONS,
type StoreSettingsFormValues,
storeSettingsFormSchema,
UNIT_SYSTEMS,
@@ -108,7 +115,10 @@ function StoreSettingsPage() {
function StoreSettingsForm({ store }: { store: Store }) {
const { t } = useTranslation()
+ const { user } = useAuth()
+ const { storeId } = useStore()
const updateMutation = useUpdateStoreSettings()
+ const switchAdminLocale = useSwitchAdminLocale()
const form = useForm<StoreSettingsFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -128,6 +138,12 @@ function StoreSettingsForm({ store }: { store: Store }) {
}, [unitSystem, form])
const onSubmit = async (values: StoreSettingsFormValues) => {
+ // Whether the admin language was changed in THIS save — compared against the
+ // store's currently-persisted value, not RHF's `dirtyFields` (which a Base UI
+ // Select via Controller doesn't reliably populate). Saving unrelated fields
+ // (name, timezone, units) must not touch the admin's UI language.
+ const code = values.preferred_admin_locale
+ const localeChanged = (code ?? '') !== (store.preferred_admin_locale ?? '')
try {
await updateMutation.mutateAsync({
name: values.name,
@@ -137,7 +153,28 @@ function StoreSettingsForm({ store }: { store: Store }) {
preferred_weight_unit: values.preferred_weight_unit,
})
toast.success(t('admin.messages.store_settings_updated'))
+ // Reset FIRST so the form is no longer dirty — otherwise the language
+ // switch below reloads the page while the `beforeunload` dirty-guard is
+ // still armed, triggering the browser's "unsaved changes" prompt.
form.reset(values)
+ // When the admin language was actually changed:
+ // - a concrete value → adopt it as this admin's own UI language and switch
+ // the dashboard into it immediately (same as the profile / top-bar);
+ // - a blank value ("use the default") → reconcile, so an admin with no
+ // personal choice who was on this store's auto-applied default reverts
+ // to the app default instead of being stuck on the old language.
+ if (localeChanged) {
+ if (code) {
+ await switchAdminLocale(code)
+ } else {
+ reconcileStoreDefaultLocale(
+ null,
+ storeId,
+ user?.selected_locale ?? null,
+ getAvailableUiLocales().map((l) => l.code),
+ )
+ }
+ }
} catch (err) {
if (mapSpreeErrorsToForm(err, form.setError)) return
if (err instanceof SpreeError) throw err
@@ -162,6 +199,18 @@ function StoreSettingsForm({ store }: { store: Store }) {
})),
[t, unitSystem],
)
+ // Admin-UI language options come from the dashboard's own shipped locale
+ // bundles (getAvailableUiLocales) — the SAME canonical source the profile
+ // picker and top-bar switcher use, so the lists never desync. The leading
+ // empty option clears the store-wide override (preferred_admin_locale is
+ // nullable → "no override, fall back to the app default").
+ const adminLocaleOptions = useMemo(
+ () => [
+ { value: '', label: t('admin.fields.store.preferred_admin_locale.placeholder') },
+ ...getAvailableUiLocales().map((l) => ({ value: l.code, label: l.name })),
+ ],
+ [t],
+ )
const { errors } = form.formState
@@ -215,7 +264,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
placeholder={t('admin.fields.store.preferred_admin_locale.placeholder')}
name="preferred_admin_locale"
control={form.control}
- options={ADMIN_LOCALE_OPTIONS}
+ options={adminLocaleOptions}
/>
<SelectField
id="store-timezone"
diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.ts
index c7e11390b9..be00e077c4 100644
--- a/packages/dashboard/src/schemas/store.ts
+++ b/packages/dashboard/src/schemas/store.ts
@@ -20,16 +20,3 @@ export const storeSettingsFormSchema = z.object({
})
export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>
-
-export const ADMIN_LOCALE_OPTIONS: Array<{ value: string; label: string }> = [
- { value: 'en', label: 'English' },
- { value: 'fr', label: 'Français' },
- { value: 'de', label: 'Deutsch' },
- { value: 'es', label: 'Español' },
- { value: 'it', label: 'Italiano' },
- { value: 'pt-BR', label: 'Português (Brasil)' },
- { value: 'pl', label: 'Polski' },
- { value: 'nl', label: 'Nederlands' },
- { value: 'ja', label: '日本語' },
- { value: 'zh-CN', label: '中文 (简体)' },
-]