From ea0c8e8a9fdc1cbcd33ab344c02df490f13f840e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ale=C5=A1=20Smodi=C5=A1?= Date: Sat, 26 Sep 2015 15:23:26 +0200 Subject: Reimplemented translation support: leave the DOM structure intact, upon display language switch only replace language-dependent content. --- js/codeq/translation.js | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 js/codeq/translation.js (limited to 'js/codeq/translation.js') diff --git a/js/codeq/translation.js b/js/codeq/translation.js new file mode 100644 index 0000000..af39cdc --- /dev/null +++ b/js/codeq/translation.js @@ -0,0 +1,71 @@ +(function () { + + var dicts = {}, + translateElement = function (jqElt, lang) { + var dictionaryKey = jqElt.data('dict'), + translationKey = jqElt.data('tkey'), + dict = dicts[dictionaryKey], + translations, html, key; + if (!dict) { + codeq.log.error('Cannot find translation dictionary ' + dictionaryKey); + return; + } + if (!(typeof translationKey === 'number' || typeof translationKey === 'string')) { + codeq.log.error('Cannot find the element\'s translation key, dictionary: ' + dictionaryKey); + return; + } + translations = dict[translationKey]; + if (!translations) { + codeq.log.error('Translation key ' + translationKey + ' is missing from dictionary ' + dictionaryKey); + return; + } + html = translations[lang]; + if (!html) { + html = translations['en']; + if (html) { + codeq.log.info('There is no translation in language ' + lang + ' for key ' + translationKey + ' in dictionary ' + dictionaryKey + ', defaulting to language en'); + } + else { + for (key in translations) { + if (!translations.hasOwnProperty(key)) continue; + html = translations[key]; + if (!html) continue; + codeq.log.info('There is no translation in languages ' + lang + ' and en for key ' + translationKey + ' in dictionary ' + dictionaryKey + ', defaulting to language ' + key); + break; + } + if (!html) { + codeq.log.warn('There is no translation in any language for key ' + translationKey + ' in dictionary ' + dictionaryKey + ', leaving empty'); + return; + } + } + } + jqElt.html(html); + }, + translateDocument = function (lang) { + $('.translatable').each(function () { + translateElement($(this), lang); + }); + }; + + // Translate the whole document when the user switches the display language + codeq.on('langchange', function (args) { + translateDocument(args.lang); + }); + + // ================================================================================ + // The module API + // ================================================================================ + + codeq.tr = { + 'registerDictionary': function (name, dict) { + dicts[name] = dict; + }, + + 'translateDom': function (jqTopElt) { + var lang = codeq.getLang(); + jqTopElt.find('.translatable').each(function () { + translateElement($(this), lang); + }); + } + }; +})(); \ No newline at end of file -- cgit v1.2.1