-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfluentTranslationParser.js
405 lines (348 loc) · 12.5 KB
/
fluentTranslationParser.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.fluentTranslationParser = {})));
}(this, (function (exports) { 'use strict';
/**
* This file automatically generated from `pre-publish.js`.
* Do not manually edit.
*/
var voidElements = {
"area": true,
"base": true,
"br": true,
"col": true,
"embed": true,
"hr": true,
"img": true,
"input": true,
"keygen": true,
"link": true,
"menuitem": true,
"meta": true,
"param": true,
"source": true,
"track": true,
"wbr": true
};
var attrRE = /([\w-]+)|=|(['"])([.\s\S]*?)\2/g;
var parseTag = function (tag) {
var i = 0;
var key;
var expectingValueAfterEquals = true;
var res = {
type: 'tag',
name: '',
voidElement: false,
attrs: {},
children: []
};
tag.replace(attrRE, function (match) {
if (match === '=') {
expectingValueAfterEquals = true;
i++;
return;
}
if (!expectingValueAfterEquals) {
if (key) {
res.attrs[key] = key; // boolean attribute
}
key = match;
} else {
if (i === 0) {
if (voidElements[match] || tag.charAt(tag.length - 2) === '/') {
res.voidElement = true;
}
res.name = match;
} else {
res.attrs[key] = match.replace(/^['"]|['"]$/g, '');
key = undefined;
}
}
i++;
expectingValueAfterEquals = false;
});
return res;
};
/*jshint -W030 */
var tagRE = /(?:<!--[\S\s]*?-->|<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>)/g;
// re-used obj for quick lookups of components
var empty = Object.create ? Object.create(null) : {}; // common logic for pushing a child node onto a list
function pushTextNode(list, html, level, start, ignoreWhitespace, ignoreCollapse) {
// calculate correct end of the content slice in case there's
// no tag after the text node.
var end = html.indexOf('<', start);
var content = html.slice(start, end === -1 ? undefined : end); // if a node is nothing but whitespace, collapse it as the spec states:
// https://www.w3.org/TR/html4/struct/text.html#h-9.1
if (!ignoreCollapse && /^\s*$/.test(content)) {
content = ' ';
} // don't add whitespace-only text nodes if they would be trailing text nodes
// or if they would be leading whitespace-only text nodes:
// * end > -1 indicates this is not a trailing text node
// * leading node is when level is -1 and list has length 0
if (!ignoreWhitespace && end > -1 && level + list.length >= 0 || content !== ' ') {
list.push({
type: 'text',
content: content
});
}
}
var parse = function parse(html, options) {
options || (options = {});
options.components || (options.components = empty);
var result = [];
var current;
var level = -1;
var arr = [];
var byTag = {};
var inComponent = false;
html.replace(tagRE, function (tag, index) {
if (inComponent) {
if (tag !== '</' + current.name + '>') {
return;
} else {
inComponent = false;
}
}
var isOpen = tag.charAt(1) !== '/';
var isComment = tag.indexOf('<!--') === 0;
var start = index + tag.length;
var nextChar = html.charAt(start);
var parent;
if (isOpen && !isComment) {
level++;
current = parseTag(tag);
if (current.type === 'tag' && options.components[current.name]) {
current.type = 'component';
inComponent = true;
}
if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') {
pushTextNode(current.children, html, level, start, options.ignoreWhitespace, options.ignoreCollapse);
}
byTag[current.tagName] = current; // if we're at root, push new base node
if (level === 0) {
result.push(current);
}
parent = arr[level - 1];
if (parent) {
parent.children.push(current);
}
arr[level] = current;
}
if (isComment || !isOpen || current.voidElement) {
if (!isComment) {
level--;
}
if (!inComponent && nextChar !== '<' && nextChar) {
// trailing text node
// if we're at the root, push a base text node. otherwise add as
// a child to the current node.
parent = level === -1 ? result : arr[level].children;
pushTextNode(parent, html, level, start, options.ignoreWhitespace, options.ignoreCollapse);
}
}
}); // If the "html" passed isn't actually html, add it as a text node.
if (!result.length && html.length) {
pushTextNode(result, html, 0, 0, options.ignoreWhitespace, options.ignoreCollapse);
}
return result;
};
function attrString(attrs) {
var buff = [];
for (var key in attrs) {
buff.push(key + '="' + attrs[key] + '"');
}
if (!buff.length) {
return '';
}
return ' ' + buff.join(' ');
}
function stringify(buff, doc) {
switch (doc.type) {
case 'text':
return buff + doc.content;
case 'tag':
buff += '<' + doc.name + (doc.attrs ? attrString(doc.attrs) : '') + (doc.voidElement ? '/>' : '>');
if (doc.voidElement) {
return buff;
}
return buff + doc.children.reduce(stringify, '') + '</' + doc.name + '>';
}
}
var stringify_1 = function (doc) {
return doc.reduce(function (token, rootEl) {
return token + stringify('', rootEl);
}, '');
};
var htmlParseStringify2 = {
parse: parse,
stringify: stringify_1
};
function parse$1(str) {
const ast = htmlParseStringify2.parse(`<dummyI18nTag>${str}</dummyI18nTag>`, {
ignoreCollapse: true
});
extendI18nextSugar(ast); // console.warn(JSON.stringify(ast, null, 2));
return ast[0].children || [];
}
const detect = ['\{[^\$\}\[>]+\}', // references
'\{ *\\$[^\}\[>]+\}', // variables
'\{[A-Z (]*\\$[^\}\[>]+\}', // variables formatted
'\{ *\\$[^\}\[]+->', // selector
'\\*\\[[^\[]+\\]', // default variant
'\\[[^\[]+\\]', // variant
'\{', // opening
'\}'].join('|');
const REGEXP = new RegExp(`(${detect})`, 'g');
function extendI18nextSugar(ast) {
function updateChildren(children) {
if (!children) return;
children.forEach(child => {
if (child.type === 'text') {
if (child.content.indexOf('{') > -1 || child.content.indexOf('[') > -1) {
const splitted = child.content.split(REGEXP); // console.warn('try splitt?', splitted.length)
const newChildren = splitted.length > 1 ? splitted.reduce((mem, match, index) => {
// console.warn(mem, match, index);
if (index % 2 === 0) {
mem.push({
type: 'text',
content: match
});
} else {
// opening
if (match.length === 1 && match === '{') {
mem.push({
type: 'openingBracket',
raw: match,
prefix: '{',
suffix: '',
content: ''
});
} // closing
else if (match.length === 1 && match === '}') {
mem.push({
type: 'closingBracket',
raw: match,
prefix: '',
suffix: '}',
content: ''
});
} // reference
else if (match.indexOf('{') === 0 && match.indexOf('$') < 0) {
const content = match.substring(1, match.length - 1);
mem.push({
type: 'reference',
raw: match,
prefix: '{',
suffix: '}',
content,
reference: content.trim()
});
} // variable with format
else if (match.indexOf('{') === 0 && match.indexOf('$') > -1 && match.indexOf('->') < 0 && match.indexOf('(') > -1) {
const content = match.substring(1, match.length - 1);
mem.push({
type: 'variable',
formatted: true,
raw: match,
prefix: '{',
suffix: '}',
content,
variable: content.substring(content.indexOf('$') + 1, content.indexOf(',')).trim()
});
} // variable
else if (match.indexOf('{') === 0 && match.indexOf('$') > -1 && match.indexOf('->') < 0) {
const content = match.substring(1, match.length - 1);
mem.push({
type: 'variable',
raw: match,
prefix: '{',
suffix: '}',
content,
variable: content.trim().replace('$', '')
});
} // selector
else if (match.indexOf('{') === 0 && match.indexOf('$') > -1 && match.indexOf('->') > -1) {
const content = match.substring(1, match.length - 2);
mem.push({
type: 'selector',
raw: match,
prefix: '{',
suffix: '->',
content,
variable: content.trim().replace('$', '')
});
} // variant
else if (match.indexOf('[') === 0 && match.indexOf('*') < 0) {
const content = match.substring(1, match.length - 1);
mem.push({
type: 'variant',
isDefault: false,
raw: match,
prefix: '[',
suffix: ']',
content,
variable: content.trim()
});
} // variant default
else if (match.indexOf('[') === 1 && match.indexOf('*') === 0) {
const content = match.substring(2, match.length - 1);
mem.push({
type: 'variant',
isDefault: true,
raw: match,
prefix: '*[',
suffix: ']',
content,
variable: content.trim()
});
}
}
return mem;
}, []) : []; // console.warn(JSON.stringify(newChildren, null, 2));
child.children = newChildren;
}
}
if (child.children) updateChildren(child.children);
});
}
updateChildren(ast);
return ast;
}
function stringify$1(ast) {
const wrappedAst = [{
type: 'tag',
name: 'dummyI18nTag',
voidElement: false,
attrs: undefined,
children: ast
}];
const str = htmlParseStringify2.stringify(wrappedAst);
return str.substring(14, str.length - 15);
}
function astStats(ast) {
// console.warn(JSON.stringify(ast, null, 2))
const stats = {
references: 0,
variables: 0,
selectors: 0,
tags: 0
};
function process(children) {
if (!children) return;
children.forEach(child => {
if (child.type === 'tag') stats.tags++;
if (child.type === 'variable') stats.variables++;
if (child.type === 'reference') stats.references++;
if (child.type === 'selector') stats.selectors++;
if (child.children) process(child.children);
});
}
process(ast); // console.warn(stats);
return stats;
}
exports.parse = parse$1;
exports.stringify = stringify$1;
exports.astStats = astStats;
Object.defineProperty(exports, '__esModule', { value: true });
})));