MediaWiki:RefToolbar.js: Difference between revisions

Content deleted Content added
m grammar fix to source comment "its" to "it is"
rm ws...
 
(48 intermediate revisions by 15 users not shown)
Line 1:
/*jshint smarttabs:true, loopfunc:true,forin:false*/
// Todo: make autodate an option in the CiteTemplate object, not a preference
/*global mw, $ */
// TODO: make autodate an option in the CiteTemplate object, not a preference
 
// Global object
// TODO:
if (typeof CiteTB == 'undefined') {
// * 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
Line 12 ⟶ 16:
}
 
// Only execute when editing/previewing wikitext pages
// only load on edit, unless it is a user JS/CSS page
// TODO: Remove tests already done by [[MediaWiki:Gadget-refToolbar.js]]
if ((wgAction == 'edit' || wgAction == 'submit') && !((wgNamespaceNumber == 2 || wgNamespaceNumber == 4) &&
if (
(wgPageName.indexOf('.js') != -1 || wgPageName.indexOf('.css') != -1 ))) {
['edit', 'submit'].indexOf( mw.config.get('wgAction') ) !== -1 &&
mw.config.get('wgPageContentModel') === 'wikitext'
) {
 
// TODO: Move this to [[MediaWiki:Gadget-refToolbarDialogs.css]] and add it to the definition of module 'ext.gadget.refToolbarDialogs'
appendCSS(".cite-form-td {"+
mw.util.addCSS(".cite-form-td {"+
"height: 0 !important;"+
"padding: 0.1em !important;"+
Line 30 ⟶ 38:
"expandtemplates": false
};
 
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
if (CiteTB.UserOptions[opt] !== undefined) {
return CiteTB.UserOptions[opt];
} else if (CiteTB.Options[opt] !== undefined) {
return CiteTB.Options[opt];
}
return CiteTB.DefaultOptions[opt];
};
 
CiteTB.init = function() {
Line 51 ⟶ 60:
*/
 
if (typeof $j('div[rel=cites]')[0] !== 'undefined') { // Mystery IE bug workaround
return;
}
$j('head').trigger('reftoolbarbase');
var $target = $j('#wpTextbox1');
var temlist = {};
var d = new Date();
var start = d.getTime();
for (var t in CiteTB.Templates) {
var tem = CiteTB.Templates[t];
var sform = CiteTB.escStr(tem.shortform);
var actionobj = {
type: 'dialog',
Line 69 ⟶ 76:
dialogobj['cite-dialog-'+sform] = {
resizeme: false,
titleMsgtitle: mw.message( 'cite-dialog-'+sform ).parse(),
id: 'citetoolbar-'+sform,
init: function() {},
html: tem.getInitial(),
dialog: {
width:675680,
open: function() {
$j(this).html(CiteTB.getOpenTemplate().getForm());
/** @param {jQuery.Event} e */
$j('.cite-prev-parse').bindon( 'click', function ( e ) {
e.preventDefault();
CiteTB.prevParseClick();
});
},
beforeclose: function() {
CiteTB.resetForm();
},
buttons: {
'cite-form-submit': function() {
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
peri: ' '
}
}, $j(this) );
var ref = CiteTB.getRef(false, true);
$j(this).dialog( 'close' );
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
prepost: ref
}
}, $j(this) );
},
'cite-form-showhide': CiteTB.showHideExtra,
Line 107 ⟶ 105:
var ref = CiteTB.getRef(false, false);
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-preview-label').show();
div.find('.cite-ref-preview').text(ref).show();
Line 119 ⟶ 117:
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
},
'cite-form-reset': function() {
Line 127 ⟶ 125:
}
};
try {
$target.wikiEditor('addDialog', dialogobj);
if} catch (!CiteTB.getOption('modal')e) {
// TypeError: range is null
//$j('#citetoolbar-'+sform).dialog('option', 'modal', false);
}
//if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
//}
temlist[sform] = {label: tem.templatename, action: actionobj };
}
Line 138 ⟶ 140:
'cites': {
type: 'toolbar',
labelMsglabel: mw.msg( 'cite-section-label' ),
groups: {
'template': {
Line 144 ⟶ 146:
'template': {
type: 'select',
labelMsglabel: mw.msg( 'cite-template-list' ),
list: temlist
}
Line 150 ⟶ 152:
},
'namedrefs': {
labelMsglabel: mw.msg( 'cite-named-refs-label' ),
tools: {
'nrefs': {
Line 161 ⟶ 163:
section: 'cites',
group: 'namedrefs',
labelMsglabel: mw.msg( 'cite-named-refs-button' )
}
}
},
'errorcheck': {
labelMsglabel: mw.msg( 'cite-errorcheck-label' ),
tools: {
'echeck': {
Line 177 ⟶ 179:
section: 'cites',
group: 'errorcheck',
labelMsglabel: mw.msg( 'cite-errorcheck-button' )
}
}
Line 188 ⟶ 190:
var defaultdialogs = {
'cite-toolbar-errorcheck': {
titleMsgtitle: mw.message( 'cite-errorcheck-label' ).parse(),
id: 'citetoolbar-errorcheck',
resizeme: false,
Line 202 ⟶ 204:
buttons: {
'cite-errorcheck-submit': function() {
var errorchecks = $j("input[name='cite-err-test']:checked");
var errors = [];
for (var i=0; i<errorchecks.length; i++) {
errors = errors.concat(CiteTB.ErrorChecks[$j(errorchecks[i]).val()].run());
}
CiteTB.displayErrors(errors);
$j(this).dialog( 'close' );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
}
}
Line 217 ⟶ 219:
},
'cite-toolbar-namedrefs': {
titleMsgtitle: mw.message( 'cite-named-refs-title' ).parse(),
resizeme: false,
id: 'citetoolbar-namedrefs',
Line 231 ⟶ 233:
buttons: {
'cite-form-submit': function() {
var refname = $j("#cite-namedref-select").val();
if (refname === '') {
return;
}
$j(this).dialog( 'close' );
$.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
peripost: 'CiteTB.getNamedRef(refname, 'true)
}
}, $j(this) );
$j(this).dialog( 'close' );
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
pre: CiteTB.getNamedRef(refname, true)
}
}, $j(this) );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
}
}
Line 257 ⟶ 253:
};
try {
$target.wikiEditor('addDialog', defaultdialogs);
$target.wikiEditor('addDialog', defaultdialogs);
$j('#citetoolbar-namedrefs').unbind('dialogopen');
} catch (e) {
// error occurred setting up wikieditor.
}
$('#citetoolbar-namedrefs').off('dialogopen');
if (!CiteTB.getOption('modal')) {
//$j('#citetoolbar-namedrefs').dialog('option', 'modal', false);
//$j('#citetoolbar-errorcheck').dialog('option', 'modal', false);
appendCSSmw.util.addCSS(".ui-widget-overlay {"+
"display:none !important;"+
"}");
}
try {
$target.wikiEditor('addToToolbar', refsection);
$target.wikiEditor('addToToolbar', refsection);
}
} catch (e) {
// error occurred setting up wikieditor.
}
};
 
// Load local data - messages, cite templates, etc.
$j(document).ready( function() {
switch( mw.config.get('wgUserLanguage') ) {
case 'de': // German
var RefToolbarMessages = importScriptmw.loader.load('/w/index.php?title=MediaWiki:RefToolbarMessages-de.js&action=raw&ctype=text/javascript');
break;
default: // English
var RefToolbarMessages = importScriptmw.loader.load('/w/index.php?title=MediaWiki:RefToolbarMessages-en.js&action=raw&ctype=text/javascript');
}
});
Line 287 ⟶ 291:
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
var i, j, g, group;
var template = CiteTB.getOpenTemplate();
var templatename = template.templatename;
Line 292 ⟶ 297:
var refobj = {'shorttag':false};
if (!inneronly) {
var group = $j('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
var refname = $j('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
res += '<ref';
if (refname) {
refname = $j.trim(refname);
res+=' name='+CiteTB.getQuotedString(refname);
refobj.refname = refname;
}
if (group) {
group = $j.trim(group);
res+=' group='+CiteTB.getQuotedString(group);
refobj.refgroup = group;
Line 308 ⟶ 313:
}
var content ='{{'+templatename;
for( varg i=0;in i<template.basic.length; i++incrementables ) {
group = template.incrementables[g];
for (i=1; i<=group.val; i++) {
for (j=0; j<group.fields.length; j++) {
var fieldname = group.fields[j].field;
var fieldid = fieldname.replace('<N>', i.toString());
var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldid).val();
if (field) {
content+=' |'+fieldid+'=';
content+= $.trim(field);
}
}
}
}
for( i=0; i<template.basic.length; i++ ) {
if (template.basic[i].increment_group) {
continue;
}
var fieldname = template.basic[i].field;
var field = $j('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
if (field) {
content+=' |'+fieldname+'=';
content+= $j.trim(field.replace("|", "{{!}}"));
}
}
if ($j('#cite-form-status').val() !== 'closed') {
for( var i=0; i<template.extra.length; i++ ) {
if (template.extra[i].increment_group) {
continue;
}
var fieldname = template.extra[i].field;
var field = $j('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
if (field) {
content+=' |'+fieldname+'=';
content+= $j.trim(field.replace("|", "{{!}}"));
}
}
Line 336 ⟶ 361:
}
return res;
};
 
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
var inner = 'name=';
if (forinsert) {
CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
}
return '<ref name='+CiteTB.getQuotedString(refname)+' />';
};
 
// Function to load the ref list
Line 353 ⟶ 377:
}
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 = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?:\/ *>|>((?:.|\n)*?)< *\/ *ref *>)/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;
}
Line 368 ⟶ 392:
if (ref[9]) { // Content + short tag check
//alert('"'+ref[9]+'"');
refobj['.content'] = ref[9];
refobj['.shorttag'] = false;
} else {
refobj['.shorttag'] = true;
}
if (ref[1] !== '') { // First name/group
if (ref[2]) {
refobj['ref'+ref[1]] = ref[2];
Line 382 ⟶ 406:
}
}
if (ref[5] !== '') { // Second name/group
if (ref[6]) {
refobj['ref'+ref[5]] = ref[6];
Line 395 ⟶ 419:
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) {
$j.post( wgServer+wgScriptPath+mw.util.wikiScript( '/api.php' ),
{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) {
$j.post( wgServer+wgScriptPath+mw.util.wikiScript( '/api.php' ),
{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 = $j("input[name='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';
}
$j.get( wgServer+wgScriptPath+mw.util.wikiScript( '/api.php' ),
postdata,
function(data) {
var pagetext = data['.query'].pages[mw.config.get('pageswgArticleId'][wgArticleId).toString()]['.revisions'][0]['*'];
callback(pagetext);
},
Line 441 ⟶ 465:
} else {
if (CiteTB.getOption('expandtemplates')) {
CiteTB.expandtemplates($j('#wpTextbox1').wikiEditor('getContents').text(), callback);
} else {
callback($j('#wpTextbox1').wikiEditor('getContents').text());
}
}
};
 
// Safe version of decodeURIComponent() that doesn't throw exceptions.
// If the native decodeURIComponent() threw an exception, the original string will be returned.
CiteTB.safeDecodeURIComponent = function(s) {
try {
s = decodeURIComponent(s);
} catch (e) {}
return s;
};
 
// Autofill a template from an ID (ISBN, DOI, PMID, URL)
CiteTB.initAutofill = function() {
var elemid = $j(this).attr('id');
var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
var tem = res[1];
var field = res[2];
var autotype = res[3];
var id = $j('#cite-'+tem+'-'+field).val();
if (!id) {
return false;
}
var url = 'http://toolserverreftoolbar.toolforge.org/~alexz/ref/lookup.php?';
// Citoid expects minimally encoded input, so do some speculative decoding here to avoid
// 404 fetches. https://phabricator.wikimedia.org/T146539
id = CiteTB.safeDecodeURIComponent(id);
url+=autotype+'='+encodeURIComponent(id);
url+='&template='+encodeURIComponent(tem);
Line 467 ⟶ 503:
document.getElementsByTagName('head')[0].appendChild(s);
return false;
};
 
// Callback for autofill
Line 473 ⟶ 509:
CiteTB.autoFill = function(data, template, type) {
var cl = 'cite-'+template+'-';
var i,j, coauthors;
$j('.'+cl+'title').val(data.title);
if ($j('.'+cl+'last1title').length != 0val(data.title) {;
// Fill for(varin i=0; i<data.authors.length; i++) {
if ($j('data.'+cl+'last'+(i+1))authors && data.authors.length > 0) {
if ($j('.'+cl+'last-incr-1'+(i+1)).val(data.authors[i][length != 0]); {
var classes = $j('.'+cl+'firstlast-incr-1'+).eq(i+1)0).valattr(data'class').authors[i][1]split(/\s+/);
var group = false;
} else {
var coauthorspatt = /cite-[^-];*?-incr-(.*)/
for for(var jc=i0; jc<data.authorsclasses.length; jc++) {
if (patt.exec(classes[c])) {
coauthors.push(data.authors[j].join(', '));
group = patt.exec(classes[c])[1];
break;
}
}
$('.'+cl+'last-incr-1').val(data.authors[0][0])
$('.'+cl+'first-incr-1').val(data.authors[0][1])
elemid = '#cite-incr-'+template+'-'+group;
for (var i=2; i<data.authors.length+1; i++) {
$(elemid).click();
$('.'+cl+'last-incr-'+i.toString()).val(data.authors[i-1][0])
$('.'+cl+'first-incr-'+i.toString()).val(data.authors[i-1][1])
}
} else if ($('.'+cl+'author-incr-1').length != 0) {
var classes = $('.'+cl+'author-incr-1').eq(0).attr('class').split(/\s+/);
var group = false;
var patt = /cite-[^-]*?-incr-(.*)/
for (var c=0; c<classes.length; c++) {
if (patt.exec(classes[c])) {
group = patt.exec(classes[c])[1];
break;
}
}
$('.'+cl+'author-incr-1').val(data.authors[0].join(', '))
elemid = '#cite-incr-'+template+'-'+group;
for (var i=2; i<data.authors.length+1; i++) {
$(elemid).click();
$('.'+cl+'author-incr-'+i.toString()).val(data.authors[i-1].join(', '))
}
} else if ($('.'+cl+'last1').length != 0) {
for(i=0; data.authors && i<data.authors.length; i++) {
if ($('.'+cl+'last'+(i+1)).length) {
$('.'+cl+'last'+(i+1)).val(data.authors[i][0]);
$('.'+cl+'first'+(i+1)).val(data.authors[i][1]);
} else {
coauthors = [];
for(j=i; j<data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
$('.'+cl+'coauthors').val(coauthors.join('; '));
break;
}
}
} else if($('.'+cl+'author1').length !== 0) {
for(i=0; data.authors && i<data.authors.length; i++) {
if ($('.'+cl+'author'+(i+1)).length) {
$('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
} else {
coauthors = [];
for(j=i; j<data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
$('.'+cl+'coauthors').val(coauthors.join('; '));
break;
}
}
$j('.'+cl+'coauthors').val(coauthors.join('; '));
break;
}
}
} else if($j('.'+cl+'author1').length != 0) {
for(var i=0; i<data.authors.length; i++) {
if ($j('.'+cl+'author'+(i+1)).length) {
$j('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
} else {
var coauthorsauthors = [];
for(var j=i=0; jdata.authors && i<data.authors.length; ji++) {
coauthorsauthors.push(data.authors[ji].join(', '));
}
$j('.'+cl+'coauthorsauthors').val(coauthorsauthors.join('; '));
break;
}
}
 
} else {
// Format partial dates of the format YYYY-MM, YYYY-MM-XX, or YYYY-MM-DD correctly
var authors = [];
for(var i=0; i<if ( data.authors.length;date i++) {
try {
authors.push(data.authors[i].join(', '));
}
$j('.'+cl+'authors').val(authors.join('; '));
}
if (type == 'pmid' || type == 'doi') {
if (type == 'doi') {
var DT = new Date(data.date);
$jif ('.'+cl+'date' /^\d{4}-\d{2}(-XX)?$/i.valtest(CiteTBdata.formatDate(DTdate) ); {
data.date = data.date.replace('-XX','');
} else {
$j('.'+cl+'date').val(dataCiteTB.dateformatDate(DT, false, true));
} else if ( /^\d{4}-\d{2}-\d{2}?/i.test(data.date) ) {
$('.'+cl+'date').val(CiteTB.formatDate(DT, true, true));
} else {
$('.'+cl+'date').val(data.date);
}
} catch (e) {}
} else {
$('.'+cl+'date').val(data.date);
}
 
if (type === 'pmid' || type === 'doi') {
$('.'+cl+'journal').val(data.journal);
$('.'+cl+'volume').val(data.volume);
$('.'+cl+'issue').val(data.issue);
$('.'+cl+'pages').val(data.pages);
if (type === 'pmid' && data.doi) {
$('.'+cl+'doi').val(data.doi);
}
} else if (type === 'isbn') {
$('.'+cl+'publisher').val(data.publisher);
$('.'+cl+'___location').val(data.___location);
$('.'+cl+'edition').val(data.edition);
} else if (type === 'url') {
$('.'+cl+'journal').val(data.journal);
$('.'+cl+'volume').val(data.volume);
$('.'+cl+'issue').val(data.issue);
$('.'+cl+'pages').val(data.pages);
$('.'+cl+'publisher').val(data.publisher);
$('.'+cl+'edition').val(data.edition);
$('.'+cl+'isbn').val(data.isbn);
$('.'+cl+'issn').val(data.issn);
$('.'+cl+'doi').val(data.doi);
// "en-US" isn't a valid value for the language parameter
if (data.language && data.language !== 'en-US' && data.language !== 'en-GB') {
$('.'+cl+'language').val(data.language);
}
$j('.'+cl+'journalchapter').val(data.journalchapter);
$j('.'+cl+'volume').val(data.volume);
$j('.'+cl+'issue').val(data.issue);
$j('.'+cl+'pages').val(data.pages);
} else if (type == 'isbn') {
$j('.'+cl+'publisher').val(data.publisher);
$j('.'+cl+'___location').val(data.___location);
$j('.'+cl+'year').val(data.year);
$j('.'+cl+'edition').val(data.edition);
}
};
 
// FORM DIALOG FUNCTIONS
// Add new incrementable fields
CiteTB.incrementFields = function() {
template = CiteTB.getOpenTemplate();
var currentrow = $(this).parents('tr')[0];
$(this).prev().css('width', '100%')
$(this).detach();
var elemid = $(this).attr('id');
var res = /^cite\-incr\-(.*?)\-(.*)$/.exec(elemid);
group = res[2];
increments = template.incrementables[group];
fields = increments.fields;
incrval = increments.val+1;
template.incrementables[group].val += 1;
trs = template.makeFormInner(fields, false);
trs.reverse();
for (var i=0; i<trs.length; i++) {
$(currentrow).after(trs[i]);
}
};
 
// fill the accessdate param with the current date
CiteTB.fillAccessdate = function() {
var elemid = $j(this).attr('id');
var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
var id = res[1];
var field = res[2];
var DT = new Date();
var datestr = CiteTB.formatDate(DT);
$j('#cite-'+id+'-'+field).val(datestr);
return false;
};
 
CiteTB.formatDate = function(DT, useday, usemonth) {
if (typeof useday == "undefined") {
useday = true;
}
if (typeof usemonth == "undefined") {
usemonth = true;
}
var datestr = CiteTB.getOption('date format');
var zmonth = '';
Line 557 ⟶ 686:
zdate = date.toString();
}
date = date.toString();
if (useday) {
datestr = datestr.replace('<date>', date);
datestr = datestr.replace('<monthzdate>', monthzdate);
} else {
datestr = datestr.replace('<zdate>', zdate);
datestr = datestr.replace('<zmonthdate>', zmonth'');
datestr = datestr.replace('<monthnamezdate>', CiteTB.getOption('months')[DT.getUTCMonth()]);
}
if (usemonth) {
datestr = datestr.replace('<month>', month);
datestr = datestr.replace('<zmonth>', zmonth);
datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
} else {
datestr = datestr.replace('<month>', '');
datestr = datestr.replace('<zmonth>', '');
datestr = datestr.replace('<monthname>', '');
}
datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
return datestr.replace(/^[ \/\-\,\.]*(.*?)[ \/\-\,\.]*$/g, "$1"); // Cleanup any dangling spaces or connectors that might result from omitting date/month
return datestr;
};
 
// 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( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
names.push(CiteTB.mainRefList[i]);
}
}
var stuff = $j('<div />');
$j('#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 = $j('<select id="cite-namedref-select">');
select.append($j('<option value="" />').text(mw.usability.getMsg('cite-named-refs-dropdown')));
for(var i=0; i<names.length; i++) {
select.append($j('<option />').text(names[i].refname));
}
stuff.after(select);
select.before('<br />');
var prevlabel = $j('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.usability.getMsg('cite-raw-preview'));
select.after(prevlabel);
prevlabel.before("<br /><br />");
prevlabel.after('<div id="cite-namedref-preview" style="padding:0.5em; font-size:110%" />');
var parselabel = $j('<span id="cite-parsed-label" style="display:none;" />').html(mw.usability.getMsg('cite-parsed-label'));
$j('#cite-namedref-preview').after(parselabel);
parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom:0.5em; font-size:110%" />');
var link = $j('<a href="#" id="cite-nref-parse" style="margin:0 1em 0 1em; display:none; color:darkblue" />');
link.html(mw.usability.getMsg('cite-form-parse'));
$j('#cite-namedref-parsed').after(link);
$j("#cite-namedref-select").bindon( 'change', CiteTB.namedRefSelectClick);
$j('#cite-nref-parse').bindon( 'click', CiteTB.nrefParseClick);
}
};
 
// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function() {
var form = $j('<div id="cite-errorcheck-heading" />').html(mw.usability.getMsg('cite-errorcheck-heading'));
var ul = $j("<ul id='cite-errcheck-list' />");
var test;
for (var t in CiteTB.ErrorChecks) {
test = CiteTB.ErrorChecks[t];
Line 614 ⟶ 755:
}
form.append(ul);
$j('#citetoolbar-errorcheck').html(form);
};
 
// Callback function for parsed preview
CiteTB.fillNrefPreview = function(parsed) {
$j('#cite-parsed-label').show();
$j('#cite-namedref-parsed').html(parsed);
};
 
// Click handler for the named-ref parsed preview
CiteTB.nrefParseClick = function() {
var choice = $j("#cite-namedref-select").val();
if (choice === '') {
$j('#cite-parsed-label').hide();
$j('#cite-namedref-parsed').text('');
return false;
}
$j('#cite-nref-parse').hide();
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
Line 638 ⟶ 779:
}
}
};
 
// Click handler for the named-ref dropdown
CiteTB.lastnamedrefchoice = '';
CiteTB.namedRefSelectClick = function() {
var choice = $j("#cite-namedref-select").val();
if (CiteTB.lastnamedrefchoice == choice) {
return;
}
CiteTB.lastnamedrefchoice = choice;
$j('#cite-parsed-label').hide();
$j('#cite-namedref-parsed').text('');
if (choice === '') {
$j('#cite-nref-preview-label').hide();
$j('#cite-namedref-preview').text('');
$j('#cite-nref-parse').hide();
return;
}
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
$j('#cite-nref-preview-label').show();
$j('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
if (CiteTB.getOption('autoparse')) {
CiteTB.nrefParseClick();
} else {
$j('#cite-nref-parse').show();
}
}
}
};
 
// callback function for parsed preview
CiteTB.fillTemplatePreview = function(text) {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-prev-parsed-label').show();
div.find('.cite-preview-parsed').html(text);
};
 
// Click handler for template parsed preview
Line 681 ⟶ 822:
var ref = CiteTB.getRef(true, false);
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-prev-parse').hide();
CiteTB.parse(ref, CiteTB.fillTemplatePreview);
};
 
// Show/hide the extra fields in the dialog box
CiteTB.showHideExtra = function() {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
var setting = div.find(".cite-form-status").val();
if ( setting === 'closed' ) {
div.find(".cite-form-status").val('open');
div.find('.cite-extra-fields').show(1, function() {
Line 698 ⟶ 839:
});
} else {
div.find(".cite-form-status").val('closed');
div.find('.cite-extra-fields').hide();
}
};
 
// Resets form fields and previews
// Resets form fields and previews
CiteTB.resetForm = function() {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.findhtml('template.cite-preview-label'getForm().hide();
};
div.find('.cite-ref-preview').text('').hide();
div.find('.cite-prev-parsed-label').hide();
div.find('.cite-preview-parsed').html('');
div.find('.cite-prev-parse').hide();
var id = CiteTB.escStr(template.shortform);
$j('#citetoolbar-'+id+' input[type=text]').val('');
}
 
// STRING UTILITY FUNCTIONS
// Returns a string quoted as necessary for name/group attributes
CiteTB.getQuotedString = function(s) {
var sp = /\s/.test(s); // spaces
var sq = /\'/.test(s); // single quotes
var dq = /\"/.test(s); // double quotes
if (!sp && !sq && !dq) { // NoAlways quotes necessaryfor non-latin alphabet
return '"'+s+'"';
} else if (!dq) { // Can use double quotes
return '"'+s+'"';
Line 729 ⟶ 864:
return "'"+s+"'";
} else { // Has double and single quotes
s = s.replace(/\"/g, '\"'');
return '"'+s+'"';
}
} ;
 
// Fix up strings for output - capitalize first char, replace underscores with spaces
CiteTB.fixStr = function(s) {
Line 738 ⟶ 874:
s = s.replace('_',' ');
return s;
};
 
// Escape spaces and quotes for use in HTML classes/ids
CiteTB.escStr = function(s) {
return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
};
 
// MISC FUNCTIONS
// Determine which template form is open, and get the template object for it
CiteTB.getOpenTemplate = function() {
var dialogs = $j(".ui-dialog-content.ui-widget-content:visible");
var templatename = $j(dialogs[0]).find(".cite-template").val();
var template = null;
return CiteTB.Templates[templatename];
};
 
// Display the report for the error checks
CiteTB.displayErrors = function(errors) {
$j('#cite-err-report').remove();
var table = $j('<table id="cite-err-report" style="width:100%; border:1px solid #A9A9A9; background-color:#FFEFD5; padding:0.25em; margin-top:0.5em" />');
$j('#editpage-copywarn').before(table);
var tr;
var tr1 = $j('<tr style="width:100%" />');
var th1 = $j('<th style="width:60%; font-size:110%" />').html(mw.usability.getMsg('cite-err-report-heading'));
var th2 = $j('<th style="text-align:right; width:40%" />');
var im = $j('<img />').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 = $j('<a id="cite-err-check-close" />').attr('href', '#');
ad.append(im);
th2.append(ad);
tr1.append(th1).append(th2);
table.append(tr1);
$j('#cite-err-check-close').bindon('click', function() { $j('#cite-err-report').remove(); });
if (errors.length === 0) {
var tr = $j('<tr style="width:100%;" />');
var td = $j('<td style="text-align:center; margin:1.5px;" />').html(mw.usability.getMsg('cite-err-report-empty'));
tr.append(td);
table.append(tr);
Line 779 ⟶ 916:
for(var e in errors) {
var err = errors[e];
var tr = $j('<tr style="width:100%;" />');
var td1 = $j('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
var td2 = $j('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.usability.getMsg(err.msg));
tr.append(td1).append(td2);
table.append(tr);
}
};
} // End of code loaded only on edit