User:Matěj Suchánek/referenceSuggestions.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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
( function( mw, wb ) {

	var api, repoApi;
	var promise = null;
	const PROPS = [ 'P248', 'P813', 'P854' ];

	function isReferenceContext( element ) {
		return element.closest( ':wikibase-referenceview' ).length > 0;
	}

	function getPromise() {
		if ( promise === null ) {
			const lang = mw.config.get( 'wgUserLanguage' ),
				path = mw.config.get( 'wgServer' ) + mw.config.get( 'wgArticlePath' );
			promise = api.get( {
				action: 'wbgetentities',
				ids: repoApi.normalizeMultiValue( PROPS ),
				props: repoApi.normalizeMultiValue( [ 'labels', 'descriptions' ] ),
				languages: lang,
				languagefallback: 1,
			} )
			.then( function ( data ) {
				return PROPS.map( function ( p ) {
					const entity = data.entities[ p ];
					return {
						id: p,
						display: {
							label: entity.labels[ lang ],
							description: entity.descriptions[ lang ]
						},
						rating: 1,
						url: path.replace( '$1', 'Property:' + p ),
					};
				} );
			} );
		}
		return promise;
	}

	mw.loader.using( [ 'mediawiki.api', 'wikibase.api.RepoApi' ] ).then( function () {
		api = new mw.Api();
		repoApi = new wb.api.RepoApi( api );
		mw.hook( 'wikibase.entityselector.search' ).add( function ( data, addPromise ) {
			if ( data.options.type !== 'property' ) {
				return;
			}
			if ( data.term !== '' ) {
				return;
			}
			if ( !isReferenceContext( data.element ) ) {
				return;
			}
			addPromise( getPromise() );
		} );
	} );

} )( mediaWiki, wikibase );