User:Erutuon/scripts/searchLang.js

/* jshint boss: true, esversion: 6, latedef: true, loopfunc: true, undef: true, unused: true, varstmt: true */ /* globals $, mw */

$.getScript("//en.wiktionary.org/w/index.php?title=User:Erutuon/scripts/apiWrapper.js&action=raw") .done(function { $.when( $.getScript("//en.wiktionary.org/w/index.php?title=User:Erutuon/scripts/LanguageSearcher.js&action=raw"), mw.loader.using([ "mediawiki.util", "mediawiki.storage" ]) ).done(function { "use strict";

if (!(window.LanguageSearcher && mw.util && mw.storage)) return console.error("failed to load necessary stuff");

function clearChildren(element) { if (!(element instanceof Node)) throw new TypeError("Expected Node"); let child; while (child = element.firstChild) element.removeChild(child); }

function newSidebarBox(idPrefix, nextElementId) { const box = document.createElement("div"); box.id = idPrefix; box.className = "portlet";

const header = document.createElement("h3"); header.id = idPrefix + "-label";

const body = document.createElement("div"); body.className = "pBody";

box.appendChild(header); box.appendChild(body); if (nextElementId) { const nextElement = document.getElementById(nextElementId); if (!nextElement) throw new Error("No element with id " + nextElementId); nextElement.parentNode.insertBefore(box, nextElement); }	else { const sidebar = document.getElementById("sidebar"); if (!sidebar) throw new Error("Could not find sidebar"); sidebar.appendChild(box); }	return { box: box, header: header, body: body }; }

const idPrefix = "p-searchlang"; const searchLangBox = newSidebarBox(idPrefix, "p-lang"); searchLangBox.header.textContent = "Search for language"; searchLangBox.body.style.padding = "0.5em 0.4em 0.4em 0.4em";

const textBox = document.createElement("input"); textBox.type = "search"; textBox.style.width = "10.9em"; textBox.placeholder = "Language search"; textBox.title = "Search for a language by name";

const resultList = document.createElement("ul"); resultList.id = idPrefix + "-list";

const $textBox = $(textBox);

$textBox.on("keydown", event => {	if (event.which == 0x0D) // enter key		event.preventDefault; });

// https://tomelliott.com/jquery/javascript-delay-input-field-change const storageKey = "WiktionaryNameToCode"; const searcher = new window.LanguageSearcher(	storageKey,	results => {		clearChildren(resultList);		if (results.length > 0)			results.forEach(result => resultList.appendChild(result.print));	}); const makeDelayedFunction = (func, delay) => { let timer; return => { window.clearTimeout(timer); timer = window.setTimeout(func, delay); }; }; let prevVal; $textBox.on("input", makeDelayedFunction( => { const val = $textBox.val; if (val === prevVal) return; else prevVal = val; searcher.doSearch(val); }, 300));

const form = document.createElement("form"); form.appendChild(textBox);

searchLangBox.body.appendChild(form); searchLangBox.body.appendChild(resultList);

});

});