Skip to content
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

fixes setLang to handle navigator.language formats (such as "fr-FR") #1499

Merged
merged 1 commit into from
Jun 15, 2024
Merged
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
1 change: 1 addition & 0 deletions leaflet-geoman.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ declare module 'leaflet' {
| 'nl'
| 'no'
| 'pl'
| 'pt'
| 'pt_br'
| 'pt_pt'
| 'ro'
Expand Down
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,
mscno marked this conversation as resolved.
Show resolved Hide resolved
// 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