UNPKG

2.02 kBJavaScriptView Raw
1/**
2 * generate i18n data
3 * {
4 * title: '按钮[en-US]button',
5 * description: '[zh-CN]一个简单的按钮[en-US] a sample buttom'
6 * }
7 * =====>
8 * {
9 * zh-CN: {
10 * title: '按钮',
11 * description: '一个简单的按钮',
12 * },
13 * en-US: {
14 * title: 'button',
15 * description: 'a sample buttom',
16 * }
17 * }
18 *
19 * @param {Object} sourceData
20 * @returns
21 */
22function generateI18nData(sourceData) {
23 const locales = {};
24
25 Object.keys(sourceData).forEach((key) => {
26 locales[key] = parseI18NString(sourceData[key]);
27 });
28
29 return mergeI18N(locales);
30}
31
32/**
33 * parse i18n string;
34 *
35 * i18n string:
36 * [zh-CN]这是个描述 [en-US]this is a description
37 * 这是个描述 [en-US] this is a description
38 * 这是个描述
39 * this is a description
40 * this is a description [zh-CN] 这是个描述
41 * this is a description [zh-CN] 这是个描述
42 *
43 * @param {string} i18nStr
44 * @returns
45 */
46function parseI18NString(i18nStr) {
47 // i18n pattern
48 const flagReg = /(.*)(\[([a-z]+-[A-Z]+)\])(.*)/;
49 const cnReg = /[\u4e00-\u9fa5]+/g;
50 const local = {};
51
52 parseString(i18nStr);
53
54 return local;
55
56 // recursive parser
57 function parseString(str = '') {
58 const match = flagReg.exec(str);
59
60 if (!match) {
61 if (cnReg.test(str)) {
62 local['zh-CN'] = str.trim();
63 } else {
64 local['en-US'] = str.trim();
65 }
66 return;
67 }
68
69 const [, $1, , $3, $4] = match;
70 local[$3] = $4.trim();
71
72 if ($1) {
73 parseString($1);
74 }
75 }
76}
77
78/**
79 * merge multi i18n data
80 *
81 * @param {object} sourceData
82 * @returns
83 */
84function mergeI18N(sourceData) {
85 const locales = {
86 'zh-CN': {},
87 'en-US': {},
88 };
89
90 Object.keys(sourceData).forEach((key) => {
91 const i18nObj = sourceData[key];
92 Object.keys(i18nObj).forEach((lang) => {
93 if (locales[lang]) {
94 locales[lang][key] = i18nObj[lang];
95 } else {
96 locales[lang] = {
97 [key]: i18nObj[lang],
98 };
99 }
100 });
101 });
102
103 return locales;
104}
105
106module.exports = generateI18nData;