'use strict';
import * as LocaleTools from '../../../utility/locale-tools';
/** Helper function to find and return the first valid locale in the list
* of supported lanugages.
* @param {array} languages - Supported languages
* @return {external:Locale} - Valid locale in supported languages
*/
function _findLocale(languages) {
for (const entry of languages) {
// If it is a locale we directly support, use it.
if (entry in LocaleTools.locales) {
return entry;
}
// If it is a language we support, use it.
if (entry in LocaleTools.languageToLocale) {
return LocaleTools.languageToLocale[entry];
}
}
return undefined;
}
/** When the user hits the English home page (/) and they do not have
* a locale cookie, attempt to set it based on navigator.languages.
*
* NOTE: This is based on EXPERIMENTAL support of navigator.languages.
* For those browsers lacking support, the navigator.language
* value will be used as a last-resort backup. This is because
* the affected footprint is primarily Internet Explorer and Edge
* (though Edge is working to support this feature soon).
*
* NOTE: In theory this will move to a page-specific JavaScript for the
* home page. I haven't figured out that section fully, and it's
* relatively trivial to do it here.
*/
export default function localeDefault() {
const isHomepage = (document.location.pathname === '/');
const ismissingLocaleCookie = (window.jsCookies.get('locale') === undefined);
const locale = _findLocale((navigator.languages || []).concat([navigator.language]));
const hasLocale = (locale !== undefined);
// Only if we're on the homepage and locale cookie is not set...
if (isHomepage && ismissingLocaleCookie && hasLocale) {
window.jsCookies.set('locale', locale);
}
}