MediaWiki

Difference between revisions of "Common.js"

(Removed some hacks, since the source code was fixed and deployed (see https://github.com/lingua-libre/RecordWizard/commits/master))
 
(96 intermediate revisions by 5 users not shown)
Line 1: Line 1:
// Replace Wikidata IDs with their [label, description]
+
// Page-specific scripts modules and conditional loading
$( '.wb-external-id' ).each( function() {
+
// RecordWizard sugar
    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 ].value,
 
                description = entity.descriptions[ lang ].value;
 
           
 
            node.html( label + ' <i>(' + node.text() + ')</i><br><small>' + description + '</small>' )
 
        } );
 
    }
 
} );
 
  
 
+
/* *************************************************************** */
 
+
/* PAGE-SPECIFIC SCRIPTS LOADINGS ******************************** */
// Fetch and display DataViz results
+
// Documentation: https://m.mediawiki.org/wiki/ResourceLoader/Architecture#Resource:_Scripts
const sparqlEndpoint = "https://v2.lingualibre.fr/bigdata/namespace/wdq/sparql";
+
// Documentation: https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.loader
 
+
//🎷🥁🎸🐣📔🗻🌏
var DataViz = function( node ) {
+
// LastAudiosBoxes
    this.node = node;
+
if (/^LinguaLibre:Main/.test(mw.config.get('wgPageName'))) {
    this.baseQuery = node.children( '.dataviz-query' ).text().replace(/\u00A0/g, ' ');
+
  console.log('🎸 Last Audios');
    this.resultNode = node.children( '.dataviz-result' );
+
  mw.loader.load('/index.php?title=MediaWiki:LastAudios.js&action=raw&ctype=text/javascript');
    this.inputsNode = node.children( '.dataviz-inputs' );
+
}
 
+
// SoundLibrary
    // Add inputs
+
if (/^LinguaLibre:Explore_the_sound_library(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
   
+
  console.log('🥁 Sound library');
    this.addInputs();
+
  mw.loader.load('/index.php?title=MediaWiki:SoundLibrary.js&action=raw&ctype=text/javascript');
    this.refresh();
+
}
};
+
// Item pages additional sugar
 
+
if (/^(Q|Property:P)[0-9]+$/.test(mw.config.get('wgPageName'))) {
DataViz.prototype.addInputs = function() {
+
  console.log('🍭 ItemsSugar ');
    var regex = /#extra:({.+?})? (.+)/g,
+
  mw.loader.load('/index.php?title=MediaWiki:ItemsSugar.js&action=raw&ctype=text/javascript');
        process = new OO.ui.Process(),
+
}
        query = this.baseQuery,
+
// Lexeme Queries Generator (OOUI)
        m;
+
if (/^Template:LexemeQueriesGenerator$/.test(mw.config.get('wgPageName')) || /^Help:SPARQL_/.test(mw.config.get('wgPageName'))) {
   
+
  console.log('📔 Lexeme Queries Generator');
    this.inputs = [];
+
  mw.loader.load('/index.php?title=MediaWiki:LexemeQueriesGenerator.js&action=raw&ctype=text/javascript');
    this.labels = {};
+
}
    this.filters = {};
+
// SPARQL to data (OOUI)
    while ( ( m = regex.exec( query ) ) !== null ) {
+
if (/SPARQL/.test(mw.config.get('wgPageName')) || /parql/.test(mw.config.get('wgPageName'))) {
        console.log( m );
+
  console.log('🚀 SPARQL to data');
        // This is necessary to avoid infinite loops with zero-width matches
+
  mw.loader.load('/index.php?title=MediaWiki:Sparql2data.js&action=raw&ctype=text/javascript');
        if (m.index === regex.lastIndex) {
+
}
            regex.lastIndex++;
+
// Click bug & browser
        }
+
if (/browser/.test(mw.config.get('wgPageName')) || /bug/.test(mw.config.get('wgPageName'))) {
       
+
  console.log('🎷 Click bug & browser');
        var input = JSON.parse( m[ 1 ] );
+
  mw.loader.load('/index.php?title=MediaWiki:Browser.js&action=raw&ctype=text/javascript');
        input[ 'query' ] = m[ 2 ];
+
}
       
+
/* *************************************************************** */
        if ( input[ 'label' ] !== undefined ) {
+
/* In development *************************************** */
            this.labels[ input[ 'label' ] ] = input[ 'label' ];
+
// User:Yug: Language overview
        }
+
if (/Languages/.test(mw.config.get('wgPageName'))) {
       
+
  console.log('🌏 Languages gallery');
        if ( input[ 'filter' ] !== undefined ) {
+
  mw.loader.load('/index.php?title=MediaWiki:LanguagesGallery.js&action=raw&ctype=text/javascript');
            this.filters[ input[ 'filter' ] ] = [];
+
}
        }
+
// User:Yug: Search by words, see https://jsfiddle.net/hugolpz/ecpzy0fo/89/
       
+
if (/^LinguaLibre:Search_by(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
        var i = this.inputs.push( input );
+
  console.log('🐣 Search by word');
        this.baseQuery = this.baseQuery.replace( m[ 0 ], '#$' + i );
+
  mw.loader.load('/index.php?title=MediaWiki:SearchBy.js&action=raw&ctype=text/javascript');
    }
 
   
 
    // Fetch labels
 
    if ( Object.keys( this.labels ).length ) {
 
        process.next( this.getLabels.bind( this ) );
 
    }
 
   
 
    // Preload values for limited inputs
 
    for ( var item in this.filters ) {
 
        process.next( this.loadFilterValues.bind( this, item ) );
 
    }
 
   
 
    // Once all data has been collected, we can create the fields
 
    for ( var i=0; i < this.inputs.length; i++ ) {
 
        process.next( this.createField.bind( this, this.inputs[ i ] ) );
 
    }
 
   
 
    var button = new OO.ui.ButtonWidget( {
 
        label: 'Filtrer!',
 
        flags: [ 'primary', 'progressive' ]
 
    } );
 
   
 
    button.on( 'click', this.refresh.bind( this ) );
 
    this.inputsNode.append( button.$element );
 
   
 
    process.execute();
 
};
 
 
 
DataViz.prototype.loadFilterValues = function( item ) {
 
    var query = 'select ?id ?idLabel where {?id prop:P2 entity:' + item + '. SERVICE wikibase:label{bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".}}';
 
   
 
    return this.postQuery( query ).then( function( data ) {
 
        var rows = data.results.bindings;
 
        for ( var i=0; i < rows.length; i++ ) {
 
            dataviz.filters[ item ].push( new OO.ui.MenuOptionWidget( {
 
                data: rows[ i ][ 'id' ].value.split( '/' ).pop(),
 
                label: rows[ i ][ 'idLabel' ].value
 
            } ) );
 
        }
 
    } );
 
};
 
 
 
DataViz.prototype.getLabels = function( query ) {
 
    var dataviz = this,
 
        lang = mw.config.get( 'wgUserLanguage' ),
 
        api = new mw.Api();
 
    return api.get( {
 
        action: 'wbgetentities',
 
        format: 'json',
 
        ids: Object.keys( this.labels ).join( '|' ),
 
        props: 'labels',
 
        languages: lang,
 
        languagefallback: 1
 
    } ).then( function( data ) {
 
        for ( entity in data.entities ) {
 
            dataviz.labels[ entity ] = data.entities[ entity ].labels[ lang ].value;
 
        }
 
    } );
 
};
 
 
 
DataViz.prototype.createField = function( infos ) {
 
    var field;
 
   
 
    switch( infos.type ) {
 
        case 'wikibase-item':
 
            field = new OO.ui.CapsuleMultiselectWidget( {
 
                menu: { items: this.filters[ infos[ 'filter' ] ] }
 
            } );
 
            break;
 
        default:
 
            field = new OO.ui.TextInputWidget();
 
    }
 
    this.inputsNode.append( new OO.ui.FieldLayout( field, {
 
        align: 'left',
 
        label: this.labels[ infos[ 'label' ] ],
 
    } ).$element );
 
   
 
    infos[ 'field' ] = field;
 
};
 
 
 
DataViz.prototype.preProcessQuery = function() {
 
    var query = this.baseQuery;
 
   
 
    for ( var i=0; i < this.inputs.length; i++ ) {
 
        if ( this.inputs[ i ].field !== undefined ) {
 
            switch( this.inputs[ i ].type ) {
 
                case 'wikibase-item':
 
                    var values = this.inputs[ i ].field.getItemsData();
 
                    for ( var j=0; j < values.length; j++ ) {
 
                        values[ j ] = '{' + this.inputs[ i ].query.replace( '[EXTRA]', values[ j ] ) + '}';
 
                    }
 
                    query = query.replace( '#$' + (i+1), values.join( ' UNION ' ) );
 
                    break;
 
                default:
 
                    var value = this.inputs[ i ].field.getValue();
 
                    query = query.replace( '#$' + (i+1), this.inputs[ i ].query.replace( '[EXTRA]', value ) );
 
            }
 
        }
 
    }
 
   
 
    return query;
 
};
 
 
 
DataViz.prototype.postQuery = function( query ) {
 
    query = query.replace(/\u00A0/g, ' ').replace( '[AUTO_LANGUAGE]', mw.config.get( 'wgUserLanguage' ) );
 
    return $.post( sparqlEndpoint, { format: 'json', query: query } );
 
};
 
 
 
DataViz.prototype.refresh = function() {
 
    var dataviz = this,
 
        query = this.preProcessQuery();
 
   
 
    this.postQuery( query ).then( function( data ) {
 
        var table = dataviz.dataToTable( data.head.vars, data.results.bindings );
 
        dataviz.resultNode.html( table );
 
    } ).fail( function( data ) {
 
        console.log( data.responseText );
 
        //TODO: manage errors
 
    } );
 
};
 
 
 
DataViz.prototype.dataToTable = function( headList, bodyList ) {
 
    var order = [],
 
        theadTr = $( '<tr>' ),
 
        thead = $( '<thead>' ).append( theadTr ),
 
        tbody = $( '<tbody>' ),
 
        table = $( '<table>' )
 
    .addClass( 'wikitable sortable' )
 
    .append( thead ).append( tbody );
 
 
 
    for ( var i = 0; i < headList.length; i++ ) {
 
        theadTr.append( $( '<th>' ).text( headList[ i ] ) );
 
        order.push( headList[ i ] );
 
    }
 
 
 
    for ( var i=0; i < bodyList.length; i++ ) {
 
        var tr = $( '<tr>' ).appendTo( tbody );
 
 
 
        for ( var j=0; j < order.length; j++ ) {
 
            var cell = bodyList[ i ][ order[ j ] ];
 
            if ( cell.type === 'uri' ) {
 
                cell.value = $( '<a>' )
 
                    .attr( 'href', cell.value )
 
                    .text( cell.value.split( '/' ).pop() );
 
            }
 
            tr.append( $( '<td>' ).html( cell.value ) );
 
        }
 
    }
 
 
 
    table.tablesorter();
 
   
 
    return table;
 
 
}
 
}
 +
// Minorities languages statistics page
  
 +
// Iframe gallery for Lingualibre:Apps
 +
// Prototype https://jsfiddle.net/hugolpz/meygpo6t/
 +
// Problem: iframe are not accepted into wikicode. Solution: hide key values in html tag, generate iframe via JS injection.
  
  
mw.loader.using( [ 'jquery.tablesorter', 'oojs-ui' ], function() {
+
/*Query visualisation: Replace loading text by a spinner gif***********************************************************/
    $( '.dataviz' ).each( function() {
+
$( '.queryviz-loading' ).html( '<center><img src="https://upload.wikimedia.org/wikipedia/commons/7/7a/Balls.gif" width="50" /></center>' );
        window.dataviz = new DataViz( $( this ) );
 
    } );
 
} );
 

Latest revision as of 08:51, 20 April 2023

// Page-specific scripts modules and conditional loading
// RecordWizard sugar

/* *************************************************************** */
/* PAGE-SPECIFIC SCRIPTS LOADINGS ******************************** */
// Documentation: https://m.mediawiki.org/wiki/ResourceLoader/Architecture#Resource:_Scripts
// Documentation: https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.loader
//🎷🥁🎸🐣📔🗻🌏
// LastAudiosBoxes
if (/^LinguaLibre:Main/.test(mw.config.get('wgPageName'))) {
  console.log('🎸 Last Audios');
  mw.loader.load('/index.php?title=MediaWiki:LastAudios.js&action=raw&ctype=text/javascript');
}
// SoundLibrary
if (/^LinguaLibre:Explore_the_sound_library(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
  console.log('🥁 Sound library');
  mw.loader.load('/index.php?title=MediaWiki:SoundLibrary.js&action=raw&ctype=text/javascript');
}
// Item pages additional sugar
if (/^(Q|Property:P)[0-9]+$/.test(mw.config.get('wgPageName'))) {
  console.log('🍭 ItemsSugar ');
  mw.loader.load('/index.php?title=MediaWiki:ItemsSugar.js&action=raw&ctype=text/javascript');
}
// Lexeme Queries Generator (OOUI)
if (/^Template:LexemeQueriesGenerator$/.test(mw.config.get('wgPageName')) || /^Help:SPARQL_/.test(mw.config.get('wgPageName'))) {
  console.log('📔 Lexeme Queries Generator');
  mw.loader.load('/index.php?title=MediaWiki:LexemeQueriesGenerator.js&action=raw&ctype=text/javascript');
}
// SPARQL to data (OOUI)
if (/SPARQL/.test(mw.config.get('wgPageName')) || /parql/.test(mw.config.get('wgPageName'))) {
  console.log('🚀 SPARQL to data');
  mw.loader.load('/index.php?title=MediaWiki:Sparql2data.js&action=raw&ctype=text/javascript');
}
// Click bug & browser
if (/browser/.test(mw.config.get('wgPageName')) || /bug/.test(mw.config.get('wgPageName'))) {
  console.log('🎷 Click bug & browser');
  mw.loader.load('/index.php?title=MediaWiki:Browser.js&action=raw&ctype=text/javascript');
}
/* *************************************************************** */
/* In development *************************************** */
// User:Yug: Language overview
if (/Languages/.test(mw.config.get('wgPageName'))) {
  console.log('🌏 Languages gallery');
  mw.loader.load('/index.php?title=MediaWiki:LanguagesGallery.js&action=raw&ctype=text/javascript');
}
// User:Yug: Search by words, see https://jsfiddle.net/hugolpz/ecpzy0fo/89/
if (/^LinguaLibre:Search_by(\/[a-z_-]+)?$/.test(mw.config.get('wgPageName'))) {
  console.log('🐣 Search by word');
  mw.loader.load('/index.php?title=MediaWiki:SearchBy.js&action=raw&ctype=text/javascript');
}
// Minorities languages statistics page

// Iframe gallery for Lingualibre:Apps
// Prototype https://jsfiddle.net/hugolpz/meygpo6t/
// Problem: iframe are not accepted into wikicode. Solution: hide key values in html tag, generate iframe via JS injection.


/*Query visualisation: Replace loading text by a spinner gif***********************************************************/
$( '.queryviz-loading' ).html( '<center><img src="https://upload.wikimedia.org/wikipedia/commons/7/7a/Balls.gif" width="50" /></center>' );