l10n.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. /**
  11. * L10N namespace with localization functions.
  12. *
  13. * @namespace
  14. */
  15. OC.L10N = {
  16. /**
  17. * String bundles with app name as key.
  18. * @type {Object.<String,String>}
  19. */
  20. _bundles: {},
  21. /**
  22. * Plural functions, key is app name and value is function.
  23. * @type {Object.<String,Function>}
  24. */
  25. _pluralFunctions: {},
  26. /**
  27. * Load an app's translation bundle if not loaded already.
  28. *
  29. * @param {String} appName name of the app
  30. * @param {Function} callback callback to be called when
  31. * the translations are loaded
  32. * @return {Promise} promise
  33. */
  34. load: function(appName, callback) {
  35. // already available ?
  36. if (this._bundles[appName] || OC.getLocale() === 'en') {
  37. var deferred = $.Deferred();
  38. var promise = deferred.promise();
  39. promise.then(callback);
  40. deferred.resolve();
  41. return promise;
  42. }
  43. var self = this;
  44. var url = OC.filePath(appName, 'l10n', OC.getLocale() + '.json');
  45. // load JSON translation bundle per AJAX
  46. return $.get(url)
  47. .then(
  48. function(result) {
  49. if (result.translations) {
  50. self.register(appName, result.translations, result.pluralForm);
  51. }
  52. })
  53. .then(callback);
  54. },
  55. /**
  56. * Register an app's translation bundle.
  57. *
  58. * @param {String} appName name of the app
  59. * @param {Object<String,String>} bundle
  60. * @param {Function|String} [pluralForm] optional plural function or plural string
  61. */
  62. register: function(appName, bundle, pluralForm) {
  63. var self = this;
  64. if (_.isUndefined(this._bundles[appName])) {
  65. this._bundles[appName] = bundle || {};
  66. if (_.isFunction(pluralForm)) {
  67. this._pluralFunctions[appName] = pluralForm;
  68. } else {
  69. // generate plural function based on form
  70. this._pluralFunctions[appName] = this._generatePluralFunction(pluralForm);
  71. }
  72. } else {
  73. // Theme overwriting the default language
  74. _.extend(self._bundles[appName], bundle);
  75. }
  76. },
  77. /**
  78. * Generates a plural function based on the given plural form.
  79. * If an invalid form has been given, returns a default function.
  80. *
  81. * @param {String} pluralForm plural form
  82. */
  83. _generatePluralFunction: function(pluralForm) {
  84. // default func
  85. var func = function (n) {
  86. var p = (n !== 1) ? 1 : 0;
  87. return { 'nplural' : 2, 'plural' : p };
  88. };
  89. if (!pluralForm) {
  90. console.warn('Missing plural form in language file');
  91. return func;
  92. }
  93. /**
  94. * code below has been taken from jsgettext - which is LGPL licensed
  95. * https://developer.berlios.de/projects/jsgettext/
  96. * http://cvs.berlios.de/cgi-bin/viewcvs.cgi/jsgettext/jsgettext/lib/Gettext.js
  97. */
  98. var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\\(\\)])+)', 'm');
  99. if (pf_re.test(pluralForm)) {
  100. //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
  101. //pf = "nplurals=2; plural=(n != 1);";
  102. //ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
  103. //pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";
  104. var pf = pluralForm;
  105. if (! /;\s*$/.test(pf)) {
  106. pf = pf.concat(';');
  107. }
  108. /* We used to use eval, but it seems IE has issues with it.
  109. * We now use "new Function", though it carries a slightly
  110. * bigger performance hit.
  111. var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
  112. Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
  113. */
  114. var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
  115. func = new Function("n", code);
  116. } else {
  117. console.warn('Invalid plural form in language file: "' + pluralForm + '"');
  118. }
  119. return func;
  120. },
  121. /**
  122. * Translate a string
  123. * @param {string} app the id of the app for which to translate the string
  124. * @param {string} text the string to translate
  125. * @param [vars] map of placeholder key to value
  126. * @param {number} [count] number to replace %n with
  127. * @param {array} [options] options array
  128. * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled)
  129. * @return {string}
  130. */
  131. translate: function(app, text, vars, count, options) {
  132. var defaultOptions = {
  133. escape: true
  134. },
  135. allOptions = options || {};
  136. _.defaults(allOptions, defaultOptions);
  137. // TODO: cache this function to avoid inline recreation
  138. // of the same function over and over again in case
  139. // translate() is used in a loop
  140. var _build = function (text, vars, count) {
  141. return text.replace(/%n/g, count).replace(/{([^{}]*)}/g,
  142. function (a, b) {
  143. var r = vars[b];
  144. if(typeof r === 'string' || typeof r === 'number') {
  145. if(allOptions.escape) {
  146. return escapeHTML(r);
  147. } else {
  148. return r;
  149. }
  150. } else {
  151. return a;
  152. }
  153. }
  154. );
  155. };
  156. var translation = text;
  157. var bundle = this._bundles[app] || {};
  158. var value = bundle[text];
  159. if( typeof(value) !== 'undefined' ){
  160. translation = value;
  161. }
  162. if(typeof vars === 'object' || count !== undefined ) {
  163. return _build(translation, vars, count);
  164. } else {
  165. return translation;
  166. }
  167. },
  168. /**
  169. * Translate a plural string
  170. * @param {string} app the id of the app for which to translate the string
  171. * @param {string} textSingular the string to translate for exactly one object
  172. * @param {string} textPlural the string to translate for n objects
  173. * @param {number} count number to determine whether to use singular or plural
  174. * @param [vars] map of placeholder key to value
  175. * @param {array} [options] options array
  176. * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled)
  177. * @return {string} Translated string
  178. */
  179. translatePlural: function(app, textSingular, textPlural, count, vars, options) {
  180. var identifier = '_' + textSingular + '_::_' + textPlural + '_';
  181. var bundle = this._bundles[app] || {};
  182. var value = bundle[identifier];
  183. if( typeof(value) !== 'undefined' ){
  184. var translation = value;
  185. if ($.isArray(translation)) {
  186. var plural = this._pluralFunctions[app](count);
  187. return this.translate(app, translation[plural.plural], vars, count, options);
  188. }
  189. }
  190. if(count === 1) {
  191. return this.translate(app, textSingular, vars, count, options);
  192. }
  193. else{
  194. return this.translate(app, textPlural, vars, count, options);
  195. }
  196. }
  197. };
  198. /**
  199. * translate a string
  200. * @param {string} app the id of the app for which to translate the string
  201. * @param {string} text the string to translate
  202. * @param [vars] map of placeholder key to value
  203. * @param {number} [count] number to replace %n with
  204. * @return {string}
  205. */
  206. window.t = _.bind(OC.L10N.translate, OC.L10N);
  207. /**
  208. * translate a string
  209. * @param {string} app the id of the app for which to translate the string
  210. * @param {string} text_singular the string to translate for exactly one object
  211. * @param {string} text_plural the string to translate for n objects
  212. * @param {number} count number to determine whether to use singular or plural
  213. * @param [vars] map of placeholder key to value
  214. * @return {string} Translated string
  215. */
  216. window.n = _.bind(OC.L10N.translatePlural, OC.L10N);
  217. Handlebars.registerHelper('t', function(app, text) {
  218. return OC.L10N.translate(app, text);
  219. });