react-translate-maker
Version:
React translation module. Internationalize your great project.
72 lines (56 loc) • 2.19 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = Translate;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _react = require("react");
var _NamespaceContext = _interopRequireDefault(require("./NamespaceContext"));
var _TranslateContext = _interopRequireDefault(require("./TranslateContext"));
function prepareItems(items) {
if (!items || !items.length) {
return '';
}
var stringsCount = 0;
var values = items.map(function (item, index) {
var value = Array.isArray(item) ? prepareItems(item) : item;
if ((0, _react.isValidElement)(value)) {
return (0, _react.cloneElement)(value, {
key: index
});
}
var type = typeof value;
if (type === 'string') {
stringsCount += 1;
return value;
} else if (type === 'number') {
stringsCount += 1;
return String(value);
}
return value;
});
return stringsCount === values.length ? values.join('') : values;
}
function Translate(props) {
var path = props.path,
description = props.description,
defaultValue = props.defaultValue,
params = props.params,
children = props.children,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, ["path", "description", "defaultValue", "params", "children"]);
var namespace = (0, _react.useContext)(_NamespaceContext.default);
var _useContext = (0, _react.useContext)(_TranslateContext.default),
translate = _useContext.translate;
var finallPath = namespace ? namespace + "." + path : path;
var updatedDefaultValue = !defaultValue && typeof children === 'string' ? children : defaultValue;
var updatedParams = params || rest;
var items = translate.get(finallPath, updatedParams, updatedDefaultValue, true);
var result = prepareItems(items);
return typeof children === 'function' ? children(result) : result;
}
Translate.defaultProps = {
defaultValue: undefined,
description: undefined,
params: undefined,
children: undefined
};
//# sourceMappingURL=Translate.js.map