react-translate-maker
Version:
React translation module. Internationalize your great project.
75 lines (61 loc) • 2.12 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Translate;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = require("react");
var _NamespaceContext = _interopRequireDefault(require("./NamespaceContext"));
var _TranslateContext = _interopRequireDefault(require("./TranslateContext"));
function prepareItems(items) {
if (!items || !items.length) {
return '';
}
let stringsCount = 0;
const values = items.map((item, index) => {
const value = Array.isArray(item) ? prepareItems(item) : item;
if ((0, _react.isValidElement)(value)) {
return (0, _react.cloneElement)(value, {
key: index
});
}
const 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) {
const {
path,
description,
defaultValue,
params,
children
} = props,
rest = (0, _objectWithoutProperties2.default)(props, ["path", "description", "defaultValue", "params", "children"]);
const namespace = (0, _react.useContext)(_NamespaceContext.default);
const {
translate
} = (0, _react.useContext)(_TranslateContext.default);
const finallPath = namespace ? `${namespace}.${path}` : path;
const updatedDefaultValue = !defaultValue && typeof children === 'string' ? children : defaultValue;
const updatedParams = params || rest;
const items = translate.get(finallPath, updatedParams, updatedDefaultValue, true);
const result = prepareItems(items);
return typeof children === 'function' ? children(result) : result;
}
Translate.defaultProps = {
defaultValue: undefined,
description: undefined,
params: undefined,
children: undefined
};
//# sourceMappingURL=Translate.js.map