Files
vanillajs-seed/node_modules/i18next-browser-languagedetector/dist/esm/i18nextBrowserLanguageDetector.js
2020-06-08 08:50:28 +02:00

360 lines
10 KiB
JavaScript

import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
import _createClass from '@babel/runtime/helpers/esm/createClass';
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
var cookie = {
create: function create(name, value, minutes, domain) {
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/'
};
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toUTCString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
cookieOptions = Object.keys(cookieOptions).reduce(function (acc, key) {
return acc + ';' + key.replace(/([A-Z])/g, function ($1) {
return '-' + $1.toLowerCase();
}) + '=' + cookieOptions[key];
}, '');
document.cookie = name + '=' + encodeURIComponent(value) + expires + ';' + domain + cookieOptions;
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};
var path = {
name: 'path',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
} else {
found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
}
}
}
return found;
}
};
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true,
checkForSimilarInWhitelist: false
};
}
var Browser =
/*#__PURE__*/
function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults()); // if checking for similar, user needs to check whitelist
if (this.options.checkForSimilarInWhitelist) this.options.checkWhitelist = true; // backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(navigator$1);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
}, {
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
if (!found && _this.options.checkForSimilarInWhitelist) {
found = _this.getSimilarInWhitelist(cleanedLng);
}
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks["default"] && fallbacks["default"][0];
}
}
return found;
}
}, {
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}, {
key: "getSimilarInWhitelist",
value: function getSimilarInWhitelist(cleanedLng) {
var _this3 = this;
if (!this.i18nOptions.whitelist) return;
if (cleanedLng.includes('-')) {
// i.e. es-MX should check if es is in whitelist
var prefix = cleanedLng.split('-')[0];
var cleanedPrefix = this.services.languageUtils.formatLanguageCode(prefix);
if (this.services.languageUtils.isWhitelisted(cleanedPrefix)) return cleanedPrefix; // if reached here, nothing found. continue to search for similar using only prefix
cleanedLng = cleanedPrefix;
} // i.e. 'pt' should return 'pt-BR'. If multiple in whitelist with 'pt-', then use first one in whitelist
var similar = this.i18nOptions.whitelist.find(function (whitelistLng) {
var cleanedWhitelistLng = _this3.services.languageUtils.formatLanguageCode(whitelistLng);
if (cleanedWhitelistLng.startsWith(cleanedLng)) return cleanedWhitelistLng;
});
if (similar) return similar;
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
export default Browser;