Skip to content

Commit

Permalink
languageToISO6391(): Fix underscore-separated codes (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
AbeJellinek authored Oct 16, 2024
1 parent 86948f9 commit c879fa1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
16 changes: 16 additions & 0 deletions test/tests/utilities_itemTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -402,5 +402,21 @@ describe("Zotero.Utilities.Item", function () {
assert.equal(language, 'French');
globalThis.Intl = Intl;
});

it("should resolve underscore-separated codes", function () {
var language = 'en_US';
language = Zotero.Utilities.Item.languageToISO6391(language);
assert.equal(language, 'en-US');

language = 'zh_Hans';
language = Zotero.Utilities.Item.languageToISO6391(language)
assert.equal(language, 'zh-Hans');
});

it("should not modify input containing an underscore if it isn't a language code", function () {
var language = 'some_other_underscore_stuff';
language = Zotero.Utilities.Item.languageToISO6391(language)
assert.equal(language, 'some_other_underscore_stuff');
});
});
});
28 changes: 25 additions & 3 deletions utilities_item.js
Original file line number Diff line number Diff line change
Expand Up @@ -735,8 +735,8 @@ var Utilities_Item = {
return '';
}

if (!globalThis.Intl || !globalThis.Intl.DisplayNames) {
Zotero.debug('Intl.DisplayNames not available: returning language as-is');
if (!globalThis.Intl || !globalThis.Intl.DisplayNames || !globalThis.Intl.Locale) {
Zotero.debug('Intl not available: returning language as-is');
return language;
}

Expand Down Expand Up @@ -768,7 +768,29 @@ var Utilities_Item = {
}
}

return languageMap.get(normalize(language)) || language;
let normalized = normalize(language);
// If it's a localized language name, return the language's code
if (languageMap.has(normalized)) {
return languageMap.get(normalized);
}

// Is the input a valid locale code?
try {
new Intl.Locale(language);
}
catch (e) {
try {
new Intl.Locale(language.replace(/_/g, '-'));
// No, but language with _ substituted for - (e.g. en_US -> en-US) is
// Return that
return language.replace(/_/g, '-');
}
catch (e) {
}
// All other cases: return the original input
}

return language;
},

/**
Expand Down

0 comments on commit c879fa1

Please sign in to comment.