aboutsummaryrefslogtreecommitdiff
path: root/yomichan-user/conf.d/word-export.js
blob: de036e4ff4d739ef715203d79020e1d512b4db4e (plain)
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
function exportWord(entry) {
	var wordElement = entry.getElementsByClassName("headword-term")[0];
	var hasKanji = false;

	function addWord(reading) {
		var out = "";
		for (var child of wordElement.childNodes) {
			if (child.nodeName == "#text") out += child.textContent;
			if (child.nodeName == "RUBY") {
				hasKanji = true;
				if (reading && out.length != 0) out += "\u30fb";
				out += rubyHelper(child, reading);
			}
		}
		return out;
	}
	var kanji = addWord(false);
	var reading = addWord(true);
	var result = `${kanji}`;
	if (hasKanji) result += `\u3010${reading}\u3011`;
	else result += " ";

	var tags = [];

	var pitchAccent = "";
	for (var tag of entry.getElementsByClassName("pronunciation-downstep-notation-number")) {
		pitchAccent = tag.innerText.trim();
		break;
	}
	if (pitchAccent) tags.push(`[${pitchAccent}]`);
	
	var usuallyKana = false;
	for (var tag of entry.getElementsByClassName("tag-label-content"))
		if (tag.innerText.trim() == "uk")
			usuallyKana = true;
	if (usuallyKana) tags.push("(uk)");

	result += tags.join(" ");

	escapeYomichanCopy(result);
}

function addWordCopyButtons() {
	var definitions = document.getElementById("dictionary-entries").getElementsByClassName("entry");
	for (var definition of definitions) {
		if (definition.classList.contains("patched")) continue;
		var actions = definition.getElementsByClassName("actions")[0];

		var button = document.createElement("button");
		button.classList.add("action-button");
		button.onclick = function() { exportWord(this.parentElement.parentElement.parentElement); };
		var icon = document.createElement("span");
		var title = "Copy definition (Alt + C)";
		icon.classList.add("icon");
		icon.classList.add("color-icon");
		icon.classList.add("action-icon");
		icon.setAttribute("data-icon", "copy-bmp");
		icon.setAttribute("title", title);
		icon.setAttribute("data-title-default", title);
		button.appendChild(icon);
		actions.insertBefore(button, actions.childNodes[0]);
		definition.classList.add("patched");
	}
}

(() => {
	window.addEventListener("message", ev => {
		// gets fired on search results render complete
		if (ev.data.action == "renderMulti.response")
			addWordCopyButtons();
	});
	window.addEventListener("keydown", ev => {
		if (ev.key != "c") return;
		if (ev.altKey != true) return;
		exportWord(document.getElementsByClassName("entry-current")[0]);
	});
})();