@prezly/theme-kit-core
Version:
Data layer and utility library for developing Prezly themes with JavaScript
58 lines (56 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getShortestLocaleSlug = getShortestLocaleSlug;
var _themeKitIntl = require("@prezly/theme-kit-intl");
var _isNumberCode = require("./isNumberCode.cjs");
/**
* Get the shortest locale code possible from full locale code
* First: try shorting to neutral language code (there should be no locales with the same language code)
* Then: try shorting to region code (there should be no locales with the same region code)
* Finally: return the original locale code (shorting is not possible)
*/
function getShortestLocaleSlug(locale, context) {
var _ref, _getUnambiguousLangCo;
var {
code: localeCode,
lang: langCode,
region: regionCode,
slug: localeSlug
} = _themeKitIntl.Locale.from(locale);
// If it's a default locale, return false (no locale needed in URL)
if (localeCode === context.defaultLocale) {
return false;
}
var shortened = // Try shortening to neutral language code
(_ref = (_getUnambiguousLangCo = getUnambiguousLangCode(langCode, context)) !== null && _getUnambiguousLangCo !== void 0 ? _getUnambiguousLangCo :
// Try shortening to region code
getUnambiguousRegionCode(regionCode, context)) !== null && _ref !== void 0 ? _ref :
// Return the original (exact) code if shortening is not possible
localeSlug;
return shortened.toLowerCase();
}
function getUnambiguousLangCode(langCode, context) {
var candidates = context.locales.filter(code => _themeKitIntl.Locale.isLanguageCode(code, langCode));
if (candidates.length === 1) {
return langCode;
}
return undefined;
}
function getUnambiguousRegionCode(regionCode, context) {
if (!regionCode) {
return undefined;
}
if ((0, _isNumberCode.isNumberCode)(regionCode)) {
// We don't want just numbers in our region code
return undefined;
}
var candidates = context.locales.filter(locale => _themeKitIntl.Locale.isRegionCode(locale, regionCode));
// Prevent collision with neutral language codes
var collisions = context.locales.filter(locale => _themeKitIntl.Locale.isLanguageCode(locale, regionCode.toLowerCase()));
if (candidates.length === 1 && collisions.length === 0) {
return regionCode;
}
return undefined;
}