-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgoogleTranslate-es6.js
209 lines (183 loc) · 6.48 KB
/
googleTranslate-es6.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
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
var googleTranslate = {
/**
* Config vars
*/
apiProxy: "",
translationNode: document.body,
observeMutationsOn: [],
nodeListSourceLanguage: [],
nodeListTextLanguage: [],
excludeElements: [],
mutatationIds: [],
sourceLanguage: "",
targetLanguage: "",
nodeList: [],
nodeTextList: [],
mutationNodeList: [],
mutationTextList: [],
/**
* Recursively traverse though DOM using a start node
* @param {object} el - start traversing at DOM node
* @param {arr} nodeList - array of DOM nodes
* @param {arr} nodeTextList - array of DOM node text
*/
traverseTextNodes: function(
el,
nodeList = this.nodeList,
nodeTextList = this.nodeTextList
) {
el.childNodes.forEach(
function(el) {
if (
!this.excludeElements.includes(el) &&
el.tagName !== "SCRIPT"
) {
// If this is a text node, replace the text
if (el.nodeType === 3 && el.nodeValue.trim() !== "") {
nodeList.push(el);
nodeTextList.push(el.nodeValue.trim());
} else {
this.traverseTextNodes(el, nodeList, nodeTextList);
}
}
}.bind(this)
);
},
/**
* Translate nodes (calls Google Translate API )
* @param {arr} nodeList - array containing list of nodes to be translated
* @param {arr} nodeTextList - array of text that requires translation
* @return {promise} - return a promise (resolve to a boolean value)
*/
translate: function(
nodeList = this.nodeList,
nodeTextList = this.nodeTextList
) {
var request = new XMLHttpRequest();
request.open("POST", this.apiProxy, true);
request.setRequestHeader(
"Content-Type",
"application/json;charset=UTF-8"
);
return new Promise(
function(resolve, reject) {
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = JSON.parse(this.response);
if (resp.error) {
console.log(resp.error);
resolve(false);
} else {
resp.translations.forEach(function(
translation,
index
) {
nodeList[index].nodeValue =
translation.translatedText;
});
resolve(true);
}
} else {
console.error("API Error: " + this.status);
resolve(false);
}
};
request.onerror = function() {
console.error("Could not connect to API.");
};
request.send(
JSON.stringify({
sourceLanguageCode: this.sourceLanguage,
targetLanguageCode: this.targetLanguage,
mimeType: "text/plain",
contents: nodeTextList
})
);
}.bind(this)
);
},
/**
* Observe mutations on a node & its children
* @param {object} targetNode - source node object
*/
mutationListener: function(targetNode) {
const config = {
childList: true,
subtree: true
};
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === "childList") {
var element = document.getElementById(mutation.target.id);
this.mutationNodeList = [];
this.mutationTextListList = [];
this.traverseTextNodes(
element,
this.mutationNodeList,
this.mutationTextListList
);
this.translate(
this.mutationNodeList,
this.mutationTextListList
);
}
}
}.bind(this);
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
},
/**
* Set target language by triggering translation API call
* Persist language preference to localStorage
* @param {string} langCode - language code in ISO format
* @return {promise} - return a promise (resolve to a boolean value)
*/
setTargetLanguage: function(langCode) {
localStorage.setItem("gTranslate_lang", langCode);
if (
langCode === this.sourceLanguage ||
this.mutationNodeList.length > 0
) {
location.reload();
return new Promise(function(resolve, reject) {
resolve(true);
});
}
this.targetLanguage = langCode;
return this.translate();
},
/**
* Initialize Google Translate
* @param {object} config - init config object
* @return {promise} - return a promise (resolve to a boolean value)
*/
init: function(config) {
//required
this.apiProxy = config.apiProxy;
this.sourceLanguage = config.sourceLanguage;
if (config.node !== undefined) {
this.translationNode = document.body;
}
if (config.excludeElements !== undefined) {
this.excludeElements = config.excludeElements;
}
this.traverseTextNodes(this.translationNode);
var targetLanguage = localStorage.getItem("gTranslate_lang");
//check lang pref. and set if different from src lang
if (targetLanguage !== null && targetLanguage !== this.sourceLanguage) {
return this.setTargetLanguage(targetLanguage);
} else {
return new Promise(function(resolve, reject) {
resolve(true);
});
}
//attach events
if (config.observeMutationsOn.length > 0) {
config.observeMutationsOn.forEach(
function(el) {
this.mutationListener(el);
}.bind(this)
);
}
}
};