summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/stringbundle.js
blob: 9a19ffc47fee3f420eaa98a4265c3a3e62a1cce5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

// This is loaded into chrome windows with the subscript loader. Wrap in
// a block to prevent accidentally leaking globals onto `window`.
{
  class MozStringbundle extends MozXULElement {
    get stringBundle() {
      if (!this._bundle) {
        try {
          this._bundle = Services.strings.createBundle(this.src);
        } catch (e) {
          dump("Failed to get stringbundle:\n");
          dump(e + "\n");
        }
      }
      return this._bundle;
    }

    set src(val) {
      this._bundle = null;
      this.setAttribute("src", val);
    }

    get src() {
      return this.getAttribute("src");
    }

    get strings() {
      // Note: this is a sucky method name! Should be:
      //       readonly attribute nsISimpleEnumerator strings;
      return this.stringBundle.getSimpleEnumeration();
    }

    getString(aStringKey) {
      try {
        return this.stringBundle.GetStringFromName(aStringKey);
      } catch (e) {
        dump(
          "*** Failed to get string " +
            aStringKey +
            " in bundle: " +
            this.src +
            "\n"
        );
        throw e;
      }
    }

    getFormattedString(aStringKey, aStringsArray) {
      try {
        return this.stringBundle.formatStringFromName(
          aStringKey,
          aStringsArray
        );
      } catch (e) {
        dump(
          "*** Failed to format string " +
            aStringKey +
            " in bundle: " +
            this.src +
            "\n"
        );
        throw e;
      }
    }
  }

  customElements.define("stringbundle", MozStringbundle);
}