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

languageToISO6391(): Fix underscore-separated codes #38

Merged
merged 1 commit into from
Oct 16, 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
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
Loading