Jump to content

User:Mooeypoo/tools/article.gender.flip.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.
/**
 * A script to add a button that can replace gender pronouns through the article.
 * Uses the neutrality.wtf API (Github: https://github.com/neutralitywtf/ConceptReplacer)
 * 
 *********************************************************
 * To use, copy this line to your User:YourName/common.js:
 * mw.loader.load('//wiki.riteme.site/w/index.php?title=User:Mooeypoo/tools/article.gender.flip.js&action=raw&ctype=text/javascript');
 *********************************************************
 */
$.when( mw.loader.using( [ 'mediawiki.util' ] ), $.ready ).then( function() {
	var $button;

	if ( mw.config.get( 'wgCanonicalNamespace' ) !== ''  ) {
		// Only work in article namespace
		return;
	}

	$button = $( '<button>' )
		.addClass( 'mw-ui-button' )
		.addClass( 'neutralitywtf-button' )
		.text( 'Swap gender pronouns' )
		.css( { display: 'none' } )
		.insertBefore( '.mw-body .firstHeading' );

	// We want to load the CSS stylesheet before we display the button.
	// mw.loader.load doesn't return a promise, and mw.loader.using can't load a file
	// So we cheat:
	// (would have been: mw.loader.load( '/w/index.php?title=User:Mooeypoo/tools/article.gender.flip.css&action=raw&ctype=text/css', 'text/css' ); )
	$.ajax( {
		url: '/w/index.php?title=User:Mooeypoo/tools/article.gender.flip.css&action=raw&ctype=text/css'
	} )
	.then( function ( stylesheet ) {
		mw.util.addCSS( stylesheet );
		$button.css( { display: 'block' } );
	} );

	$button.on( 'click', function () {
			if ( !$( 'body' ).hasClass( 'neutralitywtf-already-run' ) ) {
				$button.prop( 'disabled', true );
				$( 'div#mw-content-text' ).addClass( 'neutralitywtf-loading' );

				// Get neutrality.wtf to give us the new content:
				$.ajax( {
					url: 'https://www.neutrality.wtf/api/api.php',
					data: {
						module: 'swapgender',
						url: window.location.href
					}
				} )
				.then( function ( response ) {
					// Success
					$html = $( $.parseHTML( response ) );
					$( 'div#mw-content-text' ).empty().append( $html.find( 'div#mw-content-text' ) );
					$( 'body' ).addClass( 'neutralitywtf-already-run' );

					$button.replaceWith(
						$( '<span>' )
							.addClass( 'neutralitywtf-success-label' )
							.text( '(Swapped gender pronouns)' )
					);
				}, function () {
					// Show error message
					mw.notify( 'Could not load the swapped content. Please try again later.' );
					// Enable the button and text
					$button.prop( 'disabled', false );
				} )
				.always( function () {
					$( 'div#mw-content-text' ).removeClass( 'neutralitywtf-loading' );
				} );
			}
		} );
} );