Skip to content
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
add locales, change recursive calls to a while loop
  • Loading branch information
mapmeld committed Aug 5, 2025
commit 64fd04c4a529bebc7257c82fceed8d67392d1d3f
25 changes: 15 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
const ALT_LOCALES = {
'zh-cn': 'zh-Hans',
'zh-hk': 'zh-Hant',
'zh-mo': 'zh-Hant',
'zh-sg': 'zh-Hans',
'zh-tw': 'zh-Hant',
Comment on lines 3 to 7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how common it is, but zh-SG and zh-MO normally map to zh-Hans and zh-Hant, respectively, based on official status.

};

Expand Down Expand Up @@ -123,11 +125,13 @@ function findStreetsSource(style) {
*/
MapboxLanguage.prototype.setLanguage = function (style, language) {
language = ALT_LOCALES[language.toLowerCase()] || language;
if (this.supportedLanguages.indexOf(language) < 0) {

while (this.supportedLanguages.indexOf(language) < 0) {
if (language.indexOf('-') > -1) {
return this.setLanguage(style, language.slice(0, language.lastIndexOf('-')));
language = language.slice(0, language.lastIndexOf('-'));
} else {
throw new Error(`Language ${ language } is not supported`);
}
throw new Error(`Language ${ language } is not supported`);
}
const streetsSource = this._languageSource || findStreetsSource(style);
if (!streetsSource) return style;
Expand Down Expand Up @@ -158,14 +162,15 @@ function browserLanguage(supportedLanguages, language) {
language = language || (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage));
language = ALT_LOCALES[language.toLowerCase()] || language;

if (supportedLanguages.indexOf(language) > -1) {
return language;
}
if (language.indexOf('-') > -1) {
// reduce longer locales (en-US, zh-Hant-TW) to shorter forms
return browserLanguage(supportedLanguages, language.slice(0, language.lastIndexOf('-')));
while (supportedLanguages.indexOf(language) < 0) {
if (language.indexOf('-') > -1) {
// reduce longer locales (en-US, zh-Hant-TW) to shorter forms
language = language.slice(0, language.lastIndexOf('-'));
} else {
return null;
}
}
return null;
return language;
}

MapboxLanguage.prototype.onAdd = function (map) {
Expand Down