You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.2 KiB
45 lines
1.2 KiB
7 years ago
|
// cross-browser connection to extension i18n API
|
||
|
const log = require('loglevel')
|
||
|
|
||
7 years ago
|
/**
|
||
|
* Returns a localized message for the given key
|
||
|
* @param {object} locale The locale
|
||
|
* @param {string} key The message key
|
||
|
* @param {string[]} substitutions A list of message substitution replacements
|
||
|
* @return {null|string} The localized message
|
||
|
*/
|
||
7 years ago
|
const getMessage = (locale, key, substitutions) => {
|
||
|
if (!locale) {
|
||
7 years ago
|
return null
|
||
7 years ago
|
}
|
||
7 years ago
|
if (!locale[key]) {
|
||
6 years ago
|
log.warn(`Translator - Unable to find value for key "${key}"`)
|
||
7 years ago
|
return null
|
||
7 years ago
|
}
|
||
7 years ago
|
const entry = locale[key]
|
||
7 years ago
|
let phrase = entry.message
|
||
|
// perform substitutions
|
||
|
if (substitutions && substitutions.length) {
|
||
6 years ago
|
substitutions.forEach((substitution, index) => {
|
||
|
const regex = new RegExp(`\\$${index + 1}`, 'g')
|
||
|
phrase = phrase.replace(regex, substitution)
|
||
|
})
|
||
7 years ago
|
}
|
||
|
return phrase
|
||
|
}
|
||
|
|
||
7 years ago
|
async function fetchLocale (localeName) {
|
||
|
try {
|
||
|
const response = await fetch(`./_locales/${localeName}/messages.json`)
|
||
7 years ago
|
return await response.json()
|
||
7 years ago
|
} catch (error) {
|
||
|
log.error(`failed to fetch ${localeName} locale because of ${error}`)
|
||
|
return {}
|
||
|
}
|
||
7 years ago
|
}
|
||
|
|
||
|
module.exports = {
|
||
|
getMessage,
|
||
|
fetchLocale,
|
||
|
}
|