MediaWiki

Difference between revisions of "Common.js"

Line 165: Line 165:
 
     mw.loader.using( [ 'mediawiki.api', 'ext.recordWizard.wikibase' ] ).then( getLastRecords );
 
     mw.loader.using( [ 'mediawiki.api', 'ext.recordWizard.wikibase' ] ).then( getLastRecords );
 
}
 
}
 +
 +
 +
console.log("User:Yug/common.js")
 +
 +
 +
/* ************************************************************************** */
 +
/* Edit toolbox ************************************************************ */
 +
/* Sources: [[:mw:Manual:Interface/Sidebar#Add_or_remove_toolbox_sections_(JavaScript)]]  */
 +
 +
function ModifySidebar( action, section, name, link ) {
 +
console.log("1:", action,section, name, link)
 +
try {
 +
switch ( section ) {
 +
case 'languages':
 +
var target = 'p-lang';
 +
break;
 +
case 'toolbox':
 +
var target = 'toolbox'; // mediawiki: "p-tb" ; wikibase: "toolbox" and then remove lines selecting children div and ul
 +
break;
 +
case 'navigation':
 +
var target = 'p-navigation';
 +
break;
 +
default:
 +
var target = 'p-' + section;
 +
break;
 +
}
 +
 +
if ( action == 'add' ) {
 +
console.log(action,section, name, link)
 +
var node = document.getElementById( target )
 +
//   .getElementsByTagName( 'div' )[0]
 +
//   .getElementsByTagName( 'ul' )[0];
 +
 +
var aNode = document.createElement( 'a' );
 +
var liNode = document.createElement( 'li' );
 +
 +
aNode.appendChild( document.createTextNode( name ) );
 +
aNode.setAttribute( 'href', link );
 +
liNode.appendChild( aNode );
 +
liNode.className = 'plainlinks';
 +
node.appendChild( liNode );
 +
}
 +
 +
if ( action == 'remove' ) {
 +
var list = document.getElementById( target )
 +
//   .getElementsByTagName( 'div' )[0]
 +
//   .getElementsByTagName( 'ul' )[0];
 +
 +
var listelements = list.getElementsByTagName( 'li' );
 +
 +
for ( var i = 0; i < listelements.length; i++ ) {
 +
if (
 +
listelements[i].getElementsByTagName( 'a' )[0].innerHTML == name ||
 +
listelements[i].getElementsByTagName( 'a' )[0].href == link
 +
)
 +
{
 +
list.removeChild( listelements[i] );
 +
}
 +
}
 +
}
 +
 +
 +
} catch( e ) {
 +
// let's just ignore what's happened
 +
return;
 +
}
 +
}
 +
 +
function CustomizeModificationsOfSidebar() {
 +
ModifySidebar( "add", "toolbox", "Recent (non-audio)", "https://lingualibre.org/wiki/Special:RecentChanges?namespace=0&invert=1" );
 +
}
 +
 +
$( CustomizeModificationsOfSidebar );

Revision as of 15:01, 8 October 2020

// Replace Wikidata IDs with their [label, description]
if ( $( '.wb-external-id' ).length > 0 ) {
	mw.loader.using( 'mediawiki.ForeignApi', function() {
		$( '.wb-external-id' ).each( function() {
			if ( $( this ).attr( 'href' ).lastIndexOf( 'https://www.wikidata.org', 0 ) === 0 ) {
				var wikidataApi = new mw.ForeignApi( 'https://www.wikidata.org/w/api.php', {
						anonymous: true,
						parameters: { 'origin': '*' },
						ajax: { timeout: 10000 }
					} ),
					lang = mw.config.get( 'wgUserLanguage' ),
					node = $( this );
				wikidataApi.get( {
					'action': 'wbgetentities',
					'format': 'json',
					'ids': node.text(),
					'props': 'labels|descriptions',
					'languages': lang,
					'languagefallback': 1,
					'origin': '*'
				} ).then( function( data ) {
                                        
					var entity = data.entities[ node.text() ],
						label = ( entity.labels[ lang ] !== undefined ? entity.labels[ lang ].value + ' <i>(' + node.text() + ')</i>' : node.text() ),
						description = ( entity.descriptions[ lang ] !== undefined ? '<small>' + entity.descriptions[ lang ].value + '</small>' : '' );
					
					node.html( label + '<br>' + description )
				} );
			}
		} );
	} );
}

//Add an audio player to the audio records links in the wikibase items
const BASE_FILE_URL = 'https://commons.wikimedia.org/wiki/Special:Redirect/file?wptype=file&wpvalue=';

function playButton( audioUrl ) {
	var button = new OO.ui.ButtonWidget( {
		framed: false,
		icon: 'play',
		title: 'play'
	} );
	button.on( 'click', function() {
		var audio = new Audio( audioUrl );
		audio.play();
	} );

	return button.$element;
}

if ( $( '#P3 a.extiw' ).length > 0 ) {
    mw.loader.using( [ 'oojs-ui-widgets', 'oojs-ui.styles.icons-media' ], function() {
        $( '#P3 a.extiw' ).each( function() {
            var $node = $( this );
            $node.before( playButton( BASE_FILE_URL + $node.text() ) );
        } );
    } );
}


/**
 * Display last records on main page
 **/
var ab1, ab2;


var AudioBox = function( recordQid, $node ) {
	this.wbRecord = new mw.recordWizard.wikibase.Item( recordQid );
	
	this.$node = $node;
	this.audioNode = document.createElement( 'audio' );
	this.audioNode.preload = 'auto';

    this.api = new mw.Api();	

	this.recordQid = recordQid;
	this.langQid = null;
	this.speakerQid = null;
	
	this.label = '';
	this.media = '';
	this.lang = '';
	this.speaker = '';
	
	this.wbRecord.getFromApi( this.api ).then( this.processRecord.bind( this ), displayError );
}

AudioBox.prototype.processRecord = function() {
	this.label = this.wbRecord.getLabel( 'en' );
	this.media = 'https://commons.wikimedia.org/wiki/Special:FilePath/' + this.wbRecord.getStatements( 'P3' )[ 0 ].getValue();
	this.langQid = this.wbRecord.getStatements( 'P4' )[ 0 ].getValue();
	this.speakerQid = this.wbRecord.getStatements( 'P5' )[ 0 ].getValue();

	this.api.get( {
		action: "wbgetentities",
		format: "json",
		ids: this.langQid + '|' + this.speakerQid,
		props: "labels",
		languages: mw.config.get( 'wgUserLanguage' ) + "|en",
		languagefallback: 1,
	} ).then( this.processLabels.bind( this ), displayError );
}

AudioBox.prototype.processLabels = function( data ) {
	var langLabels;

	if ( data.entities === undefined || data.entities[ this.langQid ] === undefined || data.entities[ this.speakerQid ] === undefined ) {
		displayError( 'dataerror' );
		return;
	}
	langLabels = data.entities[ this.langQid ].labels;
	
	if ( langLabels[ mw.config.get( 'wgUserLanguage' ) ] !== undefined ) {
		this.lang = langLabels[ mw.config.get( 'wgUserLanguage' ) ].value;
	} else {
		this.lang = langLabels[ 'en' ].value;
	}
	
	this.speaker = data.entities[ this.speakerQid ].labels[ 'en' ].value;

	this.display();
}

AudioBox.prototype.display = function() {
	this.$node.find( '.ab-title' ).text( this.label );
	this.$node.find( '.ab-metadata' ).text( this.lang + ' - ' + this.speaker );
	
	this.audioNode.src = this.media;
	this.$node.find( '.ab-playbutton' ).click( this.audioNode.play.bind( this.audioNode ) );
}






function createAudioBoxes( data ) {
	if ( data.query === undefined || data.query.rwrecords === undefined || data.query.rwrecords.length < 2 ) {
		displayError( 'nodata' );
		return;
	}

	ab1 = new AudioBox( data.query.rwrecords[ 0 ], $( '.audiobox' ).eq( 0 ) );
	ab2 = new AudioBox( data.query.rwrecords[ 1 ], $( '.audiobox' ).eq( 1 ) );
}

function getLastRecords() {
    var api = new mw.Api();
	api.get( {
        action: 'query',
        format: 'json',
        list: 'rwrecords',
        rwrlimit: '2',
		rwrsort: 'pageid',
		rwrdir: 'descending',
		rwrformat: 'qid'
  } ).then( createAudioBoxes, displayError );
}

function displayError( code, error ) {
	console.warn( code, error );
}

if ( mw.config.get( 'wgPageName' ) === 'LinguaLibre:Main_Page' ) {
    mw.loader.using( [ 'mediawiki.api', 'ext.recordWizard.wikibase' ] ).then( getLastRecords );
}


console.log("User:Yug/common.js")


/* ************************************************************************** */
/* Edit toolbox ************************************************************ */
/* Sources: [[:mw:Manual:Interface/Sidebar#Add_or_remove_toolbox_sections_(JavaScript)]]  */

function ModifySidebar( action, section, name, link ) {
			console.log("1:", action,section, name, link)
	try {
		switch ( section ) {
			case 'languages':
				var target = 'p-lang';
				break;
			case 'toolbox':
				var target = 'toolbox'; // mediawiki: "p-tb" ; wikibase: "toolbox" and then remove lines selecting children div and ul
				break;
			case 'navigation':
				var target = 'p-navigation';
				break;
			default:
				var target = 'p-' + section;
				break;
		}

		if ( action == 'add' ) {
			console.log(action,section, name, link)
			var node = document.getElementById( target )
//							   .getElementsByTagName( 'div' )[0]
//							   .getElementsByTagName( 'ul' )[0];

			var aNode = document.createElement( 'a' );
			var liNode = document.createElement( 'li' );

			aNode.appendChild( document.createTextNode( name ) );
			aNode.setAttribute( 'href', link );
			liNode.appendChild( aNode );
			liNode.className = 'plainlinks';
			node.appendChild( liNode );
		}

		if ( action == 'remove' ) {
			var list = document.getElementById( target )
	//						   .getElementsByTagName( 'div' )[0]
//							   .getElementsByTagName( 'ul' )[0];

			var listelements = list.getElementsByTagName( 'li' );

			for ( var i = 0; i < listelements.length; i++ ) {
				if (
					listelements[i].getElementsByTagName( 'a' )[0].innerHTML == name ||
					listelements[i].getElementsByTagName( 'a' )[0].href == link
				)
				{
					list.removeChild( listelements[i] );
				}
			}
		}


	} catch( e ) {
		// let's just ignore what's happened
		return;
	}
}

function CustomizeModificationsOfSidebar() {
	ModifySidebar( "add", "toolbox", "Recent (non-audio)", "https://lingualibre.org/wiki/Special:RecentChanges?namespace=0&invert=1" );
}

$( CustomizeModificationsOfSidebar );