Jump to content

User:Mr. Stradivarius/gadgets/TransclusionCount.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.
/*                            TransclusionCount
 * 
 * This script adds a link to Jarry1250's Template Transclusion Count tool to
 * the Tools menu. The link is for the current page, or the referenced page if
 * you are viewing a subpage of Special:WhatLinksHere.
 * 
 * To install, add the following to your [[Special:MyPage/common.js]]:

importScript("User:Mr. Stradivarius/gadgets/TransclusionCount.js") // Linkback: [[User:Mr. Stradivarius/gadgets/TransclusionCount.js]]

 */

$( document ).ready(function() {
	function getReferencedTitle( title ) {
		// Gets the referenced title for title objects of pages that
		// reference a specific page. For example, for the title object for
		// Special:WhatLinksHere/User:Example it would give the title object
		// for User:Example.
		var pageName = title.getMain();
		var baseSubpageName = pageName.replace( /.*?\//, "" );
		if ( pageName === baseSubpageName ) {
			return title;
		} else {
			return new mw.Title( baseSubpageName );
		}
	}
	
	// Find the target title
	// We detect whether we are on a subpage of Special:WhatLinksHere, and if
	// so, we use the referenced page. For other special pages, we exit; these
	// pages cannot be transcluded, so it would not make much sense to link to
	// the transclusion count tool from them.
	// TODO: Handle Special:WhatLinksHere pages using the "target" URL query
	// parameter.
	// TODO: Handle other special pages that can reference a specific page, like
	// Special:PrefixIndex and Special:RecentChangesLinked.
	var target = new mw.Title(
		mw.config.get( 'wgTitle' ),
		mw.config.get( 'wgNamespaceNumber' )
	);
	if ( target.getNamespaceId() === -1 ) {
		// We are in the Special namespace.
		if ( mw.config.get( "wgCanonicalSpecialPageName" ) === "Whatlinkshere" ) {
			var referencedTitle = getReferencedTitle( target );
			if ( referencedTitle.toString() !== target.toString() ) {
				// We are on a subpage of Special:WhatLinksHere, so use the
				// referenced page
				target = referencedTitle;
			} else {
				return;
			}
		} else {
			return;
		}
	}
	
	// Assemble the template count URL
	var url = new mw.Uri( "https://tools.wmflabs.org/templatecount/index.php" );
	url.extend( {
		lang: mw.config.get( "wgContentLanguage" ),
		name: target.getMain(),
		namespace: target.getNamespaceId()
	} );
	
	mw.util.addPortletLink( "p-tb", url.toString(), "Transclusion count" );
});