No edit summary |
No edit summary |
||
| Line 2: | Line 2: | ||
* reFill.js — WikiEditor tab | * reFill.js — WikiEditor tab | ||
* Fills <ref>https://…</ref> and <ref>[https://… title]</ref> | * Fills <ref>https://…</ref> and <ref>[https://… title]</ref> | ||
* | * Names refs only when the same URL is used more than once | ||
*/ | */ | ||
(function () { | (function () { | ||
| Line 62: | Line 62: | ||
} | } | ||
function normUrl(url) { | function normUrl(url) { | ||
return String(url || '').trim().replace(/\/+$/, ''); | return String(url || '').trim().replace(/[?#].*$/, '').replace(/\/+$/, '').toLowerCase(); | ||
} | } | ||
function existingName(attrs) { | function existingName(attrs) { | ||
var m = String(attrs || '').match(/\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i); | var m = String(attrs || '').match(/\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i); | ||
var n = m ? (m[1] || m[2] || m[3]) : null; | |||
if (!n || /^:\d+$/.test(n)) { | |||
return null; | |||
} | |||
return n; | |||
} | } | ||
function dropName(attrs) { | function dropName(attrs) { | ||
| Line 102: | Line 106: | ||
function findBare(wikitext) { | function findBare(wikitext) { | ||
var out = [], m; | var out = [], m; | ||
var reBare = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi; | var reBare = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|{]+)\s*(?:\{\{[^}]+\}\})?\s*<\/ref>/gi; | ||
while ((m = reBare.exec(wikitext)) !== null) { | while ((m = reBare.exec(wikitext)) !== null) { | ||
out.push({ full: m[0], attrs: m[1] || '', url: m[2], index: m.index }); | out.push({ full: m[0], attrs: m[1] || '', url: m[2], index: m.index }); | ||
| Line 127: | Line 131: | ||
}); | }); | ||
} | } | ||
function run() { | |||
var text = getWikitext(); | var text = getWikitext(); | ||
if (!text) { | if (!text) { | ||
| Line 148: | Line 152: | ||
var key = normUrl(item.url); | var key = normUrl(item.url); | ||
if (!groups[key]) { | if (!groups[key]) { | ||
groups[key] = { | groups[key] = { url: item.url, count: 0, name: existingName(item.attrs), first: true }; | ||
order.push(key); | order.push(key); | ||
} | } | ||
groups[key].count++; | groups[key].count++; | ||
if (!groups[key].name) { | |||
groups[key].name = existingName(item.attrs); | |||
} | |||
}); | }); | ||
| Line 164: | Line 166: | ||
if (g.count > 1 && !g.name) { | if (g.count > 1 && !g.name) { | ||
g.name = ':' + nextNum++; | g.name = ':' + nextNum++; | ||
} | |||
if (g.count === 1) { | |||
g.name = null; | |||
} | } | ||
}); | }); | ||
| Line 196: | Line 201: | ||
var other = dropName(item.attrs); | var other = dropName(item.attrs); | ||
var neu; | var neu; | ||
if (g.count === 1 | if (!g.name || g.count === 1) { | ||
neu = '<ref' + other + '>' + templateFromCitoid(meta, item.url) + '</ref>'; | neu = '<ref' + other + '>' + templateFromCitoid(meta, item.url) + '</ref>'; | ||
} else if (g.first) { | } else if (g.first) { | ||
| Line 229: | Line 234: | ||
$textarea.wikiEditor('addToToolbar', { | $textarea.wikiEditor('addToToolbar', { | ||
sections: { | sections: { | ||
refill: { | refill: { type: 'toolbar', label: 'reFill' } | ||
} | } | ||
}); | }); | ||
Revision as of 11:02, 29 September 2026
/**
* reFill.js — WikiEditor tab
* Fills <ref>https://…</ref> and <ref>[https://… title]</ref>
* Names refs only when the same URL is used more than once
*/
(function () {
'use strict';
var CITOID = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
var TYPE_MAP = {
blogPost: 'Cite web',
webpage: 'Cite web',
email: 'Cite web',
forumPost: 'Cite web',
newspaperArticle: 'Cite news',
magazineArticle: 'Cite news',
journalArticle: 'Cite journal',
conferencePaper: 'Cite journal',
presentation: 'Cite journal',
book: 'Cite book',
manuscript: 'Cite book',
_default: 'Cite web'
};
function $box() {
return $('#wpTextbox1');
}
function getWikitext() {
var $t = $box();
if ($t.length && $.fn.textSelection) {
return $t.textSelection('getContents');
}
return $t.length ? $t.val() : '';
}
function setWikitext(text) {
var $t = $box();
if ($t.length && $.fn.textSelection) {
$t.textSelection('setContents', text);
return;
}
if ($t.length) {
$t.val(text).trigger('input');
}
}
function setSummary(ok, fail) {
var $s = $('#wpSummary');
if (!$s.length) {
return;
}
var note = 'Filled in ' + ok + ' bare reference' + (ok === 1 ? '' : 's') + ' with [[Bharatpedia:reFill|reFill]]';
if (fail) {
note += ' (' + fail + ' failed)';
}
var cur = ($s.val() || '').trim();
if (!cur) {
$s.val(note);
} else if (cur.toLowerCase().indexOf('refill') === -1) {
$s.val(cur.replace(/\s*$/, '') + '; ' + note);
}
$s.trigger('change');
}
function esc(s) {
return String(s || '').replace(/\|/g, '{{!}}').replace(/\n/g, ' ').trim();
}
function normUrl(url) {
return String(url || '').trim().replace(/[?#].*$/, '').replace(/\/+$/, '').toLowerCase();
}
function existingName(attrs) {
var m = String(attrs || '').match(/\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
var n = m ? (m[1] || m[2] || m[3]) : null;
if (!n || /^:\d+$/.test(n)) {
return null;
}
return n;
}
function dropName(attrs) {
return String(attrs || '').replace(/\s*\bname\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i, '');
}
function templateFromCitoid(item, fallbackUrl) {
var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
var p = [];
var url = (item && item.url) || fallbackUrl;
if (url) {
p.push('url=' + esc(url));
}
if (item && item.title) {
p.push('title=' + esc(item.title));
}
var site = item && (item.websiteTitle || item.publicationTitle || item.publisher);
if (site) {
p.push((name === 'Cite news' || name === 'Cite journal' ? 'work=' : 'website=') + esc(site));
}
if (item && item.date) {
p.push('date=' + esc(item.date));
}
if (item && item.author && item.author[0]) {
var a = item.author[0];
if (a[1]) {
p.push('last=' + esc(a[1]));
}
if (a[0]) {
p.push('first=' + esc(a[0]));
}
}
p.push('access-date=' + new Date().toISOString().slice(0, 10));
return '{{' + name + '|' + p.join('|') + '}}';
}
function findBare(wikitext) {
var out = [], m;
var reBare = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|{]+)\s*(?:\{\{[^}]+\}\})?\s*<\/ref>/gi;
while ((m = reBare.exec(wikitext)) !== null) {
out.push({ full: m[0], attrs: m[1] || '', url: m[2], index: m.index });
}
var reLink = /<ref(\s[^>]*)?>\s*\[(https?:\/\/[^\s\]]+)\s+[^\]]*\]\s*<\/ref>/gi;
while ((m = reLink.exec(wikitext)) !== null) {
out.push({ full: m[0], attrs: m[1] || '', url: m[2], index: m.index });
}
out.sort(function (a, b) {
return a.index - b.index;
});
return out;
}
function fetchOne(url) {
return fetch(CITOID + encodeURIComponent(url), {
headers: { Accept: 'application/json' }
}).then(function (r) {
if (!r.ok) {
throw new Error('HTTP ' + r.status);
}
return r.json();
}).then(function (data) {
return Array.isArray(data) ? data[0] : data;
});
}
function run() {
var text = getWikitext();
if (!text) {
window.alert('reFill: no editor text.');
return;
}
var bare = findBare(text);
if (!bare.length) {
window.alert('reFill: no <ref>https://…</ref> or <ref>[https://… title]</ref> found.');
return;
}
var tab = document.querySelector('.tab-refill, [rel="refill"]');
if (tab) {
tab.textContent = 'Filling…';
}
var groups = {};
var order = [];
bare.forEach(function (item) {
var key = normUrl(item.url);
if (!groups[key]) {
groups[key] = { url: item.url, count: 0, name: existingName(item.attrs), first: true };
order.push(key);
}
groups[key].count++;
if (!groups[key].name) {
groups[key].name = existingName(item.attrs);
}
});
var nextNum = 0;
order.forEach(function (key) {
var g = groups[key];
if (g.count > 1 && !g.name) {
g.name = ':' + nextNum++;
}
if (g.count === 1) {
g.name = null;
}
});
var metaByUrl = {};
var chain = Promise.resolve();
var fail = 0;
order.forEach(function (key) {
chain = chain.then(function () {
return fetchOne(groups[key].url).then(function (meta) {
metaByUrl[key] = meta || {};
}).catch(function () {
fail++;
metaByUrl[key] = null;
}).then(function () {
return new Promise(function (res) {
setTimeout(res, 350);
});
});
});
});
chain.then(function () {
var ok = 0;
bare.forEach(function (item) {
var key = normUrl(item.url);
var g = groups[key];
var meta = metaByUrl[key];
if (!g || meta === null) {
return;
}
var other = dropName(item.attrs);
var neu;
if (!g.name || g.count === 1) {
neu = '<ref' + other + '>' + templateFromCitoid(meta, item.url) + '</ref>';
} else if (g.first) {
g.first = false;
neu = '<ref name="' + g.name + '"' + other + '>' +
templateFromCitoid(meta, item.url) + '</ref>';
} else {
neu = '<ref name="' + g.name + '" />';
}
var pos = text.indexOf(item.full);
if (pos !== -1) {
text = text.slice(0, pos) + neu + text.slice(pos + item.full.length);
ok++;
}
});
setWikitext(text);
setSummary(ok, fail);
if (tab) {
tab.textContent = 'reFill';
}
window.alert('reFill finished: ' + ok + ' filled, ' + fail + ' failed. Preview before saving.');
});
}
function addSection($textarea) {
if (!$textarea || !$textarea.length || typeof $textarea.wikiEditor !== 'function') {
return;
}
if ($textarea.data('refillAdded')) {
return;
}
try {
$textarea.wikiEditor('addToToolbar', {
sections: {
refill: { type: 'toolbar', label: 'reFill' }
}
});
$textarea.data('refillAdded', true);
} catch (e) { /* already exists */ }
}
function bindTab() {
var root = document.querySelector('.wikiEditor-ui-toolbar');
if (!root || root.getAttribute('data-refill-bound')) {
return;
}
root.setAttribute('data-refill-bound', '1');
root.addEventListener('click', function (e) {
var t = e.target.closest('.tab-refill, [rel="refill"], .wikiEditor-ui-toolbar [rel="refill"]');
if (!t) {
return;
}
e.preventDefault();
e.stopPropagation();
run();
}, true);
}
function cleanupStray() {
var stray = document.getElementById('refill-toolbar-btn');
if (stray) {
stray.remove();
}
var flt = document.getElementById('refill-bare-btn');
if (flt) {
flt.remove();
}
}
function start() {
addSection($box());
bindTab();
cleanupStray();
if (mw.hook) {
mw.hook('wikiEditor.toolbarReady').add(function ($textarea) {
addSection($textarea);
bindTab();
cleanupStray();
});
}
setTimeout(function () {
addSection($box());
bindTab();
cleanupStray();
}, 800);
}
mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
})();