MediaWiki

Difference between revisions of "Common.js"

(Better hierarchy.)
(Prettify.)
Line 1: Line 1:
 
// Modules loader, conditional  
 
// Modules loader, conditional  
// RecordWizard
+
// RecordWizard
// Main page
+
// Main page
// SoundLibrary
+
// SoundLibrary
if(/^LinguaLibre:Explore_the_sound_library(\/[a-z_-]+)?$/.test( mw.config.get( 'wgPageName' ) ) ) {
+
if (/^LinguaLibre:Explore_the_sound_library(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
mw.loader.load( '/index.php?title=MediaWiki:SoundLibrary.js&action=raw&ctype=text/javascript' );
+
  mw.loader.load('/index.php?title=MediaWiki:SoundLibrary.js&action=raw&ctype=text/javascript');
 
}
 
}
// Search by words, see https://jsfiddle.net/hugolpz/ecpzy0fo/89/
+
// Search by words, see https://jsfiddle.net/hugolpz/ecpzy0fo/89/
// Languages overview
+
if (/^LinguaLibre:Search_by(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
// Minorities measures
+
  mw.loader.load('/index.php?title=MediaWiki:SearchBy.js&action=raw&ctype=text/javascript');
// Query generator , see https://jsfiddle.net/hugolpz/rygo9s5b/
+
}
 +
// Languages overview
 +
// Minorities measures
 +
// Query generator , see https://jsfiddle.net/hugolpz/rygo9s5b/
  
 
// Replace Wikidata IDs with their [label, description]
 
// Replace Wikidata IDs with their [label, description]
if ( $( '.wb-external-id' ).length > 0 ) {
+
if ($('.wb-external-id').length > 0) {
mw.loader.using( 'mediawiki.ForeignApi', function() {
+
  mw.loader.using('mediawiki.ForeignApi', function() {
$( '.wb-external-id' ).each( function() {
+
    $('.wb-external-id').each(function() {
if ( $( this ).attr( 'href' ).lastIndexOf( 'https://www.wikidata.org', 0 ) === 0 ) {
+
      if ($(this).attr('href').lastIndexOf('https://www.wikidata.org', 0) === 0) {
var wikidataApi = new mw.ForeignApi( 'https://www.wikidata.org/w/api.php', {
+
        var wikidataApi = new mw.ForeignApi('https://www.wikidata.org/w/api.php', {
anonymous: true,
+
            anonymous: true,
parameters: { 'origin': '*' },
+
            parameters: { 'origin': '*' },
ajax: { timeout: 10000 }
+
            ajax: { timeout: 10000 }
} ),
+
          }),
lang = mw.config.get( 'wgUserLanguage' ),
+
          lang = mw.config.get('wgUserLanguage'),
node = $( this );
+
          node = $(this);
wikidataApi.get( {
+
        wikidataApi.get({
'action': 'wbgetentities',
+
          'action': 'wbgetentities',
'format': 'json',
+
          'format': 'json',
'ids': node.text(),
+
          'ids': node.text(),
'props': 'labels|descriptions',
+
          'props': 'labels|descriptions',
'languages': lang,
+
          'languages': lang,
'languagefallback': 1,
+
          'languagefallback': 1,
'origin': '*'
+
          'origin': '*'
} ).then( function( data ) {
+
        }).then(function(data) {
                                       
+
 
var entity = data.entities[ node.text() ],
+
          var entity = data.entities[node.text()],
label = ( entity.labels[ lang ] !== undefined ? entity.labels[ lang ].value + ' <i>(' + node.text() + ')</i>' : 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>' : '' );
+
            description = (entity.descriptions[lang] !== undefined ? '<small>' + entity.descriptions[lang].value + '</small>' : '');
+
 
node.html( label + '<br>' + description )
+
          node.html(label + '<br>' + description)
} );
+
        });
}
+
      }
} );
+
    });
} );
+
  });
 
}
 
}
  
Line 47: Line 50:
 
const BASE_FILE_URL = 'https://commons.wikimedia.org/wiki/Special:Redirect/file?wptype=file&wpvalue=';
 
const BASE_FILE_URL = 'https://commons.wikimedia.org/wiki/Special:Redirect/file?wptype=file&wpvalue=';
  
function playButton( audioUrl ) {
+
function playButton(audioUrl) {
var button = new OO.ui.ButtonWidget( {
+
  var button = new OO.ui.ButtonWidget({
framed: false,
+
    framed: false,
icon: 'play',
+
    icon: 'play',
title: 'play'
+
    title: 'play'
} );
+
  });
button.on( 'click', function() {
+
  button.on('click', function() {
var audio = new Audio( audioUrl );
+
    var audio = new Audio(audioUrl);
audio.play();
+
    audio.play();
} );
+
  });
 
+
  return button.$element;
return button.$element;
 
 
}
 
}
  
if ( $( '#P3 a.extiw' ).length > 0 ) {
+
if ($('#P3 a.extiw').length > 0) {
    mw.loader.using( [ 'oojs-ui-widgets', 'oojs-ui.styles.icons-media' ], function() {
+
  mw.loader.using(['oojs-ui-widgets', 'oojs-ui.styles.icons-media'], function() {
        $( '#P3 a.extiw' ).each( function() {
+
    $('#P3 a.extiw').each(function() {
            var $node = $( this );
+
      var $node = $(this);
            $node.before( playButton( BASE_FILE_URL + $node.text() ) );
+
      $node.before(playButton(BASE_FILE_URL + $node.text()));
        } );
+
    });
    } );
+
  });
 
}
 
}
  
Line 76: Line 78:
 
var ab1, ab2;
 
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();
  
var AudioBox = function( recordQid, $node ) {
+
  this.recordQid = recordQid;
this.wbRecord = new mw.recordWizard.wikibase.Item( recordQid );
+
  this.langQid = null;
+
  this.speakerQid = null;
this.$node = $node;
 
this.audioNode = document.createElement( 'audio' );
 
this.audioNode.preload = 'auto';
 
  
    this.api = new mw.Api();
+
  this.label = '';
 +
  this.media = '';
 +
  this.lang = '';
 +
  this.speaker = '';
  
this.recordQid = recordQid;
+
  this.wbRecord.getFromApi(this.api).then(this.processRecord.bind(this), displayError);
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() {
 
AudioBox.prototype.processRecord = function() {
this.label = this.wbRecord.getLabel( 'en' );
+
  this.label = this.wbRecord.getLabel('en');
this.media = 'https://commons.wikimedia.org/wiki/Special:FilePath/' + this.wbRecord.getStatements( 'P3' )[ 0 ].getValue();
+
  this.media = 'https://commons.wikimedia.org/wiki/Special:FilePath/' + this.wbRecord.getStatements('P3')[0].getValue();
this.langQid = this.wbRecord.getStatements( 'P4' )[ 0 ].getValue();
+
  this.langQid = this.wbRecord.getStatements('P4')[0].getValue();
this.speakerQid = this.wbRecord.getStatements( 'P5' )[ 0 ].getValue();
+
  this.speakerQid = this.wbRecord.getStatements('P5')[0].getValue();
  
this.api.get( {
+
  this.api.get({
action: "wbgetentities",
+
    action: "wbgetentities",
format: "json",
+
    format: "json",
ids: this.langQid + '|' + this.speakerQid,
+
    ids: this.langQid + '|' + this.speakerQid,
props: "labels",
+
    props: "labels",
languages: mw.config.get( 'wgUserLanguage' ) + "|en",
+
    languages: mw.config.get('wgUserLanguage') + "|en",
languagefallback: 1,
+
    languagefallback: 1,
} ).then( this.processLabels.bind( this ), displayError );
+
  }).then(this.processLabels.bind(this), displayError);
 
}
 
}
  
AudioBox.prototype.processLabels = function( data ) {
+
AudioBox.prototype.processLabels = function(data) {
var langLabels;
+
  var langLabels;
 
+
  if (data.entities === undefined || data.entities[this.langQid] === undefined || data.entities[this.speakerQid] === undefined) {
if ( data.entities === undefined || data.entities[ this.langQid ] === undefined || data.entities[ this.speakerQid ] === undefined ) {
+
    displayError('dataerror');
displayError( 'dataerror' );
+
    return;
return;
+
  }
}
+
  langLabels = data.entities[this.langQid].labels;
langLabels = data.entities[ this.langQid ].labels;
+
  if (langLabels[mw.config.get('wgUserLanguage')] !== undefined) {
+
    this.lang = langLabels[mw.config.get('wgUserLanguage')].value;
if ( langLabels[ mw.config.get( 'wgUserLanguage' ) ] !== undefined ) {
+
  } else {
this.lang = langLabels[ mw.config.get( 'wgUserLanguage' ) ].value;
+
    this.lang = langLabels['en'].value;
} else {
+
  }
this.lang = langLabels[ 'en' ].value;
+
  this.speaker = data.entities[this.speakerQid].labels['en'].value;
}
+
  this.display();
 
this.speaker = data.entities[ this.speakerQid ].labels[ 'en' ].value;
 
 
 
this.display();
 
 
}
 
}
  
 
AudioBox.prototype.display = function() {
 
AudioBox.prototype.display = function() {
this.$node.find( '.ab-title' ).text( this.label );
+
  this.$node.find('.ab-title').text(this.label);
this.$node.find( '.ab-metadata' ).text( this.lang + ' - ' + this.speaker );
+
  this.$node.find('.ab-metadata').text(this.lang + ' - ' + this.speaker);
+
  this.audioNode.src = this.media;
this.audioNode.src = this.media;
+
  this.$node.find('.ab-playbutton').click(this.audioNode.play.bind(this.audioNode));
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;
 
+
  }
function createAudioBoxes( data ) {
+
  ab1 = new AudioBox(data.query.rwrecords[0], $('.audiobox').eq(0));
if ( data.query === undefined || data.query.rwrecords === undefined || data.query.rwrecords.length < 2 ) {
+
  ab2 = new AudioBox(data.query.rwrecords[1], $('.audiobox').eq(1));
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() {
 
function getLastRecords() {
    var api = new mw.Api();
+
  var api = new mw.Api();
api.get( {
+
  api.get({
        action: 'query',
+
    action: 'query',
        format: 'json',
+
    format: 'json',
        list: 'rwrecords',
+
    list: 'rwrecords',
        rwrlimit: '2',
+
    rwrlimit: '2',
rwrsort: 'pageid',
+
    rwrsort: 'pageid',
rwrdir: 'descending',
+
    rwrdir: 'descending',
rwrformat: 'qid'
+
    rwrformat: 'qid'
   } ).then( createAudioBoxes, displayError );
+
   }).then(createAudioBoxes, displayError);
 
}
 
}
  
function displayError( code, error ) {
+
function displayError(code, error) {
console.warn( code, error );
+
  console.warn(code, error);
 
}
 
}
  
if ( mw.config.get( 'wgPageName' ) === 'LinguaLibre:Main_Page' ) {
+
if (mw.config.get('wgPageName') === 'LinguaLibre:Main_Page') {
    mw.loader.using( [ 'mediawiki.api', 'ext.recordWizard.wikibase' ] ).then( getLastRecords );
+
  mw.loader.using(['mediawiki.api', 'ext.recordWizard.wikibase']).then(getLastRecords);
 
}
 
}
 
 
  
 
/*Confirmation message when users try to leave the Record Wizard
 
/*Confirmation message when users try to leave the Record Wizard
 
(works from the second step onwards) */
 
(works from the second step onwards) */
$( function() {
+
$(function() {
if(mw.config.get( 'wgPageName' ) !== 'Special:RecordWizard') {
+
  if (mw.config.get('wgPageName') !== 'Special:RecordWizard') {
return;
+
    return;
}
+
  }
window.onbeforeunload = function() {
+
  window.onbeforeunload = function() {
  return "Do you want to leave the page? All your unsaved changes will be lost.";
+
    return "Do you want to leave the page? All your unsaved changes will be lost.";
};
+
  };
 
});
 
});

Revision as of 21:09, 12 December 2021

// Modules loader, conditional 
// RecordWizard
// Main page
// SoundLibrary
if (/^LinguaLibre:Explore_the_sound_library(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
  mw.loader.load('/index.php?title=MediaWiki:SoundLibrary.js&action=raw&ctype=text/javascript');
}
// Search by words, see https://jsfiddle.net/hugolpz/ecpzy0fo/89/
if (/^LinguaLibre:Search_by(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
  mw.loader.load('/index.php?title=MediaWiki:SearchBy.js&action=raw&ctype=text/javascript');
}
// Languages overview
// Minorities measures
// Query generator , see https://jsfiddle.net/hugolpz/rygo9s5b/

// 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);
}

/*Confirmation message when users try to leave the Record Wizard
(works from the second step onwards) */
$(function() {
  if (mw.config.get('wgPageName') !== 'Special:RecordWizard') {
    return;
  }
  window.onbeforeunload = function() {
    return "Do you want to leave the page? All your unsaved changes will be lost.";
  };
});