react-lsm
Version:
A lightweight react hook for managing localization languages. LSM stands for Localization Storage Manager.
229 lines (211 loc) • 11.2 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _LsmContext = require("./LsmContext");
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
// Create the hook
var useLsmTranslation = function useLsmTranslation() {
// Get the context
var _useLsmContext = (0, _LsmContext.useLsmContext)(),
language = _useLsmContext.language,
translations = _useLsmContext.translations,
setLanguage = _useLsmContext.setLanguage,
availableLanguages = _useLsmContext.availableLanguages,
initOptions = _useLsmContext.initOptions;
/**
* @function
* @description Create the hook's main function to translate the key and apply the options to format the value
* @param key The key to translate
* @param {LsmTranslationOptions} options The options to format the value with
* @throws Will throw an error if language is not set, translations are not set, or if the locale for the language is not set.
* @returns The translated value or the key if no translation is found.
*/
var translate = function translate(key, options) {
var _options$overrideLang, _Object$values;
// Check if the language is set
if (!language) throw new Error("language is not set!");
// Check if the translations are set
if (!translations) throw new Error("translations are not set!");
// Check if the locale for the language is set
if (!translations[language]) throw new Error("translations for language not found!");
// Get the locale data using the language as a key
var localeData = translations[(_options$overrideLang = options === null || options === void 0 ? void 0 : options.overrideLanguage) !== null && _options$overrideLang !== void 0 ? _options$overrideLang : language] || ((_Object$values = Object.values(translations)) === null || _Object$values === void 0 ? void 0 : _Object$values[0]) || {};
// Get the translated value
var translatedValue = getKey(key, localeData);
// Format the value using the options
var value = (options ? formatValue(translatedValue, options) : translatedValue) || "_".concat(key, "_");
if (initOptions !== null && initOptions !== void 0 && initOptions.isDevMode && value === "_".concat(key, "_")) {
console.warn("Missing translation for key: ".concat(key));
}
if (initOptions !== null && initOptions !== void 0 && initOptions.disableDefaultFallback) {
return value = value.replace(/[_*]/g, "");
}
return value;
};
/**
* @function
* @description Format the value using the options
* @param value The value to format
* @param options The options to format the value with
* @returns The formatted value
* @throws Will throw an error if the value is not a string.
*
* The following options are available:
* - textCase: Capitalize, uppercase, or lowercase the value
* - replace: Replace the value with the specified values
* - mutate: Mutate the value based on the specified options
*/
var formatValue = function formatValue(value) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if ((options.capitalize || options.uppercase || options.lowercase) && options.textCase) {
throw new Error("The textCase option cannot be used with the capitalize, uppercase, or lowercase options!");
}
/**
* @deprecated This should not be used because it interferes with the textCase option
* The capitalize option will capitalize the first letter of the value
*/
if (options.capitalize) value = value.charAt(0).toUpperCase() + value.slice(1);
/**
* @deprecated This should not be used because it interferes with the textCase option
* The uppercase option will uppercase the value
*/
if (options.uppercase) value = value.toUpperCase();
/**
* @deprecated This should not be used because it interferes with the textCase option
* The lowercase option will lowercase the value
*/
if (options.lowercase) value = value.toLowerCase();
/**
* @function
* @description The following options are available:
* The textCase option will capitalize, uppercase, or lowercase the value
*/
if (options.textCase) {
var _textCases$options$te;
var textCases = {
capitalize: function capitalize() {
return value.charAt(0).toUpperCase() + value.slice(1);
},
uppercase: function uppercase() {
return value.toUpperCase();
},
lowercase: function lowercase() {
return value.toLowerCase();
}
};
value = (_textCases$options$te = textCases[options.textCase]()) !== null && _textCases$options$te !== void 0 ? _textCases$options$te : value;
}
/*
* The prefixContent option will add the specified value to the beginning of the value
*/
if (options.prefixContent) {
var _options$prefixConten = options.prefixContent,
when = _options$prefixConten.when,
prefixContent = _options$prefixConten.value,
withTranslation = _options$prefixConten.withTranslation;
if (when) {
var _prefixContent;
prefixContent = withTranslation ? translate((_prefixContent = prefixContent) !== null && _prefixContent !== void 0 ? _prefixContent : "") : prefixContent;
value = !!Boolean(prefixContent) ? "".concat(prefixContent).concat(value) : value;
} else {
value = value;
}
}
/*
* The suffixContent option will add the specified value to the end of the value
*/
if (options.suffixContent) {
var _options$suffixConten = options.suffixContent,
_when = _options$suffixConten.when,
suffixContent = _options$suffixConten.value,
_withTranslation = _options$suffixConten.withTranslation;
if (_when) {
var _suffixContent;
suffixContent = _withTranslation ? translate((_suffixContent = suffixContent) !== null && _suffixContent !== void 0 ? _suffixContent : "") : suffixContent;
value = !!Boolean(suffixContent) ? "".concat(value).concat(suffixContent) : value;
} else {
value = value;
}
}
/*
* The replace option is an object with the following properties:
* - values: An object with the keys as the placeholder and the values as the replacement
* - withTranslation: Whether to translate the replacement value
*/
if (options !== null && options !== void 0 && options.replace) {
var _options$replace;
var replacedValue = value;
Object.entries(options === null || options === void 0 || (_options$replace = options.replace) === null || _options$replace === void 0 ? void 0 : _options$replace.values).forEach(function (_ref) {
var _options$replace2, _replacedValue;
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
var mustTranslate = (options === null || options === void 0 || (_options$replace2 = options.replace) === null || _options$replace2 === void 0 ? void 0 : _options$replace2.withTranslation) || false;
var finalValue = mustTranslate ? translate(value === null || value === void 0 ? void 0 : value.toString()) : value === null || value === void 0 ? void 0 : value.toString();
replacedValue = (_replacedValue = replacedValue) === null || _replacedValue === void 0 ? void 0 : _replacedValue.replace(new RegExp("{".concat(key, "}"), "g"), finalValue);
});
value = replacedValue;
}
/*
* The mutate option is an object with the following properties:
* - when: Whether to mutate the value
* - value: The value to mutate
* - withTranslation: Whether to translate the value
* - suffixContent: The end content to add to the value
*/
if (options !== null && options !== void 0 && options.mutate) {
var _options$mutate = options === null || options === void 0 ? void 0 : options.mutate,
_when2 = _options$mutate.when,
newValue = _options$mutate.value,
_withTranslation2 = _options$mutate.withTranslation;
if (_when2) {
if (newValue) {
value = _withTranslation2 ? translate(newValue) : newValue;
} else {
value = _withTranslation2 ? translate(value) : value;
}
}
}
if (options !== null && options !== void 0 && options.rejectDefaultFallback) {
var _value;
value = (_value = value) === null || _value === void 0 ? void 0 : _value.replace(/[_*]/g, "");
}
return value;
};
return {
translate: translate,
language: language,
setLanguage: setLanguage,
availableLanguages: availableLanguages
};
};
/**
* @function
* @description Determine the key to use for the translation
* @param key The key to use for the translation
* @param localeData The json object containing the translations
* @returns The key to use for the translation, or the key if no translation is found
*/
function getKey(key, localeData) {
var _key$split;
// Check if the key is empty
if (!key) {
return "";
}
// Check if the key contains a dot, indicating a nested key
if (!key.includes(".")) {
return localeData[key] || "_".concat(key, "_");
}
// In case of nested keys, split the key into an array and reduce it using the localeData object
return (key === null || key === void 0 || (_key$split = key.split(".")) === null || _key$split === void 0 || (_key$split = _key$split.reduce(function (acc, cur) {
return acc === null || acc === void 0 ? void 0 : acc[cur];
}, localeData)) === null || _key$split === void 0 ? void 0 : _key$split.toString()) || "_".concat(key, "_");
}
var _default = exports["default"] = useLsmTranslation;