Files
mixtape/zero.Backoffice.UI/app/services/localization.ts
T

60 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-12-06 15:06:38 +01:00
2021-12-06 15:32:45 +01:00
import { extendObject } from '../utils/objects';
import { useTranslationStore } from '../stores/translations';
2021-12-06 15:06:38 +01:00
export interface LocalizeOptions
{
force: boolean,
tokens: object,
hideEmpty: boolean
}
export const localize = (key: string, options?: LocalizeOptions): string =>
{
2021-12-06 15:32:45 +01:00
let params = extendObject({
2021-12-06 15:06:38 +01:00
force: false,
tokens: {},
hideEmpty: false
}, options || {});
if (!key)
{
return '';
}
const hasAtSign = key.indexOf('@') === 0;
if (!params.force && !hasAtSign)
{
return replaceTokens(key, params.tokens);
}
key = hasAtSign ? key.slice(1) : key;
2021-12-06 16:18:58 +01:00
const store = useTranslationStore();
const value = store.find(key);
2021-12-06 15:06:38 +01:00
// TODO only return key if in debug mode
if (!params.hideEmpty && (!value || typeof value !== 'string'))
{
return '[' + key + ']';
}
return replaceTokens(value, params.tokens);
};
2021-12-06 15:32:45 +01:00
export const replaceTokens = (value: string, tokens: Record<string, string>): string =>
2021-12-06 15:06:38 +01:00
{
if (!value || value.indexOf('{') < 0)
{
return value;
}
2021-12-06 15:32:45 +01:00
for (const key in tokens)
2021-12-06 15:06:38 +01:00
{
2021-12-06 15:32:45 +01:00
value = value.replace("{" + key + "}", tokens[key]);
}
2021-12-06 15:06:38 +01:00
return value;
};