UNPKG

2.51 kBJavaScriptView Raw
1const _ = require('lodash');
2const fs = require('fs');
3const path = require('path');
4const slash = require('slash');
5
6const languages = [
7 'cs_CZ',
8 'de_DE',
9 'en_ASIA',
10 'en_AU',
11 'en_CA',
12 'en_GB',
13 'en_SG',
14 'en_US',
15 'es_ES',
16 'es_US',
17 'fi_FI',
18 'fr_CA',
19 'fr_FR',
20 'it_IT',
21 'lt_LT',
22 'nl_NL',
23 'pl_PL',
24 'pt_PT',
25];
26
27const normalizePath = p => (_.startsWith(p, '.') ? slash(p) : `./${slash(p)}`);
28
29const injectFallbackFunction = (trads, id, subdirectory, format) => {
30 let code = 'switch($translate.fallbackLanguage()) {';
31 languages.forEach((lang) => {
32 code += `case '${lang}':`;
33 trads.forEach((trad) => {
34 const dirname = path.dirname(id);
35 const fullTradPath = path.resolve(dirname, trad, subdirectory);
36 const relativePath = path.relative(dirname, fullTradPath);
37 if (fs.existsSync(path.join(fullTradPath, `Messages_${lang}.${format}`))) {
38 const toImport = normalizePath(path.join(relativePath, `Messages_${lang}.${format}`));
39 code += `promises.push(import('${toImport}').then(module => module.default));`;
40 }
41 });
42 code += 'break;';
43 });
44 code += '}';
45 return code;
46};
47
48const injectTranslationSwitch = (trads, id, subdirectory, format) => {
49 let code = 'switch($translate.use()) {';
50 languages.forEach((lang) => {
51 let importFound = 0;
52 code += `case '${lang}':`;
53 trads.forEach((trad) => {
54 const dirname = path.dirname(id);
55 const fullTradPath = path.resolve(dirname, trad, subdirectory);
56 const relativePath = path.relative(dirname, fullTradPath);
57 if (fs.existsSync(path.join(fullTradPath, `Messages_${lang}.${format}`))) {
58 const toImport = normalizePath(path.join(relativePath, `Messages_${lang}.${format}`));
59 code += `promises.push(import('${toImport}').then(module => module.default));`;
60 importFound += 1;
61 }
62 });
63 if (!importFound) {
64 code += 'useFallback();';
65 }
66 code += 'break;';
67 });
68 code += 'default: useFallback(); break; }';
69 return code;
70};
71
72const injectTranslationImports = (trads, id, subdirectory, format = 'xml') => `
73 let promises = [];
74 const useFallback = () => {
75 ${injectFallbackFunction(trads, id, subdirectory, format)}
76 };
77 ${injectTranslationSwitch(trads, id, subdirectory, format)}
78 promises.forEach(p => asyncLoader.addTranslations(p));
79 return $q.all(promises).then(() => $translate.refresh());
80`;
81
82module.exports = {
83 normalizePath,
84 injectTranslationImports,
85 languages: _.concat(languages),
86};