l10n.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. /**
  2. * Copyright (c) 2011-2013 Fabien Cazenave, Mozilla.
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to
  6. * deal in the Software without restriction, including without limitation the
  7. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. * sell copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. * IN THE SOFTWARE.
  21. */
  22. /*
  23. Additional modifications for PDF.js project:
  24. - Disables language initialization on page loading;
  25. - Removes consoleWarn and consoleLog and use console.log/warn directly.
  26. - Removes window._ assignment.
  27. - Remove compatibility code for OldIE.
  28. */
  29. /*jshint browser: true, devel: true, es5: true, globalstrict: true */
  30. 'use strict';
  31. document.webL10n = (function (window, document, undefined) {
  32. var gL10nData = {};
  33. var gTextData = '';
  34. var gTextProp = 'textContent';
  35. var gLanguage = '';
  36. var gMacros = {};
  37. var gReadyState = 'loading';
  38. /**
  39. * Synchronously loading l10n resources significantly minimizes flickering
  40. * from displaying the app with non-localized strings and then updating the
  41. * strings. Although this will block all script execution on this page, we
  42. * expect that the l10n resources are available locally on flash-storage.
  43. *
  44. * As synchronous XHR is generally considered as a bad idea, we're still
  45. * loading l10n resources asynchronously -- but we keep this in a setting,
  46. * just in case... and applications using this library should hide their
  47. * content until the `localized' event happens.
  48. */
  49. var gAsyncResourceLoading = true; // read-only
  50. /**
  51. * DOM helpers for the so-called "HTML API".
  52. *
  53. * These functions are written for modern browsers. For old versions of IE,
  54. * they're overridden in the 'startup' section at the end of this file.
  55. */
  56. function getL10nResourceLinks() {
  57. return document.querySelectorAll('link[type="application/l10n"]');
  58. }
  59. function getL10nDictionary() {
  60. var script = document.querySelector('script[type="application/l10n"]');
  61. // TODO: support multiple and external JSON dictionaries
  62. return script ? JSON.parse(script.innerHTML) : null;
  63. }
  64. function getTranslatableChildren(element) {
  65. return element ? element.querySelectorAll('*[data-l10n-id]') : [];
  66. }
  67. function getL10nAttributes(element) {
  68. if (!element)
  69. return {};
  70. var l10nId = element.getAttribute('data-l10n-id');
  71. var l10nArgs = element.getAttribute('data-l10n-args');
  72. var args = {};
  73. if (l10nArgs) {
  74. try {
  75. args = JSON.parse(l10nArgs);
  76. } catch (e) {
  77. console.warn('could not parse arguments for #' + l10nId);
  78. }
  79. }
  80. return {id: l10nId, args: args};
  81. }
  82. function fireL10nReadyEvent(lang) {
  83. var evtObject = document.createEvent('Event');
  84. evtObject.initEvent('localized', true, false);
  85. evtObject.language = lang;
  86. document.dispatchEvent(evtObject);
  87. }
  88. function xhrLoadText(url, onSuccess, onFailure) {
  89. onSuccess = onSuccess || function _onSuccess(data) {
  90. };
  91. onFailure = onFailure || function _onFailure() {
  92. console.warn(url + ' not found.');
  93. };
  94. var xhr = new XMLHttpRequest();
  95. xhr.open('GET', url, gAsyncResourceLoading);
  96. if (xhr.overrideMimeType) {
  97. xhr.overrideMimeType('text/plain; charset=utf-8');
  98. }
  99. xhr.onreadystatechange = function () {
  100. if (xhr.readyState == 4) {
  101. if (xhr.status == 200 || xhr.status === 0) {
  102. onSuccess(xhr.responseText);
  103. } else {
  104. onFailure();
  105. }
  106. }
  107. };
  108. xhr.onerror = onFailure;
  109. xhr.ontimeout = onFailure;
  110. // in Firefox OS with the app:// protocol, trying to XHR a non-existing
  111. // URL will raise an exception here -- hence this ugly try...catch.
  112. try {
  113. xhr.send(null);
  114. } catch (e) {
  115. onFailure();
  116. }
  117. }
  118. /**
  119. * l10n resource parser:
  120. * - reads (async XHR) the l10n resource matching `lang';
  121. * - imports linked resources (synchronously) when specified;
  122. * - parses the text data (fills `gL10nData' and `gTextData');
  123. * - triggers success/failure callbacks when done.
  124. *
  125. * @param {string} href
  126. * URL of the l10n resource to parse.
  127. *
  128. * @param {string} lang
  129. * locale (language) to parse. Must be a lowercase string.
  130. *
  131. * @param {Function} successCallback
  132. * triggered when the l10n resource has been successully parsed.
  133. *
  134. * @param {Function} failureCallback
  135. * triggered when the an error has occured.
  136. *
  137. * @return {void}
  138. * uses the following global variables: gL10nData, gTextData, gTextProp.
  139. */
  140. function parseResource(href, lang, successCallback, failureCallback) {
  141. var baseURL = href.replace(/[^\/]*$/, '') || './';
  142. // handle escaped characters (backslashes) in a string
  143. function evalString(text) {
  144. if (text.lastIndexOf('\\') < 0)
  145. return text;
  146. return text.replace(/\\\\/g, '\\')
  147. .replace(/\\n/g, '\n')
  148. .replace(/\\r/g, '\r')
  149. .replace(/\\t/g, '\t')
  150. .replace(/\\b/g, '\b')
  151. .replace(/\\f/g, '\f')
  152. .replace(/\\{/g, '{')
  153. .replace(/\\}/g, '}')
  154. .replace(/\\"/g, '"')
  155. .replace(/\\'/g, "'");
  156. }
  157. // parse *.properties text data into an l10n dictionary
  158. // If gAsyncResourceLoading is false, then the callback will be called
  159. // synchronously. Otherwise it is called asynchronously.
  160. function parseProperties(text, parsedPropertiesCallback) {
  161. var dictionary = {};
  162. // token expressions
  163. var reBlank = /^\s*|\s*$/;
  164. var reComment = /^\s*#|^\s*$/;
  165. var reSection = /^\s*\[(.*)\]\s*$/;
  166. var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
  167. var reSplit = /^([^=\s]*)\s*=\s*(.+)$/; // TODO: escape EOLs with '\'
  168. // parse the *.properties file into an associative array
  169. function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
  170. var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
  171. var currentLang = '*';
  172. var genericLang = lang.split('-', 1)[0];
  173. var skipLang = false;
  174. var match = '';
  175. function nextEntry() {
  176. // Use infinite loop instead of recursion to avoid reaching the
  177. // maximum recursion limit for content with many lines.
  178. while (true) {
  179. if (!entries.length) {
  180. parsedRawLinesCallback();
  181. return;
  182. }
  183. var line = entries.shift();
  184. // comment or blank line?
  185. if (reComment.test(line))
  186. continue;
  187. // the extended syntax supports [lang] sections and @import rules
  188. if (extendedSyntax) {
  189. match = reSection.exec(line);
  190. if (match) { // section start?
  191. // RFC 4646, section 4.4, "All comparisons MUST be performed
  192. // in a case-insensitive manner."
  193. currentLang = match[1].toLowerCase();
  194. skipLang = (currentLang !== '*') &&
  195. (currentLang !== lang) && (currentLang !== genericLang);
  196. continue;
  197. } else if (skipLang) {
  198. continue;
  199. }
  200. match = reImport.exec(line);
  201. if (match) { // @import rule?
  202. loadImport(baseURL + match[1], nextEntry);
  203. return;
  204. }
  205. }
  206. // key-value pair
  207. var tmp = line.match(reSplit);
  208. if (tmp && tmp.length == 3) {
  209. dictionary[tmp[1]] = evalString(tmp[2]);
  210. }
  211. }
  212. }
  213. nextEntry();
  214. }
  215. // import another *.properties file
  216. function loadImport(url, callback) {
  217. xhrLoadText(url, function (content) {
  218. parseRawLines(content, false, callback); // don't allow recursive imports
  219. }, null);
  220. }
  221. // fill the dictionary
  222. parseRawLines(text, true, function () {
  223. parsedPropertiesCallback(dictionary);
  224. });
  225. }
  226. // load and parse l10n data (warning: global variables are used here)
  227. xhrLoadText(href, function (response) {
  228. gTextData += response; // mostly for debug
  229. // parse *.properties text data into an l10n dictionary
  230. parseProperties(response, function (data) {
  231. // find attribute descriptions, if any
  232. for (var key in data) {
  233. var id, prop, index = key.lastIndexOf('.');
  234. if (index > 0) { // an attribute has been specified
  235. id = key.substring(0, index);
  236. prop = key.substr(index + 1);
  237. } else { // no attribute: assuming text content by default
  238. id = key;
  239. prop = gTextProp;
  240. }
  241. if (!gL10nData[id]) {
  242. gL10nData[id] = {};
  243. }
  244. gL10nData[id][prop] = data[key];
  245. }
  246. // trigger callback
  247. if (successCallback) {
  248. successCallback();
  249. }
  250. });
  251. }, failureCallback);
  252. }
  253. // load and parse all resources for the specified locale
  254. function loadLocale(lang, callback) {
  255. // RFC 4646, section 2.1 states that language tags have to be treated as
  256. // case-insensitive. Convert to lowercase for case-insensitive comparisons.
  257. if (lang) {
  258. lang = lang.toLowerCase();
  259. }
  260. callback = callback || function _callback() {
  261. };
  262. clear();
  263. gLanguage = lang;
  264. // check all <link type="application/l10n" href="..." /> nodes
  265. // and load the resource files
  266. var langLinks = getL10nResourceLinks();
  267. var langCount = langLinks.length;
  268. if (langCount === 0) {
  269. // we might have a pre-compiled dictionary instead
  270. var dict = getL10nDictionary();
  271. if (dict && dict.locales && dict.default_locale) {
  272. console.log('using the embedded JSON directory, early way out');
  273. gL10nData = dict.locales[lang];
  274. if (!gL10nData) {
  275. var defaultLocale = dict.default_locale.toLowerCase();
  276. for (var anyCaseLang in dict.locales) {
  277. anyCaseLang = anyCaseLang.toLowerCase();
  278. if (anyCaseLang === lang) {
  279. gL10nData = dict.locales[lang];
  280. break;
  281. } else if (anyCaseLang === defaultLocale) {
  282. gL10nData = dict.locales[defaultLocale];
  283. }
  284. }
  285. }
  286. callback();
  287. } else {
  288. console.log('no resource to load, early way out');
  289. }
  290. // early way out
  291. fireL10nReadyEvent(lang);
  292. gReadyState = 'complete';
  293. return;
  294. }
  295. // start the callback when all resources are loaded
  296. var onResourceLoaded = null;
  297. var gResourceCount = 0;
  298. onResourceLoaded = function () {
  299. gResourceCount++;
  300. if (gResourceCount >= langCount) {
  301. callback();
  302. fireL10nReadyEvent(lang);
  303. gReadyState = 'complete';
  304. }
  305. };
  306. // load all resource files
  307. function L10nResourceLink(link) {
  308. var href = link.href;
  309. // Note: If |gAsyncResourceLoading| is false, then the following callbacks
  310. // are synchronously called.
  311. this.load = function (lang, callback) {
  312. parseResource(href, lang, callback, function () {
  313. console.warn(href + ' not found.');
  314. // lang not found, used default resource instead
  315. console.warn('"' + lang + '" resource not found');
  316. gLanguage = '';
  317. // Resource not loaded, but we still need to call the callback.
  318. callback();
  319. });
  320. };
  321. }
  322. for (var i = 0; i < langCount; i++) {
  323. var resource = new L10nResourceLink(langLinks[i]);
  324. resource.load(lang, onResourceLoaded);
  325. }
  326. }
  327. // clear all l10n data
  328. function clear() {
  329. gL10nData = {};
  330. gTextData = '';
  331. gLanguage = '';
  332. // TODO: clear all non predefined macros.
  333. // There's no such macro /yet/ but we're planning to have some...
  334. }
  335. /**
  336. * Get rules for plural forms (shared with JetPack), see:
  337. * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
  338. * https://github.com/mozilla/addon-sdk/blob/master/python-lib/plural-rules-generator.p
  339. *
  340. * @param {string} lang
  341. * locale (language) used.
  342. *
  343. * @return {Function}
  344. * returns a function that gives the plural form name for a given integer:
  345. * var fun = getPluralRules('en');
  346. * fun(1) -> 'one'
  347. * fun(0) -> 'other'
  348. * fun(1000) -> 'other'.
  349. */
  350. function getPluralRules(lang) {
  351. var locales2rules = {
  352. 'af': 3,
  353. 'ak': 4,
  354. 'am': 4,
  355. 'ar': 1,
  356. 'asa': 3,
  357. 'az': 0,
  358. 'be': 11,
  359. 'bem': 3,
  360. 'bez': 3,
  361. 'bg': 3,
  362. 'bh': 4,
  363. 'bm': 0,
  364. 'bn': 3,
  365. 'bo': 0,
  366. 'br': 20,
  367. 'brx': 3,
  368. 'bs': 11,
  369. 'ca': 3,
  370. 'cgg': 3,
  371. 'chr': 3,
  372. 'cs': 12,
  373. 'cy': 17,
  374. 'da': 3,
  375. 'de': 3,
  376. 'dv': 3,
  377. 'dz': 0,
  378. 'ee': 3,
  379. 'el': 3,
  380. 'en': 3,
  381. 'eo': 3,
  382. 'es': 3,
  383. 'et': 3,
  384. 'eu': 3,
  385. 'fa': 0,
  386. 'ff': 5,
  387. 'fi': 3,
  388. 'fil': 4,
  389. 'fo': 3,
  390. 'fr': 5,
  391. 'fur': 3,
  392. 'fy': 3,
  393. 'ga': 8,
  394. 'gd': 24,
  395. 'gl': 3,
  396. 'gsw': 3,
  397. 'gu': 3,
  398. 'guw': 4,
  399. 'gv': 23,
  400. 'ha': 3,
  401. 'haw': 3,
  402. 'he': 2,
  403. 'hi': 4,
  404. 'hr': 11,
  405. 'hu': 0,
  406. 'id': 0,
  407. 'ig': 0,
  408. 'ii': 0,
  409. 'is': 3,
  410. 'it': 3,
  411. 'iu': 7,
  412. 'ja': 0,
  413. 'jmc': 3,
  414. 'jv': 0,
  415. 'ka': 0,
  416. 'kab': 5,
  417. 'kaj': 3,
  418. 'kcg': 3,
  419. 'kde': 0,
  420. 'kea': 0,
  421. 'kk': 3,
  422. 'kl': 3,
  423. 'km': 0,
  424. 'kn': 0,
  425. 'ko': 0,
  426. 'ksb': 3,
  427. 'ksh': 21,
  428. 'ku': 3,
  429. 'kw': 7,
  430. 'lag': 18,
  431. 'lb': 3,
  432. 'lg': 3,
  433. 'ln': 4,
  434. 'lo': 0,
  435. 'lt': 10,
  436. 'lv': 6,
  437. 'mas': 3,
  438. 'mg': 4,
  439. 'mk': 16,
  440. 'ml': 3,
  441. 'mn': 3,
  442. 'mo': 9,
  443. 'mr': 3,
  444. 'ms': 0,
  445. 'mt': 15,
  446. 'my': 0,
  447. 'nah': 3,
  448. 'naq': 7,
  449. 'nb': 3,
  450. 'nd': 3,
  451. 'ne': 3,
  452. 'nl': 3,
  453. 'nn': 3,
  454. 'no': 3,
  455. 'nr': 3,
  456. 'nso': 4,
  457. 'ny': 3,
  458. 'nyn': 3,
  459. 'om': 3,
  460. 'or': 3,
  461. 'pa': 3,
  462. 'pap': 3,
  463. 'pl': 13,
  464. 'ps': 3,
  465. 'pt': 3,
  466. 'rm': 3,
  467. 'ro': 9,
  468. 'rof': 3,
  469. 'ru': 11,
  470. 'rwk': 3,
  471. 'sah': 0,
  472. 'saq': 3,
  473. 'se': 7,
  474. 'seh': 3,
  475. 'ses': 0,
  476. 'sg': 0,
  477. 'sh': 11,
  478. 'shi': 19,
  479. 'sk': 12,
  480. 'sl': 14,
  481. 'sma': 7,
  482. 'smi': 7,
  483. 'smj': 7,
  484. 'smn': 7,
  485. 'sms': 7,
  486. 'sn': 3,
  487. 'so': 3,
  488. 'sq': 3,
  489. 'sr': 11,
  490. 'ss': 3,
  491. 'ssy': 3,
  492. 'st': 3,
  493. 'sv': 3,
  494. 'sw': 3,
  495. 'syr': 3,
  496. 'ta': 3,
  497. 'te': 3,
  498. 'teo': 3,
  499. 'th': 0,
  500. 'ti': 4,
  501. 'tig': 3,
  502. 'tk': 3,
  503. 'tl': 4,
  504. 'tn': 3,
  505. 'to': 0,
  506. 'tr': 0,
  507. 'ts': 3,
  508. 'tzm': 22,
  509. 'uk': 11,
  510. 'ur': 3,
  511. 've': 3,
  512. 'vi': 0,
  513. 'vun': 3,
  514. 'wa': 4,
  515. 'wae': 3,
  516. 'wo': 0,
  517. 'xh': 3,
  518. 'xog': 3,
  519. 'yo': 0,
  520. 'zh': 0,
  521. 'zu': 3
  522. };
  523. // utility functions for plural rules methods
  524. function isIn(n, list) {
  525. return list.indexOf(n) !== -1;
  526. }
  527. function isBetween(n, start, end) {
  528. return start <= n && n <= end;
  529. }
  530. // list of all plural rules methods:
  531. // map an integer to the plural form name to use
  532. var pluralRules = {
  533. '0': function (n) {
  534. return 'other';
  535. },
  536. '1': function (n) {
  537. if ((isBetween((n % 100), 3, 10)))
  538. return 'few';
  539. if (n === 0)
  540. return 'zero';
  541. if ((isBetween((n % 100), 11, 99)))
  542. return 'many';
  543. if (n == 2)
  544. return 'two';
  545. if (n == 1)
  546. return 'one';
  547. return 'other';
  548. },
  549. '2': function (n) {
  550. if (n !== 0 && (n % 10) === 0)
  551. return 'many';
  552. if (n == 2)
  553. return 'two';
  554. if (n == 1)
  555. return 'one';
  556. return 'other';
  557. },
  558. '3': function (n) {
  559. if (n == 1)
  560. return 'one';
  561. return 'other';
  562. },
  563. '4': function (n) {
  564. if ((isBetween(n, 0, 1)))
  565. return 'one';
  566. return 'other';
  567. },
  568. '5': function (n) {
  569. if ((isBetween(n, 0, 2)) && n != 2)
  570. return 'one';
  571. return 'other';
  572. },
  573. '6': function (n) {
  574. if (n === 0)
  575. return 'zero';
  576. if ((n % 10) == 1 && (n % 100) != 11)
  577. return 'one';
  578. return 'other';
  579. },
  580. '7': function (n) {
  581. if (n == 2)
  582. return 'two';
  583. if (n == 1)
  584. return 'one';
  585. return 'other';
  586. },
  587. '8': function (n) {
  588. if ((isBetween(n, 3, 6)))
  589. return 'few';
  590. if ((isBetween(n, 7, 10)))
  591. return 'many';
  592. if (n == 2)
  593. return 'two';
  594. if (n == 1)
  595. return 'one';
  596. return 'other';
  597. },
  598. '9': function (n) {
  599. if (n === 0 || n != 1 && (isBetween((n % 100), 1, 19)))
  600. return 'few';
  601. if (n == 1)
  602. return 'one';
  603. return 'other';
  604. },
  605. '10': function (n) {
  606. if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19)))
  607. return 'few';
  608. if ((n % 10) == 1 && !(isBetween((n % 100), 11, 19)))
  609. return 'one';
  610. return 'other';
  611. },
  612. '11': function (n) {
  613. if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14)))
  614. return 'few';
  615. if ((n % 10) === 0 ||
  616. (isBetween((n % 10), 5, 9)) ||
  617. (isBetween((n % 100), 11, 14)))
  618. return 'many';
  619. if ((n % 10) == 1 && (n % 100) != 11)
  620. return 'one';
  621. return 'other';
  622. },
  623. '12': function (n) {
  624. if ((isBetween(n, 2, 4)))
  625. return 'few';
  626. if (n == 1)
  627. return 'one';
  628. return 'other';
  629. },
  630. '13': function (n) {
  631. if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14)))
  632. return 'few';
  633. if (n != 1 && (isBetween((n % 10), 0, 1)) ||
  634. (isBetween((n % 10), 5, 9)) ||
  635. (isBetween((n % 100), 12, 14)))
  636. return 'many';
  637. if (n == 1)
  638. return 'one';
  639. return 'other';
  640. },
  641. '14': function (n) {
  642. if ((isBetween((n % 100), 3, 4)))
  643. return 'few';
  644. if ((n % 100) == 2)
  645. return 'two';
  646. if ((n % 100) == 1)
  647. return 'one';
  648. return 'other';
  649. },
  650. '15': function (n) {
  651. if (n === 0 || (isBetween((n % 100), 2, 10)))
  652. return 'few';
  653. if ((isBetween((n % 100), 11, 19)))
  654. return 'many';
  655. if (n == 1)
  656. return 'one';
  657. return 'other';
  658. },
  659. '16': function (n) {
  660. if ((n % 10) == 1 && n != 11)
  661. return 'one';
  662. return 'other';
  663. },
  664. '17': function (n) {
  665. if (n == 3)
  666. return 'few';
  667. if (n === 0)
  668. return 'zero';
  669. if (n == 6)
  670. return 'many';
  671. if (n == 2)
  672. return 'two';
  673. if (n == 1)
  674. return 'one';
  675. return 'other';
  676. },
  677. '18': function (n) {
  678. if (n === 0)
  679. return 'zero';
  680. if ((isBetween(n, 0, 2)) && n !== 0 && n != 2)
  681. return 'one';
  682. return 'other';
  683. },
  684. '19': function (n) {
  685. if ((isBetween(n, 2, 10)))
  686. return 'few';
  687. if ((isBetween(n, 0, 1)))
  688. return 'one';
  689. return 'other';
  690. },
  691. '20': function (n) {
  692. if ((isBetween((n % 10), 3, 4) || ((n % 10) == 9)) && !(
  693. isBetween((n % 100), 10, 19) ||
  694. isBetween((n % 100), 70, 79) ||
  695. isBetween((n % 100), 90, 99)
  696. ))
  697. return 'few';
  698. if ((n % 1000000) === 0 && n !== 0)
  699. return 'many';
  700. if ((n % 10) == 2 && !isIn((n % 100), [12, 72, 92]))
  701. return 'two';
  702. if ((n % 10) == 1 && !isIn((n % 100), [11, 71, 91]))
  703. return 'one';
  704. return 'other';
  705. },
  706. '21': function (n) {
  707. if (n === 0)
  708. return 'zero';
  709. if (n == 1)
  710. return 'one';
  711. return 'other';
  712. },
  713. '22': function (n) {
  714. if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99)))
  715. return 'one';
  716. return 'other';
  717. },
  718. '23': function (n) {
  719. if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0)
  720. return 'one';
  721. return 'other';
  722. },
  723. '24': function (n) {
  724. if ((isBetween(n, 3, 10) || isBetween(n, 13, 19)))
  725. return 'few';
  726. if (isIn(n, [2, 12]))
  727. return 'two';
  728. if (isIn(n, [1, 11]))
  729. return 'one';
  730. return 'other';
  731. }
  732. };
  733. // return a function that gives the plural form name for a given integer
  734. var index = locales2rules[lang.replace(/-.*$/, '')];
  735. if (!(index in pluralRules)) {
  736. console.warn('plural form unknown for [' + lang + ']');
  737. return function () {
  738. return 'other';
  739. };
  740. }
  741. return pluralRules[index];
  742. }
  743. // pre-defined 'plural' macro
  744. gMacros.plural = function (str, param, key, prop) {
  745. var n = parseFloat(param);
  746. if (isNaN(n))
  747. return str;
  748. // TODO: support other properties (l20n still doesn't...)
  749. if (prop != gTextProp)
  750. return str;
  751. // initialize _pluralRules
  752. if (!gMacros._pluralRules) {
  753. gMacros._pluralRules = getPluralRules(gLanguage);
  754. }
  755. var index = '[' + gMacros._pluralRules(n) + ']';
  756. // try to find a [zero|one|two] key if it's defined
  757. if (n === 0 && (key + '[zero]') in gL10nData) {
  758. str = gL10nData[key + '[zero]'][prop];
  759. } else if (n == 1 && (key + '[one]') in gL10nData) {
  760. str = gL10nData[key + '[one]'][prop];
  761. } else if (n == 2 && (key + '[two]') in gL10nData) {
  762. str = gL10nData[key + '[two]'][prop];
  763. } else if ((key + index) in gL10nData) {
  764. str = gL10nData[key + index][prop];
  765. } else if ((key + '[other]') in gL10nData) {
  766. str = gL10nData[key + '[other]'][prop];
  767. }
  768. return str;
  769. };
  770. /**
  771. * l10n dictionary functions
  772. */
  773. // fetch an l10n object, warn if not found, apply `args' if possible
  774. function getL10nData(key, args, fallback) {
  775. var data = gL10nData[key];
  776. if (!data) {
  777. console.warn('#' + key + ' is undefined.');
  778. if (!fallback) {
  779. return null;
  780. }
  781. data = fallback;
  782. }
  783. /** This is where l10n expressions should be processed.
  784. * The plan is to support C-style expressions from the l20n project;
  785. * until then, only two kinds of simple expressions are supported:
  786. * {[ index ]} and {{ arguments }}.
  787. */
  788. var rv = {};
  789. for (var prop in data) {
  790. var str = data[prop];
  791. str = substIndexes(str, args, key, prop);
  792. str = substArguments(str, args, key);
  793. rv[prop] = str;
  794. }
  795. return rv;
  796. }
  797. // replace {[macros]} with their values
  798. function substIndexes(str, args, key, prop) {
  799. var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/;
  800. var reMatch = reIndex.exec(str);
  801. if (!reMatch || !reMatch.length)
  802. return str;
  803. // an index/macro has been found
  804. // Note: at the moment, only one parameter is supported
  805. var macroName = reMatch[1];
  806. var paramName = reMatch[2];
  807. var param;
  808. if (args && paramName in args) {
  809. param = args[paramName];
  810. } else if (paramName in gL10nData) {
  811. param = gL10nData[paramName];
  812. }
  813. // there's no macro parser yet: it has to be defined in gMacros
  814. if (macroName in gMacros) {
  815. var macro = gMacros[macroName];
  816. str = macro(str, param, key, prop);
  817. }
  818. return str;
  819. }
  820. // replace {{arguments}} with their values
  821. function substArguments(str, args, key) {
  822. var reArgs = /\{\{\s*(.+?)\s*\}\}/g;
  823. return str.replace(reArgs, function (matched_text, arg) {
  824. if (args && arg in args) {
  825. return args[arg];
  826. }
  827. if (arg in gL10nData) {
  828. return gL10nData[arg];
  829. }
  830. console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');
  831. return matched_text;
  832. });
  833. }
  834. // translate an HTML element
  835. function translateElement(element) {
  836. var l10n = getL10nAttributes(element);
  837. if (!l10n.id)
  838. return;
  839. // get the related l10n object
  840. var data = getL10nData(l10n.id, l10n.args);
  841. if (!data) {
  842. console.warn('#' + l10n.id + ' is undefined.');
  843. return;
  844. }
  845. // translate element (TODO: security checks?)
  846. if (data[gTextProp]) { // XXX
  847. if (getChildElementCount(element) === 0) {
  848. element[gTextProp] = data[gTextProp];
  849. } else {
  850. // this element has element children: replace the content of the first
  851. // (non-empty) child textNode and clear other child textNodes
  852. var children = element.childNodes;
  853. var found = false;
  854. for (var i = 0, l = children.length; i < l; i++) {
  855. if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
  856. if (found) {
  857. children[i].nodeValue = '';
  858. } else {
  859. children[i].nodeValue = data[gTextProp];
  860. found = true;
  861. }
  862. }
  863. }
  864. // if no (non-empty) textNode is found, insert a textNode before the
  865. // first element child.
  866. if (!found) {
  867. var textNode = document.createTextNode(data[gTextProp]);
  868. element.insertBefore(textNode, element.firstChild);
  869. }
  870. }
  871. delete data[gTextProp];
  872. }
  873. for (var k in data) {
  874. element[k] = data[k];
  875. }
  876. }
  877. // webkit browsers don't currently support 'children' on SVG elements...
  878. function getChildElementCount(element) {
  879. if (element.children) {
  880. return element.children.length;
  881. }
  882. if (typeof element.childElementCount !== 'undefined') {
  883. return element.childElementCount;
  884. }
  885. var count = 0;
  886. for (var i = 0; i < element.childNodes.length; i++) {
  887. count += element.nodeType === 1 ? 1 : 0;
  888. }
  889. return count;
  890. }
  891. // translate an HTML subtree
  892. function translateFragment(element) {
  893. element = element || document.documentElement;
  894. // check all translatable children (= w/ a `data-l10n-id' attribute)
  895. var children = getTranslatableChildren(element);
  896. var elementCount = children.length;
  897. for (var i = 0; i < elementCount; i++) {
  898. translateElement(children[i]);
  899. }
  900. // translate element itself if necessary
  901. translateElement(element);
  902. }
  903. return {
  904. // get a localized string
  905. get: function (key, args, fallbackString) {
  906. var index = key.lastIndexOf('.');
  907. var prop = gTextProp;
  908. if (index > 0) { // An attribute has been specified
  909. prop = key.substr(index + 1);
  910. key = key.substring(0, index);
  911. }
  912. var fallback;
  913. if (fallbackString) {
  914. fallback = {};
  915. fallback[prop] = fallbackString;
  916. }
  917. var data = getL10nData(key, args, fallback);
  918. if (data && prop in data) {
  919. return data[prop];
  920. }
  921. return '{{' + key + '}}';
  922. },
  923. // debug
  924. getData: function () {
  925. return gL10nData;
  926. },
  927. getText: function () {
  928. return gTextData;
  929. },
  930. // get|set the document language
  931. getLanguage: function () {
  932. return gLanguage;
  933. },
  934. setLanguage: function (lang, callback) {
  935. loadLocale(lang, function () {
  936. if (callback)
  937. callback();
  938. translateFragment();
  939. });
  940. },
  941. // get the direction (ltr|rtl) of the current language
  942. getDirection: function () {
  943. // http://www.w3.org/International/questions/qa-scripts
  944. // Arabic, Hebrew, Farsi, Pashto, Urdu
  945. var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
  946. var shortCode = gLanguage.split('-', 1)[0];
  947. return (rtlList.indexOf(shortCode) >= 0) ? 'rtl' : 'ltr';
  948. },
  949. // translate an element or document fragment
  950. translate: translateFragment,
  951. // this can be used to prevent race conditions
  952. getReadyState: function () {
  953. return gReadyState;
  954. },
  955. ready: function (callback) {
  956. if (!callback) {
  957. return;
  958. } else if (gReadyState == 'complete' || gReadyState == 'interactive') {
  959. window.setTimeout(function () {
  960. callback();
  961. });
  962. } else if (document.addEventListener) {
  963. document.addEventListener('localized', function once() {
  964. document.removeEventListener('localized', once);
  965. callback();
  966. });
  967. }
  968. }
  969. };
  970. })(window, document);