User:Dine2016/FindLemma.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

/* adapted from [[User:Yair rand/FindTrans.js]] and https://www.mediawiki.org/wiki/API:Embeddedin */
$(document).ready(function() {
	let title;
	
	if (document.body.classList.contains('ns-0')) {
		for (let className of document.body.classList) {
			if (className.startsWith('page-')) {
				title = className.slice(5).replace('_', ' ');
			}
		}
	} else if (mw.config.get("wgPageName") === "Special:Search") {
		let $a = $(".mw-search-createlink .new");
		if ($a.length === 0) {
			$a = $(".mw-search-createlink a");
		}
		if ($a.length !== 0) {
			title = $a.text();
		}
	}
	
	if (title) {
		const lemmas = [];
		
		var url = "https://en.wiktionary.org/w/api.php"; 
		
		var params = {
			action: "query",
			format: "json",
			list: "embeddedin",
			eititle: "Template:tracking/index/infl/ja/" + title,
			eilimit: "20"
		};
		
		url = url + "?origin=*";
		Object.keys(params).forEach(function(key){url += "&" + key + "=" + params[key];});
		
		fetch(url)
			.then(function(response){return response.json();})
			.then(function(response) {
				var pages = response.query.embeddedin;
				for (var p of pages) {
					lemmas.push(p.title);
				}
				const ja = (term) => `<span class="Jpan" lang="ja">${term}</span>`;
				const jaLink = (term) => `<span class="Jpan" lang="ja"><a href="/wiki/${term}#Japanese" title="${term}">${term}</a></span>`;
				
				if (lemmas.length) {
					let result = $('<div class="wikitable" style="padding: .6em;" />');
					let ul = $('<ul />')
					for (let lemma of lemmas) {
						if (lemma !== title) {
							result.append($(`<li>${ja(title)} is an inflected form of ${jaLink(lemma)}.</li>`));
						}
					}
					result.before(ul)
					if ($(".searchresults").length) {
						$('.searchresults').before(result);
					} else {
						$('#mw-content-text').before(result);
					}
				}
			})
			.catch(function(error){console.log(error);});
	}
});