User:Gryllida/js/addSourcesUi-0.1.js

/* Author : Svetlana Tkachenko svetlana@members.fsf.org This file is a part of addSourcesUi. Licence: GPLv3+ Description: adds a button to wikieditor, which fills in from uri Version: 0.1 Change log: - Version 0.1 (2018-02-26) - initial release See also  and . mw.loader.using(['mediawiki.api', 'jquery.ui'], function {	"use strict";	var monthNames = [	    "January", "February", "March",	    "April", "May", "June", "July",	    "August", "September", "October",	    "November", "December"	  ];	var api = new mw.Api;	var getLocation = function(href) {		var l = document.createElement("a");		l.href = href;		return l;	};	var getDomain = function (url){		var l = getLocation(url);		return l.hostname;	};	var errors = {};	var articlesChecked=0;	var templatesChecked=0;	var templatesCheckedWithError=0;	var templatesTotal=0;	function _addCodeForSource(thissourceinfo2, context){		var str = '*';		console.log('1 context = ' + context);		_addSourceToArticle(str, context);	}	// == Error reporting ==	function handleError(thissourceinfo2, data, sourceurl){		console.log('checking for errors');		var warnings = [];		var params = Object.keys(thissourceinfo2);		console.log(params); $(params).each(function(i){			var paranName = params[i];			console.log(paranName);			var v2 = thissourceinfo2[paranName];			console.log(':'+v2+':');			if(v2 === ""){				warnings.push('I could not fetch "'+paranName+'" parameter. Please add it by hand.');				console.log('warning added');			}		}); return warnings; }	function _addWarnings(warnings){ console.log('adding warnings'); var message = ''; $(warnings).each(function(i){			message = message + '; ' + warnings[i];		}); alert(message); //button.prop('value','Get data'); }	// == Citoid metadata manipulation == function _getCitoidApiUrl(url){ var apiUrl = mw.config.get ('wgServer') ; apiUrl = apiUrl + '/api/rest_v1/data/citation/mediawiki/'; apiUrl = apiUrl + encodeURIComponent(url); return apiUrl; }	function _getCitoidSourceInfo(sourceurl, context){ console.log('getting citoid information'); //button.prop('value','Checking...'); var warnings = []; console.log(sourceurl); if(!sourceurl) { warnings.push('missing url'); _addWarnings(warnings); } else { _getPublicationData1(sourceurl).then(function(data) {				var thissourceinfo2 = _getPublicationData2(data, sourceurl);				warnings = handleError(thissourceinfo2, data, sourceurl);				console.log('0 context = ' + context);				_addCodeForSource(thissourceinfo2, context);				_addWarnings(warnings);				$('#wpTextbox1').focus;			}).catch(err => {				templatesCheckedWithError += 1;			}); }	}	function _getPublicationData1(url){ var apiUrl = _getCitoidApiUrl(url); return $.get(apiUrl); }	function _getPublicationData2(data, url){ // Get author var authors = data[0].author; var authorStrings = []; $(authors).each(function( index ) {			authorStrings.push(this[0] + ' ' + this [1]);		}); var author = authorStrings.join (', '); //console.log('author: '+ author); // Get publisher, title var publisher = data[0].publicationTitle || ""; var title = data[0].title; // Get date (in the correct format) var datestring = data[0].date; // 2020-12-31 var date=""; if(datestring){ var dateOrig = datestring.split('-'); // 2020-12-31 var dateYear = dateOrig[0]; var dateMonth = monthNames[dateOrig[1]-1]; var dateDay = parseInt(dateOrig[2],10); date = dateMonth + ' ' + dateDay + ', ' + dateYear; }		var sourceinfo = { url: url, title: title, author: author, pub: publisher, date: date /// xxx add lang };		return sourceinfo; }	function _addSourceToArticle(srctext, context){

$.wikiEditor.modules.toolbar.fn.doAction(           $( '#wpTextbox1' ).data( 'wikiEditor-context' ),            {                    type: 'replace',                    options: {                            peri: srctext,                            ownline: true                    }            },            $( '#wpTextbox1' )		); }	function _getStarted(context){ console.log('Get started'); var sourceurl = prompt('Source URL: '); console.log('-1 context = ' + context); _getCitoidSourceInfo(sourceurl, context); }	// == WikiEditor codes == var customizeToolbar = function { /* Your code goes here */ $( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {			'section': 'main',			'group': 'insert',			'tools': {				'addsource': {					label: 'Add a source', // or use labelMsg for a localized label, see above					type: 'button',					icon: '//upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Plus_icon.svg/22px-Plus_icon.svg.png',				     action: {				           type: 'callback',				                execute: function(context){				                		console.log('-2 context = ' + context);				                       _getStarted(context);				                }				      }				}			}		} ); };	/* Check if view is in edit mode and that the required modules are available. Then, customize the toolbar … */ if ( $.inArray( mw.config.get( 'wgAction' ), [ 'edit', 'submit' ] ) !== -1 ) { mw.loader.using( 'user.options' ).then( function {			// This can be the string "0" if the user disabled the preference (T54542)			if ( mw.user.options.get( 'usebetatoolbar' ) == 1 ) {				$.when( mw.loader.using( 'ext.wikiEditor' ), $.ready ).then( customizeToolbar );			}		} ); }	// == WikiEditor codes end == });