User:Aude/preview.js

From Wikidata
Jump to navigation Jump to search

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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// -------------------------------------------------------------------------------------------------------------
// Shows a "preview" button next to each linked article to get a preview of the article right next to the table.
// Much thanks to User:Denny/articlePreview.js, from which I got the idea.
//
// Usage: Enable the gadget Preview in your preferences.
// -------------------------------------------------------------------------------------------------------------

( function ( mw, $, wb ) {
	"use strict";

	var entityLoaded = $.Deferred();

	switch ( mw.config.get( 'wgUserLanguage' ) ) {
	case 'de':
	case 'de-at':
	case 'de-ch':
	case 'de-formal':
		mw.messages.set( {
			'title' :	'Artikelvorschau',
			'preview' :	'Vorschau',
			'noarticle' :	'Du hast noch keinen Artikel ausgewählt.',
			'missing' :	'Der Artikel existiert nicht.',
			'readmore' :	'Weiterlesen',
			'hide' :	'verstecken',
			'show' :	'zeigen'
		} );
		break;
	case 'bn':
		mw.messages.set( {
			'title' :	'নিবন্ধ প্রাকদর্শন',
			'preview' :	'প্রাকদর্শন',
			'noarticle' :	'আপনি এখনও কোন নিবন্ধ নির্বাচন করেন নি।',
			'readmore' :	'আরও পড়ুন',
			'hide' :	'আড়াল করো',
			'show' :	'দেখাও'
		} );
		break;
	case 'cs':
		mw.messages.set( {
			'title' :	'Náhled článku',
			'preview' :	'náhled',
			'noarticle' :	'Zatím není zvolen článek.',
			'readmore' :	'Více',
			'hide' :	'skryj',
			'show' :	'ukaž'
		} );
		break;
	case 'es':
		mw.messages.set( {
			'title' :	'Previsualización del artículo',
			'preview' :	'previsualizar',
			'noarticle' :	'Aún no seleccionaste ningún artículo.',
			'readmore' :	'Leer más',
			'hide' :	'ocultar',
			'show' :	'mostar'
		} );
		break;
	case 'fa':
		mw.messages.set( {
			'title' :	'پیش‌نمایش مقاله',
			'preview' :	'پیش‌نمایش',
			'noarticle' :	'شما هنوز مقاله‌ای را انتخاب نکرده‌اید.',
			'readmore' :	'مطالعهٔ بیشتر',
			'hide' :	'پنهان',
			'show' :	'نمایش'
		} );
		break;
	case 'fi':
		mw.messages.set( {
			'title' :	'Artikkelin esikatselu',
			'preview' :	'esikatselu',
			'noarticle' :	'Et ole vielä valinnut artikkelia.',
			'readmore' :	'Lue lisää',
			'hide' :	'piilota',
			'show' :	'näytä'
		} );
		break;
	case 'fr':
		mw.messages.set( {
			'title' :	'Visualisation des articles',
			'preview' :	'visualiser',
			'noarticle' :	'Aucun article n\'est sélectionné.',
			'readmore' :	'Lire la suite',
			'hide' :	'masquer',
			'show' :	'afficher'
		} );
		break;
	case 'gl':
		mw.messages.set( {
			'title' :	'Previsualización do artigo',
			'preview' :	'previsualizar',
			'noarticle' :	'Aínda non seleccionaches ningún artigo.',
			'readmore' :	'Ler máis',
			'hide' :	'ocultar',
			'show' :	'amosar'
		} );
		break;
	case 'hu':
		mw.messages.set( {
			'title' :	'Cikk előnézete',
			'preview' :	'előnézet',
			'noarticle' :	'Nem választottál cikket.',
			'readmore' :	'Tovább',
			'hide' :	'elrejt',
			'show' :	'mutat'
		} );
		break;
	case 'id':
		mw.messages.set( {
			'title' :	'Pratayang artikel',
			'preview' :	'pratayang',
			'noarticle' :	'Anda belum memilih artikel.',
			'readmore' :	'Lebih lanjut',
			'hide' :	'sembunyikan',
			'show' :	'tunjukan'
		} );
		break;
	case 'it':
		mw.messages.set( {
			'title' :	'Anteprima della voce',
			'preview' :	'anteprima',
			'noarticle' :	'Non hai ancora selezionato una voce.',
			'missing' :	'Questa voce non esiste.',
			'readmore' :	'Leggi tutto',
			'hide' :	'nascondi',
			'show' :	'mostra'
		} );
		break;
	case 'ja':
		mw.messages.set( {
			'title' :	'記事のプレビュー',
			'preview' :	'プレビュー',
			'noarticle' :	'記事が選択されていません',
			'readmore' :	'続きを読む',
			'hide' :	'非表示',
			'show' :	'表示'
		} );
		break;
	case 'ko':
		mw.messages.set( {
			'title' :	'문서 미리 보기',
			'preview' :	'미리 보기',
			'noarticle' :	'아직 문서를 선택하지 않으셧습니다.',
			'readmore' :	'더 보기',
			'hide' :	'숨기기',
			'show' :	'보이기'
		} );
		break;
	case 'min':
		mw.messages.set( {
			'title' :	'Pratonton laman',
			'preview' :	'pratonton',
			'noarticle' :	'Sanak alum mamiliah laman.',
			'readmore' :	'Labiah lanjuik',
			'hide' :	'suruakan',
			'show' :	'tunjuakan'
		} );
		break;
	case 'nl':
		mw.messages.set( {
			'title' :	'Voorbeeld van artikel',
			'preview' :	'voorbeeld',
			'noarticle' :	'Je hebt nog geen artikel geselecteerd.',
			'readmore' :	'Meer lezen',
			'hide' :	'Verbergen',
			'show' :	'Tonen'
		} );
		break;
	case 'zh':
	case 'zh-cn':
	case 'zh-hans':
	case 'zh-my':
	case 'zh-sg':
		mw.messages.set( {
			'title' :	'条目预览',
			'preview' :	'预览',
			'noarticle' :	'您尚未选择一个条目。',
			'readmore' :	'阅读更多',
			'hide' :	'隐藏',
			'show' :	'显示'
		} );
		break;
	case 'zh-hant':
	case 'zh-hk':
	case 'zh-mo':
	case 'zh-tw':
		mw.messages.set( {
			'title' :	'條目預覽',
			'preview' :	'預覽',
			'noarticle' :	'您尚無選擇一個條目。',
			'readmore' :	'閱讀更多',
			'hide' :	'隱藏',
			'show' :	'顯示'
		} );
		break;
	default:
	case 'en':
		mw.messages.set( {
			'title' :	'Article preview',
			'preview' :	'preview',
			'noarticle' :	'You have not selected an article yet.',
			'missing' :	'This article does not exist.',
			'readmore' :	'Read more',
			'hide' :	'hide',
			'show' :	'show'
		} );
	}

	mw.hook( 'wikibase.entityPage.entityLoaded' ).add( function ( entity ) {
		var html = '\
	<div class="articlepreview mw-body-content">\
		<div class="container">\
			<h2 class="title"></h2>\
			<div class="content">\
				\
			</div>\
		</div>\
		<div class="toggler"><a href="#">show</a></div>\
	</div>';
	
		var sitelinks = entity.sitelinks;
		
		if ( !sitelinks ) {
			return;
		}
	
		/**
		 * The cached previews.
		 */
		var cache = {};
	
		/**
		 * The html elements.
		 */
		var $articlepreview, $title, $content, $container, $toggler;
	
		/**
		 * The wikimedia commons site.
		 */
		var commons = wb.sites.getSite( 'commonswiki' );
	
		function toggle() {
			if ( $articlepreview.hasClass( 'open' ) ) {
				$articlepreview.removeClass( 'open' );
				$toggler.find( 'a' ).text( mw.msg( 'show' ) );
			} else {
				$toggler.find( 'a' ).text( mw.msg( 'hide' ) );
				$articlepreview.addClass( 'open' );
			}
		}
	
		/**
		 * Adds the html to the preview widget.
		 *
		 * @param wiki the wiki to show
		 */
		function showPreview( site ) {
			var data = cache[site.getId()],
				lang = site.getLanguageCode(),
				dir = site.getLanguageDirection();
	
			$title
			.attr( 'dir', dir )
			.attr( 'lang', lang )
			.html( ( data.displaytitle || mw.html.escape( data.title ) ) + ' — ' + site.getName() + ' ' )
			.append(
				$( '<span>' )
				.attr( 'dir', 'ltr' )
				.attr( 'lang', 'en' )
				.text( '(' + site.getId() + ')' )
			);
	
			$content
			.attr( {
				'class': 'mw-content-' + dir,
				'dir': dir,
				'lang': lang
			} )
			.html( data.content )
			.append(
				$( '<p>' )
				.append(
					$( '<a>' )
					.attr( {
						'href': site.getUrlTo( data.title ),
						'title': site.getId() + ':' + data.title
					} )
					.text( mw.msg( 'readmore' ) )
				) // </a>
			); // </p>
	
			if ( data.image ) {
				$content.prepend(
					$( '<a>' )
					.attr( 'href', data.image.url )
					.append(
						$( '<img>' )
						.attr( {
							'src': data.image.source,
							'width': data.image.width,
							'height': data.image.height,
							'class': 'thumbnail',
							'title': data.image.name,
							'alt': data.image.name
						} )
					)
				);
			}
		}
	
		/**
		 * Showing the preview got by an http request. Requests are cached.
		 *
		 * @param site the current site object
		 */
		function preview( site ) {
			var wiki = site.getId(),
				sitelink = sitelinks[wiki];
	
			toggle(); // show the widget
	
			if ( !sitelink ) {
				return;
			}
	
			if ( cache.hasOwnProperty( wiki ) ) {
				showPreview( site );
			} else {
				$.createSpinner( {
					size: 'small',
					type: 'block'
				} ).appendTo( $content.empty() );
				var api = new mw.Api( {
					ajax: {
						url: site.getApi(),
						dataType: 'jsonp',
						cache: true
					}
				} );
				api.get( {
					action: 'query',
					prop: 'extracts|pageprops|pageimages',
					exintro: true,
					exchars: 1000,
					piprop: 'thumbnail',
					pilicense: 'any',
					pithumbsize: Math.floor( $container.width() / 2 ),
					titles: sitelink.title,
				} )
				.done( function ( data ) {
					var page = data.query.pages[Object.keys( data.query.pages )[0]];
					if ( page.missing === '' ) {
						cache[wiki] = {
							content: '<p class="error">' + mw.message( 'missing' ).escaped() + '</p>',
							title: sitelink.title
						};
					} else {
						cache[wiki] = {
							content: page.extract.replace( /<\/p>(…|...)/, '…</p>' ),
							title: sitelink.title,
							displaytitle: page.pageprops && page.pageprops.displaytitle
						};
					
						if ( page.pageprops && ( page.pageprops.page_image || page.pageprops.page_image_free ) ) {
							var page_prop = page.pageprops.page_image || page.pageprops.page_image_free;
							
							cache[wiki].image = {
								source: page.thumbnail.source,
								width: page.thumbnail.width,
								height: page.thumbnail.height,
								url: commons.getUrlTo( 'File:' + page_prop ),
								name: page_prop
							};
						}
					}
					showPreview( site );
				} );
			}
		}
	
		/**
		 * Initialising the links.
		 */
		function init() {
			var lang = mw.config.get( 'wgUserLanguage' );
			var wiki = lang + 'wiki'; // guess default wiki
			var site = wb.sites.getSite( wiki );
	
			$( '.wikibase-entityview-side' ).first().prepend( html );
	
			$articlepreview = $( '.articlepreview' );
			$title = $articlepreview.find( '.title' ).text( mw.msg( 'title' ) );
			$content = $articlepreview.find( '.content' ).text( mw.msg( 'noarticle' ) );
			$container = $articlepreview.find( '.container' );
	
			$toggler = $articlepreview.find( '.toggler a' )
			.click( function () {
				toggle();
			} );
	
			if ( sitelinks[wiki] ) {
				if ( $( window ).width() > 1600 ) {
					preview( site );
				} else {
					$content
					.append( '<br>&nbsp;&rarr;&nbsp;' )
					.append(
						site.getLinkTo( sitelinks[wiki].title )
						.click( function ( e ) {
							e.preventDefault();
							preview( site );
						} ) // </a>
					);
				}
			}
	
			$( '.wikibase-sitelinkview' ).each( function () {
				var wiki = $( this ).data( 'wbSiteid' ),
					site = wb.sites.getSite( wiki );
					
				$( this ).prepend(
					$( '<a>' )
					.attr( {
						'class': 'articlepreview-button',
						title: mw.msg( 'preview' ),
						href: site.getUrlTo( sitelinks[wiki].title )
					} )
					.click( function ( e ) {
						e.preventDefault();
						preview( site );
					} )
				);
			} );
		}
		
		$( init );
	} );

}( mediaWiki, jQuery, wikibase ) );