มีเดียวิกิ:RefToolbar.js

/*jshint smarttabs:true, loopfunc:true,forin:false*/
/*global mw, $, importScript */
// TODO: make autodate an option in the CiteTemplate object, not a preference
// Global object
// TODO:
// * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
if (typeof CiteTB === 'undefined') {
var CiteTB = {
"Templates" : {}, // All templates
"Options" : {}, // Global options
"UserOptions" : {}, // User options
"DefaultOptions" : {}, // Script defaults
"ErrorChecks" : {} // Error check functions
};
}
// Only execute on edit, unless it is a user JS/CSS page
// TODO: Remove tests already done by MediaWiki:Gadget-refToolbar.js
if (
	( mw.config.get('wgAction') === 'edit' 
mw.config.get('wgAction') === 'submit' ) &&
	( ( mw.config.get('wgNamespaceNumber') !== 2 && mw.config.get('wgNamespaceNumber') !== 4 ) 
	( mw.config.get('wgPageName').indexOf('.js') === -1 && mw.config.get('wgPageName').indexOf('.css') === -1 ) )
) {
// TODO: Move this to MediaWiki:Gadget-refToolbarDialogs.css and add it to the definition of module 'ext.gadget.refToolbarDialogs'
mw.util.addCSS(".cite-form-td {"+
"height: 0 !important;"+
"padding: 0.1em !important;"+
"}");  
// Default options, these mainly exist so the script won't break if a new option is added
CiteTB.DefaultOptions = {
"date format" : "--",
"autodate fields" : ,
"months" : 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
"modal" : true,
"autoparse" : false,
"expandtemplates": false
};
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
if (CiteTB.UserOptionsopt !== undefined) {
return CiteTB.UserOptionsopt;
} else if (CiteTB.Optionsopt !== undefined) {
return CiteTB.Optionsopt;
}
return CiteTB.DefaultOptionsopt;
};
CiteTB.init = function() {
/* Main stuff, build the actual toolbar structure- 1. get the template list, make the dropdown list and set up the template dialog boxes- 2. actually build the toolbar:-    * A section for cites-    ** dropdown for the templates (previously defined)-    ** button for named refs with a dialog box-    ** button for errorcheck- 3. add the whole thing to the main toolbar
*/
if (typeof $('divrel=cites')0 !== 'undefined') { // Mystery IE bug workaround
return;
}
$('head').trigger('reftoolbarbase');
var $target = $('#wpTextbox1');
var temlist = {};
for (var t in CiteTB.Templates) {
var tem = CiteTB.Templatest;
var sform = CiteTB.escStr(tem.shortform);
var actionobj = { 
type: 'dialog',
module: 'cite-dialog-'+sform
};
var dialogobj = {};
dialogobj'cite-dialog-'+sform = {
resizeme: false,
titleMsg: 'cite-dialog-'+sform, 
id: 'citetoolbar-'+sform,
init: function() {}, 
html: tem.getInitial(), 
dialog: {
width:675,
open: function() { 
$(this).html(CiteTB.getOpenTemplate().getForm());
/** @param {jQuery.Event} e */
$('.cite-prev-parse').on( 'click', function ( e ) {
e.preventDefault();
CiteTB.prevParseClick();
});
},
buttons: {
'cite-form-submit': function() {
var ref = CiteTB.getRef(false, true);
$(this).dialog( 'close' );
$.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
type: 'encapsulate',
options: {
post: ref
}
}, $(this) );
},
'cite-form-showhide': CiteTB.showHideExtra,
'cite-refpreview': function() {   
var ref = CiteTB.getRef(false, false);
var template = CiteTB.getOpenTemplate();
var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-preview-label').show();
div.find('.cite-ref-preview').text(ref).show();
if (CiteTB.getOption('autoparse')) {
CiteTB.prevParseClick();
} else {
div.find('.cite-prev-parse').show();
div.find('.cite-prev-parsed-label').hide();
div.find('.cite-preview-parsed').html();
}         
},
'wikieditor-toolbar-tool-link-cancel': function() {
$(this).dialog( 'close' );
},
'cite-form-reset': function() {
CiteTB.resetForm();
}
}
} 
};
$target.wikiEditor('addDialog', dialogobj);
//if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
//}
temlistsform = {label: tem.templatename, action: actionobj };  
}
var refsection =  {
'sections': {
'cites': { 
type: 'toolbar', 
labelMsg: 'cite-section-label',
groups: { 
'template': {
tools: {
'template': {
type: 'select',
labelMsg: 'cite-template-list',
list: temlist
} 
}
},
'namedrefs': {
labelMsg: 'cite-named-refs-label',
tools: {
'nrefs': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-namedrefs'
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/b/be/Nuvola_clipboard_lined.svg/22px-Nuvola_clipboard_lined.svg.png',
section: 'cites',
group: 'namedrefs',
labelMsg: 'cite-named-refs-button'
}
}
},
'errorcheck': {
labelMsg: 'cite-errorcheck-label',
tools: {
'echeck': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-errorcheck'           
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Nuvola_apps_korganizer-NO.png/22px-Nuvola_apps_korganizer-NO.png',
section: 'cites',
group: 'errorcheck',
labelMsg: 'cite-errorcheck-button'
}
}
}
} 
} 
} 
};

var defaultdialogs = { 
'cite-toolbar-errorcheck': {
titleMsg: 'cite-errorcheck-label',
id: 'citetoolbar-errorcheck',
resizeme: false,
init: function() {},
html: +
+
' '+mw.usability.getMsg('cite-loading')+,
dialog: {
width:550,
open: function() { 
CiteTB.loadRefs();
},
buttons: {
'cite-errorcheck-submit': function() {
var errorchecks = $("inputname='cite-err-test':checked");
var errors = ;
for (var i=0; i'+
+
' '+mw.usability.getMsg('cite-loading')+,
init: function() {},
dialog: {
width: 550,
open: function() { 
CiteTB.loadRefs();
},
buttons: {
'cite-form-submit': function() {
var refname = $("#cite-namedref-select").val();
if (refname === ) {
return;
}
$(this).dialog( 'close' );
$.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
type: 'encapsulate',
options: {
post: CiteTB.getNamedRef(refname, true)
}
}, $(this) );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$(this).dialog( 'close' );
}                   
}
}      
}
};

$target.wikiEditor('addDialog', defaultdialogs);
$('#citetoolbar-namedrefs').off('dialogopen');
if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
//$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
mw.util.addCSS(".ui-widget-overlay {"+
"display:none !important;"+
"}");  
}
$target.wikiEditor('addToToolbar', refsection);
};
// Load local data - messages, cite templates, etc.
$(document).ready( function() {
switch( mw.config.get('wgUserLanguage') ) {
default: // Thai
importScript('MediaWiki:RefToolbarMessages-th.js');
}
});
// Setup the main object
CiteTB.mainRefList = ;
CiteTB.refsLoaded = false;
// REF FUNCTIONS
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
var i;
var template = CiteTB.getOpenTemplate();
var templatename = template.templatename;
var res = ;
var refobj = {'shorttag':false};
if (!inneronly) {
var group = $('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
var refname = $('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
res += ;
}
var content =;
res+=content;
refobj.content = content;
if (!inneronly) {
res+= ;
}
if (forinsert) {
CiteTB.mainRefList.push(refobj);
}
return res;
};
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
if (forinsert) {
CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
}
return ;  
};
// Function to load the ref list
CiteTB.loadRefs = function() {
if (CiteTB.refsLoaded) {
return;
}
CiteTB.getPageText(CiteTB.loadRefsInternal);
};
// Function that actually loads the list from the page text
CiteTB.loadRefsInternal = function(text) { 
// What this does:             extract first name/group                                     extract second name/group                                          shorttag   inner content
var refsregex = /*?)) *)? *(?: +(name|group) *= *(?:"(^"*?)"|'(^'*?)'|(^ '"\/\>*?)) *)? *(?:\/ *>|>((?:.|\n)*?))/gim;
// This should work regardless of the quoting used for names/groups and for linebreaks in the inner content  
while (true) {
var ref = refsregex.exec(text);
if (ref === null) {
break;
}
var refobj = {};
if (ref9) { // Content + short tag check
//alert('"'+ref9+'"');
refobj.content = ref9; 
refobj.shorttag = false;
} else {
refobj.shorttag = true;
}
if (ref1 !== ) { // First name/group
if (ref2) {
refobj'ref'+ref1 = ref2;
} else if (ref3) {
refobj'ref'+ref1 = ref3;
} else {
refobj'ref'+ref1 = ref4;
}
}
if (ref5 !== ) { // Second name/group
if (ref6) {
refobj'ref'+ref5 = ref6;
} else if (ref7) {
refobj'ref'+ref5 = ref7;
} else {
refobj'ref'+ref5 = ref8;
}
}
CiteTB.mainRefList.push(refobj);
}
CiteTB.refsLoaded = true;
CiteTB.setupErrorCheck();
CiteTB.setupNamedRefs();
};
// AJAX FUNCTIONS
// Parse some wikitext and hand it off to a callback function
CiteTB.parse = function(text, callback) {
$.post( mw.util.wikiScript( 'api' ),
{action:'parse', title:mw.config.get('wgPageName'), text:text, prop:'text', format:'json'},
function(data) {
var html = data.parse.text'*';
callback(html);
},
'json'
);  
};
// Use the API to expand templates on some text
CiteTB.expandtemplates = function(text, callback) {
$.post( mw.util.wikiScript( 'api' ),
{action:'expandtemplates', title:mw.config.get('wgPageName'), text:text, format:'json'},
function(data) {
var restext = data.expandtemplates'*';
callback(restext);
},
'json'
);
};
// Function to get the page text
CiteTB.getPageText = function(callback) {
var section = $("inputname='wpSection'").val();
if ( section !==  ) {
var postdata = {action:'query', prop:'revisions', rvprop:'content', pageids:mw.config.get('wgArticleId'), format:'json'};
if (CiteTB.getOption('expandtemplates')) {
postdata.rvexpandtemplates = '1';
}
$.get( mw.util.wikiScript( 'api' ),
postdata,
function(data) {
var pagetext = data.query.pagesmw.config.get('wgArticleId').toString().revisions0'*';
callback(pagetext);
},
'json'
);
} else {
if (CiteTB.getOption('expandtemplates')) {
CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
} else {
callback($('#wpTextbox1').wikiEditor('getContents').text());
}
}
};
// Autofill a template from an ID (ISBN, DOI, PMID, URL)
CiteTB.initAutofill = function() {
var elemid = $(this).attr('id');
var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
var tem = res1;
var field = res2;
var autotype = res3;
var id = $('#cite-'+tem+'-'+field).val();
if (!id) {
return false;
}
var url = '//reftoolbar.toolforge.org/lookup.php?';
url+=autotype+'='+encodeURIComponent(id);
url+='&template='+encodeURIComponent(tem);
var s = document.createElement('script');
s.setAttribute('src', url);
s.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')0.appendChild(s);
return false;
};
// Callback for autofill
//TODO: Autofill the URL, at least for DOI
CiteTB.autoFill = function(data, template, type) {
var cl = 'cite-'+template+'-';
var i,j, coauthors;
$('.'+cl+'title').val(data.title);
// Fill in authors
if (data.authors && data.authors.length > 0) {
	  if ($('.'+cl+'last-incr-1').length != 0) {
		var classes = $('.'+cl+'last-incr-1').eq(0).attr('class').split(/\s+/);
		var group = false;
		var patt = /cite-^-*?-incr-(.*)/
		for (var c=0; c', date);
datestr = datestr.replace(, zdate);
} else {
datestr = datestr.replace(, );
datestr = datestr.replace(, );
}
if (usemonth) {
datestr = datestr.replace(, month);
datestr = datestr.replace(, zmonth);
datestr = datestr.replace(, CiteTB.getOption('months')DT.getUTCMonth());
} else {
datestr = datestr.replace(, );
datestr = datestr.replace(, );
datestr = datestr.replace(, );
}  
datestr = datestr.replace(, DT.getUTCFullYear().toString());
return datestr.replace(/^ \/\-\,\.*(.*?) \/\-\,\.*$/g, "$1"); // Cleanup any dangling spaces or connectors that might result from omitting date/month
};
// Function called after the ref list is loaded, to actually set the contents of the named ref dialog
// Until the list is loaded, its just a "Loading" placeholder
CiteTB.setupNamedRefs = function() {
var names = , i;
for( i=0; i');
$('#citetoolbar-namedrefs').html( stuff );
if (names.length === 0) {
stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
} else {
stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
var select = $();
select.append($().text(mw.usability.getMsg('cite-named-refs-dropdown')));
for(i=0; i').text(namesi.refname));
}
stuff.after(select);
select.before();      
var prevlabel = $().html(mw.usability.getMsg('cite-raw-preview'));
select.after(prevlabel);
prevlabel.before("");
prevlabel.after();
var parselabel = $().html(mw.usability.getMsg('cite-parsed-label'));
$('#cite-namedref-preview').after(parselabel);
parselabel.after();
var link = $();
link.html(mw.usability.getMsg('cite-form-parse'));
$('#cite-namedref-parsed').after(link);

$("#cite-namedref-select").on( 'change', CiteTB.namedRefSelectClick);
$('#cite-nref-parse').on( 'click', CiteTB.nrefParseClick);
}      
};
// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function() {
var form = $().html(mw.usability.getMsg('cite-errorcheck-heading'));
var ul = $("");
var test;
for (var t in CiteTB.ErrorChecks) {
test = CiteTB.ErrorCheckst;
ul.append(test.getRow());
}
form.append(ul);
$('#citetoolbar-errorcheck').html(form);
};
// Callback function for parsed preview
CiteTB.fillNrefPreview = function(parsed) {
$('#cite-parsed-label').show();
$('#cite-namedref-parsed').html(parsed);
};
// Click handler for the named-ref parsed preview
CiteTB.nrefParseClick = function() {
var choice = $("#cite-namedref-select").val();
if (choice === ) {
$('#cite-parsed-label').hide();
$('#cite-namedref-parsed').text();
return false;
}
$('#cite-nref-parse').hide();
for( var i=0; i');
$('#editpage-copywarn').before(table);
var tr;
var tr1 = $();
var th1 = $().html(mw.usability.getMsg('cite-err-report-heading'));
var th2 = $();
var im = $().attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
im.attr('alt', mw.usability.getMsg('cite-err-report-close')).attr('title', mw.usability.getMsg('cite-err-report-close'));
var ad = $().attr('href', '#');
ad.append(im);
th2.append(ad);
tr1.append(th1).append(th2);
table.append(tr1);
$('#cite-err-check-close').on('click', function() {  $('#cite-err-report').remove(); });
if (errors.length === 0) {
tr = $();
var td = $().html(mw.usability.getMsg('cite-err-report-empty'));
tr.append(td);
table.append(tr);

return;
}
for(var e in errors) {
var err = errorse;
tr = $();
var td1 = $().html(err.err);
var td2 = $().html(mw.usability.getMsg(err.msg));
tr.append(td1).append(td2);
table.append(tr);
}
};

} // End of code loaded only on edit