forked from live-codes/livecodes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n-export.js
More file actions
405 lines (350 loc) · 11.8 KB
/
Copy pathi18n-export.js
File metadata and controls
405 lines (350 loc) · 11.8 KB
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
const fs = require('fs');
const path = require('path');
const jsdom = require('jsdom');
const prettier = require('prettier');
const babel = require('@babel/core');
const parser = require('@babel/parser');
const pkg = require('../package.json');
const tmpOutDir = path.resolve('src/livecodes/i18n/locales/tmp');
const enOutDir = path.resolve('src/livecodes/i18n/locales/en');
const srcBaseDir = path.resolve('src/livecodes');
const prettierConfig = pkg.prettier;
const autoGeneratedWarning =
'// ATTENTION: This file is auto-generated from source code. Do not edit manually!';
/**
* Saved translations.
*/
const trans = {
translation: {},
'language-info': {},
};
/**
* Structured JSON for Lokalise.
*/
const structuredJSON = {
translation: {},
'language-info': {},
};
/**
* `JSON.stringify` with keys sorted.
* @param {Record<string, unknown>} obj
* @param {number} space
*/
const sortedJSONify = (obj, space = 2) =>
JSON.stringify(
obj,
(key, value) =>
value instanceof Object && !(value instanceof Array)
? Object.keys(value)
.sort()
.reduce((sorted, key) => {
sorted[key] = value[key];
return sorted;
}, {})
: value,
space,
);
/**
* Write translation to .ts and .lokalise.json files.
* @param {'translation' | 'languageInfo'} namespace
* @param {boolean} tmpMode
*/
const writeTranslation = async (namespace, tmpMode) => {
const name = namespace === 'translation' ? 'translation' : 'languageInfo';
const type = namespace === 'translation' ? 'I18nTranslation' : 'I18nLangInfoTranslation';
const code = `${autoGeneratedWarning}
import type { I18nTranslationTemplate } from '../models';
// This is used as a template for other translations.
// Other translations should be typed like this:
// const ${name}: ${type} = { /* translation here */ };
// Since we allow nested objects, it is important to distinguish I18nTranslationTemplate from I18nAttributes.
// In view of this, properties declared in I18nAttributes (and those attributes might be used in future) shall not be used as a nested key.
const ${name} = ${sortedJSONify(trans[namespace])} as const satisfies I18nTranslationTemplate;
export default ${name};
`;
const translationContent = await prettier.format(code, {
parser: 'typescript',
...prettierConfig,
});
// Add a comment to the structured JSON for Lokalise
structuredJSON[namespace]['$comment'] = autoGeneratedWarning.substring(3);
const outDir = tmpMode ? tmpOutDir : enOutDir;
if (!fs.existsSync(outDir)) {
fs.mkdirSync(outDir, { recursive: true });
}
await Promise.all([
fs.promises.writeFile(path.join(outDir, namespace + '.ts'), translationContent),
// Save structured JSON for lokalise
fs.promises.writeFile(
path.join(outDir, namespace + '.lokalise.json'),
await prettier.format(
sortedJSONify(structuredJSON[namespace]).replace(/<(\/?)(\d+)>/g, '<$1tag-$2>'),
{
parser: 'json',
...prettierConfig,
},
),
),
]);
console.log(`Generated namespace ${namespace} in ${outDir}.`);
};
/**
* Add a translation entry to `trans` and `structuredJSON`.
* @param {string} nsKey Key with namespace.
* @param {string} value
* @param {string} desc Description for Lokalise.
* @param {string[]} props Props that needs to be translated.
*/
const addTranslation = (nsKey, value, desc, props) => {
nsKey = nsKey.split(':');
const key = nsKey.pop();
const namespace = nsKey.length === 1 ? nsKey.pop() : 'translation';
const parts = key.split('.');
let current = trans[namespace];
parts.forEach((part, index) => {
if (!current[part]) {
current[part] = index === parts.length - 1 ? value : {};
} else if (index === parts.length - 1 && current[part] !== value) {
console.error(`Duplicate key: ${key}`);
}
current = current[part];
});
if (!props || props.length === 1) {
structuredJSON[namespace][key] = {
translation: value,
notes: desc,
};
} else {
props.forEach((prop) => {
structuredJSON[namespace][key + `#${prop}`] = {
translation: value[prop],
notes: desc[prop],
};
});
}
};
/**
* Abstractify HTML string. Convert all tags to a format like `<0>`, `<1>`, etc.
*
* Should be kept same as the one in `src/livecodes/i18n/utils.ts`.
*
* @param {string} html The HTML string to abstractify.
* @returns The abstractified HTML string, with a list of objects of their tag names and attributes.
*/
const abstractifyHTML = (html) => {
const doc = new jsdom.JSDOM(html).window.document;
const elements = [];
let counter = 0;
const replaceElement = (node) => {
if (node.nodeType !== doc.ELEMENT_NODE) return;
node.childNodes.forEach((child) => {
replaceElement(child);
});
const name = node.tagName.toLowerCase();
if (name === 'body') return;
const attributes =
node.attributes.length === 0
? undefined
: Array.from(node.attributes).reduce((acc, attr) => {
acc[attr.name] = attr.value;
return acc;
}, {});
elements.push({ name, attributes });
const newElement = doc.createElement(`tag-${counter}`);
while (node.firstChild) {
newElement.appendChild(node.firstChild);
}
// node.parentNode is always defined because we're traversing from the body
node.parentNode.replaceChild(newElement, node);
counter++;
};
replaceElement(doc.body);
// Make tag numbering consistent with Lokalise
// Tag generated by `replaceElement` is in deep-first order, while Lokalise is left-to-right order
let newCounter = 1;
const closing = [];
let htmlString = doc.body.innerHTML.replace(/tag-/g, '');
const newElements = [];
htmlString = htmlString.replace(/<(\d+)>/g, (_, p1) => {
newElements.push(elements[p1]);
// Replace corresponding closing tag to a special tag, in order to avoid replaced tag being replaced again
closing.push({ from: new RegExp(`</${p1}>`, 'g'), to: `<*/${newCounter}>` });
return `<${newCounter++}>`;
});
closing.forEach(({ from, to }) => {
htmlString = htmlString.replace(from, to);
});
htmlString = htmlString.replace(/<\*\//g, '</');
return {
html: htmlString,
elements: newElements,
};
};
/**
* Generate note for Lokalise from elements.
* @param {Record<string, unknown>[]} elements List of elements.
* @returns {string} Note for Lokalise.
*/
const generateElementsNote = (elements) =>
elements
.map(
(el, index) =>
`### <${index + 1}> ###\n<${el.name} ${
el.attributes
? Object.keys(el.attributes)
.map((attr) => `${attr}="${el.attributes[attr]}"`)
.join(' ')
: ''
} />\n\n`,
)
.join('');
const processHTML = async (files) => {
const getValueAndContext = (element, prop) => {
if (prop === 'innerHTML') {
const { html, elements } = abstractifyHTML(element.innerHTML);
return {
value: html.trim(),
desc: generateElementsNote(elements),
};
}
const value = prop.startsWith('data-')
? element.dataset[prop.slice(5)]
: element[prop] || element.getAttribute(prop);
return {
value: value.trim(),
desc: '',
};
};
// Hardcoded translations for main page
addTranslation('translation:splash.loading', 'Loading LiveCodes…', '', ['textContent']);
await Promise.all(
files.map(async (file) => {
try {
const data = (await fs.promises.readFile(file, 'utf8')).replace(/\s+/g, ' ').trim();
const html = new jsdom.JSDOM(data).window.document;
html.querySelectorAll('[data-i18n]').forEach((element) => {
const key = element.getAttribute('data-i18n');
const props = (element.getAttribute('data-i18n-prop') ?? 'textContent').split(' ');
const { value, desc } =
props.length === 1
? getValueAndContext(element, props[0])
: props.reduce(
(acc, prop) => {
const vd = getValueAndContext(element, prop);
acc.value[prop] = vd.value;
acc.desc[prop] = vd.desc;
return acc;
},
{ value: {}, desc: {} },
);
addTranslation(key, value, desc, props);
});
} catch (err) {
console.error(err);
}
}),
);
};
const processTS = async (files) => {
await Promise.all(
files.map(async (file) => {
try {
const data = await fs.promises.readFile(file, 'utf8');
const ast = parser.parse(data, {
sourceType: 'module',
plugins: ['typescript'],
});
// Find all following two calls
babel.traverse(ast, {
CallExpression(path) {
if (
path.node.callee.type === 'MemberExpression' &&
path.node.callee.property.type === 'Identifier' &&
path.node.callee.property.name === 'translateString' &&
path.node.arguments.length >= 2 &&
path.node.arguments[0].type === 'StringLiteral' &&
path.node.arguments[1].type === 'StringLiteral'
) {
if (
!path.node.arguments[2] ||
path.node.arguments[2].properties.every(
(prop) =>
!prop.key ||
!prop.value ||
prop.key.name !== 'isHTML' ||
(prop.key.name === 'isHTML' && prop.value.value !== true),
)
) {
addTranslation(
path.node.arguments[0].value,
path.node.arguments[1].value,
'',
undefined,
);
} else {
const { html, elements } = abstractifyHTML(path.node.arguments[1].value);
addTranslation(
path.node.arguments[0].value,
html.trim(),
generateElementsNote(elements),
undefined,
);
}
}
},
});
} catch (err) {
console.error(err);
}
}),
);
};
const walkSync = function (dir, fileList = []) {
const files = fs.readdirSync(dir);
files.forEach(function (file) {
const filePath = dir + path.sep + file;
if (fs.statSync(filePath).isDirectory()) {
fileList = walkSync(filePath, fileList);
} else {
fileList.push(filePath);
}
});
return fileList;
};
/**
* Generate .ts and .lokalise.json files from .html and .ts files.
*
* If no files are provided, it will process all relevant files in the base directory.
*/
const generateTranslation = async () => {
const files = process.argv.slice(2).filter((file) => !file.startsWith('-'));
const tmpMode = process.argv.includes('--save-temp');
const HTMLFiles = [];
const TSFiles = [];
if (!files.length) {
files.push(...walkSync(srcBaseDir));
// we can use this instead when we upgrade to node v20.1+
// files.push(...fs.readdirSync(srcBaseDir, { recursive: true }));
}
HTMLFiles.push(
...files
.filter(
(file) =>
file.endsWith('.html') && file.startsWith(path.resolve(srcBaseDir, `html${path.sep}`)),
)
.map((file) => path.resolve(srcBaseDir, file)),
);
TSFiles.push(
...files.filter((file) => file.endsWith('.ts')).map((file) => path.resolve(srcBaseDir, file)),
);
await processHTML(HTMLFiles);
await processTS(TSFiles);
writeTranslation('translation', tmpMode);
if (Object.keys(trans['language-info']).length > 0) {
writeTranslation('language-info', tmpMode);
}
};
module.exports = { generateTranslation, sortedJSONify, prettierConfig, autoGeneratedWarning };
if (require.main === module) {
generateTranslation();
}