Skip to content

Commit

Permalink
chore: interpolate translations
Browse files Browse the repository at this point in the history
  • Loading branch information
Benmuiruri committed Nov 4, 2024
1 parent 9d1c055 commit 8fee9e8
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
2 changes: 1 addition & 1 deletion api/src/controllers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ const validatePassword = (password, confirmPassword) => {
return {
isValid: false,
error: 'short',
params: { minimum: PASSWORD_MINIMUM_LENGTH}
params: { minimum: PASSWORD_MINIMUM_LENGTH }
};
}

Expand Down
27 changes: 26 additions & 1 deletion api/src/public/login/auth-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,38 @@ export const parseTranslations = function() {
return JSON.parse(decodeURIComponent(raw));
};

const replaceTranslationPlaceholders = (text, translateValues) => {
if (!text || !translateValues) {
return text;
}

try {
const values = JSON.parse(translateValues);
console.log(values);
return Object.entries(values).reduce((result, [key, value]) =>
result.replace(new RegExp(`{{${key}}}`, 'g'), value),
text
);
} catch (e) {
console.error('Error parsing translation placeholders', e);
return text;
}
}

export const baseTranslate = (selectedLocale, translations) => {
if (!selectedLocale) {
return console.error('No enabled locales found - not translating');
}
document
.querySelectorAll('[translate]')
.forEach(elem => elem.innerText = translations[selectedLocale][elem.getAttribute('translate')]);
.forEach(elem => {
let text = translations[selectedLocale][elem.getAttribute('translate')];
const translateValues = elem.getAttribute('translate-values');
if (translateValues) {
text = replaceTranslationPlaceholders(text, translateValues);
}
elem.innerText = text;
});
document
.querySelectorAll('[translate-title]')
.forEach(elem => elem.title = translations[selectedLocale][elem.getAttribute('translate-title')]);
Expand Down
8 changes: 6 additions & 2 deletions api/src/public/login/password-reset.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ const displayPasswordValidationError = (serverResponse) => {
const { error, params } = JSON.parse(serverResponse);
setState(error);

if (params) {
//add translate values param
if (params?.minimum) {
const passwordError = document.querySelector('.error.password-short');
if (passwordError) {
passwordError.setAttribute('translate-values', JSON.stringify(params));
baseTranslate(selectedLocale, translations);
}
}
};

Expand Down

0 comments on commit 8fee9e8

Please sign in to comment.