81 lines
2 KiB
TypeScript
81 lines
2 KiB
TypeScript
const getBaseResources = (state, resourceNames) => {
|
|
if (!resourceNames.length) {
|
|
return {}
|
|
}
|
|
|
|
// [{}, {}, {}]
|
|
const texts = resourceNames.map((resourceName) => {
|
|
const resource = state.resources[resourceName]
|
|
return {
|
|
...resource.texts,
|
|
...getBaseResources(state, resource.baseResources),
|
|
}
|
|
})
|
|
|
|
return Object.assign({}, ...texts)
|
|
}
|
|
|
|
export const setLocalization = (state) => {
|
|
const values = {}
|
|
Object.entries(state.resources).forEach(([key, value]) => {
|
|
values[key] = {
|
|
...value.texts,
|
|
...getBaseResources(state, value.baseResources),
|
|
}
|
|
})
|
|
|
|
return values
|
|
}
|
|
|
|
export const getLocalization = (texts, defaultResourceName, key, ...interpolateParams) => {
|
|
if (!key) key = ''
|
|
let defaultValue = ''
|
|
|
|
if (typeof key !== 'string') {
|
|
defaultValue = key.defaultValue
|
|
key = key.key
|
|
}
|
|
|
|
const keys = key.split('::')
|
|
const warn = (message) => {
|
|
if (import.meta.env.DEV) console.warn(message)
|
|
}
|
|
|
|
if (keys.length < 2) {
|
|
warn('The localization source separator (::) not found.')
|
|
return defaultValue || key
|
|
}
|
|
if (!texts) return defaultValue || keys[1]
|
|
|
|
const sourceName = keys[0] || defaultResourceName
|
|
const sourceKey = keys[1]
|
|
|
|
if (sourceName === '_') {
|
|
return defaultValue || sourceKey
|
|
}
|
|
|
|
if (!sourceName) {
|
|
warn('Localization source name is not specified and the defaultResourceName was not defined!')
|
|
|
|
return defaultValue || sourceKey
|
|
}
|
|
|
|
const source = texts[sourceName]
|
|
if (!source) {
|
|
warn('Could not find localization source: ' + sourceName)
|
|
return defaultValue || sourceKey
|
|
}
|
|
|
|
let localization = source[sourceKey]
|
|
if (typeof localization === 'undefined') {
|
|
return defaultValue || sourceKey
|
|
}
|
|
|
|
//TODO: Interpolate
|
|
// interpolateParams = interpolateParams.filter((params) => params != null)
|
|
// if (localization) localization = interpolate(localization, interpolateParams)
|
|
|
|
if (typeof localization !== 'string') localization = ''
|
|
|
|
return localization || defaultValue || key
|
|
}
|