1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// TODO(arv): Namespace
6
7/**
8 * The local strings get injected into the page using a variable named
9 * {@code templateData}. This class provides a simpler interface to access those
10 * strings.
11 *
12 * @param {Object} opt_templateData Optional object containing translated
13 *     strings.  If this is not supplied during construction, it can be
14 *     assigned to the templateData property after construction.  If all else
15 *     fails, the value of window.templateDate will be used.
16 * @constructor
17 */
18function LocalStrings(opt_templateData) {
19  this.templateData = opt_templateData;
20}
21
22// Start of anonymous namespace.
23(function() {
24
25/**
26 * Returns a formatted string where $1 to $9 are replaced by the second to the
27 * tenth argument.
28 * @param {string} s The format string.
29 * @param {...string} The extra values to include in the formatted output.
30 * @return {string} The string after format substitution.
31 */
32function replaceArgs(s, args) {
33  return s.replace(/\$[$1-9]/g, function(m) {
34    return (m == '$$') ? '$' : args[m[1]];
35  });
36}
37
38/**
39 * Returns a string after removing Windows-style accelerators.
40 * @param {string} s The input string that may contain accelerators.
41 * @return {string} The resulting string with accelerators removed.
42 */
43function trimAccelerators(s) {
44  return s.replace(/&{1,2}/g, function(m) {
45    return (m == '&&') ? '&' : '';
46  });
47}
48
49LocalStrings.prototype = {
50  /**
51   * The template data object.
52   * @type {Object}
53   */
54  templateData: null,
55
56  /**
57   * Gets a localized string by its id.
58   * @param {string} s The ID of the string we want.
59   * @return {string} The localized string.
60   */
61  getString: function(id) {
62    // TODO(arv): We should not rely on a global variable here.
63    return (this.templateData || window.templateData)[id] || '';
64  },
65
66  /**
67   * Returns a formatted localized string where $1 to $9 are replaced by the
68   * second to the tenth argument.
69   * @param {string} id The ID of the string we want.
70   * @param {...string} The extra values to include in the formatted output.
71   * @return {string} The formatted string.
72   */
73  getStringF: function(id, var_args) {
74    return replaceArgs(this.getString(id), arguments);
75  },
76};
77
78// End of anonymous namespace.
79})();
80