Handle nonexistent locale switch

This commit is contained in:
Christian Kaisermann 2018-08-09 15:49:01 -03:00
parent a264c3a282
commit 5662f0401c
3 changed files with 38 additions and 17 deletions

View File

@ -1,6 +1,6 @@
{
"name": "svelte-i18n",
"version": "0.0.2",
"version": "0.0.3",
"license": "MIT",
"main": "dist/i18n.js",
"module": "dist/i18n.m.js",

View File

@ -5,9 +5,9 @@ import Formatter from './formatter'
export { capital, title, upper, lower }
export function i18n(store, { dictionary }) {
export function i18n(store, { dictionary: initialDictionary }) {
const formatter = new Formatter()
let dictionaries = {}
let dictionary = {}
let currentLocale
const getLocalizedMessage = (
@ -16,7 +16,7 @@ export function i18n(store, { dictionary }) {
locale = currentLocale,
transformers = undefined,
) => {
let message = resolvePath(dictionaries[locale], path)
let message = resolvePath(dictionary[locale], path)
if (!message) return path
@ -57,25 +57,33 @@ export function i18n(store, { dictionary }) {
},
}
store.on('locale', newLocale => {
if (!Object.keys(dictionary).includes(newLocale)) {
console.error(`[svelte-i18n] Couldn't find the "${newLocale}" locale.`)
return
}
currentLocale = newLocale
const _ = getLocalizedMessage
_.upper = utilities.upper
_.lower = utilities.lower
_.title = utilities.title
_.capital = utilities.capital
_.plural = utilities.plural
store.set({ locale: newLocale, _ })
})
store.i18n = {
setLocale(locale) {
store.fire('locale', locale)
},
extendDictionary(...list) {
dictionaries = deepmerge.all([dictionaries, ...list])
dictionary = deepmerge.all([dictionary, ...list])
},
}
store.i18n.extendDictionary(dictionary)
store.on('locale', newLocale => {
currentLocale = newLocale
const _ = getLocalizedMessage
Object.assign(_, utilities)
store.set({ locale: newLocale, _ })
})
store.i18n.extendDictionary(initialDictionary)
return store
}

View File

@ -42,6 +42,14 @@ describe('Utilities', () => {
})
describe('Localization', () => {
beforeEach(() => {
console.error = jest.fn()
})
afterEach(() => {
console.error.mockRestore()
})
it('should start with a clean store', () => {
const { _, locale } = store.get()
expect(locale).toBeFalsy()
@ -49,10 +57,10 @@ describe('Localization', () => {
})
it('should change the locale after a "locale" store event', () => {
store.fire('locale', 'en')
store.fire('locale', 'pt-br')
const { locale, _ } = store.get()
expect(locale).toBe('en')
expect(locale).toBe('pt-br')
expect(_).toBeInstanceOf(Function)
})
@ -65,6 +73,11 @@ describe('Localization', () => {
expect(locale).toBe('pt-br')
})
it('should handle nonexistent locale', () => {
expect(store.i18n.setLocale('foo'))
expect(console.error).toHaveBeenCalledTimes(1)
})
it('should return the message id when no message identified by it was found', () => {
store.i18n.setLocale('pt-br')
const { _ } = store.get()