Jump to content

User:Chlod/Scripts/FoldArchives.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Fold Archives
// Author: Chlod
// Version: 1.0.0-REL

// Makes archived threads foldable to reduce taken screen space.
mw.hook('wikipage.content').add(function() {
	// Prevent from running twice.
	if (document.body.getAttribute("data-archives-folded") != null)
		return;
		
	document.body.toggleAttribute("data-archives-folded", true);
	
    var prefix = window.folda_prefix || "folda-";
    var maxHeight = window.folda_maxHeight || "50vh";
    var fadeGradient = window.folda_gradient || (window.folda_dark ? "linear-gradient(to bottom, transparent 70%, rgba(0,0,0,0.3) 90%, rgba(0,0,0,0.75))" : "linear-gradient(to bottom, transparent 75%, white 95%, white)")

    var archivedElements = document.querySelectorAll(".mw-body-content .boilerplate.archived");
    
    mw.util.addCSS(`.${prefix}collapsed { height: ${maxHeight}; overflow: hidden; position: relative; }`);

    mw.util.addCSS(`.${prefix}collapsed .${prefix}expander { user-select: none; display: block; bottom: 0; left: 0; position: absolute; width: 100%; height: 100%; background: ${fadeGradient}; color: black; text-align: center; padding-top: calc(${maxHeight} - 1.5rem); line-height: 1.5rem; font-style: italic; box-sizing: border-box; cursor: pointer; }`);

    archivedElements.forEach(function (element) {
    	// Prevent collapsing already-small archives.
    	var oldHeight = element.style.height;
    	var oldHeightValue = element.clientHeight;
    	element.style.height = maxHeight;
    	var newHeightValue = element.clientHeight;
    	element.style.height = "";
    	if (newHeightValue > oldHeightValue) {
    		// We're only going to make it bigger. Give up here.
    		return;
    	}
    	element.classList.add(`${prefix}collapsed`);
    	
        var expander = document.createElement("div");
        expander.classList.add(`${prefix}expander`);
        expander.innerText = "Click to expand";

        expander.onclick = () => {
        	expander.parentElement.classList.remove(`${prefix}collapsed`);
            expander.parentElement.classList.add(`${prefix}expanded`);
            expander.parentElement.removeChild(expander);
        }

        element.appendChild(expander);
    });
    
    // Scroll back to anchor if available due to scrolling changes
    if (mw.config.get("wgNamespaceNumber") !== -1 && window.location.hash && window.location.hash.length > 0)
    	document.getElementById(window.location.hash.substr(1)).scrollIntoView();
});