@prezly/theme-kit-core
Version:
Data layer and utility library for developing Prezly themes with JavaScript
52 lines (51 loc) • 2.04 kB
JavaScript
import { Locale } from '@prezly/theme-kit-intl';
import { isNumberCode } from "./isNumberCode.mjs";
/**
* 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)
*/
export function getShortestLocaleSlug(locale, context) {
var _ref, _getUnambiguousLangCo;
var {
code: localeCode,
lang: langCode,
region: regionCode,
slug: localeSlug
} = 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 => Locale.isLanguageCode(code, langCode));
if (candidates.length === 1) {
return langCode;
}
return undefined;
}
function getUnambiguousRegionCode(regionCode, context) {
if (!regionCode) {
return undefined;
}
if (isNumberCode(regionCode)) {
// We don't want just numbers in our region code
return undefined;
}
var candidates = context.locales.filter(locale => Locale.isRegionCode(locale, regionCode));
// Prevent collision with neutral language codes
var collisions = context.locales.filter(locale => Locale.isLanguageCode(locale, regionCode.toLowerCase()));
if (candidates.length === 1 && collisions.length === 0) {
return regionCode;
}
return undefined;
}