ttag-org / ttag

:orange_book: simple approach for javascript localization
https://ttag.js.org/
MIT License
338 stars 41 forks source link

Support clearing or overriding locales #221

Open jekor opened 3 years ago

jekor commented 3 years ago

Once useLocales(...some locales...) is called, calling useLocales([]) retains the existing locales (though I would expect it to override them and force no translation). I haven't tested what happens when a different set of locales is used in the second call.

The use case for this is responding to dynamic changes to the UI language (such as the languagechange event). For example, given a project where untranslated strings are in English:

addLocale('zh-CN', require('./zh-CN.po.json'));
function changeLocale () {
  // Remove any locales after any locales after any English locale to prevent them from overriding the source English text.
  const preferredOverEnglish = ...
  // on the first call:  preferredOverEnglish = ['zh-CN']
  // on the second call: preferredOverEnglish = []
  useLocales(preferredOverEnglish);
}
// To begin, navigator.languages is ['zh-CN', 'en-US']
changeLocale();
window.addEventListener('languagechange', changeLocale);
// Now the user moves en-US to the top of their preferences, navigator.languages is ['en-US', 'zh-CN'], the languagechange event fires, and changeLocale() gets called.