fluent-l10n.js (2030B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const FluentReact = require("resource://devtools/client/shared/vendor/fluent-react.js"); 8 9 /** 10 * Wrapper over FluentReact. It encapsulates instantiation of the localization 11 * bundles, and offers a simpler way of accessing `getString`. 12 */ 13 class FluentL10n { 14 /** 15 * Initializes the wrapper, generating the bundles for the given resource ids. 16 * It can optionally add the right attributes to the document element. 17 * 18 * @param {Array} resourceIds 19 * @param {object} [options] 20 * @param {boolean} [options.setAttributesOnDocument] 21 */ 22 async init(resourceIds, { setAttributesOnDocument } = {}) { 23 if (setAttributesOnDocument) { 24 const primaryLocale = Services.locale.appLocalesAsBCP47[0]; 25 document.documentElement.setAttribute("lang", primaryLocale); 26 const direction = Services.locale.isAppLocaleRTL ? "rtl" : "ltr"; 27 document.documentElement.setAttribute("dir", direction); 28 } 29 30 const locales = Services.locale.appLocalesAsBCP47; 31 const generator = L10nRegistry.getInstance().generateBundles( 32 locales, 33 resourceIds 34 ); 35 36 this._bundles = []; 37 for await (const bundle of generator) { 38 this._bundles.push(bundle); 39 } 40 this._reactLocalization = new FluentReact.ReactLocalization(this._bundles); 41 } 42 43 /** 44 * Returns the fluent bundles generated. 45 */ 46 getBundles() { 47 return this._bundles; 48 } 49 50 /** 51 * Returns the localized string for the provided id, formatted using args. 52 */ 53 getString(...args) { 54 // Forward arguments via .apply() so that the original method can: 55 // - perform asserts based on the number of arguments 56 // - add new arguments 57 return this._reactLocalization.getString.apply( 58 this._reactLocalization, 59 args 60 ); 61 } 62 } 63 64 // Export the class 65 exports.FluentL10n = FluentL10n;