MediaWiki:TemplateCreate.js:修订间差异
Tbpedia>Sophivorus 无编辑摘要 |
小 (导入1个版本) |
(没有差异)
| |
2024年3月2日 (六) 16:47的最新版本
/**
* 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 );