Ir al contenido

Diferencia entre revisiones de «Usuario:Sophivorus/PageviewsLinked.js»

De Wikipedia, la enciclopedia libre
Contenido eliminado Contenido añadido
Sin resumen de edición
Sin resumen de edición
Línea 29: Línea 29:


getPagesContinue: function ( response, params, pages, $div ) {
getPagesContinue: function ( response, params, pages, $div ) {
console.log( 'getPagesContinue' );
console.log( 'getPagesContinue', response );
for ( var page of response.query.pages ) {
for ( var page of response.query.pages ) {
if ( !page.missing && page.pageviews ) {
if ( !page.missing && page.pageviews ) {

Revisión del 11:38 16 ago 2024

/**
 * This gadget creates a chart showing the pageviews of pages linked from a given page
 */
const PageviewsLinked = {

	init: function () {
		console.log( 'init' );
		$( '.PageviewsLinked' ).each( PageviewsLinked.getPages );
	},

	getPages: function () {
		console.log( 'getPages' );
		const $div = $( this );
		const page = $div.data( 'page' ) || mw.config.get( 'wgPageName' );
		const days = $div.data( 'days' ) || 30;
		const params = {
			action: 'query',
			titles: page,
			prop: 'pageviews',
			pvipdays: days,
			generator: 'links',
			gpllimit: 'max',
			redirects: true,
			formatversion: 2
		};
		const pages = [];
		new mw.Api().get( params ).fail( console.log ).done( response => PageviewsLinked.getPagesContinue( response, params, pages, $div ) );
	},

	getPagesContinue: function ( response, params, pages, $div ) {
		console.log( 'getPagesContinue', response );
		for ( var page of response.query.pages ) {
			if ( !page.missing && page.pageviews ) {
				pages.push( page );
			}
		}
		if ( response.continue ) {
			const cont = response.continue.continue.split( '|' )[0];
			params[ cont ] = response.continue[ cont ];
			new mw.Api().get( params ).fail( console.log ).done( response => PageviewsLinked.getPagesContinue( response, params, pages, $div ) );
		} else {
			PageviewsLinked.makeChart( pages, $div );
		}
	},

	makeChart: function ( pages, $div ) {
		console.log( 'makeChart' );
		// Add up all the pageviews per day
		let total;
		for ( const page of pages ) {
			const pageviews = page.pageviews;
			const subtotal = Object.values( pageviews ).reduce( ( a, b ) => a + b, 0 );
			if ( total ) {
				for ( const [ day, subtotal ] of Object.entries( pageviews ) ) {
					total[ day ] += subtotal;
				}
			} else {
				total = pageviews;
			}
		}

		// Make the line chart using echarts
		const div = $div.get(0);
		$.getScript( '//cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js', function () {
			console.log( div );
			echarts.init( div ).setOption( {
				xAxis: {
					type: 'category',
					data: Object.keys( total )
				},
				yAxis: {
					type: 'value'
				},
				tooltip: {
					trigger: 'item',
					show: true
				},
				series: [ {
					data: Object.values( total ),
					type: 'line'
				} ]
			} );
		} );
	}
};

$( PageviewsLinked.init );