MediaWiki:Common.js

From Sun Haven Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */

/* -------- Collapsible Navigation on Mobile ---------- */
$(document).ready(function() {
    $('#p-Navigation-label').click(function() {
    	$(this).siblings('.vector-menu-content.body').first().toggleClass("mobile-expanded");
    });
  
  	$('#p-Wiki-label').click(function() {
    	$(this).siblings('.vector-menu-content.body').first().toggleClass("mobile-expanded");
    });
  
  	$('#p-tb-label').click(function() {
    	$(this).siblings('.vector-menu-content.body').first().toggleClass("mobile-expanded");
    });
    
	/**** mobile views ****/
	if ($(window).width() < 768) {
		/* Wrap Tables for scrolling in mobile views */
		$('table').not('.mw-collapsible').not('.pi-horizontal-group').wrap(
			'<div style="max-width: 90vw; overflow-x: scroll" class="table-scroll-shadow"></div>'
		);
		
		/* Hide heading if infobox exists - shows duplicate information */
		var infobox = $('.portable-infobox');
		if (infobox.length > 0) {
		    $('.firstHeading').hide();
		}
	}
});

	/*******************
	* Tooltips Configuration *
	*******************/
/** see: https://sunhaven.wiki.gg/wiki/MediaWiki:Gadget-SHTooltips.js **/
mw.loader.getScript('https://sunhaven.wiki.gg/index.php?title=MediaWiki:Gadget-SHTooltips.js&action=raw&ctype=text/javascript').then(function() {
	window.shTooltips = $.extend(true, window.shTooltips, {RegExp: (window.shTooltips || {}).RegExp || {} });
	window.shTooltips.templates = [
		{
			templatename: "LOCATION",
			template: "{{Location tooltip|%PAGE%|description=%TEXT%" +
	                    "|location=<#location#>" + 
	                    "|hours=<#hours#>" +
	                    "|map=<#map#>" +
	                    "|image=<#image#>" +
	                    "}}"
		},
	    {
			templatename: "NPC infobox",
			template: "{{NPC tooltip|%PAGE%|name=<#name#>|romanceable=<#romanceable#>" + 
						"|occupation=<#occupation#>|birthday=<#birthday#>|region=<#region#>" + 
						"}}"
		},
	    {
			templatename: "Item infobox",
			template: "{{Item tooltip|%PAGE%|image=<#image#>|sell=<#sell#>|selltype=<#selltype#>" +
	                    "|itemType=<#itemType#>|selltype=<#selltype#>|restores=<#restores#>" +
	                    "|statInc=<#statInc#>|statAmt=<#statAmt#>|region=<#region#>|location=<#location#>" +
	                    "|node=<#node#>|season=<#season#>|seed=<#seed#>|produces=<#produces#>|exp=<#exp#>" +
	                    "|requirement=<#requirement#>|set=<#armorset#>" + 
	                    "}}"
		},
	    {
	        linkmatch: /Template:.+/,
	        template: '{{Tooltip/template|%PAGE%}}'
	    }
	];
	
	var loadingImage = "https://sunhaven.wiki.gg/images/8/86/Crafting_Table.gif";
	window.shTooltips.loadingContent = '<div style="padding: 10px;"><img src="' + loadingImage + '"/>';
	window.shTooltips.delay = 300;
});
/* ------------------------------------------ */

	/*******************
	* Checklist tables *
	*******************/
	/* Special thanks to the Palia wiki for helping us with this! */
	$.when(
		mw.loader.using([ 'mediawiki.storage' ]),
		$.ready
	).then(function () {
        var loadTableData = function () {
            var checklists = [];
            // if table has "data-checklist=Some_Bundle", add it to the list
            $.each($("tr"), function (index) {
                if ($(this).data("checklist") !== undefined) {
                    checklists.push($(this).data("checklist").replace("'", ""));
                }
            })

            // Load data for the checklists
            for (var i = 0; i < checklists.length; i++) {
                var serialized = mw.storage.get('mwchecklist-' + checklists[i].replace("'", ""));

                if (serialized === null) continue;
                
                var items = serialized.split(';');
                // Restore saved items
                for (var itemIndex = 0; itemIndex < items.length; itemIndex++) {
                    try {
                        // Update the checkbox to the saved value
                        $("*[data-item='" + items[itemIndex].replace("'", "") + "']")
                            .find('input[type=checkbox]')
                            .prop("checked", true)
                            .trigger("change");
                    } catch (error) {
                        console.log("Error trying to check", items[itemIndex], ". Resetting it.", error)
                        mw.storage.set('mwchecklist-' + checklists[i], "");
                    }
                }
            }
        };
        
        var storeItem = function (tableId, item) {
            var saved = mw.storage.get('mwchecklist-' + tableId);
            if (saved === undefined || saved === null) {
                mw.storage.set(
                    'mwchecklist-' + tableId,
                    item
                );
            } else {
                var items = saved.split(';');
                // Check we aren't adding duplicates (edge case)
                if (!items.includes(item)) {
                    items.push(item);
                    mw.storage.set(
                        'mwchecklist-' + tableId,
                        items.join(';')
                    );
                }
            }
        };

        var removeItem = function (tableId, item) {
            var saved = mw.storage.get('mwchecklist-' + tableId);
            // Only remove if there are existing items
            if (saved !== undefined && saved !== null) {
                var items = saved.split(';')
                mw.storage.set(
                    'mwchecklist-' + tableId,
                    items.filter(function (x) { return x !== item }).join(';')
                );
            }
        }
    
        // Add checkboxes to all icons in required column
        $.each($(".collection-requires"), function (index) {
            // Important to try/catch here so the rest of the javascript still executes
            // if something funky happened.
            try {
                // Get all the icons and check they have data-items
                var $icons = $(this).find(".custom-icon").filter(function (index) {
                    return $(this).data("item") !== undefined;
                });

                // Prepend checkboxes to elements and handle hover & click
                $.each($icons, function (index) {
                    // When hovering over an item, indicate that it is actionable
                    // by applying the dropdown background
                    $(this)
                        .css("border-radius", "6px")
                        .css("padding", "2px")
                        .hover(
                            function() { $(this).css("background-color", "var(--theme-dropdown-hover)") },
                            function() { $(this).css("background-color", "var(--theme-table-td-background)") }
                        )
                        .prepend('<input type="checkbox" style="margin-right: 4px;"/>')
                        .on("click", function(event) {
                            // If this isn't the checkbox or link, click the item
                            // This allows clicking the area around instead of just the checkbox itself
                            if (event.target.localName !== "input" && event.target.localName !== "a") {
                                var isChecked = $(this).find('input[type=checkbox]').prop('checked');
                                $(this).find('input[type=checkbox]')
                                    .prop("checked", !isChecked)
                                    .trigger("change");
                            }
                        });
                });

                // When a checkbox is clicked, strikethru text and make it less visible
                $.each($(this).find('input[type=checkbox]'), function(index) {
                    var itemId = $(this).parent().data("item");
                    
                   $(this).on("change", function() {
                        if (this.checked) {
                            // Item is complete - Make less visible
                            // note: "transition" applies a smooth opacity shift instead of
                            //       instantly changing it. 
                            $(this).siblings()
                                .css("transition", "opacity")
                                .css("opacity", ".5")
                                .css("text-decoration-line", "line-through");

                            storeItem(
                            	$(this).closest('tr').data("checklist").replace("'", ""),
                            	itemId.replace("'", "")
                        	);
                        } else {
                            // Marked incomplete - Return to normal
                            $(this).siblings()
                                .css("transition", "opacity")
                                .css("opacity", "1")
                                .css("text-decoration-line", "none");
                            
                            removeItem(
                            	$(this).closest('tr').data("checklist").replace("'", ""),
                            	itemId.replace("'", "")
                        	);
                        }
                    });
                });

                // Check all checkboxes that were previously isChecked
                loadTableData();
            } catch (error) {
                console.log("Couldn't enable museum checkboxes -", error)
            }
        });
	});

	/*********************
    * Clickable Spoilers *
    Special thanks to the Palia wiki for helping us with this!
	*********************/
	
	var $spoilers = $('.mw-spoilertext');
	
	$spoilers.find('a').each(function() {
		var $this = $(this);
		var href = $this.attr('href');
		$this.attr('data-href', href);
		$this.removeAttr('href');
	});
	
	$spoilers.click(function( e ) {
		var $this = $(this);
		var was_visible = $this.hasClass('mw-spoilertext-visible');
		
		if ($(e.target).closest('a').length) {
			if (was_visible)
				return;
			e.preventDefault();
		}
		
		$this.toggleClass('mw-spoilertext-visible');
		
		var links = $this.find('a');
		for (var l = 0; l < links.length; l++) {
			var $anchor = $(links[l]);
			var href = $anchor.attr('data-href');
			
			if (!was_visible)
				$anchor.attr('href', href);
			else
				$anchor.removeAttr('href');
		}
	});