i18next / i18next-browser-languageDetector

language detector used in browser environment for i18next
MIT License
865 stars 88 forks source link

Add an option like singleDetect #272

Closed NotEvenANeko closed 1 year ago

NotEvenANeko commented 1 year ago

🚀 Feature Proposal

Add an option like singleDetect which only detect one language code instead of multiple codes. Like detect method from @lingui/detect-locale.

Motivation

Current detection order will return multiple language codes, like order: ['querystring', 'navigator'] will return [...codesFromQueryString, ...codesFromNavigator]. But I want something can return only one code or only codesFromQueryString.

Assume we need to support ['ja', 'zh-CN', 'zh-HK', 'en'], I set supportedLngs to this array to support fallback between zh-CN and zh-HK. But when user sets the querystring to ja-JP and navigator.languages returns ['en'], it matches en in the supportedLngs, not ja.

Example


// url: example.com/?lang=ja-JP
// navigator.languages -> ["en"]
i18n.use(LanguageDetector).init({
  resources,
  fallbackLng: ["en"],
  supportedLngs: ["ja", "zh-CN", "zh-HK", "en"],
  interpolation: {
    escapeValue: false
  },
  detection: {
    order: ["querystring", "navigator"],
    lookupQuerystring: "lang",
    caches: [],
    singleDetect: true, // detect only one code or only result from querystring
  }
});

console.log(i18n.languages); // should be ["ja", "en"/* fallback en */], not ["en"/* getBestMatchFromCodes, because detect() returns ["ja-JP", "en"] now */]
jamuhl commented 1 year ago

ja-JP is not in your supportedLngs list....therefore it gets rejected resulting in en only

use option nonExplicitSupportedLngs: true to allow ja-JP if ja is in the list https://www.i18next.com/overview/configuration-options#languages-namespaces-resources

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.