User:Fadirra/coolwd.js

From Wikidata
Jump to navigation Jump to search

Note: After saving, 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: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
/**
 * COOL-WD: COmpleteness toOL for WikiData
 * 
 * The script enables creating, viewing, and updating completeness statements
 * directly inside Wikidata. Complete properties are highlighted green,
 * while potentially incomplete ones are yellow.
 * 
 * To enable the script, simply copy and paste 
 *    importScript( 'User:Fadirra/coolwd.js' );
 * to your common.js page at
 *    https://www.wikidata.org/wiki/User:[[USERNAME]]/common.js
 * 
 * See more (consumption) features, including completeness analytics
 * and query completeness diagnostics at 
 *    http://cool-wd.inf.unibz.it/
 *
 * Developer   : Fadirra (fariz.darari@stud-inf.unibz.it)
 * Inspired by : Wikimedia Commons image gadget by Bene* (Thanks, Bene*!)
 */

( function( mw, $ ) {
	"use strict"; // strict JavaScript execution model

    // set global variables
    var colorIncomplete = "rgb(255, 255, 160)", // incomplete -> yellow
    	colorComplete   = "rgb(160, 255, 160)"; // complete   -> green

    // to generate dialog boxes for reference URLs
	var	dialog  = {};

    // show the provenance info of a complete property
	function show( title, entityId, propertyId ) {

		mw.loader.using( 'jquery.ui.dialog', function () {

			dialog[ title ] = $( '<div>' )
				.append( "<form class=\"referenceURLForm\">" + 
				            "<input type=\"text\" name=\"referenceURL\" style=\"width: 100%;\" placeholder=\"\">" + 
				            "<input style=\"float:right; margin-right: 0.4em; margin-top: 0.5em\" type=\"submit\" value=\"Update\">" +
				         "</form>" + 
				         "<div class=\"completenesscreator\"></div>" +
				         "<div class=\"completenesstimestamp\"></div>" )
				.dialog( {
					title: title,
					width: 400,
					height: 130,
					resizable: false,
					dialogClass: 'completenessgadget',
					show: { effect: 'fade', duration: 500 },
				} );
			
			$( '.ui-dialog-title' ).css( {
				'width' : 'auto'
			} );
			
			$( '.ui-widget' ).css( {
				'font-size' : '0.8em'
			} );
			
			$( '.ui-widget-content' ).css( {
				'height' : 'auto'
			} );
			
			$( '.completenesstimestamp' ).css( {
				'margin-top' : '5px'
			} );
		     
			$( '.completenesscreator' ).css( {
				'margin-top' : '5px'
			} );
			
			// API request to get reference URL, timestamp, and creator of the completeness statement
			$.getJSON( 'https://cool-wd.inf.unibz.it/corner_wd/gadget?callback=?', 'entityId=' + entityId + '&propertyId=' + propertyId,
			           function ( result ) {
			           	
	     		if( result.boolean == 'true' ) { // if complete, then
	    			$( ".referenceURLForm" ).find( "input[name='referenceURL']" ).val( result.referenceurl );
	    			$( ".completenesstimestamp" ).text( "Timestamp: " + result.completenesstimestamp );
	    			$( ".completenesscreator" ).text( "Creator: " + result.wikidatausername );
				}
				else {
					$( ".referenceURLForm" ).find( "input[name='referenceURL']" ).prop( 'disabled', true );
					$( ".referenceURLForm" ).find( "input[type='submit']" ).prop( 'disabled', true );
				}
				
			});
			
		    $( ".referenceURLForm" ).submit( function( event ) {
		 
				  // stop form from submitting normally
				  event.preventDefault();
				 
				  // get the reference URL value
				  var $form = $( this ),
				      reference = $form.find( "input[name='referenceURL']" ).val();

                  // API request to edit reference URL
				  $.post( "https://cool-wd.inf.unibz.it/corner_wd/gadget", 
				     { entityId: entityId, propertyId: propertyId, referenceurl: reference, user: mw.config.get( 'wgUserName' ), } );
				  	  
				  // close the window after submitting reference URL
				  dialog[ title ].dialog( "close" );
		  
			} );
			
		} );
		
	}

    // load a reference URL window
    function load( title, entityId, propertyId ) {

			mw.loader.load( 'jquery.ui.dialog' );
			show( title, entityId, propertyId );
		
	}

    // initialization (after Wikidata page has been loaded)
	function init() {

    	var entityId = mw.config.get( 'wbEntityId' );

	    // API request to color property boxes according to their completeness status
		$.getJSON( 'https://cool-wd.inf.unibz.it/corner_wd/gadget?callback=?', 'entityId='+entityId,
    	           function ( result ) { 
    	           
			var completeProperties = [];
			for (var i = 0; i < result.length; i++) {
    			var counter = result[i];
				completeProperties.push("P" + counter.propertyId);
			}
    	    
    	    // for every property, do ...
			$( '.wikibase-statementgroupview-property' ).each( function() {
			
				var $this = $( this );
				var propertyId = $this.parent().attr( 'id' );
    	           			
       			// set color       	
 				if( $.inArray(propertyId, completeProperties) > -1 ) // if complete then...
					$this.css( "background-color", colorComplete );
				else
					$this.css( "background-color", colorIncomplete );
    	           	
				// keep the property link clickable without switching completeness status
				$this.find( ".wikibase-statementgroupview-property-label" ).find( "a" ).click( function ( e ) {
					e.stopPropagation();
				} );
						    	           	
           		// add the provenance (i) icon with its click listener (shown iff complete)
				$this.find( ".wikibase-statementgroupview-property-label" ).find( "a" ).after(
					$( '<div>' )
					.addClass( 'magnify' )
					.css( $.inArray(propertyId, completeProperties) > -1 ? // if complete then... 
						{
							'margin-left': '5px',
							'float': 'none',
							'display': 'inline-block', // ...display the icon
						} :
						{
							'margin-left': '5px',
							'float': 'none',
							'display': 'none', // ...otherwise, not
						})
					.append(
						$( '<a>' )
						.css( {
							'background' 		: "url('https://upload.wikimedia.org/wikipedia/commons/8/89/Exquisite-khelpcenter.png')",
							'background-size'	: '12px 12px',
							'background-repeat'	: 'no-repeat',
						} )
						.attr( {
							title	: "Click to see the provenance info",
							href	: "",
						} )
						.click( function ( e ) {
							e.stopPropagation();
							e.preventDefault();
							load( "Provenance info for " + propertyId + "'s completeness", entityId, propertyId );
						} )
					)
				);
    	           	
   			 	$this.click( function() {

						// API request to switch the completeness status of an entity's property
						$.post( "https://cool-wd.inf.unibz.it/corner_wd/gadget",
						   { entityId: entityId, propertyId: propertyId, user: mw.config.get('wgUserName'), } );

		                // switch the color
						if( $this.css( "background-color" ) == colorComplete ) {
						    $this.css( "background-color", colorIncomplete );
					    	$this.find( ".magnify" ).css({ 'display': 'none' });
						}
						else {
					        $this.css( "background-color", colorComplete );
					        $this.find( ".magnify" ).css({'display': 'inline-block'});
						}
						
				});
	           	
			});
    	           		
		});

	}

	$( function () {
		mw.hook( 'wikipage.content' ).add( init );
	});

} ( mediaWiki, jQuery ) );