feat(i18n): add localeStore with localStorage persistence
This commit is contained in:
1 parent
0a05c479a0
commit
a57047505d
3 files changed
+53
No files matched your search
@@ -0,0 +1,2 @@
|
||||
export type Locale = 'fr' | 'en'
|
||||
export type Dict = Record<string, string>
|
||||
@@ -0,0 +1,28 @@
|
||||
import { create } from 'zustand'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export const LOCALE_STORAGE_KEY = 'osteo:locale'
|
||||
|
||||
function readInitial(): Locale {
|
||||
if (typeof localStorage === 'undefined') return 'fr'
|
||||
const raw = localStorage.getItem(LOCALE_STORAGE_KEY)
|
||||
return raw === 'fr' || raw === 'en' ? raw : 'fr'
|
||||
}
|
||||
|
||||
export interface LocaleStore {
|
||||
locale: Locale
|
||||
setLocale: (next: Locale) => void
|
||||
}
|
||||
|
||||
export const useLocaleStore = create<LocaleStore>((set) => ({
|
||||
locale: readInitial(),
|
||||
setLocale: (next) => {
|
||||
set({ locale: next })
|
||||
if (typeof localStorage === 'undefined') return
|
||||
try {
|
||||
localStorage.setItem(LOCALE_STORAGE_KEY, next)
|
||||
} catch {
|
||||
// Quota / private mode — in-memory only.
|
||||
}
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { useLocaleStore, LOCALE_STORAGE_KEY } from '@/state/localeStore'
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.removeItem(LOCALE_STORAGE_KEY)
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
})
|
||||
|
||||
describe('localeStore', () => {
|
||||
it('defaults to fr when localStorage is empty', () => {
|
||||
expect(useLocaleStore.getState().locale).toBe('fr')
|
||||
})
|
||||
|
||||
it('setLocale updates state', () => {
|
||||
useLocaleStore.getState().setLocale('en')
|
||||
expect(useLocaleStore.getState().locale).toBe('en')
|
||||
})
|
||||
|
||||
it('setLocale writes to localStorage', () => {
|
||||
useLocaleStore.getState().setLocale('en')
|
||||
expect(localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('en')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user