מדיה ויקי:Gadget-quickLinker.js

גרסה מ־19:45, 24 באפריל 2017 מאת wikipedia:he>ערן (החלפת קישורים)

הערה: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
/*
This is EXPERIMENTAL script for quickly adding links to article from related articles. It is especially useful for orphan articles (invoked automatically), stub articles (invoked automatically) and new articles which usually have less links compared to long existing articles.

Author: [[:he:User:ערן]]
*/
if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) $(function(){

var titleNoBrackets = /(.+?)( \(|$)/.exec(mw.config.get('wgTitle'));
if (titleNoBrackets) titleNoBrackets = titleNoBrackets[1];
else return;

mw.messages.set({
	'qlinker-title' : 'עריכה מהירה',
	'linkify-summary': 'הוספת קישור ל[[$1]]',
	'qlinker-save-success': 'שמירת $1 בוצעה בהצלחה!',
	'qlinker-save-continue': 'שמירה',
	'qlinker-skip': 'דילוג לדף הבא',
	'qlinker-invoke': 'הוספת בזק של קישורים',
	'qlinker-sidelink': 'הוספת קישורים',
	'qlinker-no-results': 'לא נמצאו תוצאות'
});

function createQuickEditorDialog(searchRes){
	function QuickEditorDialog( config ) {
	  this.contextRgx = new RegExp('(.*[^\[])(' + mw.RegExp.escape(titleNoBrackets) +')((?!\]\]).*)', 'i');
	  this.contextRgxLink = new RegExp('(.*\\[\\[)([^\\]]+?)\\|(' + mw.RegExp.escape(titleNoBrackets) +')(\\]\\].*)', 'i');
	  this.pageI = -1;
	  this.searchData = null;
	  this.curPage = null;
	  QuickEditorDialog.super.call( this, config );
	}
	OO.inheritClass( QuickEditorDialog, OO.ui.ProcessDialog ); 

	// Specify a name for .addWindows()
	QuickEditorDialog.static.name = 'QuickEditorDialog';
	// Specify a title statically (or, alternatively, with data passed to the opening() method). 
	QuickEditorDialog.static.title = mw.msg('qlinker-title');

	QuickEditorDialog.static.actions = [
	  { action: 'saveContinue', label: mw.msg('qlinker-save-continue'), flags: [ 'other', 'constructive' ] },
	  { action: 'skipOne', label: mw.msg('qlinker-skip'), flags: [ 'other', 'progressive' ] },
	  { label: 'Cancel', flags: 'safe' }
	];

	// Customize the initialize() function: This is where to add content to the dialog body and set up event handlers. 
	QuickEditorDialog.prototype.initialize = function () {
	  // Call the parent method
	  QuickEditorDialog.super.prototype.initialize.call( this );
	  // Create and append a layout and some content.
	  this.content = new OO.ui.PanelLayout( { padded: true, expanded: true } );
	  this.$body.append( this.content.$element );
	};
	  
	QuickEditorDialog.prototype.getBodyHeight = function () {
	  return 400;
	};

	QuickEditorDialog.prototype.getSetupProcess = function ( data ) {
	  data = data || {};
	  return QuickEditorDialog.super.prototype.getSetupProcess.call( this, data )
	  .next( function () {
		// Set up contents based on data
	    this.searchData = data.searchData.query;
		this.nextPage();
	  }, this );
	};

	// Use the getActionProcess() method to specify a process to handle the 
	// actions (for the 'save' action, in this example).
	QuickEditorDialog.prototype.getActionProcess = function ( action ) {
	  var dialog = this;
	  switch ( action ) {
		case 'skipOne':
			return new OO.ui.Process( function () {
			  dialog.nextPage();
			}, this );
		case 'saveContinue':
			return new OO.ui.Process( function () {
			  dialog.savePage();
			}, this );
	  }

	  // Fallback to parent handler.
	  return QuickEditorDialog.super.prototype.getActionProcess.call( this, action );
	};

	QuickEditorDialog.prototype.savePage = function ( ) {
		if (this.curPage)
		{
			var api = new mw.Api(), pagename = this.curPage;
			api.postWithToken('csrf', {
				action: 'edit',
				title: this.curPage,
				summary: mw.msg('linkify-summary', mw.config.get('wgTitle')),
				minor: 1,
				basetimestamp: this.timestamp,
				text: this.text
			}).done(function(d) {
				if (d && d.edit && d.edit.result == 'Success')	mw.notify(mw.msg('qlinker-save-success', pagename));
			});
		}
		this.nextPage();
	}

	QuickEditorDialog.prototype.nextPage = function ( ) {
		var m, contextPre, contextPost, contextInner, contextInnerOld, newContext;
		this.pageI++;
		if (this.searchData.pageids.length==this.pageI)
		{
			this.close();
			return;
		}
		var page = this.searchData.pages[this.searchData.pageids[this.pageI]],
			pagecontent = page.revisions[0]['*'];

		if (m = this.contextRgx.exec(pagecontent)) {
			contextPost = m[3];
			contextInner = (m[2] == mw.config.get('wgTitle')) ? '[['+mw.config.get('wgTitle')+']]' : '[['+mw.config.get('wgTitle')+'|' + m[2] + ']]';
			contextInnerOld = '';
		}
		else if (m = this.contextRgxLink.exec(pagecontent)) {
			contextPost = m[3] == mw.config.get('wgTitle')? m[4] : '|' + m[3] + m[4];
			contextInner = mw.config.get('wgTitle');
			contextInnerOld = '<s>' + m[2] + (m[3] == mw.config.get('wgTitle')? '|' : '') + '</s>';
		}
		if ((page.title!=mw.config.get('wgTitle')) && m) {
			var context = m[0];
		 	contextPre = m[1];
			newContext = contextPre+contextInner+contextPost;
			this.content.$element.html('<h1>'+page.title+'</h1><p>'+contextPre+contextInnerOld+'<b>'+contextInner+'</b>'+contextPost+'</p>');
			this.curPage = page.title;
			this.text = pagecontent.replace(context, newContext)
			this.timestamp = page.timestamp;
		}
		else {
			this.nextPage();
		}
	}

	// Make the window.
	var qlinkerEditor = new QuickEditorDialog( {
	  size: 'medium'
	} );

	// Create and append a window manager, which will open and close the window. 
	var windowManager = new OO.ui.WindowManager();
	$( 'body' ).append( windowManager.$element );

	// Add the window to the window manager using the addWindows() method.
	windowManager.addWindows( [ qlinkerEditor ] );

	// Open the window!
	windowManager.openWindow( qlinkerEditor,  { searchData: searchRes } );
}

function createAddLinksButton(){
	var addLinksWizard = $(mw.util.addPortletLink(
					'p-tb',
					'#',
					mw.msg('qlinker-sidelink'),
					't-quicklinker',
					mw.msg('qlinker-invoke'),
					null,
					'#t-whatlinkshere'
	));
	
	addLinksWizard.click(function(e){
		var api = new mw.Api();
		api.get( {
			action: 'query',
			generator: 'search',
			gsrnamespace: 0,
			gsrsearch: '"' + titleNoBrackets +'" -linksto:'+mw.config.get('wgPageName'),
			gsrlimit: 50,
			prop: 'revisions',
			rvprop: 'content|timestamp',
			indexpageids: 1
		}).done(function(d){
			if (d.error) mw.notify(d.error.info);
			if (!d.query || !d.query.pageids || d.query.pageids.length<=1) {
				mw.notify(mw.msg('qlinker-no-results'));
				return;
			}
			mw.loader.using('oojs-ui-windows', function() {	createQuickEditorDialog(d) } );
		});
		e.preventDefault();
	});
	return addLinksWizard;
}

if ($('.orphanpage, .stub').length>0) {
	var api = new mw.Api();
	api.get( {
		action: 'query',
		generator: 'search',
		gsrnamespace: 0,
		gsrsearch: '"' + titleNoBrackets +'" -linksto:'+mw.config.get('wgPageName'),
		gsrlimit: 50,
		prop: 'revisions',
		rvprop: 'content|timestamp',
		indexpageids: 1
	}).done(function(d){
		if (d.query && d.query.pageids && d.query.pageids.length>1) createAddLinksButton().css('font-weight', 'bold')
	});
}
else 
{
	createAddLinksButton();
}
});