Skip to content

Node.js based forum software built for the modern web

tx() helper for translations (#14313)

Barış Uşaklıd9c1b178310f
diff --git a/public/src/ajaxify.js b/public/src/ajaxify.js
index 2907d8a2ec..a17f7c1fc0 100644
--- a/public/src/ajaxify.js
+++ b/public/src/ajaxify.js
@@ -277,20 +277,23 @@ ajaxify.widgets = { render: render };
});
}
- function updateTitle(title) {
+ async function updateTitle(title) {
if (!title) {
return;
}
- title = config.titleLayout.replace(/{/g, '{').replace(/}/g, '}')
- .replace('{pageTitle}', () => title)
- .replace('{browserTitle}', () => config.browserTitle);
-
const data = { title: title };
hooks.fire('action:ajaxify.updateTitle', data);
- translator.translate(data.title, function (translated) {
- window.document.title = $('<div></div>').html(translated).text();
- });
+
+ const [titleTranslated, browserTitleTranslated] = await translator.translateKeys([
+ data.title, config.browserTitle || '',
+ ]);
+
+ const documentTitle = config.titleLayout.replace(/&#123;/g, '{').replace(/&#125;/g, '}')
+ .replace('{pageTitle}', () => titleTranslated)
+ .replace('{browserTitle}', () => browserTitleTranslated);
+
+ window.document.title = $('<div></div>').html(documentTitle).text();
}
ajaxify.updateTitle = updateTitle;
diff --git a/public/src/app.js b/public/src/app.js
index 76094e6c5f..fb58180fe5 100644
--- a/public/src/app.js
+++ b/public/src/app.js
@@ -12,6 +12,7 @@ require('timeago');
const Benchpress = require('benchpressjs');
Benchpress.setGlobal('config', config);
+Benchpress.setGlobal('_i18n', window._i18n);
require('./sockets');
require('./overrides');
diff --git a/public/src/modules/helpers.common.js b/public/src/modules/helpers.common.js
index 058aa3019b..7ce9b29e4a 100644
--- a/public/src/modules/helpers.common.js
+++ b/public/src/modules/helpers.common.js
@@ -1,6 +1,6 @@
'use strict';
-module.exports = function (utils, Benchpress, relative_path) {
+module.exports = function (utils, Benchpress, translator, relative_path) {
Benchpress.setGlobal('true', true);
Benchpress.setGlobal('false', false);
const oneDayInMs = 24 * 60 * 60 * 1000;
@@ -36,6 +36,7 @@ module.exports = function (utils, Benchpress, relative_path) {
humanReadableNumber,
formattedNumber,
isNumber,
+ tx,
txEscape,
uploadBasename,
generatePlaceholderWave,
@@ -393,6 +394,31 @@ module.exports = function (utils, Benchpress, relative_path) {
return utils.isNumber(value);
}
+ function tx(token, ...args) {
+ if (!token) {
+ return '';
+ }
+ const [txToken, argsFromToken] = translator.normalizeToken(token);
+ if (Array.isArray(argsFromToken) && argsFromToken.length > 0) {
+ args = argsFromToken;
+ }
+ const [namespace, key] = txToken.split(':', 2);
+ if (!namespace || !key || !this._i18n || !this._i18n[namespace] || !this._i18n[namespace][key]) {
+ return token;
+ }
+ // translate the arguments if they are tokens themselves
+ args = args.map((arg) => {
+ arg = translator.escapeHTML(arg);
+ if (typeof arg === 'string' && arg.startsWith('[[') && arg.endsWith(']]')) {
+ return helpers.tx.call(this, arg, []); // no arguments on nested tokens for now
+ }
+ return arg;
+ });
+
+ const translation = this._i18n[namespace][key];
+ return translator.replaceArguments(translation, args);
+ }
+
function txEscape(text) {
return String(text)
.replace(/\[\[/g, '&lsqb;&lsqb;').replace(/\]\]/g, '&rsqb;&rsqb;')
diff --git a/public/src/modules/helpers.js b/public/src/modules/helpers.js
index f471d869b6..26eb68fd46 100644
--- a/public/src/modules/helpers.js
+++ b/public/src/modules/helpers.js
@@ -2,6 +2,6 @@
const factory = require('./helpers.common');
-define('helpers', ['utils', 'benchpressjs'], function (utils, Benchpressjs) {
- return factory(utils, Benchpressjs, config.relative_path);
+define('helpers', ['utils', 'benchpressjs', 'translator'], function (utils, Benchpressjs, translator) {
+ return factory(utils, Benchpressjs, translator, config.relative_path);
});
diff --git a/public/src/modules/translator.common.js b/public/src/modules/translator.common.js
index 81299cbce8..40cf494605 100644
--- a/public/src/modules/translator.common.js
+++ b/public/src/modules/translator.common.js
@@ -11,6 +11,19 @@ module.exports = function (utils, load, warn) {
));
}
+ function validateHrefAttributes(translated) {
+ return translated.replace(/href="([^"]*)"/gi, (match, href) => {
+ return isSafeHref(href) ? match : 'href=""';
+ });
+ }
+
+ function isSafeHref(href) {
+ const normalizedHref = String(href).trim().toLowerCase();
+ const isHttpUrl = normalizedHref.startsWith('https://') || normalizedHref.startsWith('http://');
+ const isRelativeUrl = normalizedHref.startsWith('/') && !normalizedHref.startsWith('//');
+ return isHttpUrl || isRelativeUrl;
+ }
+
const Translator = (function () {
/**
* Construct a new Translator object
@@ -273,19 +286,6 @@ module.exports = function (utils, load, warn) {
});
};
- function validateHrefAttributes(translated) {
- return translated.replace(/href="([^"]*)"/gi, (match, href) => {
- return isSafeHref(href) ? match : 'href=""';
- });
- }
-
- function isSafeHref(href) {
- const normalizedHref = String(href).trim().toLowerCase();
- const isHttpUrl = normalizedHref.startsWith('https://') || normalizedHref.startsWith('http://');
- const isRelativeUrl = normalizedHref.startsWith('/') && !normalizedHref.startsWith('//');
- return isHttpUrl || isRelativeUrl;
- }
-
/**
* Load translation file (or use a cached version), and optionally return the translation of a certain key
* @param {string} namespace - The file name of the translation namespace
@@ -521,13 +521,13 @@ module.exports = function (utils, load, warn) {
* @param {string} name - Translation name
* @param {...string} arg - Optional argument for the pattern
*/
- Translator.compile = function compile() {
- const args = Array.prototype.slice.call(arguments, 0).map(function (text) {
+ Translator.compile = function compile(...args) {
+ const compiled = args.map(function (text) {
// escape commas and percent signs in arguments
return String(text).replace(/%/g, '&#37;').replace(/,/g, '&#44;');
});
- return '[[' + args.join(', ') + ']]';
+ return `[[${compiled.join(', ')}]]`;
};
return Translator;
@@ -594,19 +594,97 @@ module.exports = function (utils, load, warn) {
warn('Translation failed: ' + err.stack);
});
},
- translateKeys: async function (keys, language, callback) {
+
+ // takes a old style token '[[topic:moved-from, arg1, arg2]]' and
+ // normalizes it to ['topic:moved-from', ['arg1', 'arg2']]
+ normalizeToken: function (token) {
+ if (typeof token !== 'string' || token === '') {
+ return [String(token), []];
+ }
+ if (token.startsWith('[[') && token.endsWith(']]')) {
+ token = token.slice(2, -2);
+ }
+ const parts = token.trim().split(',');
+ const txToken = parts[0].trim();
+ const args = parts.slice(1).map(part => part.trim());
+ return [txToken, args];
+ },
+
+ translateKeys: async function (data, language, callback) {
+ if (!Array.isArray(data)) {
+ throw new Error('[[error:invalid-data]]');
+ }
let cb = callback;
let lang = language;
if (typeof language === 'function') {
cb = language;
lang = null;
}
- const translations = await Promise.all(keys.map(key => adaptor.translate(key, lang)));
+ lang = lang || Translator.getLanguage();
+
+ // convert old format([[topic:moved-from]]) to new format [token, args, language]
+ data = data.map(key => (typeof key === 'string' ? [key, [], lang] : key));
+
+ const translations = await Promise.all(data.map(async (item) => {
+ const [token, itemArgs, language] = item;
+ const [txToken, argsFromToken] = adaptor.normalizeToken(token);
+ let args = itemArgs;
+ if (Array.isArray(argsFromToken) && argsFromToken.length > 0) {
+ args = argsFromToken;
+ }
+ const [namespace, key] = txToken.split(':', 2);
+ if (!key) {
+ return token;
+ }
+ const tokenLanguage = language || lang;
+ let txArgs = Array.isArray(args) ? args.map(arg => escapeHTML(arg)) : [];
+ txArgs = await adaptor.txArgs(args, tokenLanguage);
+
+ return Translator.create(tokenLanguage).getTranslation(namespace, key).then(function (translation) {
+ if (!translation) {
+ // if translation is missing/or not a translation, return the token as is
+ return token;
+ }
+ return adaptor.replaceArguments(translation, txArgs);
+ });
+ }));
if (typeof cb === 'function') {
return setTimeout(cb, 0, translations);
}
return translations;
},
+ // single tx token '[[topic:moved-from]]'
+ translateKey: async function (token, args, language) {
+ const [translation] = await adaptor.translateKeys([[token, args, language]]);
+ return translation;
+ },
+
+ escapeHTML: escapeHTML,
+
+ txArgs: async function (args, language) {
+ if (!Array.isArray(args) || args.length === 0) {
+ return args;
+ }
+
+ return await Promise.all(args.map(async (arg) => {
+ if (typeof arg === 'string' && arg.startsWith('[[') && arg.endsWith(']]')) {
+ return await adaptor.translateKey(arg, [], language);
+ }
+ return arg;
+ }));
+ },
+
+ replaceArguments: (translation, args) => {
+ if (!Array.isArray(args) || args.length === 0) {
+ return translation;
+ }
+ args.forEach((arg, index) => {
+ const argEscaped = arg.replace(/%(?=\d)/g, '&#37;').replace(/\\,/g, '&#44;');
+ const placeholder = `%${index + 1}`;
+ translation = translation.split(placeholder).join(argEscaped);
+ });
+ return validateHrefAttributes(translation);
+ },
/**
* Add translations to the cache
diff --git a/src/helpers.js b/src/helpers.js
index b75e950c26..d9163559a7 100644
--- a/src/helpers.js
+++ b/src/helpers.js
@@ -3,5 +3,6 @@
module.exports = require('../public/src/modules/helpers.common')(
require('./utils'),
require('benchpressjs'),
+ require('./translator'),
require('nconf').get('relative_path'),
);
diff --git a/src/languages.js b/src/languages.js
index d307a439df..655b83147e 100644
--- a/src/languages.js
+++ b/src/languages.js
@@ -84,4 +84,12 @@ Languages.userTimeagoCode = async function (userLang) {
return '';
};
+Languages.getFull = async function (language) {
+ const pathToLanguageFile = path.join(languagesPath, language, 'full.json');
+ if (!pathToLanguageFile.startsWith(languagesPath)) {
+ throw new Error('[[error:invalid-path]]');
+ }
+ return require(pathToLanguageFile);
+};
+
require('./promisify')(Languages);
diff --git a/src/meta/languages.js b/src/meta/languages.js
index fe9dfd302b..1fc36c4aca 100644
--- a/src/meta/languages.js
+++ b/src/meta/languages.js
@@ -14,6 +14,8 @@ const { paths } = require('../constants');
const buildLanguagesPath = path.join(paths.baseDir, 'build/public/language');
const coreLanguagesPath = path.join(paths.baseDir, 'public/language');
+let allLanguages = {};
+
async function getTranslationMetadata() {
const paths = await file.walk(coreLanguagesPath);
let languages = [];
@@ -90,6 +92,11 @@ async function buildNamespaceLanguage(lang, namespace, plugins) {
if (Object.keys(translations).length) {
await writeLanguageFile(lang, namespace, translations);
+ allLanguages[lang] = allLanguages[lang] || { full: {}, client: {} };
+ allLanguages[lang].full[namespace] = translations;
+ if (!namespace.startsWith('admin/')) {
+ allLanguages[lang].client[namespace] = translations;
+ }
}
}
@@ -132,7 +139,24 @@ async function assignFileToTranslations(translations, path) {
}
exports.build = async function buildLanguages() {
+ allLanguages = {};
await fs.promises.rm(buildLanguagesPath, { recursive: true, force: true });
const data = await getTranslationMetadata();
await buildTranslations(data);
+
+ for (const lang of Object.keys(allLanguages)) {
+ const jsonfilePath = path.join(buildLanguagesPath, lang, `full.json`);
+ const jsFilePath = path.join(buildLanguagesPath, lang, `full.min.js`);
+ const clientJsonFilePath = path.join(buildLanguagesPath, lang, `client.json`);
+ const clientJsFilePath = path.join(buildLanguagesPath, lang, `client.min.js`);
+ await mkdirp(path.dirname(jsonfilePath));
+ const fullJsonStr = JSON.stringify(allLanguages[lang].full);
+ const clientJsonStr = JSON.stringify(allLanguages[lang].client);
+ await Promise.all([
+ fs.promises.writeFile(jsonfilePath, fullJsonStr),
+ fs.promises.writeFile(jsFilePath, `window._i18n = ${fullJsonStr}`),
+ fs.promises.writeFile(clientJsonFilePath, clientJsonStr),
+ fs.promises.writeFile(clientJsFilePath, `window._i18n = ${clientJsonStr}`),
+ ]);
+ }
};
diff --git a/src/middleware/render.js b/src/middleware/render.js
index fee9461c69..a5fc1653a6 100644
--- a/src/middleware/render.js
+++ b/src/middleware/render.js
@@ -91,12 +91,14 @@ module.exports = function (middleware) {
req.app.set('json spaces', process.env.NODE_ENV === 'development' || req.query.pretty ? 4 : 0);
return res.json(options);
}
+
+ res.locals._i18n = await languages.getFull(getLang(req, res));
const optionsString = JSON.stringify(options).replace(/<\//g, '<\\/');
const headerFooterData = await loadHeaderFooterData(req, res, options);
const results = await utils.promiseParallel({
- header: renderHeaderFooter('renderHeader', req, res, options, headerFooterData),
+ header: renderHeaderFooter(render, 'renderHeader', req, res, options, headerFooterData),
content: renderContent(render, templateToRender, req, res, options),
- footer: renderHeaderFooter('renderFooter', req, res, options, headerFooterData),
+ footer: renderHeaderFooter(render, 'renderFooter', req, res, options, headerFooterData),
});
const str = `${results.header +
@@ -325,7 +327,7 @@ module.exports = function (middleware) {
});
}
- async function renderHeader(req, res, options, headerFooterData) {
+ async function renderHeader(render, req, res, options, headerFooterData) {
const hookReturn = await plugins.hooks.fire('filter:middleware.renderHeader', {
req: req,
res: res,
@@ -334,10 +336,10 @@ module.exports = function (middleware) {
data: options,
});
- return await req.app.renderAsync('header', hookReturn.templateData);
+ return await renderContent(render, 'header', req, res, hookReturn.templateData);
}
- async function renderFooter(req, res, options, headerFooterData) {
+ async function renderFooter(render, req, res, options, headerFooterData) {
const hookReturn = await plugins.hooks.fire('filter:middleware.renderFooter', {
req,
res,
@@ -354,10 +356,10 @@ module.exports = function (middleware) {
hookReturn.templateData.customJS = hookReturn.templateData.useCustomJS ? meta.config.customJS : '';
hookReturn.templateData.isSpider = req.uid === -1;
- return await req.app.renderAsync('footer', hookReturn.templateData);
+ return await renderContent(render, 'footer', req, res, hookReturn.templateData);
}
- async function renderAdminHeader(req, res, options, headerFooterData) {
+ async function renderAdminHeader(render, req, res, options, headerFooterData) {
const hookReturn = await plugins.hooks.fire('filter:middleware.renderAdminHeader', {
req,
res,
@@ -366,10 +368,10 @@ module.exports = function (middleware) {
data: options,
});
- return await req.app.renderAsync('admin/header', hookReturn.templateData);
+ return await renderContent(render, 'admin/header', req, res, hookReturn.templateData);
}
- async function renderAdminFooter(req, res, options, headerFooterData) {
+ async function renderAdminFooter(render, req, res, options, headerFooterData) {
const hookReturn = await plugins.hooks.fire('filter:middleware.renderAdminFooter', {
req,
res,
@@ -378,25 +380,25 @@ module.exports = function (middleware) {
data: options,
});
- return await req.app.renderAsync('admin/footer', hookReturn.templateData);
+ return await renderContent(render, 'admin/footer', req, res, hookReturn.templateData);
}
- async function renderHeaderFooter(method, req, res, options, headerFooterData) {
+ async function renderHeaderFooter(render, method, req, res, options, headerFooterData) {
let str = '';
if (res.locals.renderHeaderType === 'client') {
if (method === 'renderHeader') {
- str = await renderHeader(req, res, options, headerFooterData);
+ str = await renderHeader(render, req, res, options, headerFooterData);
} else if (method === 'renderFooter') {
- str = await renderFooter(req, res, options, headerFooterData);
+ str = await renderFooter(render, req, res, options, headerFooterData);
}
} else if (res.locals.renderHeaderType === 'admin') {
if (method === 'renderHeader') {
- str = await renderAdminHeader(req, res, options, headerFooterData);
+ str = await renderAdminHeader(render, req, res, options, headerFooterData);
} else if (method === 'renderFooter') {
- str = await renderAdminFooter(req, res, options, headerFooterData);
+ str = await renderAdminFooter(render, req, res, options, headerFooterData);
}
}
- return await translate(str, getLang(req, res));
+ return str;
}
function getLang(req, res) {
diff --git a/src/topics/index.js b/src/topics/index.js
index 91505c3458..198cf7e7e6 100644
--- a/src/topics/index.js
+++ b/src/topics/index.js
@@ -1,5 +1,6 @@
'use strict';
+const nconf = require('nconf');
const _ = require('lodash');
const validator = require('validator');
@@ -14,6 +15,8 @@ const activitypub = require('../activitypub');
const privileges = require('../privileges');
const social = require('../social');
+const relative_path = nconf.get('relative_path');
+
const Topics = module.exports;
require('./data')(Topics);
@@ -267,6 +270,7 @@ async function getMerger(topicData) {
Topics.getTopicField(topicData.mergeIntoTid, 'title'),
]);
merger.mergedIntoTitle = mergedIntoTitle;
+ merger.mergedIntoHref = `${relative_path}/topic/${topicData.mergedIntoTid}`;
return merger;
}
diff --git a/src/views/admin/header.tpl b/src/views/admin/header.tpl
index b9af555fd2..20a3cee3e5 100644
--- a/src/views/admin/header.tpl
+++ b/src/views/admin/header.tpl
@@ -21,6 +21,7 @@
}
</script>
+ <script src="{relative_path}/assets/language/{config.userLang}/full.min.js?{config.cache-buster}"></script>
<script type="text/javascript" src="{relative_path}/assets/admin.min.js?{cache-buster}"></script>
{{{ each scripts }}}
diff --git a/src/views/partials/footer/js.tpl b/src/views/partials/footer/js.tpl
index 5e35e36830..e3b555d306 100644
--- a/src/views/partials/footer/js.tpl
+++ b/src/views/partials/footer/js.tpl
@@ -1,3 +1,4 @@
+<script defer src="{relative_path}/assets/language/{config.userLang}/client.min.js?{config.cache-buster}"></script>
<script defer src="{relative_path}/assets/nodebb.min.js?{config.cache-buster}"></script>
{{{each scripts}}}
diff --git a/src/views/partials/reconnect-alert.tpl b/src/views/partials/reconnect-alert.tpl
index b8eba8b67e..e825f57959 100644
--- a/src/views/partials/reconnect-alert.tpl
+++ b/src/views/partials/reconnect-alert.tpl
@@ -1,4 +1,4 @@
<div id="reconnect-alert" class="alert alert-dismissible alert-warning fade hide" component="toaster/toast" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="[[global:buttons.close]]"></button>
<p class="mb-0">[[global:reconnecting-message, {config.siteTitle}]]</p>
-</div>
\ No newline at end of file
+</div>
diff --git a/src/views/partials/topic/merged-message.tpl b/src/views/partials/topic/merged-message.tpl
index 210c0b371e..0129a877a5 100644
--- a/src/views/partials/topic/merged-message.tpl
+++ b/src/views/partials/topic/merged-message.tpl
@@ -1,5 +1,5 @@
<div component="topic/merged/message" class="alert alert-info d-flex justify-content-between flex-wrap">
- <span>[[topic:merged-message, {config.relative_path}/topic/{mergeIntoTid}, {merger.mergedIntoTitle}]]</span>
+ <span>{tx("topic:merged-message", mergedIntoHref, merger.mergedIntoTitle)}</span>
<span>
<a class="fw-bold" href="{config.relative_path}/user/{merger.userslug}">{merger.username}</strong></a> <small class="timeago" title="{mergedTimestampISO}"></small>
</span>
diff --git a/test/translator.js b/test/translator.js
index 201671e29f..41b8195efc 100644
--- a/test/translator.js
+++ b/test/translator.js
@@ -3,12 +3,110 @@
// For tests relating to Transifex configuration, check i18n.js
const assert = require('assert');
+const benchpress = require('benchpressjs');
+
const shim = require('../src/translator');
const { Translator } = shim;
const db = require('./mocks/databasemock');
+const helpers = require('../src/helpers');
describe('Translator shim', () => {
+
+ describe('tx helper', () => {
+ const context = {
+ _i18n: {
+ topic: {
+ 'moved-from': 'Moved from %1',
+ 'merged-message': 'This topic has been merged into <a href="%1/topic/%2">%3</a>',
+ 'argument-test': 'Test arguments like %1 and %2, in them: %3',
+ 'no-arguments': 'no arguments here',
+ },
+ },
+ };
+
+ shim.addTranslation('en-GB', 'topic', {
+ 'argument-test': 'Test arguments like %1 and %2, in them: %3',
+ });
+
+ it('should return translated string with interpolation when has _i18n', (done) => {
+ const str = helpers.tx.call(context, 'topic:moved-from', 'general discussion');
+ assert.strictEqual(str, 'Moved from general discussion');
+ done();
+ });
+
+ it('should fallback to passed in string when translation is missing', (done) => {
+ const str = helpers.tx.call(context, 'topic:missing-key', 'general discussion');
+ assert.strictEqual(str, 'topic:missing-key');
+ done();
+ });
+
+ it('should work with [[topic:moved-from]] syntax', (done) => {
+ const str = helpers.tx.call(context, '[[topic:moved-from]]', 'general discussion');
+ assert.strictEqual(str, 'Moved from general discussion');
+ done();
+ });
+
+ it('should work with handle % and , in arguments syntax', async () => {
+ const compiled = shim.compile('topic:argument-test', 'ar%1g1', 'arg,2', 'arg3');
+ const shimStr = await shim.translate(compiled);
+ const str = helpers.tx.call(context, '[[topic:argument-test, ar&#37;1g1, arg&#44;2, arg3]]');
+
+ assert.strictEqual(str, 'Test arguments like ar&#37;1g1 and arg,2, in them: arg3');
+ assert.strictEqual(str, shimStr);
+ });
+
+ it('should escape html escape arguments', (done) => {
+ const str = helpers.tx.call(context, 'topic:moved-from', '<script>alert("xss")</script>');
+ assert.strictEqual(str, 'Moved from &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;');
+ done();
+ });
+
+ it('should validate href arguments', (done) => {
+ const str = helpers.tx.call(context, 'topic:merged-message', 'javascript:alert(origin)', 'foo', 'baz');
+ assert.strictEqual(str, 'This topic has been merged into <a href="">baz</a>');
+ done();
+ });
+
+ it('should properly translate if arguments have % or , in them', (done) => {
+ const str = helpers.tx.call(context, 'topic:argument-test', '%2 awesome, really', 'wow 2%', ',works');
+ assert.strictEqual(str, 'Test arguments like &#37;2 awesome, really and wow 2%, in them: ,works');
+ done();
+ });
+
+ it('should translate arguments if they are tokens themselves', (done) => {
+ const str = helpers.tx.call(context, 'topic:moved-from', '[[topic:no-arguments]]');
+ assert.strictEqual(str, 'Moved from no arguments here');
+ done();
+ });
+
+ it('should escape html escape arguments but keep it if it\'s coming from tx file', (done) => {
+ const str = helpers.tx.call(context, 'topic:merged-message', '/forum', '<script>alert("xss")</script>', 'topic name');
+ assert.strictEqual(str, 'This topic has been merged into <a href="/forum/topic/&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;">topic name</a>');
+ done();
+ });
+
+ it('should return passed in string if it\'s not found in _i18n and not replace arguments', (done) => {
+ const str = helpers.tx.call({}, 'this is a regular % 1 string', 'general discussion');
+
+ assert.strictEqual(str, 'this is a regular % 1 string');
+ done();
+ });
+
+ it('should work with benchpress.compileRender to parse and translate a custom string', async () => {
+ const compiled = await benchpress.compileRender('some {foo} with translation {tx("topic:moved-from", "general discussion")}', {
+ foo: 'bar',
+ _i18n: {
+ topic: {
+ 'moved-from': 'Moved from %1',
+ },
+ },
+ });
+ assert.strictEqual(compiled, 'some bar with translation Moved from general discussion');
+ });
+ });
+
+
describe('.translate()', () => {
it('should translate correctly', (done) => {
shim.translate('[[global:pagination.out-of, (foobar), [[global:home]]]]', (translated) => {
@@ -42,7 +140,53 @@ describe('Translator shim', () => {
});
});
- describe('translateKeys', () => {
+ describe('translateKey / translateKeys', () => {
+ shim.addTranslation('en-GB', 'topic', {
+ 'tx-token': 'TX TOKEN',
+ });
+
+ it('should translate a single key with no arguments', async () => {
+ const translated = await shim.translateKey('global:search', [], 'en-GB');
+ assert.deepStrictEqual(translated, 'Search');
+ });
+
+ it('should translate a single key with arguments', async () => {
+ const translated = await shim.translateKey('topic:moved-from', ['general discussion']);
+ assert.deepStrictEqual(translated, 'Moved from general discussion');
+ });
+
+ it('should translate a single key with brackets arguments', async () => {
+ const translated = await shim.translateKey('[[topic:moved-from]]', ['general discussion']);
+ assert.deepStrictEqual(translated, 'Moved from general discussion');
+ });
+
+ it('should translate nested keys', async () => {
+ const translated = await shim.translateKey('[[topic:moved-from, [[topic:merged-message]]]]');
+ assert.deepStrictEqual(translated, 'Moved from This topic has been merged into <a href="">&#37;2</a>');
+ });
+
+ it('should translate arguments if they are tokens themselves', async () => {
+ const str = await shim.translateKey('topic:moved-from', ['[[topic:tx-token]]']);
+ assert.strictEqual(str, 'Moved from TX TOKEN');
+ });
+
+ it('should return string untouched if it\'s not a tx string', async () => {
+ assert.deepStrictEqual(
+ await shim.translateKey('nodebb forum', [], 'en-GB'),
+ 'nodebb forum',
+ );
+
+ assert.deepStrictEqual(
+ await shim.translateKey('this is a [[foo:baz]] regular string %1 test', [], 'en-GB'),
+ 'this is a [[foo:baz]] regular string %1 test',
+ );
+
+ assert.deepStrictEqual(
+ await shim.translateKey('[[this is a [[foo:baz, "foo"]], regular string %1 test]]', [], 'en-GB'),
+ '[[this is a [[foo:baz, "foo"]], regular string %1 test]]'
+ );
+ });
+
it('should translate each key in array', async () => {
const translated = await shim.translateKeys(['[[global:home]]', '[[global:search]]'], 'en-GB');
assert.deepStrictEqual(translated, ['Home', 'Search']);
@@ -54,6 +198,28 @@ describe('Translator shim', () => {
done();
});
});
+
+ it('should translate all the elements in array in new format', async () => {
+ const translated = await shim.translateKeys([
+ ['topic:share-mail-subject', ['nodebb']],
+ ['topic:share-mail-body', ['http://example.com/post/123'], 'de'],
+ ]);
+ assert.deepStrictEqual(translated, [
+ 'Check out this post on "nodebb"',
+ 'Ich dachte, dieser Beitrag könnte dich interessieren: http://example.com/post/123',
+ ]);
+ });
+
+ it('should translate keys with args in old format', async () => {
+ const translated = await shim.translateKeys([
+ '[[topic:share-mail-subject, nodebb]]',
+ '[[topic:share-mail-body, http://example.com/post/123]]',
+ ], 'en-GB');
+ assert.deepStrictEqual(translated, [
+ 'Check out this post on "nodebb"',
+ 'I thought you might be interested in this post: http://example.com/post/123',
+ ]);
+ });
});
it('should load translations for language', (done) => {
@@ -214,13 +380,13 @@ describe('new Translator(language)', () => {
});
assert.strictEqual(
- await shim.translate('[[topic:merged-message, https://example.com, foo]]'),
- 'This topic has been merged into <a href="https://example.com">foo</a>'
+ await shim.translate('[[topic:merged-message, https://example.com/topic/1, foo]]'),
+ 'This topic has been merged into <a href="https://example.com/topic/1">foo</a>'
);
assert.strictEqual(
- await shim.translate('[[topic:merged-message, http://example.com, foo]]'),
- 'This topic has been merged into <a href="http://example.com">foo</a>'
+ await shim.translate('[[topic:merged-message, http://example.com/topic/1, foo]]'),
+ 'This topic has been merged into <a href="http://example.com/topic/1">foo</a>'
);
assert.strictEqual(
@@ -228,6 +394,11 @@ describe('new Translator(language)', () => {
'This topic has been merged into <a href="/topic/123">foo</a>'
);
+ assert.strictEqual(
+ await shim.translate('[[topic:merged-message, javascript is a nice language, foo]]'),
+ 'This topic has been merged into <a href="">foo</a>'
+ );
+
assert.strictEqual(
await shim.translate('[[topic:href-test-1, /topic/123, foo, bar]]'),
'This topic has been merged into <a href="/topic/123">foo</a> and <a href="/topic/123">bar</a>'
@@ -243,10 +414,7 @@ describe('new Translator(language)', () => {
'This topic has been merged into <a href="">bar</a>'
);
- assert.strictEqual(
- await shim.translate('[[topic:merged-message, javascript is a nice language, foo]]'),
- 'This topic has been merged into <a href="">foo</a>'
- );
+
assert.strictEqual(
await shim.translate('[[topic:href-test-3, javascript:alert(origin), foo, data:123, baz]]'),
@@ -259,7 +427,7 @@ describe('new Translator(language)', () => {
);
assert.strictEqual(
- await shim.translate('[[topic:merged-message, "javascript:alert(origin), foo]]'),
+ await shim.translate('[[topic:merged-message, "javascript:alert(origin), foo, bar]]'),
'This topic has been merged into <a href="">foo</a>'
);
});