MediaWiki:ExcerptTree.js

Dari Wikipedia bahasa Indonesia, ensiklopedia bebas

Catatan: Setelah menyimpan, Anda harus memintas tembolok (cache) peramban Anda untuk melihat perubahannya. Google Chrome, Firefox, Microsoft Edge dan Safari: Tahan tombol Shift dan klik Muat ulang (Reload) di tombol bilah alat. Untuk detail dan instruksi tentang peramban lain, lihat halaman menghapus singgahan (Inggris).

/**
 * ExcerptTree is a script to view and navigate excerpt trees in Wikipedia
 * Author/Maintainer: Sophivorus
 * Expected use will be via ?withJS links, so may not appear in what-links-here
 */
var ExcerptTree = {

	/**
	 * Initialization script
	 */
	init: function () {
		$( '.ExcerptTree' ).show();
		$( '.ExcerptTree li' ).each( ExcerptTree.addChildren );
	},

	addChildren: function () {
		var node = $( this ),
			title = $( node ).children( 'a' ).text();
		ExcerptTree.getChildren( title ).done( function ( data ) {
			var page = data.query.pages[0],
				children = page.templates;
			if ( children ) {
				children = children.map( function ( x ) { return x.title } );
				children = children.filter( function ( x ) { return x !== title } );
				if ( page.redirects ) {
					children = children.filter( function ( x ) {
						return page.redirects.map( function ( x ) {
							return x.title;
						} ).indexOf( x ) == -1;
					} );
				}
				if ( children.length ) {
					ExcerptTree.addButton( node );
					var list = $( '<ul>' ).hide().data( 'virgin', true );
					children.forEach( function ( title ) {
						var link = $( '<a>', { 'href': mw.util.getUrl( title ), 'title': title } ).text( title ),
							item = $( '<li>' ).html( link );
						list.append( item );
					});
					node.append( list );
				}
			}
		});
	},

	/**
	 * Add a clickable right-arrow to the given node
	 */
	addButton: function ( node ) {
		var button = $( '<span>' ).text( '►' ).css({
			'cursor': 'pointer',
			'position': 'absolute',
			'left': '-1em'
		});
		node.css({
			'list-style': 'none',
			'position': 'relative'
		}).prepend( button );
		button.click( node, ExcerptTree.toggleChildren );
	},

	toggleChildren: function ( event ) {
		var node = event.data,
			button = $( node ).children( 'span' ),
			list = $( node ).children( 'ul' ),
			virgin = list.data( 'virgin' );

		list.toggle();
		if ( virgin ) {
			list.data( 'virgin', false );
			list.children( 'li' ).each( ExcerptTree.addChildren );
			button.text( '▼' );
		} else {
			if ( list.is( ':visible' ) ) {
				button.text( '▼' );
			} else {
				button.text( '►' );
			}
		}
	},

	getChildren: function ( title ) {
		var api = new mw.Api();
		return api.get({
			titles: title,
			action: 'query',
			formatversion: 2,
			prop: 'templates|redirects',
			rdlimit: 'max',
			tllimit: 'max',
			tlnamespace: '0'
		});
	}
};

mw.loader.using( 'mediawiki.api', ExcerptTree.init );