User:Fytcha/TranscludeTranslationSubpages.js

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

Note: You may have to bypass your browser’s cache to see the changes. In addition, after saving a sitewide CSS file such as MediaWiki:Common.css, it will take 5-10 minutes before the changes take effect, even if you clear your cache.

  • 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.

const pagename = location.pathname.split("/").pop();
const fetches = {}

// As [[Template:see translation subpage]] uses class="pseudo NavFrame".
const potential_boxes = document.querySelectorAll(".pseudo.NavFrame");
const promises = Array.from(potential_boxes).map(async function(box) {
	// To differentiate from [[Template:trans-see]], we check whether pagename/translations is present.
    if (box.innerHTML.indexOf(pagename + "/translations") < 0)
        return;
    
    // Decompose the href into link and fragment.
    const href = box.children[0].children[0].href;
    const [_, link, section] = href.match(/^(.+?)#(.+)$/);
    
    // If that page has not been fetched yet, fetch it.
    if (fetches[link] === undefined)
        fetches[link] = fetch(link).then(r => r.text());
    const text = await fetches[link];
    const parser = new DOMParser();
    const doc = parser.parseFromString(text, "text/html");
    
    // Find the header that the link points to.
    const header = doc.getElementById(section).parentElement;
    
    // Copy its edit link here.
    const edit = box.previousElementSibling.getElementsByTagName("a")[0];
    edit.after(header.getElementsByTagName("a")[0]);
    edit.remove();
    
    // Copy its translation boxes (all consecutive divs following the header) here.
    const boxes = [];
    for (let i = header.nextElementSibling; !!i && i.tagName == "DIV"; i = i.nextElementSibling)
        boxes.push(i);
    box.after(...boxes);
    box.remove();
});
Promise.all(promises);