-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathi18n.js
170 lines (157 loc) · 4.78 KB
/
i18n.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// System.js plugin
function normalizeLocaleId(localeId) {
return localeId && localeId.replace(/-/g, '_').toLowerCase();
}
// Helper for getting a prioritized, normalized list of relevant locale ids from a specific locale id.
// For instance, 'en_US' produces ['en_us', 'en']
function expandLocaleIdToPrioritizedList(localeId) {
if (!localeId) {
return [];
}
localeId = normalizeLocaleId(localeId);
const localeIds = [localeId];
while (/_[^_]+$/.test(localeId)) {
localeId = localeId.replace(/_[^_]+$/, '');
localeIds.push(localeId);
}
return localeIds;
}
function createTr(localeData) {
function tokenizePattern(pattern) {
if (typeof pattern !== 'string') {
let valueString = pattern;
try {
valueString = JSON.stringify(pattern);
} catch (e) {}
throw new Error(
'i18nTools.tokenizePattern: Value must be a string: ' + valueString,
);
}
const tokens = [];
const fragments = pattern.split(/(\{\d+\})/);
for (let i = 0; i < fragments.length; i += 1) {
const fragment = fragments[i];
if (fragment.length > 0) {
const matchPlaceHolder = fragment.match(/^\{(\d+)\}$/);
if (matchPlaceHolder) {
tokens.push({
type: 'placeHolder',
value: parseInt(matchPlaceHolder[1], 10),
});
} else {
tokens.push({
type: 'text',
value: fragment,
});
}
}
}
return tokens;
}
const TR = function (key, defaultValue) {
return localeData[key] || defaultValue || '[!' + key + '!]';
};
const tr = TR; // Avoid triggering "i18nTools.eachTrInAst: Invalid TR key name syntax: TR(key, defaultPattern)"
TR.PAT = function (key, defaultPattern) {
const pattern = tr(key, defaultPattern);
const tokens = tokenizePattern(pattern);
return function () {
// placeHolderValue, ...
const placeHolderValues = arguments;
let renderedString = '';
for (let i = 0; i < tokens.length; i += 1) {
const token = tokens[i];
if (token.type === 'placeHolder') {
renderedString += placeHolderValues[token.value];
} else {
// token.type === 'text'
renderedString += token.value;
}
}
return renderedString;
};
};
TR.HTML = function (htmlString) {
const div = document.createElement('div');
div.innerHTML = htmlString;
require('i18n/lib/eachI18nTagInHtmlDocument')(
div,
require('i18n/lib/createI18nTagReplacer')({
allKeysForLocale: localeData,
keepI18nAttributes: true,
keepSpans: true,
}),
function nestedTemplateHandler(node) {
if (node.firstChild && node.firstChild.nodeType === node.TEXT_NODE) {
// Use window.TRHTML instead of TRHTML to prevent the recursive call from being recognized as a relation:
node.firstChild.nodeValue = window.TR.HTML(node.firstChild.nodeValue);
}
},
);
return div.innerHTML;
};
return TR;
}
function gatherKeysForLocale(source, locale) {
const prioritizedLocale = expandLocaleIdToPrioritizedList(locale);
return Object.keys(source).reduce(function (data, key) {
for (let i = 0; i < prioritizedLocale.length; i += 1) {
const value = source[key][prioritizedLocale[i]];
if (typeof value !== 'undefined') {
data[key] = value;
break;
}
}
return data;
}, {});
}
module.exports = {
// fetch: sideeffect: load relevant parts of i18n file filtered by locale
fetch: function (load, fetch) {
load.metadata.newAddress = load.address.replace(
/\.([^.]+)\.i18n/,
function (str, matchedLocale) {
load.metadata.locale = matchedLocale;
return '.i18n';
},
);
return fetch({ address: load.metadata.newAddress, metadata: {} });
},
translate: function (load) {
if (this.builder) {
load.metadata.format = 'cjs';
load.metadata.originalSource = load.source;
return (
'module.exports = (' +
createTr.toString() +
')(' +
JSON.stringify(
gatherKeysForLocale(JSON.parse(load.source), load.metadata.locale),
) +
');'
);
}
},
instantiate: function (load) {
if (!this.builder) {
return createTr(
gatherKeysForLocale(JSON.parse(load.source), load.metadata.locale),
);
}
},
listAssets: function (loads) {
const isSeenByNewAddress = {};
const i18nAssets = [];
loads.forEach(function (load) {
if (!isSeenByNewAddress[load.metadata.newAddress]) {
isSeenByNewAddress[load.metadata.newAddress] = true;
i18nAssets.push({
url: load.metadata.newAddress,
source: load.metadata.originalSource,
type: 'i18n',
});
}
});
return i18nAssets;
},
};