-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
423 lines (372 loc) · 14.3 KB
/
main.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
Main processing handler for popup.html
*/
var main = (function () {
"use strict";
// this will be called when message listener fires
function onMessageListener(message, sender, sendResponse) { // eslint-disable-line no-unused-vars
if (message.messageType == "SyosetuGoogle-ParseResults") {
// convert the string returned from content script back into a DOM
let dom = new DOMParser().parseFromString(message.document, "text/html");
populateUiWithDom(message.url, dom);
} else if (message.messageType == "SyosetuGoogle-TranslatedText") {
Bing.onMessageListener(message);
}
};
// details
let initialWebPage = null;
let initialUrl = null;
let googleContent = null;
// register listener that is invoked when script injected into HTML sends its results
function addMessageListener() {
try {
// note, this will throw if not running as an extension.
if (!chrome.runtime.onMessage.hasListener(onMessageListener)) {
chrome.runtime.onMessage.addListener(onMessageListener);
}
} catch (chromeError) {
alert(chromeError);
}
}
function getActiveTabDOM(tabId) {
addMessageListener();
chrome.tabs.executeScript(tabId, { file: "ContentScript.js", runAt: "document_end" },
function (result) { // eslint-disable-line no-unused-vars
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
};
}
);
}
function isRunningInTabMode() {
// if query string supplied, we're running in Tab mode.
let search = window.location.search;
return !Util.isNullOrEmpty(search);
}
function populateUiWithDom(url, dom) {
initialWebPage = dom;
initialUrl = url;
if (isSyosetuUrl(url)) {
importTranslatedJapanese(dom);
addAuthorHeaderNoteDivider();
addAuthorNoteDivider();
return;
}
alert("Is not Syosetu!");
importFile(dom);
}
function enableControls() {
for(let button of document.querySelectorAll("button")) {
button.hidden = false;
}
}
function importTranslatedJapanese(dom) {
enableControls();
googleContent = extractChapterContent(dom);
let title = document.getElementById("title");
title.appendChild(Util.labelElementWithSource(googleContent.title, "google"));
let body = document.getElementById("body");
for(let p of googleContent.paragraphs) {
body.appendChild(Util.labelElementWithSource(p, "google"));
}
}
function addAuthorNoteDivider() {
let element = document.querySelector("p#La1");
if (element != null) {
let hr = document.createElement("hr");
element.parentElement.insertBefore(hr, element);
}
}
function addAuthorHeaderNoteDivider() {
let elements = [...document.querySelectorAll("p")]
.filter(p => p.id.startsWith("Lp"));
if (0 < elements.length) {
let element = elements[elements.length - 1];
let hr = document.createElement("hr");
element.parentElement.insertBefore(hr, element.nextSibling);
}
}
function importFile(dom) {
enableControls();
let content = dom.getElementById("Translated");
let oldContent = document.getElementById("Translated");
oldContent.parentElement.insertBefore(content, oldContent);
oldContent.remove();
}
function isSyosetuUrl(url) {
let parsed = new URL(url);
return parsed.hostname === "ncode.syosetu.com";
}
function extractChapterContent(dom) {
return {
title: cloneElement(dom.querySelector("div#novel_contents .novel_subtitle")),
paragraphs: [...dom.querySelectorAll("div#novel_p p, div#novel_honbun p, div#novel_a p")]
.map(p => cloneElement(p))
};
}
function cloneElement(element) {
return document.importNode(element, true);
}
function interleaveParagraps(japaneseDom) {
let japaneseContent = extractChapterContent(japaneseDom);
japaneseContent.title.id = "L0";
interleaveParagraph(japaneseContent.title, googleContent.title);
for(let jp of japaneseContent.paragraphs) {
let english = document.getElementById(jp.id);
if (english != null) {
interleaveParagraph(jp, english);
}
}
}
function interleaveParagraph(japanese, english) {
if (!Util.isNullOrEmpty(japanese.textContent)) {
let lebelled = Util.labelElementWithSource(japanese, "syosetu");
english.parentElement.insertBefore(lebelled, english);
japanese.setAttribute("lang", "jp");
english.setAttribute("lang", "en");
english.setAttribute("orig", japanese.id);
english.removeAttribute("id");
}
}
function openTabWindow() {
// open new tab window, passing ID of open tab with content to convert to epub as query parameter.
getActiveTab().then(function (tabId) {
let url = chrome.extension.getURL("popup.html") + "?id=";
url += tabId;
chrome.tabs.create({ url: url });
window.close();
});
}
function getActiveTab() {
return new Promise(function (resolve, reject) {
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
if ((tabs != null) && (0 < tabs.length)) {
resolve(tabs[0].id);
} else {
reject();
};
});
});
}
function extractTabIdFromQueryParameter() {
let windowId = window.location.search.split("=")[1];
if (!Util.isNullOrEmpty(windowId)) {
return parseInt(windowId, 10);
}
}
function loadOriginalJapanese() {
return HttpClient.fetchOriginalJapanese(initialUrl)
.then(japaneseDom => interleaveParagraps(japaneseDom));
}
function saveToFile() {
let fileName = constructFileName();
let content = constructHtmlToSave();
return Download.save(content, fileName);
}
function constructFileName() {
if (initialUrl.startsWith("http")) {
return constructFileNameFromHttp();
}
return constructFileNameFromFile();
}
function constructFileNameFromFile() {
let split = initialUrl.split("/");
return split[split.length - 1];
}
function constructFileNameFromHttp() {
let split = initialUrl.split("/")
.filter(s => !Util.isNullOrEmpty(s));
let chapterNum = '000' + split[split.length - 1];
chapterNum = chapterNum.substring(chapterNum.length - 4);
return `chapter-${chapterNum}.html`;
}
function constructHtmlToSave() {
let dom = new DOMParser().parseFromString("<html><head><title></title>"+
"<style>table {border-collapse: collapse;} table, th, td {border: 1px solid black;}</style>"+
"</head><body></body></html>", "text/html");
let content = document.getElementById("Translated");
dom.body.appendChild(dom.importNode(content, true));
flattenFontElements(dom);
crudePrettyPrint(dom, dom.getRootNode().children[0], '', ' ');
let htmlAsText = [dom.all[0].outerHTML];
return new Blob(htmlAsText, {type : "text/html"});
}
function crudePrettyPrint(dom, element, indent, indentIncrement) {
let children = [...element.children];
for(let c of children) {
let newIdent = indent + indentIncrement;
indentElement(dom, c, newIdent);
crudePrettyPrint(dom, c, newIdent, indentIncrement);
}
}
function indentElement(dom, element, indent) {
let text = '\r\n' + indent;
let node = dom.createTextNode(text);
element.parentElement.insertBefore(node, element);
if (element.lastElementChild !== null) {
element.appendChild(dom.createTextNode(text));
}
}
function flattenFontElements(dom) {
let font = [...dom.querySelectorAll("font[style='vertical-align: inherit;']")]
.filter(f => f.querySelector("font") !== null);
for(let f of font) {
let pp = f.parentElement;
let subfont = [...f.querySelectorAll("font")];
if (1 == subfont.length) {
let node = dom.createTextNode(subfont[0].textContent);
pp.insertBefore(node, f);
} else {
for(let s of subfont) {
let node = dom.createElement("span");
node.textContent = s.textContent;
pp.insertBefore(node, f);
}
}
f.remove();
}
}
function toGrid() {
let rubbish = [...document.querySelectorAll("p span.source")];
rubbish.forEach(e => e.remove());
let paragraphs = [...document.querySelectorAll("#Translated p")];
let table = document.createElement("table");
let originalJapanese = "";
let originalId = "L0";
for(let p of paragraphs) {
originalId = setLastSeenId(p, originalId);
if (isOriginalJapanses(p)) {
originalJapanese = p.textContent.trim();
}
let row = createRow(p);
addRefToOriginalText(row, p, originalId);
table.appendChild(row);
if (row.getAttribute("source") == "bing") {
let newRow = table.appendChild(createRowForMyTranslation(originalJapanese));
addRefToOriginalText(newRow, p, originalId);
}
p.remove();
}
let translated = document.getElementById("Translated");
for(let c of [...translated.children]) {
c.remove();
}
translated.appendChild(table);
}
function setLastSeenId(paragraph, originalId) {
let id = paragraph.id;
return (id === "") ? originalId : id;
}
function addRefToOriginalText(row, p, originalId) {
if (!isOriginalJapanses(p)) {
row.setAttribute("orig", originalId);
}
}
function isOriginalJapanses(paragraph) {
let lang = paragraph.getAttribute("lang");
return lang === "jp";
}
function createRow(paragraph) {
let row = document.createElement("tr");
let td = document.createElement("td");
row.appendChild(td);
if ((paragraph.id != null) && isOriginalJapanses(paragraph)) {
row.id = paragraph.id;
}
let source = paragraph.getAttribute("source");
if (source != null) {
row.setAttribute("source", source);
row.setAttribute("lang", paragraph.getAttribute("lang"));
td.textContent = source;
}
td = document.createElement("td");
row.appendChild(td);
moveChildNodes(paragraph, td);
return row;
}
function moveChildNodes(from, to) {
while (from.hasChildNodes()) {
let node = from.childNodes[0];
to.appendChild(node);
};
}
function createRowForMyTranslation(originalJapanese) {
let row = document.createElement("tr");
let td = document.createElement("td");
row.appendChild(td);
td.textContent = "Mine";
td = document.createElement("td");
row.appendChild(td);
td.textContent = Language.notesForMyTranslation(originalJapanese);
row.className = "Edited";
return row;
}
function createBingRow() {
let row = document.createElement("tr");
row.className = "Bing";
let td = document.createElement("td");
td.textContent = "Bing";
row.appendChild(td);
td = document.createElement("td");
row.appendChild(td);
return row;
}
function makeFairyDoc() {
extractRows("tr[lang='jp'] td:nth-of-type(2), tr.Edited td:nth-of-type(2)");
}
function showMissedText() {
let finished = document.getElementById("Finished");
for(let cell of document.querySelectorAll("tr")) {
cell.hidden = true;
let td = cell.querySelector("td:nth-of-type(2)");
let text = td.textContent.trim();
if ((text === "") || (text === "「」")) {
cell.hidden = false;
}
}
}
function showMyTranslatedOnly() {
extractRows("tr.Edited td:nth-of-type(2)");
}
function extractRows(selector) {
let finished = document.getElementById("Finished");
for(let cell of document.querySelectorAll(selector)) {
finished.appendChild(document.createTextNode("\r\n"));
let p = document.createElement("p");
p.appendChild(document.createTextNode(cell.textContent));
finished.appendChild(p);
}
document.getElementById("controls").hidden = true;
document.getElementById("Translated").hidden = true;
}
function removeAuthorNote() {
let paragraphs = [...document.querySelectorAll("p")]
.filter(p => p.id.startsWith("La"));
for (let p of paragraphs) {
p.remove();
}
let hr = document.querySelector("hr");
if (hr != null) {
hr.remove();
}
}
function connectControls() {
document.getElementById("LoadOriginalJapanese").onclick = loadOriginalJapanese;
document.getElementById("LoadBing").onclick = Bing.doTranslation;
document.getElementById("SaveToFile").onclick = saveToFile;
document.getElementById("ToGrid").onclick = toGrid;
document.getElementById("ShowMyTranslatedOnly").onclick = showMyTranslatedOnly;
document.getElementById("MakeFairyDoc").onclick = makeFairyDoc;
document.getElementById("ShowMissedText").onclick = showMissedText;
document.getElementById("RemoveAuthorNote").onclick = removeAuthorNote;
}
// actions to do when window opened
window.onload = function () {
if (isRunningInTabMode()) {
connectControls();
getActiveTabDOM(extractTabIdFromQueryParameter());
} else {
openTabWindow();
}
}
})();