MediaWiki:Gadget-CatWatch.js
Questa pagina definisce alcuni parametri di aspetto e comportamento generale di tutte le pagine. Per personalizzarli vedi Aiuto:Stile utente.
Nota: dopo aver salvato è necessario pulire la cache del proprio browser per vedere i cambiamenti (per le pagine globali è comunque necessario attendere qualche minuto). Per Mozilla / Firefox / Safari: fare clic su Ricarica tenendo premuto il tasto delle maiuscole, oppure premere Ctrl-F5 o Ctrl-R (Command-R su Mac); per Chrome: premere Ctrl-Shift-R (Command-Shift-R su un Mac); per Konqueror: premere il pulsante Ricarica o il tasto F5; per Opera può essere necessario svuotare completamente la cache dal menù Strumenti → Preferenze; per Internet Explorer: mantenere premuto il tasto Ctrl mentre si preme il pulsante Aggiorna o premere Ctrl-F5.
/**
* Gadget-CatWatch.js
* Quando si visita [[Speciale:OsservatiSpeciali]] questo gadget vi aggiunge anche ogni voce
* a cui è stata inserita una delle categorie monitorate (non la rimozione).
*
* Il funzionamento si basa sull'utilizzo di [[mw:API:Categorymembers]]:
* quando l'utente visita [[Speciale:OsservatiSpeciali]] viene scaricata la lista di tutte le pagine
* che si trovano in quel momento nelle categorie monitorate. Ogni pagina, se la data di categorizzazione
* è presente in OsservatiSpeciali, viene allora aggiunta a quelle già presenti in OsservatiSpeciali.
*
* Riscritto da zero a partire da:
* http://it.wikipedia.org/w/index.php?title=Wikipedia:Monobook.js/Catwatch.js&oldid=52893797
* che a sua volta lo importava da:
* http://en.wikipedia.org/w/index.php?title=User:Ais523/catwatch.js&oldid=216824057
*
* @author [[:it:User:Rotpunkt]]
*/
/*jshint unused: false, evil: true */
/*global mediaWiki, jQuery */
( function ( mw, $ ) {
'use strict';
var i18n = {
en : {
errorEval: 'Error evaluating',
errorGet: 'Error retrieving',
msgConfig: 'Category watchlist not found. Do you want to create a new one?',
monthNames: 'wgMonthNames'
},
it : {
errorEval: 'Errore in',
errorGet: 'Errore nel leggere',
msgConfig: 'Non hai ancora una lista di categorie da controllare. Vuoi crearne una?',
monthNames: 'wgMonthNamesShort'
}
},
// Massimo numero di pagine monitorate per categoria (max 500)
maxPagesInCategory = 100,
// Configurazione utente
userConfig = 'User:' + mw.config.get( 'wgUserName' ) + '/CategorieOsservate.js',
// Modello di configurazione
configModel = 'MediaWiki:Gadget-CatWatch.js/CategorieOsservateTemplate.js';
function msg( key ) {
var msgs = i18n[mw.config.get( 'wgUserLanguage' )] || i18n.en;
return msgs[key];
}
// Ritorna la variabile CategorieOsservate nel CategorieOsservate.js dell'utente
function getUserConfig( categoryHandler ) {
$.ajax( {
url: mw.config.get( 'wgScript' ),
data: {
title: userConfig,
action: 'raw',
ctype: 'text/javascript'
},
dataType: 'script',
cache: false
} )
.done( function ( data ) {
try {
eval( data );
} catch ( e ) {
alert( '[CatWatch] ' + msg( 'errorEval' ) + ' ' + userConfig );
return;
}
if ( window.CategorieOsservate !== undefined ) {
if ( window.CategorieOsservate.length > 0 ) {
categoryHandler( window.CategorieOsservate );
}
} else if ( confirm( '[CatWatch] ' + msg( 'msgConfig' ) ) ) {
document.___location = mw.config.get( 'wgScript' ) +
'?action=edit&title=' + userConfig +
'&preload=' + configModel;
}
} )
.fail( function ( jqXHR, textStatus, errorThrown ) {
if ( mw.util.getParamValue( 'debug' ) ) {
alert( '[CatWatch] ' + msg('errorGet') + ' ' +
userConfig + ': ' + errorThrown );
}
} );
}
// Ritorna la lista delle pagine in una categoria ( in formato JSON )
function getCategoryPages( name, end, pageHandler ) {
$.ajax( {
url: mw.util.wikiScript( 'api' ),
data: {
action: 'query',
list: 'categorymembers',
cmtitle: 'Category:' + name,
cmlimit: maxPagesInCategory,
cmprop: 'title|timestamp',
cmsort: 'timestamp',
cmdir: 'desc',
cmend: end,
format: 'json'
},
dataType: 'json'
} )
.done( function ( data ) {
pageHandler( data.query.categorymembers );
} );
}
function padleft0( num ) {
return ( num < 10 ? '0' : '' ) + num;
}
// Parsifica un timestamp in date (1 gen 2001) e time (01:23)
function parseTimestamp( timestamp ) {
var date, hours, minutes, months;
date = new Date( timestamp );
hours = date.getHours();
minutes = date.getMinutes();
months = mw.config.get( msg( 'monthNames' ) );
return {
date: date.getDate() + ' ' + months[date.getMonth() + 1] + ' ' +
date.getFullYear(),
time: padleft0( hours ) + ':' + padleft0( minutes )
};
}
function makeTimestamp( text ) {
var months, month, date = text.split( ' ' );
months = mw.config.get( msg('monthNames') );
month = months.indexOf( date[1] );
return month !== -1 ? ( date[2] + '-' + padleft0( month ) + '-' + padleft0( parseInt( date[0], 10 ) ) + 'T00:00:00Z' ) : null;
}
// Crea un nuovo elemento di OsservatiSpeciali
function createWatchlistEl( title, time, category ) {
var url, urlcat, $cron, $cat, $page, $last;
url = mw.config.get( 'wgScript' ) + '?title=' + title;
urlcat = mw.config.get( 'wgArticlePath' ).replace( '$1', 'Categoria:' + category );
$cron = $( '<a>' ).attr( 'href', url + '&action=history' ).text( 'cron' );
$cat = $( '<a>' ).attr( 'href', urlcat ).text( 'Categoria:' + category );
$page = $( '<a>' ).attr( 'href', mw.config.get( 'wgArticlePath' )
.replace( '$1', encodeURIComponent( title ) ) + '?redirect=no' ).text( title );
$last = $( '<a>' ).attr( 'href', url + '&diff=last' ).text( 'last' );
return $( '<li>' ).css( 'font-weight', 'bold' )
.append( '(diff | ', $cron, ') . . ', $cat, '; ', time,
' . . (+ ', $page, ' (', $last, '))' );
}
// Parsifica l'elenco di pagine di OsservatiSpeciali
function parseWatchlistDOM() {
var date, ret = {};
// ogni giorno è un <h4>
$( 'h4' ).each( function () {
date = $( this ).text();
ret[date] = [];
// la pagina di ogni giorno è un <li> in un <ul class='special'>
$( this ).next( 'ul.special' ).find( 'li' ).each( function () {
ret[date].push( {
time: $( this ).find( 'span.mw-changeslist-date' ).text(),
el: $( this )
} );
} );
// retrocompatibilità con il vecchio CatWatch: con la vista raggruppata
// visualizzava le pagine del CatWatch al fondo del giorno
if ( ret[date].length === 0 ) {
ret[date].push( {
time: '23:59',
el: $( this ).next( 'div' ).find( 'table:last-child()' )
} );
}
} );
ret.oldestDate = date ? makeTimestamp( date ) : null;
return ret;
}
// Aggiunge una pagina ad OsservatiSpeciali, se quel giorno è visualizzato
function watchlistAdd( watchlist, page, category ) {
var ts, el, daypages, prepended = false;
ts = parseTimestamp( page.timestamp );
daypages = watchlist[ts.date];
if ( daypages ) {
el = createWatchlistEl( page.title, ts.time, category );
// per tutte le pagine di quel giorno cerca quella col time antecedente
$.each( daypages, function ( i, entry ) {
if ( ts.time > entry.time ) {
entry.el.before( el );
daypages.splice( i, 0, { time: ts.time, el: el } );
prepended = true;
return false;
}
} );
if ( !prepended ) {
daypages[daypages.length - 1].el.after( el );
daypages.push( { time: ts.time, el: el } );
}
}
}
$( function () {
// Se la pagina corrente è Speciale:OsservatiSpeciali
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Watchlist' ) {
// scarica la lista delle categorie da monitorare.
getUserConfig( function ( categories ) {
// Parsifica OsservatiSpeciali.
var watchlist = parseWatchlistDOM();
// Per ogni categoria da monitorare
$.each( categories, function ( i, category ) {
// scarica la lista delle pagine in quella categoria.
getCategoryPages( category, watchlist.oldestDate, function ( categorymembers ) {
// Per ogni pagina nella categoria monitorata
$.each( categorymembers, function ( i, page ) {
// aggiunge la pagina a OsservatiSpeciali.
watchlistAdd( watchlist, page, category );
} );
} );
} );
} );
}
} );
}( mediaWiki, jQuery ) );