mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 09:52:26 +01:00
* Prevent multiple warnings for the same locale message Our i18n helper issues warnings whenever a requested message is missing. These warnings are helpful in assisting translation efforts, but they can be distracting otherwise. They're especially problematic for locales that are missing many messages. My browser ended up crashing on more than one occasion due to the sheer volume of warnings. The warning has been updated to only be issued once per missing key. This required updating the method to pass in the current locale. The current locale was added to the warning itself as well, which could be helpful for cases where a message is missing in both the current locale and the fallback ('en'). * Change locale and localeMessages as single action Updating the current locale and the locale messages resulted in two renders, and during the first the state was inconsistent (it would say the locale had changed to the new one, but still be using the old set of locale messages). Instead the locale is now updated with one atomic action. This was required after adding the locale to the missing locale message warning, as otherwise it would say the message was missing from the wrong locale.
53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
// cross-browser connection to extension i18n API
|
|
const log = require('loglevel')
|
|
|
|
const warned = {}
|
|
/**
|
|
* Returns a localized message for the given key
|
|
* @param {string} localeCode The code for the current locale
|
|
* @param {object} localeMessages The map of messages for the current locale
|
|
* @param {string} key The message key
|
|
* @param {string[]} substitutions A list of message substitution replacements
|
|
* @return {null|string} The localized message
|
|
*/
|
|
const getMessage = (localeCode, localeMessages, key, substitutions) => {
|
|
if (!localeMessages) {
|
|
return null
|
|
}
|
|
if (!localeMessages[key]) {
|
|
if (!warned[localeCode] || !warned[localeCode][key]) {
|
|
if (!warned[localeCode]) {
|
|
warned[localeCode] = {}
|
|
}
|
|
warned[localeCode][key] = true
|
|
log.warn(`Translator - Unable to find value of key "${key}" for locale "${localeCode}"`)
|
|
}
|
|
return null
|
|
}
|
|
const entry = localeMessages[key]
|
|
let phrase = entry.message
|
|
// perform substitutions
|
|
if (substitutions && substitutions.length) {
|
|
substitutions.forEach((substitution, index) => {
|
|
const regex = new RegExp(`\\$${index + 1}`, 'g')
|
|
phrase = phrase.replace(regex, substitution)
|
|
})
|
|
}
|
|
return phrase
|
|
}
|
|
|
|
async function fetchLocale (localeCode) {
|
|
try {
|
|
const response = await fetch(`./_locales/${localeCode}/messages.json`)
|
|
return await response.json()
|
|
} catch (error) {
|
|
log.error(`failed to fetch ${localeCode} locale because of ${error}`)
|
|
return {}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
getMessage,
|
|
fetchLocale,
|
|
}
|