MediaWiki:Gadget-addprefixVE.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.
/**
 * The Visual Editor version of the AddPrefix gadget.
 *
 * This script adds the test wiki's prefix in front of any link when
 * you add a link via the Visual Editor.
 *
 * @author Jon Harald Søby
 */

mw.hook( 've.activationComplete' ).add( function() {
	var pagename = mw.config.get( 'wgTitle' ),
		prefix;
	
	if ( !pagename.match( /W\w\/\w{2,3}(-\w+){0,2}/g )) {
		return;
	} else {
		prefix = pagename.split( '/', 2 ).join( '/' ) + '/';
	}
	
	var targetNodes = $( '.ve-ui-overlay' ),
		MutationObserver = window.MutationObserver,
		addLinkObserver = new MutationObserver( mutationHandler ),
		obsConfig = { childList: true, subtree: true };
	
	targetNodes.each( function() {
		addLinkObserver.observe( this, obsConfig );
	});
	
	function mutationHandler( mutationRecords ) {
		mutationRecords.forEach( function( mutation ) {
			if ( typeof mutation.addedNodes == 'object' ) {
				var $linkSearchField = $( mutation.addedNodes ).find( '.oo-ui-searchWidget-query .oo-ui-inputWidget-input');
				if ( $linkSearchField.length && !$linkSearchField[ 0 ].value.includes( prefix ) ) {
					$linkSearchField[ 0 ].value = prefix + $linkSearchField[ 0 ].value;
				}
			}
		});
	}
});