forked from rudnam/ZH-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_Mining_Back.html
712 lines (623 loc) · 21 KB
/
2_Mining_Back.html
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<!---------- Header ------------->
<header>
<div class="top-container">
<p class="stars"></p>
{{FreqSort}}
</div>
</header>
<main>
<div class="template">
<!--------- Vocab card ---------->
{{^*IsSentenceCard}}
<div lang="zh-Hant" class="show-furigana vocab">
{{#ExpressionFurigana}}{{furigana:ExpressionFurigana}}{{/ExpressionFurigana}}
{{^ExpressionFurigana}}{{Expression}}{{/ExpressionFurigana}}
</div>
{{#Hint}}
<div id="hint">{{Hint}}</div>
{{/Hint}}
<hr class="divider" />
<div lang="zh-Hant" class="info">
{{ExpressionAudio}} {{SentenceAudio}}
<div class="reading">
{{#ExpressionFurigana}}{{kana:ExpressionFurigana}}{{/ExpressionFurigana}}
{{^ExpressionFurigana}}{{ExpressionReading}}{{/ExpressionFurigana}}
</div>
【{{Expression}}】
</div>
<div lang="zh-Hant" class="main-def popup">
<div class="definition">{{MainDefinition}}</div>
<div class="def-info"></div>
</div>
<br />
<div class="image">{{Image}}</div>
<div lang="zh-Hant" class="small-sentence">
{{#SentenceFurigana}} {{furigana:SentenceFurigana}} {{/SentenceFurigana}}
{{^SentenceFurigana}} {{furigana:Sentence}} {{/SentenceFurigana}}
</div>
{{#Translation}}
<div class="translation" lang="en">{{hint:Translation}}</div>
{{/Translation}} {{/*IsSentenceCard}}
<!------- Sentence card --------->
{{#*IsSentenceCard}}
<div lang="zh-Hant" class="sentence">
{{#SentenceFurigana}} {{furigana:SentenceFurigana}} {{/SentenceFurigana}}
{{^SentenceFurigana}} {{furigana:Sentence}} {{/SentenceFurigana}}
</div>
{{#Hint}}
<div id="hint">{{Hint}}</div>
{{/Hint}} {{#Translation}}
<div class="translation" lang="en">{{hint:Translation}}</div>
{{/Translation}}
<hr class="divider" />
<div lang="zh-Hant" class="info">
{{ExpressionAudio}} {{SentenceAudio}}
<div class="reading">
{{#ExpressionFurigana}}{{kana:ExpressionFurigana}}{{/ExpressionFurigana}}
{{^ExpressionFurigana}}{{ExpressionReading}}{{/ExpressionFurigana}}
</div>
【{{Expression}}】
</div>
<div lang="zh-Hant" class="main-def popup">
<div class="definition">{{MainDefinition}}</div>
<div class="def-info"></div>
</div>
<br />
<div class="image">{{Image}}</div>
{{/*IsSentenceCard}}
<!------- Image modal --------->
<div class="modal-bg"></div>
<div class="img-popup"></div>
</div>
<div class="extras">
{{#MiscInfo}}
<div style="text-align: center">
<div lang="zh-Hant">
<details>
<summary>Misc. info</summary>
<div class="misc-info popup">
=== Details ===
<br />
{{MiscInfo}} {{#Frequency}}
<br />
== Frequency == {{Frequency}} {{/Frequency}}
</div>
</details>
</div>
</div>
{{/MiscInfo}} {{#FullDefinition}}
<div style="text-align: center">
<div lang="zh-Hant">
<details>
<summary>Full definition</summary>
<div class="full-def popup">{{FullDefinition}}</div>
</details>
</div>
</div>
{{/FullDefinition}}
</div>
</main>
<!----------- Footer ------------->
<footer>
<div class="bot-container">
{{#Tags}}
<div lang="zh-Hant" class="tags-container">
<div class="tags">{{Tags}}</div>
</div>
{{/Tags}}
<input type="checkbox" class="extras-toggle" />
</div>
</footer>
<!----------- Scripts ------------>
<script>
function setLanguage(language) {
document.documentElement.lang = language;
const elements = document.querySelectorAll('[lang="zh-Hant"]');
elements.forEach((element) => {
element.setAttribute("lang", language);
});
}
function decode_pinyin(pinyin) {
// From Destroyer862K2 in https://www.reddit.com/r/Anki/comments/i6rmp6/chinese_flashcards_automatic_coloring_according/
const core = ["a", "e", "i", "o", "u", "ü"];
let arr = pinyin.replace(/<b>|<\/b>|<div>|<\/div>/g, "").split("");
is_core = function (c, c_previous_two = "", c_next = "") {
//pre conditions
if (
c == "r" &&
(c_next == " " || c_next == "") &&
c_previous_two != " " &&
c_previous_two != ""
) {
return [true, true];
}
//pre conditions
c = c
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase();
for (let i = 0; i < core.length; i++) {
if (c === core[i]) {
return [true, false];
}
}
return [false, false];
};
get_tone = function (str) {
let pure = str.replace(/a|e|i|o|u|ü|r/g, "");
if (pure == "") {
return 5;
} else if (["ā", "ē", "ī", "ō", "ū", "ǖ"].includes(pure)) {
return 1;
} else if (["á", "é", "í", "ó", "ú", "ǘ"].includes(pure)) {
return 2;
} else if (["ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǚ"].includes(pure)) {
return 3;
} else if (["à", "è", "ì", "ò", "ù", "ǜ"].includes(pure)) {
return 4;
}
return pure;
};
let tones_arr = [];
let buff = [];
flush = function () {
if (buff.length > 0) {
tones_arr.push(get_tone(buff.join("")));
buff = [];
}
};
for (let i = 0; i < arr.length; i++) {
let res = is_core(arr[i], arr[i - 2], arr[i + 1]);
if (res[1]) {
flush();
}
if (res[0]) {
buff.push(arr[i]);
} else {
flush();
}
}
if (buff.length > 0) {
tones_arr.push(get_tone(buff.join("")));
buff = [];
}
return tones_arr;
}
function containsZhuyin(str) {
const zyChars =
"ˉˊˇˋ˙ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩㄪㄫㄬㄭㄮㄯ";
const zyRegex = new RegExp(`[${zyChars}]`);
return zyRegex.test(str);
}
function getTonePattern(reading) {
if (!containsZhuyin(reading)) {
console.log("pinyin reading, tone pattern:", decode_pinyin(reading));
return decode_pinyin(reading);
}
const separators = " '";
reading = [...reading]
.filter((c) => containsZhuyin(c) || separators.includes(c))
.join("");
const zyTones = {
ˉ: 1,
ˊ: 2,
ˇ: 3,
ˋ: 4,
"˙": 5,
};
const zyConsonants = "ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ";
const zyFalseInitials = "ㄨㄧㄩ";
const zySentence = `{{Sentence}}`;
let tonePattern = [];
let buff = [];
for (const char of reading) {
console.log(
char,
buff,
char in zyTones && buff.length > 0,
char === " " && buff.length > 0,
zyFalseInitials.includes(char) &&
buff.length > 0 &&
!(buff.length === 1 && zyConsonants.includes(buff[0])),
zyConsonants.includes(char) && buff.length > 0
);
if (char in zyTones && buff.length > 0) {
const isEr =
buff.length === 1 &&
buff[0] === "ㄦ" &&
char === "˙" &&
!zySentence.includes("兒");
const isZherr =
buff.length === 2 && char === "ˋ" && buff.join("") === "ㄓㄦ";
if (isEr) {
// pass
} else if (isZherr) {
tonePattern.push(zyTones[char]);
tonePattern.push(5);
} else {
tonePattern.push(zyTones[char]);
}
buff = [];
} else if (separators.includes(char) && buff.length > 0) {
tonePattern.push(1);
buff = [];
} else if (
zyFalseInitials.includes(char) &&
buff.length > 0 &&
!(buff.length === 1 && zyConsonants.includes(buff[0]))
) {
tonePattern.push(1);
buff = [char];
} else if (zyConsonants.includes(char) && buff.length > 0) {
tonePattern.push(1);
buff = [char];
} else {
if (!separators.includes(char)) {
buff.push(char);
}
}
}
if (buff.length > 0) tonePattern.push(1);
console.log("zhuyin reading, tone pattern:", tonePattern);
return tonePattern;
}
function addToneColor(tonePattern, targetWordEl) {
const innerText = targetWordEl.innerText.split("");
let newInnerHtml = "";
if (tonePattern.length === targetWordEl.innerText.length) {
for (let i = 0; i < tonePattern.length; i++) {
newInnerHtml += `<span class="tone${tonePattern[i]}">${innerText[i]}</span>`;
}
} else {
return;
}
targetWordEl.innerHTML = newInnerHtml;
}
function paintTargetWord() {
const wordTranscription = `{{ExpressionReading}}`;
if (!wordTranscription) return;
const tonePattern = getTonePattern(wordTranscription);
const sentences = Array.from(
document.querySelectorAll(".sentence, .small-sentence")
);
for (const sentence of sentences) {
for (const targetWord of sentence.getElementsByTagName("b")) {
addToneColor(tonePattern, targetWord);
}
}
const vocabElement = document.querySelector(".vocab ruby rb");
if (vocabElement !== null) {
addToneColor(tonePattern, vocabElement);
}
}
function tweakHTML() {
// Modify translation button label
const tlButton = document.querySelector(".translation > a.hint");
if (tlButton) {
tlButton.innerText = "Show Translation";
}
// Split tags
const tagsContainer = document.querySelector(".tags-container");
const tags = `{{Tags}}`.split(" ");
if (tagsContainer) {
tagsContainer.innerHTML = "";
for (tag of tags) {
const tagElem = document.createElement("div");
tagElem.className = "tags";
tagElem.innerText = tag;
tagsContainer.appendChild(tagElem);
}
}
// Get stars
const freq = Number(`{{FreqSort}}`);
const stars = document.querySelector(".stars");
if (freq > 0 && freq < 1500) stars.innerText = "★★★★★";
else if (freq >= 1500 && freq < 5000) stars.innerText = "★★★★";
else if (freq >= 5000 && freq < 15000) stars.innerText = "★★★";
else if (freq >= 15000 && freq < 30000) stars.innerText = "★★";
else if (freq >= 30000 && freq < 60000) stars.innerText = "★";
else stars.innerText = "";
if (freq === 0) document.querySelector(".top-container").innerHTML = "";
// Toggle extras display
const checkBox = document.querySelector(".extras-toggle");
const extras = document.querySelector(".extras");
checkBox.addEventListener("change", (e) => {
extras.style.display = checkBox.checked ? "block" : "none";
});
extras.style.display = checkBox.checked ? "block" : "none";
}
function cleanDictDef(element) {
let cleanedElement = element.cloneNode(true);
const hide = (selector) => {
const target = cleanedElement.querySelector(selector);
if (target) target.style.display = "none";
};
const containsText = (text) => cleanedElement.innerHTML.includes(text);
// Remove headword
hide("*[data-sc-cccedict='headword']");
if (
cleanedElement.querySelector(
"span+div[data-sc-name='definition'], span+div[data-sc-name='意味']"
)
) {
hide(":scope > span > span");
}
// } else {
// const regex = /(<i>.*?<\/i>)(.*?)(<br>)/;
// cleanedElement.innerHTML = cleanedElement.innerHTML.replace(regex, "");
// }
// Remove dict name
hide(":scope > i:first-child");
// Remove images
const minImageWidthEm = 130;
cleanedElement.querySelectorAll("a > span > img").forEach((img) => {
const anchor = img.closest("a");
const width = parseFloat(img.parentNode.style.width.replace("em", ""));
if (width > minImageWidthEm) {
anchor.remove();
} else {
anchor.removeAttribute("href");
}
});
// Remove extra newlines, etc.
cleanedElement.innerHTML = cleanedElement.innerHTML
.replace(/(<br>\s*)+/gi, "<br>")
.replace(/^<br\s*\/?>|<br\s*\/?>$/g, "")
.replace("筆順:", "");
Array.from(cleanedElement.children).forEach((e) => {
e.innerHTML = e.innerHTML.replace(/^<br\s*\/?>|<br\s*\/?>$/g, "");
});
return cleanedElement;
}
function createDictDef(dictEntry) {
const dictDefContainer = document.createElement("div");
dictDefContainer.classList.add("dict-def");
const textContainer = document.createElement("div");
textContainer.classList.add("text-container");
const imagesContainer = document.createElement("div");
imagesContainer.classList.add("images-container");
const minImageWidthEm = 131;
dictEntry.querySelectorAll("a > span > img").forEach((img) => {
let width = parseFloat(img.parentNode.style.width.replace("em", ""));
if (width > minImageWidthEm) {
const image = document.createElement("img");
const anchor = img.closest("a");
image.src = img.src;
imagesContainer.appendChild(image);
}
});
const ul = dictEntry.querySelector(":scope > ul");
const cleanedElement = cleanDictDef(
ul !== null ? ul.querySelector("li") : dictEntry
);
textContainer.innerHTML = cleanedElement.innerHTML;
dictDefContainer.appendChild(textContainer);
dictDefContainer.appendChild(imagesContainer);
return dictDefContainer;
}
function createCedictDef(cedictEntries) {
const cedictDefContainer = document.createElement("div");
cedictDefContainer.classList.add("cedict-def");
let newHtml = cedictEntries
.map((dictEntry) => {
const ul = dictEntry.querySelector("ul");
if (ul !== null) {
return cedictEntries.length > 1
? `<li>${ul.outerHTML}</li>`
: ul.outerHTML;
} else {
const innerText = Array.from(dictEntry.childNodes)
.filter((node) => node.nodeType === Node.TEXT_NODE)
.map((node) => node.textContent.trim())
.join(" ");
return cedictEntries.length > 1 ? `<li>${innerText}</li>` : innerText;
}
})
.join("");
if (cedictEntries.length > 1) {
newHtml = `<ol>${newHtml}</ol>`;
}
cedictDefContainer.innerHTML = newHtml;
return cedictDefContainer;
}
function createDefinition(dictName) {
if (isJidoujisho || dictName.toLowerCase().includes("maindefinition")) {
return dictEntries[dictName];
} else if (dictName.toLowerCase().includes("cedict")) {
let cedictEntries = [];
Object.entries(dictEntries).forEach(([name, entry]) => {
if (name.toLowerCase().includes("cedict") && !name.includes("forms")) {
cedictEntries.push(entry);
}
});
return createCedictDef(cedictEntries);
} else {
return createDictDef(dictEntries[dictName]);
}
}
function initializeDef(priorityDicts, ignoredDicts) {
isJidoujisho = `{{Tags}}`.includes("Yuuna");
const fullDefContainer = document.querySelector(".full-def");
const definitionContainer = document.querySelector(
".main-def > .definition"
);
const liEntries = fullDefContainer.querySelectorAll(
":scope > div > ol > li"
);
const allEntries =
liEntries.length > 0
? liEntries
: [fullDefContainer.querySelector("div")];
dictEntries = Array.from(allEntries).reduce((entries, entry) => {
let dictName;
if (entry?.querySelector(":scope > i:first-child")) {
dictName = entry.querySelector(":scope > i:first-child").innerText;
} else if (isJidoujisho) {
dictName = "Jidoujisho";
} else {
dictName = "FullDefinition";
}
let newName = dictName;
let ctr = 2;
if (ignoredDicts.some((name) => newName.includes(name))) {
// skip
} else if (newName === "Jidoujisho") {
const jidoujishoEntries = `{{FullDefinition}}`.split("<br><br>");
jidoujishoEntries.forEach((entry) => {
const match = /(?<!\S)【(.*?)】<br>/.exec(entry);
if (match) {
dictName = `(${match[1]})`;
newName = `(${match[1]})`;
entry = entry.replace(`【${match[1]}】<br>`, "");
}
const match2 = /^(.*?)<br>/.exec(entry);
if (
match2 &&
`{{ExpressionReading}}`
.split("")
.every((char) => match2[1].includes(char))
) {
entry = entry.replace(/.*?<br>/i, "");
}
while (Object.keys(entries).includes(newName)) {
newName = `${dictName}-${ctr}`;
ctr += 1;
}
const jidouDiv = document.createElement("div");
jidouDiv.innerHTML = entry;
jidouDiv.classList.add("dict-def");
entries[newName] = jidouDiv;
});
} else if (newName === "FullDefinition") {
const fullDefDiv = document.createElement("div");
fullDefDiv.innerHTML = `{{FullDefinition}}`;
entries[newName] = fullDefDiv;
} else {
while (Object.keys(entries).includes(newName)) {
newName = `${dictName}-${ctr}`;
ctr += 1;
}
entries[newName] = entry;
}
return entries;
}, {});
if (`{{MainDefinition}}`) {
const mainDefDiv = document.createElement("div");
mainDefDiv.innerHTML = `{{MainDefinition}}`;
dictEntries["MainDefinition"] = mainDefDiv;
}
dictNames = Object.keys(dictEntries);
if (
!isJidoujisho &&
dictNames.toString().toLowerCase().includes("cedict")
) {
dictNames = dictNames.filter(
(name) => !name.toLowerCase().includes("cedict")
);
// dictNames.unshift("(Cedict)");
}
if (priorityDicts) {
dictNames = dictNames.sort((a, b) => {
const indexA = priorityDicts.findIndex((item) =>
a.toLowerCase().includes(item.toLowerCase())
);
const indexB = priorityDicts.findIndex((item) =>
b.toLowerCase().includes(item.toLowerCase())
);
if (indexA === -1 && indexB === -1) return 0;
else if (indexA === -1) return 1;
else if (indexB === -1) return -1;
return indexA - indexB;
});
}
definitionContainer.innerHTML = "";
definitionContainer.appendChild(createDefinition(dictNames[0]));
}
function toggleDef(index) {
const definitionContainer = document.querySelector(
".main-def > .definition"
);
const indexDisplay = document.querySelector(".def-info");
indexDisplay.style.opacity = 1;
currentIndex = index % dictNames.length;
while (currentIndex < 0) currentIndex += dictNames.length;
indexDisplay.innerText = `${dictNames[currentIndex]} ${currentIndex + 1}/${
dictNames.length
}`;
definitionContainer.innerHTML = "";
definitionContainer.appendChild(createDefinition(dictNames[currentIndex]));
}
function setUpDefToggle() {
const mainDefContainer = document.querySelector(".main-def");
const leftEdge = document.createElement("div");
const rightEdge = document.createElement("div");
leftEdge.classList.add("left-edge");
rightEdge.classList.add("right-edge");
mainDefContainer.appendChild(leftEdge);
mainDefContainer.appendChild(rightEdge);
let index = 0;
leftEdge.addEventListener("click", (e) => {
index -= 1;
toggleDef(index);
});
rightEdge.addEventListener("click", (e) => {
index += 1;
toggleDef(index);
});
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") index -= 1;
else if (e.key === "ArrowRight") index += 1;
toggleDef(index);
});
}
function setUpImageModal() {
const modalBg = document.querySelector(".modal-bg");
const imgPopup = document.querySelector(".img-popup");
const image = document.querySelector(".image img");
if (!image) return;
image.addEventListener("click", () => {
const imgPopupContainer = document.createElement("div");
const imgPopupImg = document.createElement("img");
imgPopupContainer.classList.add("img-popup-container");
imgPopupImg.src = image.src;
imgPopupImg.classList.add("img-popup-img");
if (image.height > image.width) {
imgPopupContainer.style.height = "calc(100% - 20px)";
imgPopupContainer.style.width = "max-content";
}
imgPopup.innerHTML = "";
imgPopup.appendChild(imgPopupContainer);
imgPopupContainer.appendChild(imgPopupImg);
document.body.classList.add("img-popup");
modalBg.style.display = "block";
imgPopupContainer.style.display = "flex";
});
modalBg.addEventListener("click", () => {
document.body.classList.remove("img-popup");
modalBg.style.display = "none";
imgPopup.innerHTML = "";
});
}
function initialize() {
// Global vars
let isJidoujisho;
let dictEntries;
let dictNames;
// Set to "zh-Hans" for Simplified Chinese
const language = "zh-Hant";
setLanguage(language);
tweakHTML();
paintTargetWord();
setUpImageModal();
setUpDefToggle();
let priorityDicts = [
"MainDefinition",
"CC-CEDICT",
"Wenlin ABC",
"中日大辞典",
];
let ignoredDicts = ["子", "句", "造"];
initializeDef(priorityDicts, ignoredDicts);
}
initialize();
</script>