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

Content deleted Content added
page title can change
YMD date button; removing <ref name="..."
 
(3 intermediate revisions by the same user not shown)
Line 1:
// v. 20142021-0509-1701; 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
templateName: 'Cite web',
title: 'title',
transTitle: 'trans-title', // the title translated to English
work: 'work',
date: 'date',
accessDate: 'accessdateaccess-date',
url: 'url',
publisher: 'publisher',
Line 45 ⟶ 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 barV = tp.barV, barH = tp.barH, eqV = tp.eqV, eqH = tp.eqH;
 
var msgs = webRef.idToText = webRef.msgs = webRef.msgs || webRef.idToText || {};
var msgs_default = { // LOCALIZE
programName: 'WebRef',
monthWarning: 'Check month!',
monthWarningTitle: 'Was the date in the MM/DD/YY(YY) or DD/MM/YY(YY) format?',
quoteUsedWarning: 'Quotation!',
quoteUsedWarningTitle: 'The selected text on the page was used for the value of the "quote"Quote parameter.',
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 83 ⟶ 102:
 
aboutSiteH: 'About the site',
aboutSiteSectionIntro: 'You can fill this information, but data that is automatically filled doesn\'t need saving in the configuration. Using en as the language code for sites in English will hide the language parameter in the Cite web template. Use en-US if the date is in the MM/DD/YY(YY) format, with the month number instead of its name used in the date.',
siteName_L: 'Site name (can be a wikilink):',
lang_L: 'Language code for the site:',
Line 137 ⟶ 156:
 
var codeTextArea;
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 306 ⟶ 327:
 
 
function dateFormatter(dateStr, format, dontCheckUSuseUSFormatIfUnclear) { // format is optional
var formattedDate = '';
var monthStr = '';
var month;
format = format || dateFormatDefault;
 
for (var m in monthNameToNum) {
Line 350 ⟶ 372:
year = '19' + year; // 1900+ otherwise :)
 
if (siteLang == 'en-US' || dateParts[2] > 12) { // American style date
var lang = metaContent ? metaContent['misc html-lang'] : '';
if ((!dontCheckUS && lang == 'en-US') || dateParts[2] > 12) { // American style date
month = dateParts[1];
day = dateParts[2];
}
else {
if (!siteLang || siteLang == 'en')
day = dateParts[1];
month monthWarningNeeded = dateParts[2]true;
if (useUSFormatIfUnclear) {
month = dateParts[1];
day = dateParts[2];
}
else {
day = dateParts[1];
month = dateParts[2];
}
}
day = ('0' + day).slice(-2);
Line 370 ⟶ 399:
 
 
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 386 ⟶ 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){
monthWarningNeeded = false;
userDate = dateInTemplate;
var formattedDate = dateFormatter(dateInTemplate, format, useUSFormatIfUnclear);
else
if (formattedDate) {
userDate = trimCollapse((prompt(msgs.formatDatePrompt, dateInTemplate) || ''));
var pos = templStr.search(dateParamRe);
 
if (pos < 0) pos = templStr.indexOf('|');
if (userDate) {
if (pos < 0) pos = 0;
formatted = dateFormatter(userDate, format, true);
if (formatted) {
var dateParamPos = templStr.indexOf('| ' + paramName + ' =') - 1;
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 415 ⟶ 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 438 ⟶ 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 473 ⟶ 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 531 ⟶ 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 565 ⟶ 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 579 ⟶ 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);
val = oldVal.replace(/^<ref name="[^"]*"/, '<ref');
if (val == oldVal)
val = val.replace(/^<ref/, '<ref name=""');
codeTextArea.value = val;
}
},
Line 624 ⟶ 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
docFrag.appendChild(dom.newEl('button', {
}));
dom.text(': 'msgs[btn.id], docFrag);
onclick: btn.onclick
}
}));
 
dom.text(' ', docFrag);
}
 
dom.text('| ', docFrag);
docFrag.appendChild(dom.newEl('a', {
Line 646 ⟶ 685:
css: {display: 'none'}
}));
docFrag.appendChild(dom.newEl('span', {id: 'warnings'}));
id: 'warnings',
css: {backgroundColor: 'green'}
}));
 
refFrame.frame = dom.byId('ref00ref');
Line 785 ⟶ 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 792 ⟶ 828:
.replace(/%M%/, (month + 1))
.replace(/%YYYY%/, year)
.replace(/%YY%/, year % 100));
}
 
Line 802 ⟶ 838:
today.getMonth(),
today.getFullYear(),
(templateParams.dateFormatRetrieved || templateParams.dateFormatdateFormatDefault)
);
}
Line 818 ⟶ 854:
}
return siteName;
}
 
 
function makeRefName(title) {
return ___domain.slice(0, 4) + '_' + title.replace(/\s+/g, '').slice(0, 4);
}
 
Line 859 ⟶ 890:
return text;
}
 
 
function addWarning(label, title) {
var warnSpan = dom.byId('warnings', refFrame.doc);
var warnSepar = dom.byId('warningsSeparator', refFrame.doc);
warnSepar.style.display = 'inline';
warnSpan.appendChild(dom.textNode(' '));
warnSpan.appendChild(dom.newEl('span', {
text: label,
title: title,
css: {backgroundColor: 'green'}
}));
}
 
 
function clearWarnings() {
var warnSpan = dom.byId('warnings', refFrame.doc);
var warnSepar = dom.byId('warningsSeparator', refFrame.doc);
warnSpan.innerHTML = '';
warnSepar.style.display = 'none';
}
 
 
 
function go() {
var title, date, lang, langParam, quote, selection, work, publisher;
var t = templateParams;
var title, lang, langParam, quote, selection, work, publisher;
 
metaContent = window.webRef.metaContent = getMetaContent();
Line 875 ⟶ 927:
return sO || {};
})();
siteLang = siteObj.lang || '';
 
clearWarnings();
var warnings = [];
 
title = cleanParam(searchFor('title'));
 
monthWarningNeeded = false;
date = searchFor('date');
if (monthWarningNeeded) { // set in dateFormatter() if not clear whether the date is MM/DD/YYYY or DD/MM/YYYY
warnings.push([msgs.monthWarning, msgs.monthWarningTitle]);
}
 
langParam = '';
if (siteLang.search(/^en-US/i) == 0) siteLang = 'en-US';
lang = siteObj.lang;
lang = (siteLang == 'en-US' ? 'en' : siteLang);
if (!lang) {
lang = autoSearchFor('lang') || '';
Line 887 ⟶ 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();
var warnSpan = dom.byId('warnings', refFrame.doc);
if (selection) {
quote += cleanParam(selection);
warnings.push([msgs.quoteUsedWarning, msgs.quoteUsedWarningTitle]);
dom.byId('warningsSeparator', refFrame.doc).style.display = 'inline';
warnSpan.innerHTML = msgs.quoteUsedWarning;
warnSpan.title = msgs.quoteUsedWarningTitle;
}
 
else {
for (var i = 0; i < warnings.length; i++) {
dom.byId('warningsSeparator', refFrame.doc).style.display = 'none';
addWarning(warnings[i][0], warnings[i][1]);
warnSpan.innerHTML = '';
}
 
Line 906 ⟶ 966:
publisher = siteObj.publisher || '';
 
codeTextArea.value = '<ref name="' + makeRefName(title) + '">{{'
+ ttp.templateName
+ '\n| ' + tbarV + tp.title + ' = 'eqV + title
+ (!lang || lang == langToIgnore ? '' : '\n' + barV + tp.transTitle + eqV) // translated title
+ authorParams()
+ '\n| ' + t.work + ' = ' +authorParams(null, work)
+ '\n| ' + t.datebarV + 'tp.work =+ 'eqV + searchFor('date')work
+ '\n| ' + t.accessDatebarV + 'tp.date =+ 'eqV + getTodaysDateStr()date
+ '\n| ' + t.urlbarV + 'tp.accessDate =+ 'eqV + decodeURIgetTodaysDateStr(___location.href) + '\n'
+ (publisher ? '| \n' + t.publisherbarV + 'tp.url =+ 'eqV + publisher___location.href + '\n' : '')
+ (publisher ? barV + tp.publisher + eqV + publisher + '\n' : '')
+ langParam
+ quote