User:Samwilson/LinkIndexToWikidata.js

( function ( mw, $ ) {

/** @var {string} The fully-qualified URL of the Index page. */	const indexPageUrl = 'https://en.wikisource.org/wiki/' + mw.config.get( 'wgRelevantPageName' );

/** @var {jQuery} The table cell to add info to. */	const $tableCell = $( ' ' );

/**	 * jQuery ajax result handler. */	function handleQueryResult( result ) { if ( !result.results || !result.results.bindings || !result.results.bindings[0] || !result.results.bindings[0].item.value ) { return; var $out = $( ' ' ) .addClass( 'error' ) .text( "This Index appears to not yet be referenced from a Wikidata item. Please go to the edition's item on Wikidata and add the following value for 'Wikisource index page' (P1957): " ) .append( $( ' ' ).css( { fontSize: 'smaller', display: 'block' } ).text( indexPageUrl ) ); } else { var itemUrl = result.results.bindings[0].item.value, itemId = itemUrl.substring( "http://www.wikidata.org/entity/".length ); var $out = $( '' ) .attr( 'href', itemUrl ) .attr( 'target', '_blank' ) .text( itemId ); }		$tableCell.prepend( $out ); }

/**	 * Set up HTML, and send request to Wikidata Query Service. */	function queryWikidata { // First up, add a row to the metadata table, that we'll later add content to. var $tableHeader = $( ' ' ) .attr( 'class', 'ws-index-label' ) .text( 'Wikidata' ); $tableCell.attr( 'class', 'ws-index-value' ); var $row = $( ' ' ) .attr( 'class', 'ws-index-row' ) .append( $tableHeader, $tableCell ); $( '#ws-index-metadata tbody' ).prepend( $row );

// Now query for the Wikidata item. const query = 'SELECT ?item WHERE { ?item wdt:P1957 <' + indexPageUrl + '> }' url = 'https://query.wikidata.org/sparql?format=json&query=' + encodeURIComponent( query ); $.ajax( { url: url } ).done( handleQueryResult ); }

/**	 * Entry point. */	function main { if ( mw.config.get( 'wgCanonicalNamespace' ) === 'Index' ) { queryWikidata; }	}

main; }( mediaWiki, jQuery ) );