User:Jack Phoenix/AutocompleteTest

From MediaWiki.org
Jump to navigation Jump to search

AutocompleteTest.php[edit]

<?php

$wgResourceModules['ext.autocomplete.test'] = array(
	'scripts' => 'AutocompleteTest.js',
	'dependencies' => array( 'jquery.ui.autocomplete', 'mediawiki.util' ),
	'localBasePath' => __DIR__,
	'remoteExtPath' => 'AutocompleteTest'
);

$wgSpecialPages['AutocompleteTest'] = 'SpecialAutocompleteTest';
$wgAutoloadClasses['SpecialAutocompleteTest'] = __DIR__ . '/SpecialAutocompleteTest.php';

SpecialAutocompleteTest.php[edit]

<?php
class SpecialAutocompleteTest extends SpecialPage {
	public function getDescription() { return 'jQuery UI Autocomplete Test Page'; }
	public function __construct() { parent::__construct( 'AutocompleteTest' ); }

	public function execute( $par ) {
		$this->getOutput()->addModules( 'ext.autocomplete.test' );
		$this->getOutput()->addHTML( Html::input( 'au-test', '', 'text', array( 'id' => 'au-test' ) ) );
	}
}

AutocompleteTest.js[edit]

$( function() {
	var selector = '#au-test';
	$( selector ).autocomplete( {
		minLength: 3,
		source: function( request, response ) {
			$.ajax( {
				type: 'GET',
				dataType: 'json',
				url: mw.util.wikiScript( 'api' ),
				data: {
					action: 'opensearch',
					search: request.term,
					namespace: 14 // NS_CATEGORY
				}
			} ).done( function( data ) {
				var re = $.ui.autocomplete.escapeRegex( request.term );
				var matcher = new RegExp( '^' + re, 'i' );

				var a = $.grep( data[1], function( item, index ) {
					item = item.split( ':' )[1]; // remove the namespace and the colon from the suggestion; needed so that the next line returns bool true instead of false (??? I have no idea...)
					return matcher.test( item );
				} );

				response( a );
			} );
		},
		response: function( event, ui ) {
			$.each( ui.content, function( idx, elem ) {
				elem.label = elem.label.split( ':' )[1];
				elem.value = elem.value.split( ':' )[1];
			} );
		},
		select: function( event, ui ) {
			$( selector ).val( ui.item.value );
		}
	} );
} );