UNPKG

@applicaster/zapp-react-native-utils

Version:

Applicaster Zapp React Native utilities package

114 lines (99 loc) 2.85 kB
import { appStore } from "@applicaster/zapp-react-native-redux/AppStore"; import * as R from "ramda"; import { NativeModules } from "react-native"; import { isWeb } from "@applicaster/zapp-react-native-utils/reactUtils"; const { QuickBrickCommunicationModule: { languageLocale, countryLocale, uiLanguage = null, }, } = NativeModules; /** * helper function which returns the first entry in an object * @param {Object} * @returns {Any} */ const getFirstObjectValue = R.compose(R.head, R.values); /** * gets the app's locale. * @return {string} example: en-gb */ export function getLocale() { return R.toLower(`${languageLocale}-${countryLocale}`); } /** * TODO: refactor to get language in unified way thru all platforms * Gets country code from the locale string and returns it's lowercase value * @returns {string} example: en */ export function getLanguageCode() { if (isWeb?.()) { return R.pathOr( null, ["QuickBrickCommunicationModule", "languageCode"], NativeModules ); } const { languageCode } = appStore.get("appData"); return languageCode || null; } /** * * Gets country code from the locale string and returns it's lowercase value * @returns {string} example: gb */ export function getCountryCode() { const { countryLocale } = appStore.get("appData"); return R.toLower(countryLocale); } export function getUILanguage() { if (uiLanguage) { return uiLanguage; } // TODO: Legacy way, remove after SDK upgrade return getLanguageCode(); } /** * fallback to en for missing dayjslocalization * converts the locale code to a dayjs compatible locale code * lowercase input code is expected, e.g. "en-GB" => "en-gb" * @param {string} code - locale code, e.g. "en", "fr", "es-LA" * */ export const toDayJSLocaleMap = (code) => { const map = { hy: "hy-am", fj: null, la: null, no: null, pa: "pa-in", qu: null, sm: null, to: null, xh: null, tt: null, "es-LA": "es", "en-UK": "en-gb", }; if (map[code] === null) { return "en"; } else if (map[code]) { return map[code]; } else { return code.toLowerCase(); } }; /** * returns the localization for the app based on the locale. If the locale is null * or undefined, or if the given locale doesn't exist in the localizations, * it will return the first locale available in the localizations dictionary * @param {Object} options * @param {Object} options.localizations dictionary of localized strings * indexed by their respective locale * @returns {Object} dictionary of localized strings for the given locale */ export function getLocalizations({ localizations }) { const languageCode = getUILanguage(); const localizedStrings = localizations?.[languageCode]; return localizedStrings || getFirstObjectValue(localizations); }