-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathlib_message_manager.js
More file actions
245 lines (225 loc) · 7.58 KB
/
lib_message_manager.js
File metadata and controls
245 lines (225 loc) · 7.58 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2012 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {lib} from './lib.js';
/**
* MessageManager class handles internationalized strings.
*
* Note: chrome.i18n isn't sufficient because...
* 1. There's a bug in chrome that makes it unavailable in iframes:
* https://crbug.com/130200
* 2. The client code may not be packaged in a Chrome extension.
* 3. The client code may be part of a library packaged in a third-party
* Chrome extension.
*/
lib.MessageManager = class {
/**
* @param {!Array<string>} languages List of languages to load, in the order
* they are preferred. The first language found will be used. 'en' is
* automatically added as the last language if it is not already present.
* @param {boolean=} useCrlf If true, '\n' in messages are substituted for
* '\r\n'. This fixes the translation process which discards '\r'
* characters.
*/
constructor(languages, useCrlf = false) {
/**
* @private {!Array<string>}
* @const
*/
this.languages_ = [];
let stop = false;
for (let i = 0; i < languages.length && !stop; i++) {
for (const lang of lib.i18n.resolveLanguage(languages[i])) {
// There is no point having any language with lower priorty than 'en'
// since 'en' always contains all messages.
if (lang == 'en') {
stop = true;
break;
}
if (!this.languages_.includes(lang)) {
this.languages_.push(lang);
}
}
}
// Always have 'en' as last fallback.
this.languages_.push('en');
this.useCrlf = useCrlf;
/**
* @private {!Object<string, string>}
* @const
*/
this.messages_ = {};
}
/**
* Add message definitions to the message manager.
*
* This takes an object of the same format of a Chrome messages.json file.
* See <https://developer.chrome.com/extensions/i18n-messages>.
*
* @param {!lib.MessageManager.Messages} defs The message to add to the
* database.
*/
addMessages(defs) {
for (const key in defs) {
const def = defs[key];
if (!def.placeholders) {
// Upper case key into this.messages_ since our translated
// bundles are lower case, but we request msg as upper.
this.messages_[key.toUpperCase()] = def.message;
} else {
// Replace "$NAME$" placeholders with "$1", etc.
this.messages_[key.toUpperCase()] =
def.message.replace(/\$([a-z][^\s$]+)\$/ig, function(m, name) {
return defs[key].placeholders[name.toUpperCase()].content;
});
}
}
}
/**
* Load language message bundles. Loads in reverse order so that higher
* priority languages overwrite lower priority.
*
* @param {string} pattern A url pattern containing a "$1" where the locale
* name should go.
*/
async findAndLoadMessages(pattern) {
if (lib.i18n.browserSupported()) {
return;
}
for (let i = this.languages_.length - 1; i >= 0; i--) {
const lang = this.languages_[i];
const url = lib.i18n.replaceReferences(pattern, lang);
try {
await this.loadMessages(url);
} catch (e) {
console.warn(
`Error fetching ${lang} messages at ${url}`, e,
'Trying all languages in reverse order:', this.languages_);
}
}
}
/**
* Load messages from a messages.json file.
*
* @param {string} url The URL to load the messages from.
* @return {!Promise<void>}
*/
async loadMessages(url) {
const response = await fetch(url);
if (!response.ok) {
throw Error(`fetch failed: ${response.statusText}`, {cause: response});
}
this.addMessages(/** @type {!lib.MessageManager.Messages} */ (
await response.json()));
}
/**
* Get a message by name, optionally replacing arguments too.
*
* @param {string} msgname String containing the name of the message to get.
* @param {!Array<string>=} args Array containing the argument values.
* @param {string=} fallback Optional value to return if the msgname is not
* found. Returns the message name by default.
* @return {string} The formatted translation.
*/
get(msgname, args, fallback) {
// First try the integrated browser getMessage. We prefer that over any
// registered messages as only the browser supports translations.
let message = lib.i18n.getMessage(msgname, args);
if (!message) {
// Look it up in the registered cache next.
message = this.messages_[msgname];
if (!message) {
console.warn('Unknown message: ' + msgname);
message = fallback === undefined ? msgname : fallback;
// Register the message with the default to avoid multiple warnings.
this.messages_[msgname] = message;
}
message = lib.i18n.replaceReferences(message, args);
}
if (this.useCrlf) {
message = message.replace(/\n/g, '\r\n');
}
return message;
}
/**
* Process all of the "i18n" html attributes found in a given element.
*
* The real work happens in processI18nAttribute.
*
* @param {!HTMLDocument|!Element} node The element whose nodes will be
* translated.
*/
processI18nAttributes(node) {
const nodes = node.querySelectorAll('[i18n]');
for (let i = 0; i < nodes.length; i++) {
this.processI18nAttribute(nodes[i]);
}
}
/**
* Process the "i18n" attribute in the specified node.
*
* The i18n attribute should contain a JSON object. The keys are taken to
* be attribute names, and the values are message names.
*
* If the JSON object has a "_" (underscore) key, its value is used as the
* textContent of the element.
*
* Message names can refer to other attributes on the same element with by
* prefixing with a dollar sign. For example...
*
* <button id='send-button'
* i18n='{"aria-label": "$id", "_": "SEND_BUTTON_LABEL"}'
* ></button>
*
* The aria-label message name will be computed as "SEND_BUTTON_ARIA_LABEL".
* Notice that the "id" attribute was appended to the target attribute, and
* the result converted to UPPER_AND_UNDER style.
*
* @param {!Element} node The element to translate.
*/
processI18nAttribute(node) {
// Convert the "lower-and-dashes" attribute names into
// "UPPER_AND_UNDER" style.
const thunk = (str) => str.replace(/-/g, '_').toUpperCase();
let i18n = node.getAttribute('i18n');
if (!i18n) {
return;
}
try {
i18n = JSON.parse(i18n);
} catch (ex) {
console.error(`Can't parse ${node.tagName}#${node.id}: ${i18n}`);
throw ex;
}
// Load all the messages specified in the i18n attributes.
for (let key in i18n) {
// The node attribute we'll be setting.
const attr = key;
let msgname = i18n[key];
// For "=foo", re-use the referenced message name.
if (msgname.startsWith('=')) {
key = msgname.substr(1);
msgname = i18n[key];
}
// For "$foo", calculate the message name.
if (msgname.startsWith('$')) {
msgname = thunk(node.getAttribute(msgname.substr(1)) + '_' + key);
}
// Finally load the message.
const msg = this.get(msgname);
if (attr == '_') {
node.textContent = msg;
} else {
node.setAttribute(attr, msg);
}
}
}
};
/**
* @typedef {!Object<string, {
* message: string,
* description: (string|undefined),
* placeholders: ({content: string, example: string}|undefined),
* }>}
*/
lib.MessageManager.Messages;