Jump to content

User:Salix alba/Citoid.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Salix alba (talk | contribs) at 14:37, 31 August 2014 (basic UI). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
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.
/*************

Generates a skeleton template data for a given template

Author User:Salix alba
Date: 31 Aug 2014
Version: 0.01

Heavily borrowed from 
User:Mvolz/veCiteFromURL.js

Interface element taken from
TemplateDataEditor
http://fr.wikipedia.org/w/index.php?title=Utilisateur:Ltrlg/scripts/TemplateDataEditor.js

 ***************/



function Citoid($) {

	////// Customization for local wikis

	lang = mw.config.get('wgUserLanguage');
	messages = {
			"en": {
				"toolbox-label": 'Citoid',
				"toolbox-tooltip": 'Generate reference from a URL',
				"title": 'Citoid reference ',
				'section-description': 'TemplateData',
				"close": 'Close'
			},
	};
    if(messages[lang]==null) lang='en';


/* Returns full template given search results */
	function getPlainObject( url, searchResults ) {
 
		var content, plainObject, d, templateHref, templateName,
			citation = jQuery.parseJSON( JSON.stringify( searchResults ) )[0], //uses the first citation result for the time being
 
		templateTypeMap = {
			book: 'Cite book',
			bookSection: 'Cite book',
			journalArticle: 'Cite journal',
			magazineArticle: 'Cite news',
			newspaperArticle: 'Cite news',
			thesis: 'Cite journal',
			letter: 'Citation',
			manuscript: 'Cite book',
			interview: 'Citation',
			film: 'Citation',
			artwork: 'Citation',
			webpage: 'Cite web',
			report: 'Cite journal',
			bill: 'Citation',
			hearing: 'Citation',
			patent: 'Citation',
			statute: 'Citation',
			email: 'Cite web',
			map: 'Citation',
			blogPost: 'Cite web',
			instantMessage: 'Citation',
			forumPost: 'Cite web',
			audioRecording: 'Citation',
			presentation: 'Cite journal',
			videoRecording: 'Citation',
			tvBroadcast: 'Citation',
			radioBroadcast: 'Citation',
			podcast: 'Citation',
			computerProgram: 'Citation',
			conferencePaper: 'Cite journal',
			'document': 'Citation',
			encyclopediaArticle: 'Cite journal',
			dictionaryEntry: 'Cite journal'
		},
 
			//Parameter map for Template:Citation on en-wiki
			//In the format citation-template-field:citoid-field
			citationParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				//a large number of Zotero types have the field publicationTitle
				//however, in setting journal to publicationTitle, the citation
				//will be formatted as a journal article, which may not always be
				//desirable.
				'journal': 'publicationTitle',
			//	'newspaper': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			webParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'date': 'date',
				'publisher': 'publisher',
				'website': 'publicationTitle'
			},
 
			newsParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'newspaper': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			bookParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'journal': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			journalParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'journal': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			//format 'template name':parameter obj name
			templateParamMap = {
				'Citation': citationParams,
				'Cite web': webParams,
				'Cite news': newsParams,
				'Cite journal': journalParams,
				'Cite book': bookParams
			},
 
			//This will contain the correct template with the fields filled out
			paramObj = {};
 
		templateName = templateTypeMap[citation.itemType];
 
		templateHref = 'Template:' + templateName;
 
		//hack for now- set citation url to supplied url if not given
		if (!citation.url) {citation.url =  url;}
 
		$.each( templateParamMap[templateName], function ( key, value ) {
			var objString = citation[value] !== undefined ? citation[value] : '';
			paramObj[key] = { 'wt': objString };
		} );
 
		d = new Date();
		paramObj.accessdate = { 'wt': d.toDateString() };
 
		plainObject = { //before paren put get plain object
			'parts': [ {
 
				'template': {
					'target': {
						'href': templateHref,
						'wt': templateName.toLowerCase()
					},
					'params': paramObj
				}
			} ]
		};
 
		content = [
			{
				'type': 'mwTransclusionInline',
				'attributes': {
					'mw': plainObject
				}
			},
			{ 'type': '/mwTransclusionInline' }
		];
		return content;
	};


ve.ui.CiteFromURLDialog.prototype.getActionProcess = function ( action ) {
		if ( action === 'apply' || action === 'insert' ) {
			return new OO.ui.Process( function () {
 
				this.pushPending();
				var citoidService,
					that = this;
 
				citoidService = "https://citoid.wmflabs.org/url";
 
				$.ajax( {
					beforeSend: function (request) {
						request.setRequestHeader('Content-Type', 'application/json');
					},
					url: citoidService,
					type: 'POST',
					data: JSON.stringify( { url: this.searchInput.getValue() } ),
					dataType: 'json',
					success: function ( result ) {
						that.close();
 
						var item,
							surfaceModel = that.getFragment().getSurface(),
							doc = surfaceModel.getDocument(),
							internalList = doc.getInternalList();
 
						//sets up referencemodel with blank stuff
						if ( !that.referenceModel ) {
							// Collapse returns a new fragment, so update this.fragment
							that.fragment = that.getFragment().collapseRangeToEnd();
							that.referenceModel = new ve.dm.MWReferenceModel();
							that.referenceModel.insertInternalItem( surfaceModel );
							that.referenceModel.insertReferenceNode( that.getFragment() );
						}
						//gets bank stuff again
						item = that.referenceModel.findInternalItem( surfaceModel );
						if ( item ) {
							//actually inserts full transclusion model here!
							that.getFragment().clone( item.getChildren()[0].getRange()).insertContent(that.getPlainObject( that.searchInput.getValue(), result ) );
						}
 
						// HACK: Scorch the earth - this is only needed because without it, the reference list won't
						// re-render properly, and can be removed once someone fixes that
						that.referenceModel.setDocument(
							doc.cloneFromRange(
								internalList.getItemNode( that.referenceModel.getListIndex() ).getRange()
							)
						);
 
						that.referenceModel.updateInternalItem( surfaceModel );
 
						//hack- doesn't seem to be working in always
						that.popPending();
					},
					error: function ( XMLHttpRequest, textStatus, errorThrown) {
						that.popPending();
						mw.notify( 'Status:'  + textStatus +  'Error: ' + errorThrown );
						that.popPending();
					},
					always: function () {
						that.popPending();
					}
				} );
			}, this );
		}
 
		// Parent method
		return getActionProcess( this, action );
	};
 
	onTransclusionReady = function () {
		// Parent method
		ve.ui.CiteFromURLDialog.super.prototype.onTransclusionReady.call( this );
		//hack- always enabled for now
		this.actions.setAbilities( { 'apply': true, 'insert': true } );
	};
 
	//hack for inheriting from template dialog
	//Sets the title of the dialog correctly
	getTemplatePartLabel = function ( part ) {
		return ve.msg( 'citoid-citeFromURLTool-title' );
	};

	////// Called when toolbox link clicked

	function callCitoid() {

		var URL = mw.util.wikiScript();
		$.ajax({
			url: URL,
			data: { title: pagename, action: "raw" },
			dataType: "text"
		}).done(doneAjax);
	}

	/////// Called when raw template code read in

	function doneAjax(data) {
		var params = findParams(data);
                var defaults = findDefaults(data,params);
		var code = generateSkel(params);
		//var aliases = findAliases(params);
                var aliases = genAliases(defaults);
		$cont.fadeIn('slow');

		$title.text( messages[lang]['title'] + pagename );
		$body.html( $('<textarea>')
				.attr('id', 'citoid-code')
				.text(code+'\n'+aliases)
		);
	}

	function openCitoidWindow() {
		$cont.fadeIn('slow');
	}

	///// Close the dialog
	function close() {
		$cont.fadeOut('slow', function(){
		});
	}

	////////// Building called after page loads 
	function buildHTML() {
		$body = $('<div>')
		.attr('id', 'citoid-body');
		$body.append("<input type='text' id='citoid-url' size='80 />");
		$body.append("<input type='text' id='citoid-reference' size='80 />");
		
		$title = $('<h2>').text( messages[lang]['title'] );
		
		$cont = $('<div>')
		.attr('id', 'citoid-cont')
		.append($('<div>')
				.attr('id', 'citoid-dialog')
				.append( $title )
				.append($('<a>')
						.attr({
							id: 'citoid-close',
							href: '#',
							title: messages[lang]['close']
						})
						.click(function(){
							close();
							return false;
						})
						.append($('<img>')
								.attr({
									alt: messages[lang]['close'],
									src: '/media/wikipedia/commons/thumb/8/8d/VisualEditor_-_Icon_-_Close.svg/24px-VisualEditor_-_Icon_-_Close.svg.png'
								})
						)
				)
				.append($body)
		)
		.hide();

		$(document.body).append($cont);
	}

	////// Adds a link in the toolbox
	function addPortletLink() {

		$(
				mw.util.addPortletLink('p-tb', '#', messages['en']['toolbox-label'], 'citoid', messages['en']['toolbox-tooltip'] )
		).click(function(){
			openCitoidWindow();
			return false;
		})
	}

	/////// Actions to do once page loads, 
	function start() {
		//alert("TDSkel 0.21" + mw.config.get( 'wgPageName' ));
		addPortletLink();
		buildHTML();
	}

	////////// START //////////
	start(); 
}

/////// Wrapper code, only run if in user or template namespaces
if( true
	/* $.inArray( mw.config.get('wgNamespaceNumber'), [ 2, 10 ] ) !== -1 
/* && $.inArray( mw.config.get('wgAction'), [ 'edit', 'submit' ] ) !== -1  */ ) {
	mw.loader.load( 
  	  '//en.wikipedia.org/w/index.php?title=User:Salix alba/Citoid.css&action=raw&ctype=text/css&smaxage=21600&maxage=86400',
	'text/css' );
        mw.loader.using('mediawiki.util', function(){
	  $(document).ready(Citoid);
        });
}