cncjs
81 строка · 1.9 Кб
1import omit from 'lodash/omit';2import PropTypes from 'prop-types';3import React, { Component } from 'react';4import i18n from 'app/lib/i18n';5
6const REGEXP = /{{(.+?)}}/;7
8class I18n extends Component {9static propTypes = {10t: PropTypes.string,11_: PropTypes.string,12options: PropTypes.object,13parent: PropTypes.string,14replacement: PropTypes.oneOfType([15PropTypes.array,16PropTypes.object17])18};19
20static defaultProps = {21t: '',22_: '',23parent: 'span'24};25
26render() {27const { t, _, parent, replacement } = this.props;28const i18nOptions = {29...this.props.options,30...{31interpolation: {32prefix: '#$?',33suffix: '?$#'34}35}36};37let format = null;38if (this.props.children) {39format = this.props.children;40} else if (t) {41format = i18n.t(t, i18nOptions);42} else if (_) {43format = i18n._(_, i18nOptions);44}45if (!format || typeof format !== 'string') {46return React.createElement('noscript', null);47}48
49let props = omit(this.props, ['t', '_', 'options', 'parent', 'replacement']);50let matches = [];51let children = [];52
53// "AAA {{foo}} BBB {{bar}}".split(REGEXP)54// ["AAA ", "foo", " BBB ", "bar", ""]55format.split(REGEXP).reduce((memo, match, index) => {56let child = null;57
58if (index % 2 === 0) {59if (match.length === 0) {60return memo;61}62child = match;63} else if (replacement) {64child = replacement[match];65} else {66child = this.props[match];67matches.push(match);68}69
70memo.push(child);71
72return memo;73}, children);74
75props = omit(props, matches);76
77return React.createElement.apply(this, [parent, props].concat(children));78}79}
80
81export default I18n;82