MediaWiki:Gadget-CategoryData.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
const Category = {

	init( $content ) {

		// Get automatic translations
		const translations = [];
		$content.find( '#mw-pages a' ).each( ( index, link ) => {
			if ( link.textContent.match( '/[a-z]{2,3}$' ) ) {
				const item = link.closest( 'li' );
				translations.push( item );
			}
		} );

		// Hide automatic translations and show a switch to toggle them
		if ( translations.length ) {
			Category.toggleTranslations( translations );
			Category.addSwitch( translations );
		}
	},

	toggleTranslations( translations ) {
		for ( const translation of translations ) {
			translation.hidden = !translation.hidden;
		}
	},

	addSwitch( translations ) {
		mw.loader.using( '@wikimedia/codex' ).then( require => {
			const Vue = require( 'vue' );
			const Codex = require( '@wikimedia/codex' );
			const data = { translations: translations };
			const app = Vue.createMwApp( Category.switchComponent, data );
			app.component( 'cdx-toggle-switch', Codex.CdxToggleSwitch );
			app.mount( '#toggle-translations-switch' );
		} );
	},

	switchComponent: {

		props: [ 'translations' ],

		template: `<cdx-toggle-switch
				style="height: 1em; margin-left: .5em; vertical-align: middle;"
				v-model="showTranslations"
				@update:model-value="onUpdate"
			></cdx-toggle-switch>`,

		data() {
			return {
				showTranslations: false
			};
		},

		methods: {
			onUpdate() {
				Category.toggleTranslations( this.translations );
			}
		},
	},
};

mw.hook( 'wikipage.content' ).add( Category.init );