Skip to content

Detect browser language to set default language for new users #3492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion client/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import {
enIN
} from 'date-fns/locale';

import getPreferredLanguage from './utils/language-utils';

const fallbackLng = ['en-US'];

export const availableLanguages = [
Expand All @@ -42,6 +44,21 @@ export const availableLanguages = [
'ur'
];

const detectedLanguage = getPreferredLanguage(
availableLanguages,
fallbackLng[0]
);

let initialLanguage = detectedLanguage;

// if user has a saved preference (e.g., from redux or window.__INITIAL_STATE__), use that
if (
window.__INITIAL_STATE__?.preferences?.language &&
availableLanguages.includes(window.__INITIAL_STATE__.preferences.language)
) {
initialLanguage = window.__INITIAL_STATE__.preferences.language;
}

export function languageKeyToLabel(lang) {
const languageMap = {
be: 'বাংলা',
Expand Down Expand Up @@ -104,7 +121,7 @@ i18n
// .use(LanguageDetector)// to detect the language from currentBrowser
.use(Backend) // to fetch the data from server
.init({
lng: 'en-US',
lng: initialLanguage,
fallbackLng, // if user computer language is not on the list of available languages, than we will be using the fallback language specified earlier
debug: false,
backend: options,
Expand Down
3 changes: 2 additions & 1 deletion client/modules/IDE/reducers/preferences.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as ActionTypes from '../../../constants';
import i18n from '../../../i18n';

export const initialState = {
tabIndex: 0,
Expand All @@ -11,7 +12,7 @@ export const initialState = {
gridOutput: false,
theme: 'light',
autorefresh: false,
language: 'en-US',
language: i18n.language,
autocloseBracketsQuotes: true,
autocompleteHinter: false
};
Expand Down
107 changes: 107 additions & 0 deletions client/utils/language-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/**
* Utility functions for language detection and handling
*/

function detectLanguageFromUserAgent(userAgent) {
const langRegexes = [
/\b([a-z]{2}(-[A-Z]{2})?);/i, // matches patterns like "en;" or "en-US;"
/\[([a-z]{2}(-[A-Z]{2})?)\]/i // matches patterns like "[en]" or "[en-US]"
];

const match = langRegexes.reduce((result, regex) => {
if (result) return result;
const matches = userAgent.match(regex);
return matches && matches[1] ? matches[1] : null;
}, null);

return match;
}

function getPreferredLanguage(supportedLanguages = [], defaultLanguage = 'en') {
if (typeof navigator === 'undefined') {
return defaultLanguage;
}

const normalizeLanguage = (langCode) => langCode.toLowerCase().trim();

const normalizedSupported = supportedLanguages.map(normalizeLanguage);

if (navigator.languages && navigator.languages.length) {
const matchedLang = navigator.languages.find((browserLang) => {
const normalizedBrowserLang = normalizeLanguage(browserLang);

const hasExactMatch =
normalizedSupported.findIndex(
(lang) => lang === normalizedBrowserLang
) !== -1;

if (hasExactMatch) {
return true;
}

const languageOnly = normalizedBrowserLang.split('-')[0];
const hasLanguageOnlyMatch =
normalizedSupported.findIndex(
(lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`)
) !== -1;

return hasLanguageOnlyMatch;
});

if (matchedLang) {
const normalizedMatchedLang = normalizeLanguage(matchedLang);
const exactMatchIndex = normalizedSupported.findIndex(
(lang) => lang === normalizedMatchedLang
);

if (exactMatchIndex !== -1) {
return supportedLanguages[exactMatchIndex];
}

const languageOnly = normalizedMatchedLang.split('-')[0];
const languageOnlyMatchIndex = normalizedSupported.findIndex(
(lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`)
);

if (languageOnlyMatchIndex !== -1) {
return supportedLanguages[languageOnlyMatchIndex];
}
}
}

if (navigator.language) {
const normalizedNavLang = normalizeLanguage(navigator.language);
const exactMatchIndex = normalizedSupported.findIndex(
(lang) => lang === normalizedNavLang
);

if (exactMatchIndex !== -1) {
return supportedLanguages[exactMatchIndex];
}

const languageOnly = normalizedNavLang.split('-')[0];
const languageOnlyMatchIndex = normalizedSupported.findIndex(
(lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`)
);

if (languageOnlyMatchIndex !== -1) {
return supportedLanguages[languageOnlyMatchIndex];
}
}

if (navigator.userAgent) {
const userAgentLang = detectLanguageFromUserAgent(navigator.userAgent);
if (
userAgentLang &&
normalizedSupported.includes(normalizeLanguage(userAgentLang))
) {
const index = normalizedSupported.indexOf(
normalizeLanguage(userAgentLang)
);
return supportedLanguages[index];
}
}
return defaultLanguage;
}

export default getPreferredLanguage;