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

65 lines
1.2 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
{
2021-12-17 00:26:06 +01:00
force?: boolean,
2021-12-17 20:10:14 +01:00
tokens?: Record<string, any>,
2021-12-17 00:26:06 +01:00
hideEmpty?: boolean
2021-12-06 15:06:38 +01:00
}
2021-12-22 10:55:40 +01:00
export const localize = (key: string | null, options?: LocalizeOptions): string =>
2021-12-06 15:06:38 +01:00
{
2021-12-06 15:32:45 +01:00
let params = extendObject({
2021-12-06 15:06:38 +01:00
force: false,
tokens: {},
hideEmpty: false
2021-12-17 00:26:06 +01:00
}, options || {}) as LocalizeOptions;
2021-12-06 15:06:38 +01:00
if (!key)
{
return '';
}
2021-12-19 01:16:02 +01:00
if (!isNaN(key))
{
return key;
}
2021-12-06 15:06:38 +01:00
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;
};