Created
May 4, 2022 13:13
-
-
Save MartinMalinda/68662fdc52998d0c1309a50fff4c4abe to your computer and use it in GitHub Desktop.
i18n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { defineStore } from 'pinia'; | |
import get from 'deep-access'; | |
import { isDevelopment } from '../media/detect'; | |
export type PluralizeFn = (parts: string[], n: number) => string; | |
export const useI18n = () => { | |
const store = useI18nStore(); | |
const t = (key, params?: Record<string, any>, n?: number) => store.t(key, params, n); | |
const setLocale = (locale: string, { data, pluralizeFn }: { data: Record<string, any>, pluralizeFn?: PluralizeFn }) => { | |
store.locale = locale; | |
store.localeData = data; | |
store.pluralizeFn = pluralizeFn || defaultPluralizeFn; | |
}; | |
return { t, setLocale }; | |
}; | |
const defaultPluralizeFn = (parts, n) => { | |
if (n === 1) { | |
// singular | |
return parts[0]; | |
} | |
// plural | |
return parts[1]; | |
}; | |
export const slavicPluralizeFn = (parts, n) => { | |
if (n === 0) { | |
return parts[2]; | |
} | |
if (n === 1) { | |
return parts[0]; | |
} | |
if (n > 4) { | |
return parts[2]; | |
} | |
return parts[1]; | |
}; | |
export const useI18nStore = defineStore({ | |
id: 'i18n', | |
state: () => ({ | |
locale: null as null | string, | |
localeData: {} as Record<string, any>, | |
pluralizeFn: defaultPluralizeFn, | |
}), | |
actions: { | |
t(key, params?: Record<string, any>, n?) { | |
let _value: string | undefined; | |
try { | |
_value = get(this.localeData, key); | |
// eslint-disable-next-line no-empty | |
} catch (e) { } | |
if (!_value) { | |
return isDevelopment() ? showKeyInfo(key, params, n) : ''; | |
} | |
if (typeof n === 'number' && _value.includes('|')) { | |
const parts = _value.split('|'); | |
_value = this.pluralizeFn(parts, n); | |
} | |
if (params) { | |
Object.entries(params).forEach(([param, value]) => { | |
_value = (_value as string).replaceAll(`{${param}}`, value); | |
}); | |
} | |
if (isDevelopment() && !_value) { | |
return showKeyInfo(key, params, n); | |
} | |
return _value || ''; | |
} | |
} | |
}); | |
const showKeyInfo = ( | |
key, | |
pluralOrNamedValue: any, | |
plural?: any | |
): string => { | |
const _plural = plural | pluralOrNamedValue; | |
if (_plural) { | |
const isObject = typeof _plural === 'object'; | |
const pluralOpt = isObject | |
? JSON.stringify(_plural) | |
: _plural; | |
return `${key} (${pluralOpt})`; | |
} | |
console.warn(`Translation might be missing for ${key}`); | |
return key; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment