cncjs

Форк
0
81 строка · 1.9 Кб
1
import omit from 'lodash/omit';
2
import PropTypes from 'prop-types';
3
import React, { Component } from 'react';
4
import i18n from 'app/lib/i18n';
5

6
const REGEXP = /{{(.+?)}}/;
7

8
class I18n extends Component {
9
    static propTypes = {
10
      t: PropTypes.string,
11
      _: PropTypes.string,
12
      options: PropTypes.object,
13
      parent: PropTypes.string,
14
      replacement: PropTypes.oneOfType([
15
        PropTypes.array,
16
        PropTypes.object
17
      ])
18
    };
19

20
    static defaultProps = {
21
      t: '',
22
      _: '',
23
      parent: 'span'
24
    };
25

26
    render() {
27
      const { t, _, parent, replacement } = this.props;
28
      const i18nOptions = {
29
        ...this.props.options,
30
        ...{
31
          interpolation: {
32
            prefix: '#$?',
33
            suffix: '?$#'
34
          }
35
        }
36
      };
37
      let format = null;
38
      if (this.props.children) {
39
        format = this.props.children;
40
      } else if (t) {
41
        format = i18n.t(t, i18nOptions);
42
      } else if (_) {
43
        format = i18n._(_, i18nOptions);
44
      }
45
      if (!format || typeof format !== 'string') {
46
        return React.createElement('noscript', null);
47
      }
48

49
      let props = omit(this.props, ['t', '_', 'options', 'parent', 'replacement']);
50
      let matches = [];
51
      let children = [];
52

53
      // "AAA {{foo}} BBB {{bar}}".split(REGEXP)
54
      // ["AAA ", "foo", " BBB ", "bar", ""]
55
      format.split(REGEXP).reduce((memo, match, index) => {
56
        let child = null;
57

58
        if (index % 2 === 0) {
59
          if (match.length === 0) {
60
            return memo;
61
          }
62
          child = match;
63
        } else if (replacement) {
64
          child = replacement[match];
65
        } else {
66
          child = this.props[match];
67
          matches.push(match);
68
        }
69

70
        memo.push(child);
71

72
        return memo;
73
      }, children);
74

75
      props = omit(props, matches);
76

77
      return React.createElement.apply(this, [parent, props].concat(children));
78
    }
79
}
80

81
export default I18n;
82

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.