Jump to content

User:Fred Gandt/ambiguousLinks.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.
$( document ).ready( () => {
	"use strict";
	if ( mw.config.get( "wgNamespaceNumber" ) === 0 ) {
		let article_link_titles_array = [];
		const ARTICLE_ID = mw.config.get( "wgArticleId" ),
			CONTENT_TEXT = document.getElementById( "mw-content-text" ),
			ARTICLE_AMBIGUOUS_LINK_TITLES_ARRAY = [],
			apiQuery = ( qd, fnc ) => {
				$.ajax( {
					type: "POST",
					url: "/w/api.php",
					dataType: "json",
					data: Object.assign( {
						format: "json",
						action: "query"
					}, qd ),
					success: data => fnc( data ),
					error: data => console.error( data )
				} );
			},
			populateArticleLinkTitlesArray = data => article_link_titles_array.push( ...data.query.pages[ ARTICLE_ID ].links ),
			getAllAmbiguousArticleLinkTitles = qd => {
				qd.titles = article_link_titles_array.splice( 0, 50 ).join( "|" );
				apiQuery( qd, data => {
					for ( const [key, value] of Object.entries( data.query.pages ) ) {
						if ( value.pageprops?.hasOwnProperty( "disambiguation" ) ) {
							ARTICLE_AMBIGUOUS_LINK_TITLES_ARRAY.push( value.title );
						}
					}
					if ( article_link_titles_array.length ) {
						getAllAmbiguousArticleLinkTitles( qd );
					} else if ( ARTICLE_AMBIGUOUS_LINK_TITLES_ARRAY.length ) {
						CONTENT_TEXT.querySelectorAll( ARTICLE_AMBIGUOUS_LINK_TITLES_ARRAY.map( ttl => `a[title="${ttl}"]` ).join( "," ) ).forEach( link => {
							link.style.backgroundColor = "#fd9a35";
							link.style.color = "#000000";
						} );
					}
				} );
			},
			getAllArticleLinks = qd => {
				apiQuery( qd, data => {
					if ( data.continue ) {
						qd.plcontinue = data.continue.plcontinue;
						populateArticleLinkTitlesArray( data );
						getAllArticleLinks( qd );
					} else if ( data.hasOwnProperty( "batchcomplete" ) ) {
						populateArticleLinkTitlesArray( data );
						article_link_titles_array = [ ... new Set( article_link_titles_array.map( link_object => link_object.title ) ) ];
						getAllAmbiguousArticleLinkTitles( { prop: "pageprops", ppprop: "disambiguation" } );
					}
				} );
			};
		getAllArticleLinks( { prop: "links", pllimit: "max", titles: mw.config.get( "wgTitle" ) } );
	}
} );