MediaWiki:Gadget-Descriptions.js: Difference between revisions

From Resistance in Belgium
(Created page with "// required modules: mediawiki.api, jquery.wikibase.wbtooltip ( function ( mw, $, wb ) { // only works for items if ( !mw.config.exists( 'wbEntityId' ) ) { return; }...")
 
No edit summary
 
(15 intermediate revisions by the same user not shown)
Line 1: Line 1:
// required modules: mediawiki.api, jquery.wikibase.wbtooltip
// Fonction pour diviser un tableau en sous-tableaux
function chunkArray(array, chunkSize) {
    var results = [];
    while (array.length) {
        results.push(array.splice(0, chunkSize));
    }
    return results;
}


( function ( mw, $, wb ) {
// Fonction principale
function init() {
    var api = new mw.Api(),
        userLang = mw.config.get('wgUserLanguage') || 'en',
        ids = [],
        anchors = {},
        $tooltip = $('<span>').appendTo('body');


// only works for items
    // Sélectionner tous les liens avec des entités dans les statements
if ( !mw.config.exists( 'wbEntityId' ) ) {
    $( '.wikibase-statementgroupview a[href^="/wiki/"]' ).each(function() {
return;
        var $anchor = $(this),
}
            id = $anchor.attr('href').replace(/.*Item:(Q\d+)/, '$1').replace(/.*Property:(P\d+)/, '$1');
       
        if (id.indexOf('Q') !== 0 && id.indexOf('P') !== 0) {
            return;
        }


/* T222491, hovercards were uninstalled
        ids.push(id);
// disable when hovercards are activated
        if (anchors[id]) {
if ( mw.user.options.get( 'popups' ) === "1" ) {
            anchors[id].push($anchor);
return;
        } else {
}
            anchors[id] = [$anchor];
*/
        }
    });


function init() {
    if (ids.length === 0) {
var api = new mw.Api(),
        return;
userLang = mw.config.get( 'wgUserLanguage' ),
    }
ids = [],
anchors = {},
$tooltip = $( '<span>' )
.appendTo( 'body' );


$( '.wikibase-statementgroupview a[href^="/wiki/"]' )
    // Fractionner les IDs en lots de 50 entités
.each( function () {
    var chunks = chunkArray(ids.slice(), 50);
var $anchor = $( this ),
id = $anchor.attr( 'href' ).replace( /.*Item:(Q\d+)/, '$1' ).replace( /.*Property:(P\d+)/, '$1' );
if ( id.indexOf( 'Q' ) !== 0 && id.indexOf( 'P' ) !== 0 ) {
return;
}


ids.push( id );
    // Pour chaque lot, faire une requête API
if ( anchors[ id ] ) {
    chunks.forEach(function(chunk) {
anchors[ id ].push( $anchor );
        api.get({
} else {
            action: 'wbgetentities',
anchors[ id ] = [ $anchor ];
            ids: chunk,
}
            props: ['descriptions'],
} );
            languages: userLang,
            languagefallback: 1,
        })
        .done(function(data) {
            $.each(data.entities || {}, function(id, entity) {
                if (!entity.descriptions[userLang] || !anchors[id]) {
                    return;
                }


if ( ids.length === 0 ) {
                // Appliquer les tooltips sur chaque lien
return;
                $.each(anchors[id], function(i, $anchor) {
}
                    $anchor.hover(function() {
                        $tooltip.wbtooltip({
                            content: $('<span>').text(entity.descriptions[userLang].value),
                            permanent: true,
                            gravity: 'nw',
                            $anchor: $anchor
                        }).data('wbtooltip').show();
                    }, function() {
                        $tooltip.data('wbtooltip').hide();
                    });
                });
            });
        })
        .fail(function(error) {
            // Gérer les erreurs si nécessaire, sinon ignorer
        });
    });
}


api.get( {
// Charger les dépendances avant d'exécuter le script
action: 'wbgetentities',
mw.loader.using(['mediawiki.api', 'jquery.wikibase.wbtooltip'], function() {
ids: ids,
    $(init); // Initialiser une fois les modules chargés
props: [ 'descriptions' ],
});
languages: userLang,
languagefallback: 1,
} )
.then( function ( data ) {
$.each( data.entities || {}, function ( id, entity ) {
if ( !entity.descriptions[ userLang ] || !anchors[ id ] ) {
return;
}
 
$.each( anchors[ id ], function ( i, $anchor ) {
$anchor.hover( function () {
$tooltip
.wbtooltip( {
content: $( '<span>' ).text( entity.descriptions[ userLang ].value ),
permanent: true,
gravity: 'nw',
$anchor: $anchor
} )
.data( 'wbtooltip' ).show();
}, function () {
$tooltip.data( 'wbtooltip' ).hide();
} );
} );
} );
} );
}
 
$( init );
 
} ( mediaWiki, jQuery, wikibase ) );

Latest revision as of 21:03, 9 October 2024

// Fonction pour diviser un tableau en sous-tableaux
function chunkArray(array, chunkSize) {
    var results = [];
    while (array.length) {
        results.push(array.splice(0, chunkSize));
    }
    return results;
}

// Fonction principale
function init() {
    var api = new mw.Api(),
        userLang = mw.config.get('wgUserLanguage') || 'en',
        ids = [],
        anchors = {},
        $tooltip = $('<span>').appendTo('body');

    // Sélectionner tous les liens avec des entités dans les statements
    $( '.wikibase-statementgroupview a[href^="/wiki/"]' ).each(function() {
        var $anchor = $(this),
            id = $anchor.attr('href').replace(/.*Item:(Q\d+)/, '$1').replace(/.*Property:(P\d+)/, '$1');
        
        if (id.indexOf('Q') !== 0 && id.indexOf('P') !== 0) {
            return;
        }

        ids.push(id);
        if (anchors[id]) {
            anchors[id].push($anchor);
        } else {
            anchors[id] = [$anchor];
        }
    });

    if (ids.length === 0) {
        return;
    }

    // Fractionner les IDs en lots de 50 entités
    var chunks = chunkArray(ids.slice(), 50);

    // Pour chaque lot, faire une requête API
    chunks.forEach(function(chunk) {
        api.get({
            action: 'wbgetentities',
            ids: chunk,
            props: ['descriptions'],
            languages: userLang,
            languagefallback: 1,
        })
        .done(function(data) {
            $.each(data.entities || {}, function(id, entity) {
                if (!entity.descriptions[userLang] || !anchors[id]) {
                    return;
                }

                // Appliquer les tooltips sur chaque lien
                $.each(anchors[id], function(i, $anchor) {
                    $anchor.hover(function() {
                        $tooltip.wbtooltip({
                            content: $('<span>').text(entity.descriptions[userLang].value),
                            permanent: true,
                            gravity: 'nw',
                            $anchor: $anchor
                        }).data('wbtooltip').show();
                    }, function() {
                        $tooltip.data('wbtooltip').hide();
                    });
                });
            });
        })
        .fail(function(error) {
            // Gérer les erreurs si nécessaire, sinon ignorer
        });
    });
}

// Charger les dépendances avant d'exécuter le script
mw.loader.using(['mediawiki.api', 'jquery.wikibase.wbtooltip'], function() {
    $(init);  // Initialiser une fois les modules chargés
});