User:Petr Matas/ExportClaims.js

From Wikidata
Jump to navigation Jump to search

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * When hovering over the Statements heading,
 * a box is whown with the claims exported in the QuickStatements format.
 */

/*jslint browser: true, vars: true*/
/*global jQuery, mediaWiki*/

( function ( mw, $ ) {
	'use strict';

	if ( mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
		!mw.config.exists( 'wbEntity' )
	) {
		return;
	}
	
	function formatValue(dataValue) {
		var value = dataValue.value;
		switch(dataValue.type) {
			case 'wikibase-entityid': return 'Q' + value['numeric-id'];
			case 'string': return '"' + value + '"';
			case 'monolingualtext': return value.language + ':"' + value.text + '"';
			case 'time': return value.time + '/' + value.precision;
			case 'quantity': return value.amount;
			case 'globecoordinate': return '@' + value.latitude + '/' + value.longitude;
			default: return value;
		}
	}
	
	function getClaims() {
		var result = '';
		var claims = JSON.parse(mw.config.get('wbEntity')).claims;

		$.each(claims, function(property, statementList) {
			/*jslint unparam: true*/
			$.each(statementList, function(i, statement) {
				result += 'LAST\t' + property + '\t' + formatValue(statement.mainsnak.datavalue) + '\n';
			});
			/*jslint unparam: false*/
		});

		return result;
	}
	
	function init() {
		$( '#claims' )
			.css('overflow', 'visible')
			.mouseover( function () {
				$( '.export-claims-panel' ).show();
				$( '.export-claims-textbox' ).select().focus();
			} )
			.mouseout( function () {
				$( '.export-claims-panel' ).hide();
			} )
			.append(
				$( '<div class="export-claims-panel" style="position: relative">' )
					.hide()
					.append(
						$( '<textarea class="export-claims-textbox" readonly="readonly" style="position: absolute; top: -0.5ex; left: 0.3em; z-index: 5; width: 30em; height: 20ex">' )
							.val(getClaims())
				)
			)
		;
	}
	
	mw.loader.using( [ 'json' ], init );
	
} ( mediaWiki, jQuery ) );