Ir al contenido

Usuario:Sophivorus/WikiProject.js

De Wikipedia, la enciclopedia libre

Nota: Después de guardar, debes refrescar la caché de tu navegador para ver los cambios. Internet Explorer: mantén presionada Ctrl mientras pulsas Actualizar. Firefox: mientras presionas Mayús pulsas el botón Actualizar, (o presiona Ctrl-Shift-R). Los usuarios de Google Chrome y Safari pueden simplemente pulsar el botón Recargar. Para más detalles e instrucciones acerca de otros exploradores, véase Ayuda:Cómo limpiar la caché.

//<nowiki>
 /**
 * Interactúa con la [[Plantilla:Wikiproyecto]] para agregar funcionalidad a los wikiproyectos
 *
 * <nowiki>
 */
const WikiProject = {

	init: function ( require ) {
		$wikiproject = $( '#wikiproject' );
		if ( !$wikiproject.length ) {
			return;
		}

		// Save require for later
		WikiProject.require = require;

		// Get and set the config
		const config = $wikiproject.data();
		mw.config.set( config );

		// Add the wikiproject hashtag to edits done from this tool
		mw.hook( 've.saveDialog.stateChanged' ).add( WikiProject.addHashtagToEditSummary );

		WikiProject.getPages();
	},

	getPages: function () {
		const pages = [];
		const watchlist = mw.config.get( 'wikiprojectWatchlist' );
		const updateTemplates = mw.config.get( 'wikiprojectUpdateTemplates' ).split( ',' ).join( '|' );
		const referenceTemplates = mw.config.get( 'wikiprojectReferenceTemplates' ).split( ',' ).join( '|' );
		const templates = updateTemplates + '|' + referenceTemplates;
		const params = {
			action: 'query',
			titles: watchlist,
			prop: 'info|templates',
			tltemplates: templates,
			tllimit: 'max',
			generator: 'links',
			gpllimit: 'max',
			redirects: true,
			formatversion: 2,
		};
		new mw.Api().get( params ).fail( console.log ).done( response => WikiProject.getPagesContinue( response, params, pages ) );
	},

	getPagesContinue: function ( response, params, pages ) {
		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 => WikiProject.getPagesContinue( response, params, pages ) );
		} else {
			WikiProject.makeTasksLists( pages );
		}
	},

	/**
	 * Mount the Vue app
 	 */
	makeTasksLists: function ( pages ) {
		Codex = WikiProject.require( '@wikimedia/codex' );
		Vue = WikiProject.require( 'vue' );
		Vue.createApp( {
			template: `
				<cdx-accordion>
					<template #title>Referenciar</template>
					<p>Toda la información en Wikipedia debe ser <a target="_blank" href="/wiki/Wikipedia:Verificabilidad">verificable</a>, es decir que debe tener <a target="_blank" href="/wiki/Wikipedia:Referencias">referencias</a> que permitan rastrear el origen de la información.</p>
					<p>Los artículos en esta lista necesitan referencias. Haz click en alguno para empezar. Si ninguno de estos artículos es de tu interés, puedes actualizar la página para regenerar la lista.</p>
					<ul v-if="pagesToReference"><li v-for="page in pagesToReference"><a target="_blank" :href="page.href">{{page.title}}</a></li></ul>
					<p v-else>No hay artículos en esta lista.</p>
				</cdx-accordion>
				<cdx-accordion>
					<template #title>Actualizar</template>
					<p>Los artículos en esta lista necesitan actualizarse con información actual. Haz click en alguno para empezar. Si ninguno de estos artículos es de tu interés, puedes actualizar la página para regenerar la lista.</p>
					<ul v-if="pagesToUpdate"><li v-for="page in pagesToUpdate"><a target="_blank" :href="page.href">{{page.title}}</a></li></ul>
					<p v-else>No hay artículos en esta lista.</p>
				</cdx-accordion>
				<cdx-accordion>
					<template #title>Expandir</template>
					<p>Los artículos en esta lista son demasiado breves y necesitan expansión. Haz click en alguno para empezar. Si ninguno de estos artículos es de tu interés, puedes actualizar la página para regenerar la lista.</p>
					<ul v-if="pagesToExpand"><li v-for="page in pagesToExpand"><a target="_blank" :href="page.href">{{page.title}}</a></li></ul>
					<p v-else>No hay artículos en esta lista.</p>
				</cdx-accordion>
				<cdx-accordion>
					<template #title>Traducir</template>
					<p>Los artículos en esta lista no existen en la Wikipedia en español pero sí en otras Wikipedias. Haz click en alguno para empezar una traducción.</p>
					<ul v-if="pagesToTranslate"><li v-for="page in pagesToTranslate"><a target="_blank" :href="page.href">{{page.title}}</a> ({{page.source}})</li></ul>
					<p v-else>No hay artículos en esta lista.</p>
				</cdx-accordion>
				<cdx-accordion>
					<template #title>Otras</template>
					<p>Aquí se listan otras tareas que puedes realizar. Para agregar, modificar o quitar tareas, edita <a target="_blank" :href="otherTasks.href">esta página</a>.</p>
					<div v-html="otherTasks.text"></div>
				</cdx-accordion>
			`,
			data: function () {
				return {
					pagesToReference: [],
					pagesToUpdate: [],
					pagesToExpand: [],
					pagesToTranslate: [],
					otherTasks: [],
				};
			},
			beforeMount: function () {
				WikiProject.getPagesToReference( this, pages );
				WikiProject.getPagesToUpdate( this, pages );
				WikiProject.getPagesToExpand( this, pages );
				WikiProject.getPagesToTranslate( this );
				WikiProject.getOtherTasks( this );
			}
		} )
		.component( 'cdx-accordion', Codex.CdxAccordion )
		.mount( '#wikiproject-tasks' );
	},

	/**
	 * Hacky way to track edits made through the wikiproject tasks lists
 	 */
	addHashtagToEditSummary: function () {
		$( '.oo-ui-processDialog-actions-primary' ).on( 'mousedown', function () {
			const $summary = $( '.ve-ui-mwSaveDialog-summary' ).find( 'textarea' );
			let summary = $summary.val();

			// Add the wikiproject hashtag
			const params = new URLSearchParams( window.location.search );
			const hashtag = params.get( 'hashtag' );
			if ( hashtag ) {
				summary += ' #' + hashtag;
			}

			$( '.ve-ui-mwSaveDialog-summary' ).find( 'textarea' ).val( summary );
		} );
	},

	getPagesToReference: function ( data, pages ) {
		const editintro = mw.config.get( 'wikiprojectReferenceEditintro' );
		const templates = mw.config.get( 'wikiprojectReferenceTemplates' ).split( ',' );
		const limit = mw.config.get( 'wikiprojectReferenceLimit' );
		const hashtag = mw.config.get( 'wikiprojectHashtag' );
		for ( const page of pages ) {
			if ( page.templates ) {
				for ( const template of page.templates ) {
					if ( templates.includes( template.title ) ) {
						page.href = mw.util.getUrl( page.title, { veaction: 'edit', editintro: editintro, hashtag: hashtag, withJS: 'MediaWiki:Gadget-WikiProject.js' } );
						data.pagesToReference.push( page );
					}
				}
			}
		}
		WikiProject.shuffle( data.pagesToReference );
		if ( data.pagesToReference.length > limit ) {
			data.pagesToReference.length = limit;
		}
		if ( data.pagesToReference.length === 0 ) {
			data.pagesToReference = null;
		}
	},

	getPagesToUpdate: function ( data, pages ) {
		const editintro = mw.config.get( 'wikiprojectUpdateEditintro' );
		const templates = mw.config.get( 'wikiprojectUpdateTemplates' ).split( ',' );
		const limit = mw.config.get( 'wikiprojectUpdateLimit' );
		const hashtag = mw.config.get( 'wikiprojectHashtag' );
		for ( const page of pages ) {
			if ( page.templates ) {
				for ( const template of page.templates ) {
					if ( templates.includes( template.title ) ) {
						page.href = mw.util.getUrl( page.title, { veaction: 'edit', editintro: editintro, hashtag: hashtag, withJS: 'MediaWiki:Gadget-WikiProject.js' } );
						data.pagesToUpdate.push( page );
					}
				}
			}
		}
		WikiProject.shuffle( data.pagesToUpdate );
		if ( data.pagesToUpdate.length > limit ) {
			data.pagesToUpdate.length = limit;
		}
		if ( data.pagesToUpdate.length === 0 ) {
			data.pagesToUpdate = null;
		}
	},

	getPagesToTranslate: function ( data ) {
		const sources = mw.config.get( 'wikiprojectTranslateSources' ).split( ',' );
		const seed = mw.config.get( 'wikiprojectTranslateSeed' );
		const limit = mw.config.get( 'wikiprojectTranslateLimit' );
		const language = mw.config.get( 'wgContentLanguage' );
		sources.forEach( function ( source ) {
			const params = {
				s: source,
				t: language,
				article: seed,
				n: limit,
			};
			$.get( '//api.wikimedia.org/service/lw/recommendation/v1/api', params ).done( results => WikiProject.getPagesToTranslateComplete( results, source, data ) );
		} );
	},

	getPagesToTranslateComplete: function ( results, source, data ) {
		for ( const result of results ) {
			const title = result.title.replaceAll( '_', ' ' );
			const href = mw.util.getUrl( 'Special:ContentTranslation', { page: title, from: source, to: mw.config.get( 'wgContentLanguage' ) } );
			data.pagesToTranslate.push( { title: title, href: href, source: source } );
		}
	},

	getPagesToExpand: function ( data, pages ) {
		const length = mw.config.get( 'wikiprojectExpandLength' );
		const editintro = mw.config.get( 'wikiprojectExpandEditintro' );
		const hashtag = mw.config.get( 'wikiprojectHashtag' );
		const limit = mw.config.get( 'wikiprojectExpandLimit' );
		for ( const page of pages ) {
			if ( page.length < length ) {
				page.href = mw.util.getUrl( page.title, { veaction: 'edit', editintro: editintro, hashtag: hashtag, withJS: 'MediaWiki:Gadget-WikiProject.js' } );
				data.pagesToExpand.push( page );
			}
		}
		WikiProject.shuffle( data.pagesToExpand );
		if ( data.pagesToExpand.length > limit ) {
			data.pagesToExpand.length = limit;
		}
		if ( data.pagesToExpand.length === 0 ) {
			data.pagesToExpand = null;
		}
	},

	getOtherTasks: function ( data ) {
		const tasks = mw.config.get( 'wikiprojectTasks' );
		const href = mw.util.getUrl( tasks );
		data.otherTasks = { href: href };
		const params = {
			action: 'parse',
			page: tasks,
			prop: 'text',
			formatversion: 2,
		};
		new mw.Api().get( params ).fail( console.log ).done( function ( response ) {
			if ( response.parse && response.parse.text ) {
				data.otherTasks.text = response.parse.text;
			}
		} );
	},

	/**
	 * Helper method to shuffle an array
	 * Credit: https://stackoverflow.com/a/12646864/809356
 	 */
	shuffle: function ( array ) {
		for ( let i = array.length - 1; i > 0; i-- ) {
			const j = Math.floor( Math.random() * ( i + 1 ) );
			[ array[i], array[j] ] = [ array[j], array[i] ];
		}
	}
};

mw.loader.using( [
	'mediawiki.api',
	'mediawiki.user',
	'mediawiki.util',
	'@wikimedia/codex'
], WikiProject.init );
//</nowiki>