2018-09-04 22:30:11 +02:00
|
|
|
const { FluentBundle } = require('fluent');
|
2017-12-19 19:06:45 +01:00
|
|
|
const fs = require('fs');
|
2017-08-24 23:54:02 +02:00
|
|
|
|
|
|
|
function toJSON(map) {
|
|
|
|
return JSON.stringify(Array.from(map));
|
|
|
|
}
|
|
|
|
|
2017-12-19 19:06:45 +01:00
|
|
|
function merge(m1, m2) {
|
|
|
|
const result = new Map(m1);
|
|
|
|
for (const [k, v] of m2) {
|
|
|
|
result.set(k, v);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2017-08-24 23:54:02 +02:00
|
|
|
module.exports = function(source) {
|
2018-07-12 22:13:49 +02:00
|
|
|
const localeExp = /([^/]+)\/[^/]+\.ftl$/;
|
2017-08-24 23:54:02 +02:00
|
|
|
const result = localeExp.exec(this.resourcePath);
|
|
|
|
const locale = result && result[1];
|
|
|
|
if (!locale) {
|
|
|
|
throw new Error(`couldn't find locale in: ${this.resourcePath}`);
|
|
|
|
}
|
2017-12-19 19:06:45 +01:00
|
|
|
// load default language and "merge" contexts
|
|
|
|
// TODO: make this configurable
|
|
|
|
const en_ftl = fs.readFileSync(
|
|
|
|
require.resolve('../public/locales/en-US/send.ftl'),
|
|
|
|
'utf8'
|
|
|
|
);
|
2018-09-04 22:30:11 +02:00
|
|
|
const en = new FluentBundle('en-US');
|
2017-12-19 19:06:45 +01:00
|
|
|
en.addMessages(en_ftl);
|
|
|
|
// pre-parse the ftl
|
2018-09-04 22:30:11 +02:00
|
|
|
const context = new FluentBundle(locale);
|
2017-12-19 19:06:45 +01:00
|
|
|
context.addMessages(source);
|
|
|
|
|
|
|
|
const merged = merge(en._messages, context._messages);
|
2017-08-24 23:54:02 +02:00
|
|
|
return `
|
|
|
|
module.exports = \`
|
|
|
|
if (typeof window === 'undefined') {
|
2018-08-03 19:48:00 +02:00
|
|
|
var fluent = require('fluent');
|
2017-08-24 23:54:02 +02:00
|
|
|
}
|
2018-03-02 22:40:29 +01:00
|
|
|
(function () {
|
2018-09-04 22:30:11 +02:00
|
|
|
var bundle = new fluent.FluentBundle('${locale}', {useIsolating: false});
|
|
|
|
bundle._messages = new Map(${toJSON(merged)});
|
2018-03-02 22:40:29 +01:00
|
|
|
function translate(id, data) {
|
2018-09-04 22:30:11 +02:00
|
|
|
var msg = bundle.getMessage(id);
|
2018-03-02 22:40:29 +01:00
|
|
|
if (typeof(msg) !== 'string' && !msg.val && msg.attrs) {
|
|
|
|
msg = msg.attrs.title || msg.attrs.alt
|
|
|
|
}
|
2018-09-04 22:30:11 +02:00
|
|
|
return bundle.format(msg, data);
|
2017-08-24 23:54:02 +02:00
|
|
|
}
|
2018-03-02 22:40:29 +01:00
|
|
|
if (typeof window === 'undefined') {
|
|
|
|
module.exports = translate;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
window.translate = translate;
|
|
|
|
}
|
|
|
|
})();
|
2017-08-24 23:54:02 +02:00
|
|
|
\``;
|
|
|
|
};
|