MediaWiki:TemplateCreate.js

蓮花祖泉讨论 | 贡献2024年3月2日 (六) 16:47的版本 (导入1个版本)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer或Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:Ctrl-F5
/**
 * This script interacts with [[Template:Create]]
 * [[Category:Template script pages]]
 */
var TemplateCreate = {

	init: function () {

		// Add datalist to DOM
		$( '.template-create' ).each( function ( index ) {
			var template = $( this );
			var datalist = $( '<datalist id="template-create-suggestions-' + index + '" class="template-create-suggestions"></datalist>' );
			template.append( datalist );
			template.find( '.mw-ui-input' ).attr( 'list', 'template-create-suggestions-' + index );
		} );

		// Bind events
		$( '.template-create form' ).submit( TemplateCreate.exists );
		$( '.template-create .mw-ui-input' ).keyup( TemplateCreate.suggest );

		// Focus on the first input that has autofocus
		$( '.template-create[data-autofocus]' ).first().find( '.mw-ui-input' ).focus();
	},

	/**
	 * Check if the selected title exists
	 */
	exists: function () {
		var form = $( this );
		if ( form.data( 'valid' ) ) {
			return true;
		}
		var title = form.find( '.mw-ui-input' ).val().trim();
		new mw.Api().get( {
			action: 'query',
			titles: title,
			prop: 'info',
			format: 'json',
			formatversion: 2
		} ).done( function ( data ) {
			var page = data.query.pages[0]; // Unwrap the data
			var Title = new mw.Title( page.title );
			if ( 'missing' in page ) {
				form.data( 'valid', true ).submit();
			} else {
				var href = Title.getUrl();
				var text = Title.getPrefixedText();
				var link = $( '<a>' ).attr( { 'href': href, 'target': '_blank' } ).text( title ).prop( 'outerHTML' );
				var template = form.closest( '.template-create' );
				var error = template.find( '.template-create-error' );
				error.html( 'A page named ' + link + ' already exists. Please choose another title or contribute to the page that already exists.' );
			}
		} );
		return false;
	},

	/**
	 * Suggest existing titles
	 */
	suggest: function ( event ) {
		var input = $( this );
		var template = input.closest( '.template-create' );
		var suggestions = template.find( '.template-create-suggestions' );

		// Little trick to detect clicks on suggestions
		// See https://stackoverflow.com/a/65073572/809356
		if ( ! event.key ) {
			suggestions.empty();
			return;
		}
		var query = input.val().trim();
		if ( ! query ) {
			return;
		}
		new mw.Api().get( {
			action: 'opensearch',
			search: query
		} ).done( function ( data ) {
			suggestions.empty();
			var titles = data.slice( 1, 2 )[0];
			if ( titles.length === 1 ) {
				return;
			}
			titles.forEach( function ( title ) {
				var option = $( '<option>' ).val( title );
				suggestions.append( option );
			} );
		} );
	}
};

$( TemplateCreate.init );