Skip to content

Commit

Permalink
Avoid __MSG_*__ format requirement for Localizer's message ids.
Browse files Browse the repository at this point in the history
It is not really needed in HTML files (as explicit data attributes are used)
and it clutters HTML source a lot.
  • Loading branch information
ivilata committed Feb 8, 2021
1 parent 414675e commit d9ea578
Showing 1 changed file with 2 additions and 24 deletions.
26 changes: 2 additions & 24 deletions localizer/Localizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,6 @@ const I18N_DATASET_KEEP_CHILDREN = "optI18nKeepChildren";
const UNIQUE_REPLACEMENT_SPLIT = "$i18nSplit$";
const UNIQUE_REPLACEMENT_ID = "i18nKeepChildren#";

/**
* Splits the _MSG__*__ format and returns the actual tag.
*
* The format is defined in {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/Locale-Specific_Message_reference#name}.
*
* @private
* @param {string} tag
* @returns {string}
* @throws {Error} if pattern does not match
*/
function getMessageTag(tag) {
/** {@link https://regex101.com/r/LAC5Ib/2} **/
const splitMessage = tag.split(/^__MSG_([\w@]+)__$/);

// throw custom exception if input is invalid
if (splitMessage.length < 2) {
throw new Error(`invalid message tag pattern "${tag}"`);
}

return splitMessage[1];
}

/**
* Converts a dataset value back to a real attribute.
*
Expand Down Expand Up @@ -237,7 +215,7 @@ function replaceI18n(elem, tag) {
// localize main content
if (tag !== "") {
try {
const translatedMessage = getTranslatedMessage(getMessageTag(tag), subsContainer.substitutions);
const translatedMessage = getTranslatedMessage(tag, subsContainer.substitutions);

// if we have substrings to replace
if (subsContainer.substitutions) {
Expand All @@ -264,7 +242,7 @@ function replaceI18n(elem, tag) {
const replaceAttribute = convertDatasetToAttribute(dataAttribute.slice(I18N_DATASET_INT));

try {
const translatedMessage = getTranslatedMessage(getMessageTag(dataValue));
const translatedMessage = getTranslatedMessage(dataValue);
replaceWith(elem, replaceAttribute, translatedMessage);
} catch (error) {
// log error but continue translating as it was likely just one problem in one translation
Expand Down

0 comments on commit d9ea578

Please sign in to comment.