l10n.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. this._bundles[appName] = bundle || {};
  64. if (_.isFunction(pluralForm)) {
  65. this._pluralFunctions[appName] = pluralForm;
  66. } else {
  67. // generate plural function based on form
  68. this._pluralFunctions[appName] = this._generatePluralFunction(pluralForm);
  69. }
  70. },
  71. /**
  72. * Generates a plural function based on the given plural form.
  73. * If an invalid form has been given, returns a default function.
  74. *
  75. * @param {String} pluralForm plural form
  76. */
  77. _generatePluralFunction: function(pluralForm) {
  78. // default func
  79. var func = function (n) {
  80. var p = (n !== 1) ? 1 : 0;
  81. return { 'nplural' : 2, 'plural' : p };
  82. };
  83. if (!pluralForm) {
  84. console.warn('Missing plural form in language file');
  85. return func;
  86. }
  87. /**
  88. * code below has been taken from jsgettext - which is LGPL licensed
  89. * https://developer.berlios.de/projects/jsgettext/
  90. * http://cvs.berlios.de/cgi-bin/viewcvs.cgi/jsgettext/jsgettext/lib/Gettext.js
  91. */
  92. var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\\(\\)])+)', 'm');
  93. if (pf_re.test(pluralForm)) {
  94. //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
  95. //pf = "nplurals=2; plural=(n != 1);";
  96. //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)
  97. //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)";
  98. var pf = pluralForm;
  99. if (! /;\s*$/.test(pf)) {
  100. pf = pf.concat(';');
  101. }
  102. /* We used to use eval, but it seems IE has issues with it.
  103. * We now use "new Function", though it carries a slightly
  104. * bigger performance hit.
  105. var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
  106. Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
  107. */
  108. var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
  109. func = new Function("n", code);
  110. } else {
  111. console.warn('Invalid plural form in language file: "' + pluralForm + '"');
  112. }
  113. return func;
  114. },
  115. /**
  116. * Translate a string
  117. * @param {string} app the id of the app for which to translate the string
  118. * @param {string} text the string to translate
  119. * @param [vars] map of placeholder key to value
  120. * @param {number} [count] number to replace %n with
  121. * @param {array} [options] options array
  122. * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled)
  123. * @return {string}
  124. */
  125. translate: function(app, text, vars, count, options) {
  126. var defaultOptions = {
  127. escape: true
  128. },
  129. allOptions = options || {};
  130. _.defaults(allOptions, defaultOptions);
  131. // TODO: cache this function to avoid inline recreation
  132. // of the same function over and over again in case
  133. // translate() is used in a loop
  134. var _build = function (text, vars, count) {
  135. return text.replace(/%n/g, count).replace(/{([^{}]*)}/g,
  136. function (a, b) {
  137. var r = vars[b];
  138. if(typeof r === 'string' || typeof r === 'number') {
  139. if(allOptions.escape) {
  140. return escapeHTML(r);
  141. } else {
  142. return r;
  143. }
  144. } else {
  145. return a;
  146. }
  147. }
  148. );
  149. };
  150. var translation = text;
  151. var bundle = this._bundles[app] || {};
  152. var value = bundle[text];
  153. if( typeof(value) !== 'undefined' ){
  154. translation = value;
  155. }
  156. if(typeof vars === 'object' || count !== undefined ) {
  157. return _build(translation, vars, count);
  158. } else {
  159. return translation;
  160. }
  161. },
  162. /**
  163. * Translate a plural string
  164. * @param {string} app the id of the app for which to translate the string
  165. * @param {string} textSingular the string to translate for exactly one object
  166. * @param {string} textPlural the string to translate for n objects
  167. * @param {number} count number to determine whether to use singular or plural
  168. * @param [vars] map of placeholder key to value
  169. * @param {array} [options] options array
  170. * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled)
  171. * @return {string} Translated string
  172. */
  173. translatePlural: function(app, textSingular, textPlural, count, vars, options) {
  174. var identifier = '_' + textSingular + '_::_' + textPlural + '_';
  175. var bundle = this._bundles[app] || {};
  176. var value = bundle[identifier];
  177. if( typeof(value) !== 'undefined' ){
  178. var translation = value;
  179. if ($.isArray(translation)) {
  180. var plural = this._pluralFunctions[app](count);
  181. return this.translate(app, translation[plural.plural], vars, count, options);
  182. }
  183. }
  184. if(count === 1) {
  185. return this.translate(app, textSingular, vars, count, options);
  186. }
  187. else{
  188. return this.translate(app, textPlural, vars, count, options);
  189. }
  190. }
  191. };
  192. /**
  193. * translate a string
  194. * @param {string} app the id of the app for which to translate the string
  195. * @param {string} text the string to translate
  196. * @param [vars] map of placeholder key to value
  197. * @param {number} [count] number to replace %n with
  198. * @return {string}
  199. */
  200. window.t = _.bind(OC.L10N.translate, OC.L10N);
  201. /**
  202. * translate a string
  203. * @param {string} app the id of the app for which to translate the string
  204. * @param {string} text_singular the string to translate for exactly one object
  205. * @param {string} text_plural the string to translate for n objects
  206. * @param {number} count number to determine whether to use singular or plural
  207. * @param [vars] map of placeholder key to value
  208. * @return {string} Translated string
  209. */
  210. window.n = _.bind(OC.L10N.translatePlural, OC.L10N);
  211. Handlebars.registerHelper('t', function(app, text) {
  212. return OC.L10N.translate(app, text);
  213. });