handle strings with args in localize controller

This commit is contained in:
Mads Rasmussen
2025-01-30 22:36:39 +01:00
parent 1872a9a139
commit 25ca146eee

View File

@@ -191,9 +191,10 @@ export class UmbLocalizationController<LocalizationSetType extends UmbLocalizati
* If the term is found in the localization set, it will be replaced with the localized term.
* If the term is not found, the original term will be returned.
* @param {string} text The text to translate.
* @param {Record<string, Array<string>>} argsMap An object where the keys are the terms to translate and the values are arrays of arguments to pass to the term function.
* @returns {string} The translated text.
*/
string(text: unknown): string {
string(text: unknown, argsMap?: Record<string, Array<string>>): string {
if (typeof text !== 'string') {
return '';
}
@@ -203,14 +204,26 @@ export class UmbLocalizationController<LocalizationSetType extends UmbLocalizati
const localizedText = text.replace(regex, (match: string) => {
const key = match.slice(1);
// TODO: find solution to pass dynamic string to term
const args = argsMap?.[key] || [];
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const localized = this.term(key);
const localized = this.term(key, ...args);
// we didn't find a localized string, so we return the original string with the #
return localized === key ? match : localized;
});
return localizedText;
}
/**
* Extracts all keys from a string that start with a `#` character.
* @param {string} text The text to parse.
* @returns {Array<string>} An array of keys.
*/
getKeysFromString(text: string): Array<string> {
const regex = /#\w+/g;
const keys = text.match(regex) || [];
return keys.map((key) => key.slice(1));
}
}