Jump to content

User:Fred Gandt/subdueLinks.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.
// TOD session caching to session/local storage to save mad api calls

mw.loader.load( "/w/index.php?title=User:Fred_Gandt/subdueLinks.css&action=raw&ctype=text/css", "text/css" );
$( document ).ready( () => {
	"use strict";
	let dflt_opts = { "On load": false, "Subdue links": false },
		frm = document.createElement( "form" ),
		opts = Object.assign( {}, dflt_opts ), // TEMPORARY KLUDGE
		lbl, npt, trg;
	const FGSL = "fg-subdue-links",
		OPTS_NAME = `userjs-${FGSL}`,
		toggleSubduction = tggl => document.getElementById( "mw-content-text" ).classList.toggle( FGSL, tggl ),
		stringyOpts = () => JSON.stringify( opts ),
		setOpts = () => {
			opts = Array.from( frm.querySelectorAll( "input" ) ).reduce( ( o, cv ) => {
				o[ cv.name ] = cv.checked;
				return o;
			}, {} );
			toggleSubduction( opts[ "Subdue links" ] );
			$.ajax( {
				url: "/w/api.php",
				dataType: "json",
				type: "POST",
				data: {
					token: mw.user.tokens.values.csrfToken,
					optionvalue: stringyOpts(),
					optionname: OPTS_NAME,
					action: "options",
					format: "json"
				},
				success: data => {
					if ( data.error ) {
						console.error( data.error.info );
					}
				},
				error: ( something, went, wrong ) => {
					console.error( something );
					window.alert( `Something went wrong:\n\n${went}:\n\n${wrong}` );
				}
			} );
		};
	
	opts = JSON.parse( mw.user.options.values[ OPTS_NAME ] || stringyOpts() );
	
	if ( !Object.getOwnPropertyNames( opts ).length ) { // TEMPORARY FIX just in case anyone was using it while I was messing it up
		opts = Object.assign( {}, dflt_opts );
	}
	
	opts[ "Subdue links" ] = toggleSubduction( opts[ "On load" ] && opts[ "Subdue links" ] ); // TODO revisit this *cough* "logic" kludge when doing the session caching
	
	Object.getOwnPropertyNames( opts ).forEach( pn => {
		npt = document.createElement( "input" );
		npt.checked = opts[ pn ];
		npt.type = "checkbox";
		lbl = document.createElement( "label" );
		npt.name = lbl.textContent = pn;
		lbl.append( npt );
		frm.append( lbl );
	} );
	frm.id = FGSL;
	frm.addEventListener( "change", setOpts, { passive: true } );
	document.getElementById( "p-tb" ).querySelector( "div" ).append( frm );
} );