User:Yair rand/WatchSubpages.js

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.
// Allow adding a watch button to transcluded subpages.
// Afaik, there wasn't already a system for this. 

// <span class="subpagewatch" data-subpagename="PAGENAME">[{{fullurl:PAGENAME|action=watch}} watch]</span>

mw.config.get( 'wgNamespaceNumber' ) !== 4 && mw.config.get( 'wgUserName' ) && $( document ).ready( function () {
	var $subpagewatchlinks = $( '.subpagewatch' ),
		pages,
		namesToPages,
		api;
	if ( $subpagewatchlinks.length ) {
		mw.util.addCSS( 
			'.subpagewatch {' +
				'cursor: pointer;' +
				'background-image: url(/w/skins/Vector/images/watch-icon.png);' +
			'}' +
			// Unused
			'.subpagewatch.loading {' +
				'background-image: url(/w/skins/Vector/images/watch-icon-loading.png);' +
			'}' +
			'.subpagewatch.subpagewatched {' +
				'background-image: url(/w/skins/Vector/images/unwatch-icon.png);' +
			'}' +
			'.subpagewatch:hover {' +
				'background-image: url(/w/skins/Vector/images/watch-icon-hl.png);' +
			'}' +
			'.subpagewatch.subpagewatched:hover {' +
				'background-image: url(/w/skins/Vector/images/unwatch-icon-hl.png);' +
			'}'
		);
		pages = [];
		namesToPages = {};
		$subpagewatchlinks.each( function () {
			var page = $( this ).data( 'subpagename' );
			if ( pages.indexOf( page ) === -1 ) {
				pages.push( page );
				namesToPages[ page ] = this;
			}
		} );
		
		api = new mw.Api();
		api.get( { 
			action: 'query', 
			prop: 'info', 
			inprop: 'watched', 
			titles: pages.join( '|' )
		} ).done( function ( response ) {
			$.each( response.query.pages, function ( i, a ) {
				var $link = $( namesToPages[ a.title ] ),
					watched = "watched" in a;
				if ( watched ) {
					$link.addClass( 'subpagewatched' );
				}
				$link.on( 'click', function () {
					watched = !watched;
					api[ watched ? 'watch' : 'unwatch' ]( a.title ).done( function ( watchResponse ) {
						$link
							.removeClass( 'loading' )
							.toggleClass( 'subpagewatched', watched );
						mw.notify( $.parseHTML( watchResponse.message ), {
							// No idea what this does
							tag: 'watch-sub'
						} );
					} );
					return false;
				} );
			} );
		} );
	}
} );