Skip to content

Commit

Permalink
fixes setLang to handle navigator.language formats (such as "fr-FR")
Browse files Browse the repository at this point in the history
  • Loading branch information
mscno committed Jun 13, 2024
1 parent 03a794c commit be1c983
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/assets/translations/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ import fi from './fi.json';
import ko from './ko.json';
import ky from './ky.json';

// eslint-disable-next-line camelcase
const pt = pt_pt;

export default {
en,
de,
Expand All @@ -39,6 +42,7 @@ export default {
es,
nl,
fr,
pt,
// eslint-disable-next-line camelcase
pt_br,
// eslint-disable-next-line camelcase
Expand Down
36 changes: 33 additions & 3 deletions src/js/L.PM.Map.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,40 @@ const Map = L.Class.extend({
this.Keyboard._initKeyListener(map);
},
// eslint-disable-next-line default-param-last
setLang(lang = 'en', t, fallback = 'en') {
setLang(lang = 'en', override, fallback = 'en') {
// Normalize the language code to lowercase and trim any whitespace
lang = lang.trim().toLowerCase();

// First, check if the input is already in the expected format (e.g., 'fr')
if (/^[a-z]{2}$/.test(lang)) {
// No further processing needed for single-letter codes
} else {
// Handle formats like 'fr-FR', 'FR', 'fr-fr', 'fr_FR'
const normalizedLang = lang
.replace(/[-_\s]/g, '-')
.replace(/^(\w{2})$/, '$1-');
const match = normalizedLang.match(/([a-z]{2})-?([a-z]{2})?/);

if (match) {
// Construct potential keys to search for in the translations object
const potentialKeys = [
`${match[1]}_${match[2]}`, // e.g., 'fr_BR'
`${match[1]}`, // e.g., 'fr'
];

// Search through the translations object for a matching key
for (const key of potentialKeys) {
if (translations[key]) {
lang = key; // Set lang to the matching key
break; // Exit the loop once a match is found
}
}
}
}

const oldLang = L.PM.activeLang;
if (t) {
translations[lang] = merge(translations[fallback], t);
if (override) {
translations[lang] = merge(translations[fallback], override);
}

L.PM.activeLang = lang;
Expand Down

0 comments on commit be1c983

Please sign in to comment.