User:V111P/js/webRef.js: Difference between revisions

Content deleted Content added
MM/DD/YYYY date support for U.S. date button and sites with language set to en-US ; trans-title param if lang is not en
YMD date button; removing <ref name="..."
 
(2 intermediate revisions by the same user not shown)
Line 1:
// v. 20152021-0309-0601; en.wikipedia.org/wiki/User:V111P/js/WebRef
window.webRef = window.webRef || {}; // object used to communicate with webRefSetup
window.webRef.getRef = (function () {
Line 31:
// these words are used when spliting names in the case of multipe article authors
var andWords = ['and']; // LOCALIZE by adding the word(s) for "and" in the local lang
 
// Use %D% or %DD%, %M% or %MM% or %MMM%, %YY% or %YYYY%.
// %M% -> Feb is 2; %MM% -> Feb is 02; %MMM% -> Feb is monthNumToName[1]
var dateFormatMDY = '%MMM% %D%, %YYYY%';
var dateFormatDMY = '%D% %MMM% %YYYY%';
var dateFormatYMD = '%YYYY%-%MM%-%DD%';
var dateFormatDefault = dateFormatDMY;
var dateFormatRetrieved = ''; // Leave empty to use dateFormatDefault
 
var templateParams = { // LOCALIZE
Line 38 ⟶ 46:
work: 'work',
date: 'date',
accessDate: 'accessdateaccess-date',
url: 'url',
publisher: 'publisher',
Line 46 ⟶ 54:
last: 'last',
first: 'first',
coauthors: 'coauthors', // not used if (coauthorsNumParams == true); if not set, only "author" is used
authorWikiArticle: 'authorlink',
barV: '| ', // bar and spaces around it (but no newlines) for Vertical format
coauthorsNumParams: true, // last2, first2, last3, first3, etc. instead of "coauthors" or only "author"
dateFormatbarVsameLine: '%D% %MMM%| %YYYY%', // %M%(e.g. ->first Febname is 2;on %MM%the ->same Febline isas 02;last %MMM%name ->even Febin isvertical monthNumToName[1]mode)
barH: ' |', // ... for Horizontal format
altDateFormat: '%MMM% %D%, %YYYY%',
eqV: ' = ', // equal sign and spaces around it (but no newline) for Vertical format
dateFormatRetrieved: '%YYYY%-%MM%-%DD%' // %D% or %DD%, %M% or %MM% or %MMM%, %YY% or %YYYY%
eqH: '=', // ... for Horizontal format
urlEqH: '= ' // a space before the URL helps with line wrapping
};
var tp = templateParams;
var altDateFormatIsUSFormat = true; // LOCALIZE. True in the case of the English Wikipedia
var barV = tp.barV, barH = tp.barH, eqV = tp.eqV, eqH = tp.eqH;
 
var msgs = webRef.idToText = webRef.msgs = webRef.msgs || webRef.idToText || {};
Line 64 ⟶ 75:
setupButton: 'Site setup',
hideButton: 'Close',
markButtonselectButton: 'Select',
copyButton: 'Copy',
compactCopyButton: 'Compact & Copy',
compactSelectButton : 'Compact & Select',
copyFailed: ' Copying failed!',
reloadButton: 'Reload',
formatNamesPromptButton: 'Authors',
formatNamesPrompt: 'Enter the author names (separated by commas if more than one author) to be formatted and inserted into the template:',
dmy: 'DMY',
singleMultiLineButton: 'Single/multi line',
mdy: 'MDY',
formatDatePromptButton: 'Date formatter',
ymd: 'YMD',
formatDatePrompt: 'Enter the date to be formatted and inserted into the template:',
refName: 'RefName',
altDateFormatButton: 'U.S. date',
singleMultiLineButton: 'Horiz./Vertical',
couldntParse: 'Sorry, I couldn\'t parse that.',
 
Line 142 ⟶ 158:
var siteLang; // used for date formatting if equals en-US and month is represented as a number
var monthWarningNeeded; // set in dateFormatter if not clear if date is in U.S. format or not
var siteDateIsUS = false;
 
var refDocData = window.webRef.refDocData = {
Line 314 ⟶ 331:
var monthStr = '';
var month;
format = format || dateFormatDefault;
 
for (var m in monthNameToNum) {
Line 353 ⟶ 371:
else if (year < 100)
year = '19' + year; // 1900+ otherwise :)
 
if (siteLang == 'en-US' || dateParts[2] > 12) { // American style date
month = dateParts[1];
Line 382 ⟶ 400:
 
function formatDateParams(format, useUSFormatIfUnclear) {
var t = templateParams;
var trimCollapse = aux.collapseWhitespace;
var strt = '\\|\\s*';
var end = '\\s*=\\s*([^|}]+*)';
var oldVal = codeTextArea.value;
var val = formatDateParam(oldVal, format, tp.date);
var val;
 
if (tp.accessDate && dateFormatRetrieved == '')
val = formatDateParam(oldVal, format, t.date);
val = formatDateParam(val, format, tp.accessDate);
if (t.accessDate && t.dateFormatRetrieved == '')
val = formatDateParam(val, format, t.accessDate, true);
if (val != oldVal) {
codeTextArea.value = val;
Line 397 ⟶ 413:
}
 
function formatDateParam(templStr, format, paramName, noPrompt) {
var dateParamRe = new RegExp(strt + paramName + end);
var dateInTemplate = trimCollapse((templStr.match(dateParamRe) || ['', ''])[1]);
var userDate, formatted;
 
if (dateInTemplate) || noPrompt){
userDate = dateInTemplate;
else
userDate = trimCollapse((prompt(msgs.formatDatePrompt, dateInTemplate) || ''));
 
if (userDate) {
monthWarningNeeded = false;
formattedvar formattedDate = dateFormatter(userDatedateInTemplate, format, useUSFormatIfUnclear);
if (formattedformattedDate) {
var dateParamPospos = templStr.indexOfsearch('| ' + paramName + ' ='dateParamRe) - 1;
if (pos < 0) pos = templStr.indexOf('|');
if (pos < 0) pos = 0;
templStr = templStr.replace(dateParamRe, '');
templStr = templStr.slice(0, pos) + '\n'
var pos = (dateParamPos > 0 ? dateParamPos : templStr.indexOf('|') - 1);
templStr = templStr.slice(0, pos) + '\n| 'barV + paramName + ' = 'eqV + formattedformattedDate + templStr.slice(pos);
if (monthWarningNeeded)
addWarning(msgs.monthWarning, msgs.monthWarningTitle);
}
else
alert(msgs.programName + ':\n' + msgs.couldntParse + '\n' + userDatedateInTemplate);
}
return templStr;
Line 429 ⟶ 441:
function formatNamesPrompt() {
var val = codeTextArea.value;
var t = templateParams;
var names = '';
var authorParamNames = [ttp.author, ttp.coauthors, ttp.first, ttp.last];
for (var n = 1; n <= 9; n++) {
authorParamNames.push(ttp.first + n)
authorParamNames.push(ttp.last + n);
}
 
var strt = '\\|\\s*';
var end = '\\s*=\\s*([^|}]+)';
names = (val.match(strt + ttp.author + end) || ['', ''])[1] + ',';
var trimCollapse = aux.collapseWhitespace;
for (var n = 0; n <= 9; n++)
names += (val.match(strt + ttp.first + (n == 0 ? '' : n) + end) || ['', ''])[1] + ' '
+ trimCollapseaux.collapseWhitespace((val.match(strt + ttp.last + (n == 0 ? '' : n) + end) || ['', ''])[1])
.replace(/ /g, '_') + ',';
if (ttp.coauthors)
names += (val.match(strt + ttp.coauthors + end) || ['', ''])[1];
names = names.replace(/\s+/g, ' ').replace(/\s?,\s?/g, ',')
.replace(/,,+/g, ',').replace(/^,|,$/g, '').replace(/,/g, ', ');
Line 452 ⟶ 463:
var namesNewParams = authorParams(nameFormatter(userAuthors));
if (namesNewParams) {
var authorPospos = val.indexOfsearch(new RegExp('\\| \\s*(' + ttp.last + '1?|' + tp.author + ')\\s*='));
if (authorPospos < 0) pos == -1val.indexOf('|');
authorPosif = val.indexOf('|pos '< +0) t.authorpos += ' =')0;
for (var n = 0; n < authorParamNames.length; n++)
val = val.replace(new RegExp(strt + authorParamNames[n] + end), '');
 
var pos = (val.charAt(authorPos) == '|' ? authorPos : val.indexOf('|')) - 1;
val = val.slice(0, pos) + namesNewParams + val.slice(pos);
codeTextArea.value = val;
Line 487 ⟶ 497:
 
 
function authorParams(arrauthorsArr, additionalNotAnAuthor) {
var t = templateParams;
var str = '';
var nl = '\n| ' + barV;
if (!authorsArr && siteObj.authorName) {
var authors;
if str (!arr= &&nl + tp.author + eqV + siteObj.authorName) {;
str = nl + t.author + ' = ' + siteObj.authorName;
if (siteObj.authorWikiArticle)
str += nl + ttp.authorWikiArticle + ' = 'eqV + siteObj.authorWikiArticle;
}
else if ((authorsauthorsArr = arrauthorsArr || searchFor('author', siteObj.notAnAuthor)) !== null) {
if (additionalNotAnAuthor) { // to remove e.g. "CNN" from "James Smith, CNN"
var co = ''; // coauthors
var i = authorsArr.length;
var last1 = authors[0][0];
while (i--) {
var first1 = authors[0][1];
if (authorsArr[i][0] === additionalNotAnAuthor && !authorsArr[i][1])
if (first1 && (
authors authorsArr.length ==splice(i, 1);
}
|| !(!t.coauthorsNumParams && !t.coauthors)
)) {
str = nl + t.last + ' = ' + last1;
str += ' | ' + t.first + ' = ' + first1;
}
if ( authorsArr.length == 1 && !authorsArr[0][1] ) // only 1 author without a first name
else
str = nl + ttp.author + ' = 'eqV + last1authorsArr[0][0]; + (first1// ?use ',the 'author' + first1 : '');param
else { // use the 'last' and 'first' params
 
for (var i = 10; i < authorsauthorsArr.length; i++) {
var num = (i > 0 || authorsArr.length > 1 ? String(i + 1) : ''); // omit number if only 1 author
if (t.coauthorsNumParams) {
if (authorsauthorsArr[i][0]) {
costr += nl + ttp.last + (inum + 1)eqV + ' = ' + authorsauthorsArr[i][0];
if (authorsauthorsArr[i][1])
costr += ' | 'tp.barVsameLine + ttp.first + (inum + 1) + ' = 'eqV + authorsauthorsArr[i][1];
}
}
else {
if (i > 1)
co += ', ';
if (authors[i][1])
co += authors[i][1] + ' ';
co += authors[i][0];
}
}
if (t.coauthorsNumParams) {
if (co)
str += co;
}
else if (co) {
if (t.coauthors)
str += nl + t.coauthors + ' = ' + co;
else
str += ', ' + co; // add them to the author param value
}
 
 
}
return str;
Line 545 ⟶ 535:
var val = aux.trimStr(codeTextArea.value);
var nowMulti = (val.indexOf('\n') > -1) && !toMulti;
if ( toMulti === false || (!toMulti && nowMulti) ) {
val = val.replace(/\n/g, ' ');
.replace(/\s*\|\s*([^|= ]+)\s*=\s*/g, barH + '$1' + eqH)
else {
// a space after |url= helps with line wrapping :
var t = templateParams;
val = val .replace(/new RegExp('(\\|/g,\\s*' + tp.url + ')\n|\s*=\\s*').replace(/ }}/, '\n}}$1' + tp.urlEqH);
} else {
val = val.replace(/\s*\|\s*([^|= ]+)\s*=\s*/g, '\n' + barV + '$1' + eqV ).replace(/\s*}}/, '\n}}')
.replace( // move the "last" and "first" parameters on one line
new RegExp('(\\|\\s*' + ttp.last + '\\d?\\s*=[^\\n|}]*)\n(\\| ' + ttp.first + '\\d?\\s*=)', 'g'),
'$1 $2'
);
Line 579 ⟶ 571:
 
function createUI() {
var copyButtonSupported;
try {
copyButtonSupported = document.queryCommandSupported && document.queryCommandSupported('copy');
} catch (e) {
copyButtonSupported = false;
}
var buttons = [
{
id: copyButtonSupported ? 'compactCopyButton' : 'compactSelectButton',
id: 'markButton',
onclick: function () {
var taval = domcodeTextArea.byId('codeTA', refFrame.doc)value;
val = val.replace(new RegExp('\\s*\\|\\s*' + tp.quote + '\\s*=\\s*(\\||})'), '$1') // rm empty quote
ta.focus();
.replace(new RegExp('\\s*\\|\\s*' + tp.lang + '\\s*=\\s*(\\||})'), '$1') // rm empty lang
ta.select();
.replace(/\s+}}\s*$/, '}}'); // remove spaces before and after final }}
codeTextArea.value = val;
singleMultiLine(false);
codeTextArea.focus();
codeTextArea.select();
if (copyButtonSupported) {
var copyFailed = !refFrame.doc.queryCommandEnabled('copy');
if (!copyFailed) try {
copyFailed = !refFrame.doc.execCommand('copy');
} catch (e) { copyFailed = true; }
if (copyFailed) this.parentNode.insertBefore(dom.textNode(msgs['copyFailed']), this.nextSibling);
}
}
},
Line 593 ⟶ 603:
},
{
id: 'formatDatePromptButtondmy',
onclick: function () { formatDateParams(dateFormatDMY); }
},
{
id: 'mdy',
onclick: function () { formatDateParams(dateFormatMDY); }
},
{
id: 'ymd',
onclick: function () { formatDateParams(dateFormatYMD); }
},
{
id: 'refName',
id: (templateParams.altDateFormat ? 'altDateFormatButton' : ''),
onclick: function () {
var val, oldVal = codeTextArea.value;
formatDateParams(templateParams.altDateFormat, altDateFormatIsUSFormat);
val = oldVal.replace(/^<ref name="[^"]*"/, '<ref');
if (val == oldVal)
val = val.replace(/^<ref/, '<ref name=""');
codeTextArea.value = val;
}
},
Line 638 ⟶ 660:
br();
 
var btn;
for (var i = 0; i < buttons.length; i++) {
ifbtn = (buttons[i].id) {;
if (!btn.id)
docFrag.appendChild(dom.newEl('button', {
continue;
text: msgs[buttons[i].id],
onclick: buttons[i].onclick
}));
dom.text(' ', docFrag);
}
}
 
docFrag.appendChild(dom.newEl('button', {
text: msgs[btn.id],
onclick: btn.onclick
}));
 
dom.text(' ', docFrag);
}
dom.text('| ', docFrag);
docFrag.appendChild(dom.newEl('a', {
Line 796 ⟶ 821:
function dateToString(day, month, year, format) { // month is 0..11
day = +day; month = +month; year = +year;
return ((format || templateParams.dateFormat)
.replace(/%DD%/, (day > 9 ? '' : '0') + day)
.replace(/%D%/, day)
Line 803 ⟶ 828:
.replace(/%M%/, (month + 1))
.replace(/%YYYY%/, year)
.replace(/%YY%/, year % 100));
}
 
Line 813 ⟶ 838:
today.getMonth(),
today.getFullYear(),
(templateParams.dateFormatRetrieved || templateParams.dateFormatdateFormatDefault)
);
}
Line 829 ⟶ 854:
}
return siteName;
}
 
 
function makeRefName(title) {
return ___domain.slice(0, 4) + '_' + title.replace(/\s+/g, '').slice(0, 4);
}
 
Line 895 ⟶ 915:
 
function go() {
var t = templateParams;
var title, date, lang, langParam, quote, selection, work, publisher;
 
Line 914 ⟶ 933:
 
title = cleanParam(searchFor('title'));
 
monthWarningNeeded = false;
date = searchFor('date');
Line 930 ⟶ 950:
}
if (!lang || lang != langToIgnore) // add the param only if lang is not langToIgnore
langParam = '| 'barV + ttp.lang + ' = 'eqV + lang + ' \n';
 
quote = '| 'barV + ttp.quote + ' = 'eqV;
selection = getSelectedText();
if (selection) {
Line 946 ⟶ 966:
publisher = siteObj.publisher || '';
 
codeTextArea.value = '<ref name="' + makeRefName(title) + '">{{'
+ ttp.templateName
+ '\n| ' + tbarV + tp.title + ' = 'eqV + title
+ (!lang || lang == langToIgnore ? '' : '\n| ' + tbarV + tp.transTitle + ' = 'eqV) // translated title
+ authorParams(null, work)
+ '\n| ' + tbarV + tp.work + ' = 'eqV + work
+ '\n| ' + tbarV + tp.date + ' = 'eqV + date
+ '\n| ' + tbarV + tp.accessDate + ' = 'eqV + getTodaysDateStr()
+ '\n| ' + tbarV + tp.url + ' = 'eqV + decodeURI(___location.href) + '\n'
+ (publisher ? '| 'barV + ttp.publisher + ' = 'eqV + publisher + '\n' : '')
+ langParam
+ quote