User:Stavats/common.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.

This JavaScript is executed for Stavats on every page load.


// Close L2 sections in mainspace.
// Checking the URL is a hack. See [[phab:T349908#9932746]].
if (mw.config.get("wgNamespaceNumber") === 0 && (window.location.hostname == "en.m.wiktionary.org")) {
	let L2sToClose = Array.from(document.querySelectorAll(".mw-heading2"));
	let anchorElement = document.getElementById(window.location.hash.substring(1));
	
	if (anchorElement) {
		// If the URL contains a valid anchor, don't close the L2 containing that ID.
		// Note: the HTML structure for an L2 on mobile is `<div class="mw-heading2"> [L2 header] </div> <section> [L2 content] </section>`.
		L2sToClose = L2sToClose.filter(L2 => !L2.contains(anchorElement) && !L2.nextElementSibling.contains(anchorElement));
	} else {
		// Otherwise, don't close the first L2.
		L2sToClose.shift();
	}
	
	let L2clickPromises = L2sToClose.map(L2 => new Promise(resolve => {
		let observer = new MutationObserver(() => {
			// Check if element has fully loaded.
			if (L2.classList.contains("collapsible-heading")) {
				observer.disconnect();
				// Check if element is open.
				if (L2.classList.contains("open-block")) {
					L2.click();
				}
				resolve();
			}
		});
		observer.observe(L2, { attributes: true });
	}));

	// After all elements have been clicked, try jumping to the anchor.
	Promise.all(L2clickPromises).then(() => {
		if (anchorElement) { 
			anchorElement.scrollIntoView();
		}
	});
}