-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathkatakana-terminator.user.js
295 lines (263 loc) · 9.42 KB
/
katakana-terminator.user.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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// ==UserScript==
// @name Katakana Terminator
// @description Convert gairaigo (Japanese loan words) back to English
// @author Arnie97
// @license MIT
// @copyright 2017-2024, Katakana Terminator Contributors (https://github.com/Arnie97/katakana-terminator/graphs/contributors)
// @namespace https://github.com/Arnie97
// @homepageURL https://github.com/Arnie97/katakana-terminator
// @supportURL https://greasyfork.org/scripts/33268/feedback
// @icon https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-Ruby.png
// @match *://*/*
// @exclude *://*.bilibili.com/video/*
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @connect translate.google.cn
// @connect translate.google.com
// @connect translate.googleapis.com
// @version 2024.05.05
// @name:ja-JP カタカナターミネーター
// @name:zh-CN 片假名终结者
// @description:zh-CN 在网页中的日语外来语上方标注英文原词
// ==/UserScript==
// define some shorthands
var _ = document;
var queue = {}; // {"カタカナ": [rtNodeA, rtNodeB]}
var cachedTranslations = {}; // {"ターミネーター": "Terminator"}
var newNodes = [_.body];
// Recursively traverse the given node and its descendants (Depth-first search)
function scanTextNodes(node) {
// The node could have been detached from the DOM tree
if (!node.parentNode || !_.body.contains(node)) {
return;
}
// Ignore text boxes and echoes
var excludeTags = {ruby: true, script: true, select: true, textarea: true};
switch (node.nodeType) {
case Node.ELEMENT_NODE:
if (node.tagName.toLowerCase() in excludeTags || node.isContentEditable) {
return;
}
return Array.from(node.childNodes).forEach(scanTextNodes);
case Node.TEXT_NODE:
while ((node = addRuby(node)));
}
}
// Recursively add ruby tags to text nodes
// Inspired by http://www.the-art-of-web.com/javascript/search-highlight/
function addRuby(node) {
var katakana = /[\u30A1-\u30FA\u30FD-\u30FF][\u3099\u309A\u30A1-\u30FF]*[\u3099\u309A\u30A1-\u30FA\u30FC-\u30FF]|[\uFF66-\uFF6F\uFF71-\uFF9D][\uFF65-\uFF9F]*[\uFF66-\uFF9F]/, match;
if (!node.nodeValue || !(match = katakana.exec(node.nodeValue))) {
return false;
}
var ruby = _.createElement('ruby');
ruby.appendChild(_.createTextNode(match[0]));
var rt = _.createElement('rt');
rt.classList.add('katakana-terminator-rt');
ruby.appendChild(rt);
// Append the ruby title node to the pending-translation queue
queue[match[0]] = queue[match[0]] || [];
queue[match[0]].push(rt);
// <span>[startカナmiddleテストend]</span> =>
// <span>start<ruby>カナ<rt data-rt="Kana"></rt></ruby>[middleテストend]</span>
var after = node.splitText(match.index);
node.parentNode.insertBefore(ruby, after);
after.nodeValue = after.nodeValue.substring(match[0].length);
return after;
}
// Split word list into chunks to limit the length of API requests
function translateTextNodes() {
var apiRequestCount = 0;
var phraseCount = 0;
var chunkSize = 200;
var chunk = [];
for (var phrase in queue) {
phraseCount++;
if (phrase in cachedTranslations) {
updateRubyByCachedTranslations(phrase);
continue;
}
chunk.push(phrase);
if (chunk.length >= chunkSize) {
apiRequestCount++;
translate(chunk, apiList);
chunk = [];
}
}
if (chunk.length) {
apiRequestCount++;
translate(chunk, apiList);
}
if (phraseCount) {
console.debug('Katakana Terminator:', phraseCount, 'phrases translated in', apiRequestCount, 'requests, frame', window.location.href);
}
}
// {"keyA": 1, "keyB": 2} => "?keyA=1&keyB=2"
function buildQueryString(params) {
return '?' + Object.keys(params).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');
}
function translate(phrases) {
if (!apiList.length) {
console.error('Katakana Terminator: fallbacks exhausted', phrases);
phrases.forEach(function(phrase) {
delete cachedTranslations[phrase];
});
}
// Prevent duplicate HTTP requests before the request completes
phrases.forEach(function(phrase) {
cachedTranslations[phrase] = null;
});
var api = apiList[0];
GM_xmlhttpRequest({
method: "GET",
url: 'https://' + api.hosts[0] + api.path + buildQueryString(api.params(phrases)),
onload: function(dom) {
try {
api.callback(phrases, JSON.parse(dom.responseText.replace("'", '\u2019')));
} catch (err) {
console.error('Katakana Terminator: invalid response', err, dom.responseText);
apiList.shift();
return translate(phrases);
}
},
onerror: function() {
console.error('Katakana Terminator: request error', api.url);
apiList.shift();
return translate(phrases);
},
});
}
var apiList = [
{
// https://github.com/Arnie97/katakana-terminator/pull/8
name: 'Google Translate',
hosts: ['translate.googleapis.com'],
path: '/translate_a/single',
params: function(phrases) {
var joinedText = phrases.join('\n').replace(/\s+$/, '');
return {
sl: 'ja',
tl: 'en',
dt: 't',
client: 'gtx',
q: joinedText,
};
},
callback: function(phrases, resp) {
resp[0].forEach(function(item) {
var translated = item[0].replace(/\s+$/, ''),
original = item[1].replace(/\s+$/, '');
cachedTranslations[original] = translated;
updateRubyByCachedTranslations(original);
});
},
},
{
// https://github.com/ssut/py-googletrans/issues/268
name: 'Google Dictionary',
hosts: ['translate.google.cn'],
path: '/translate_a/t',
params: function(phrases) {
var joinedText = phrases.join('\n').replace(/\s+$/, '');
return {
sl: 'ja',
tl: 'en',
dt: 't',
client: 'dict-chrome-ex',
q: joinedText,
};
},
callback: function(phrases, resp) {
// ["katakana\nterminator"]
if (!resp.sentences) {
var translated = resp[0].split('\n');
if (translated.length !== phrases.length) {
throw [phrases, resp];
}
translated.forEach(function(trans, i) {
var orig = phrases[i];
cachedTranslations[orig] = trans;
updateRubyByCachedTranslations(orig);
});
return;
}
resp.sentences.forEach(function(s) {
if (!s.orig) {
return;
}
var original = s.orig.trim(),
translated = s.trans.trim();
cachedTranslations[original] = translated;
updateRubyByCachedTranslations(original);
});
},
},
];
// Clear the pending-translation queue
function updateRubyByCachedTranslations(phrase) {
if (!cachedTranslations[phrase]) {
return;
}
(queue[phrase] || []).forEach(function(node) {
node.dataset.rt = cachedTranslations[phrase];
});
delete queue[phrase];
}
// Watch newly added DOM nodes, and save them for later use
function mutationHandler(mutationList) {
mutationList.forEach(function(mutationRecord) {
mutationRecord.addedNodes.forEach(function(node) {
newNodes.push(node);
});
});
}
function main() {
GM_addStyle("rt.katakana-terminator-rt::before { content: attr(data-rt); }");
var observer = new MutationObserver(mutationHandler);
observer.observe(_.body, {childList: true, subtree: true});
function rescanTextNodes() {
// Deplete buffered mutations
mutationHandler(observer.takeRecords());
if (!newNodes.length) {
return;
}
console.debug('Katakana Terminator:', newNodes.length, 'new nodes were added, frame', window.location.href);
newNodes.forEach(scanTextNodes);
newNodes.length = 0;
translateTextNodes();
}
// Limit the frequency of API requests
rescanTextNodes();
setInterval(rescanTextNodes, 500);
}
// Polyfill for Greasemonkey 4
if (typeof GM_xmlhttpRequest === 'undefined' &&
typeof GM === 'object' && typeof GM.xmlHttpRequest === 'function') {
GM_xmlhttpRequest = GM.xmlHttpRequest;
}
if (typeof GM_addStyle === 'undefined') {
GM_addStyle = function(css) {
var head = _.getElementsByTagName('head')[0];
if (!head) {
return null;
}
var style = _.createElement('style');
style.setAttribute('type', 'text/css');
style.textContent = css;
head.appendChild(style);
return style;
};
}
// Polyfill for ES5
if (typeof NodeList.prototype.forEach === 'undefined') {
NodeList.prototype.forEach = function(callback, thisArg) {
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
main();