-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathl10n.js
95 lines (89 loc) · 2.93 KB
/
l10n.js
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
/**
* Translates a HTMl page in the web l10n style from the Add-on SDK with
* WebExtensions strings.
* Large parts of the logic are very similar to the SDK implmentation.
* All you have to do to use this in a document is load it.
*
* @license MPL-2.0
* @author Martin Giger
*/
function translateElementAttributes(element) {
const attributeList = new Set([
'abbr',
'alt',
'content',
'download',
'label',
'placeholder',
'srcdoc',
'style',
'title',
'value',
]),
ariaAttributeMap = {
'aria-label': 'ariaLabel',
'aria-value-text': 'ariaValueText',
'aria-moz-hint': 'ariaMozHint',
},
attributeSeparator = '_',
presentAttributes = element.dataset.l10nAttrs.split(",");
// Translate allowed attributes.
for(const attribute of presentAttributes) {
let data;
if(attributeList.has(attribute)) {
data = browser.i18n.getMessage(element.dataset.l10nId + attributeSeparator + attribute);
}
// Translate ARIA attributes
else if(attribute in ariaAttributeMap) {
data = browser.i18n.getMessage(element.dataset.l10nId + attributeSeparator + ariaAttributeMap[attribute]);
}
if(data && data != "??") {
element.setAttribute(attribute, data);
}
}
}
const C_TRANSLATE_VALUES = new Set([
'yes',
'no',
]);
function getTranslateState(element) {
if(element.hasAttribute("translate") && C_TRANSLATE_VALUES.has(element.getAttribute("translate"))) {
return element.getAttribute("translate");
}
const closestTranslate = element.closest('[translate]:not([translate="inherit"])');
if(closestTranslate) {
return closestTranslate.getAttribute("translate");
}
return "yes";
}
function translateElement(element = document) {
// Set the language attribute of the document.
if(element === document) {
document.documentElement.setAttribute("lang", browser.i18n.getUILanguage().replace("_", "-"));
}
// Get all children that are marked as being translateable.
const children = element.querySelectorAll('*[data-l10n-id]:not([translate="no"])');
for(const child of children) {
if(getTranslateState(child) !== "no") {
if(!child.dataset.hasOwnProperty("l10nNocontent")) {
const data = browser.i18n.getMessage(child.dataset.l10nId);
if(data && data != "??") {
child.textContent = data;
}
}
if(child.dataset.l10nAttrs) {
translateElementAttributes(child);
}
}
}
}
if(document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", () => translateElement(), {
capture: false,
passive: true,
once: true,
});
}
else {
translateElement();
}