MediaWiki:Gadget-TemplatePreloader.js
Увага: Після публікування слід очистити кеш браузера, щоб побачити зміни.
- Firefox / Safari: тримайте Shift, коли натискаєте Оновити, або натисніть Ctrl-F5 чи Ctrl-Shift-R (⌘-R на Apple Mac)
- Google Chrome: натисніть Ctrl-Shift-R (⌘-Shift-R на Apple Mac)
- Internet Explorer / Edge: тримайте Ctrl, коли натискаєте Оновити, або натисніть Ctrl-F5
- Opera: натисніть Ctrl-F5
/* Preload Template:Header when adding a new text */
function preloadHeaderTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "")
{
//fill in header template
var subpageDepth = 0
var isSubpage
var pathToTOC = "" //typically "../"
var subpageTitle
var subpageTitleRegExp
var rawBasePageRequest
var tocPageTitle
var beginningOfShortSectionTitle //for example, if tocPageTitle == "Democracy in America/Volume 2", then beginningOfShortSectionTitle == "Volume 2, " - this is used to determine the values for "previous" and "next"
var rawTocPageRequest //table of contents page
var rawTocPageWithoutHeader
//title
var wpTextbox1value = "{" + "{заголовок\n | назва = "
if (mw.config.get('wgTitle').indexOf("/") != -1) //a slash could indicate that it's a subpage
{
rawBasePageRequest = new XMLHttpRequest()
//determine where the base page name ends and where the subpage name begins
for (var slashPosition = mw.config.get('wgTitle').indexOf("/"); slashPosition != -1; slashPosition = mw.config.get('wgTitle').indexOf("/", slashPosition + 1))
{
rawBasePageRequest.open("GET", mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=" + mw.config.get('wgTitle').substr(0, slashPosition) + "&action=raw", false)
rawBasePageRequest.send(null)
if (rawBasePageRequest.responseText != "") //base page found
{
wpTextbox1value += "[["
//output however many "../" will take us to the base page
for (var i = mw.config.get('wgTitle').lastIndexOf("/"); i >= slashPosition; i = mw.config.get('wgTitle').lastIndexOf("/", i - 1))
{
wpTextbox1value += "../"
subpageDepth += 1
}
wpTextbox1value += "]]"
isSubpage = true
break
}
}
//output
if (isSubpage == false) //despite the slash in this page's title, no base page was found, so assume that this page is the base page (for example, "9/11 Commission Report")
{
wpTextbox1value += mw.config.get('wgTitle')
}
//round 2: find the table of contents page, not necessarily the same as the base page
var slashPosition = mw.config.get('wgTitle').lastIndexOf("/")
if (subpageDepth > 1)
{
rawTocPageRequest = new XMLHttpRequest()
for (; slashPosition != -1; slashPosition = mw.config.get('wgTitle').lastIndexOf("/", slashPosition - 1))
{
pathToTOC += "../"
tocPageTitle = mw.config.get('wgTitle').substr(0, slashPosition) //will be used later
rawTocPageRequest.open("GET", mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=" + tocPageTitle + "&action=raw", false)
rawTocPageRequest.send(null)
if (rawTocPageRequest.responseText != "") //TOC page found
{
break
}
}
}
else //if the depth is only 1 then the base page and the TOC page are the same
{
//set up variables without going through the whole loop
pathToTOC = "../"
tocPageTitle = mw.config.get('wgTitle').substr(0, slashPosition)
rawTocPageRequest = rawBasePageRequest
}
//for later
subpageTitle = mw.config.get('wgTitle').substr(slashPosition + 1) //subpageTitle is relative to the table of contents, not the base page
var indexOfSlashInTocPageTitle = tocPageTitle.indexOf("/")
if (indexOfSlashInTocPageTitle != -1)
{
beginningOfShortSectionTitle = tocPageTitle.substring(tocPageTitle.indexOf("/") + 1).replace(/\//g, ", ") + ", " //change / to , - better than doing nothing
}
else
{
beginningOfShortSectionTitle = ""
}
}
else //definitely not a subpage
{
wpTextbox1value += mw.config.get('wgTitle')
}
wpTextbox1value += "\n<!-- | назва_альт = альтернативна назва твору старим правописом, в перекладі тощо -->"
wpTextbox1value += "\n<!-- | версії = версії цього твору -->"
wpTextbox1value += "\n<!-- | подібне = неоднозначності -->"
//author
wpTextbox1value += "\n | автор = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|[\s]*автор[\s]*\=\s+([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
//override author
wpTextbox1value += "\n<!-- | перевизначити_автора = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|[\s]*перевизначити_автора[\s]*\=\s+([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
wpTextbox1value += "-->"
//editor
wpTextbox1value += "\n<!-- | редактор = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|\s*редактор\s*\=\s*([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
wpTextbox1value += "-->"
//override editor
wpTextbox1value += "\n<!-- | перевизначити_редактора = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|\s*перевизначити_редактора\s*\=\s*([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
wpTextbox1value += "-->"
//translator
wpTextbox1value += "\n<!-- | перекладач = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|\s*перекладач\s*\=\s*([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
wpTextbox1value += "-->"
//override translator
wpTextbox1value += "\n<!-- | перевизначити_перекладача = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{\s*(?:[Hh]eader|[Зз]аголовок)\s*[\s\S]*\|\s*перевизначити_перекладача\s*\=\s*([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
wpTextbox1value += "-->"
//section
wpTextbox1value += "\n | секція = "
if (isSubpage) //only subpages have section titles
{
try
{
subpageTitleRegExp = subpageTitle.replace(/[ _]/, "[ _]") //subpageTitleRegExp will also be used later
subpageTitleRegExp = "[" + subpageTitleRegExp[0].toUpperCase() + subpageTitleRegExp[0].toLowerCase() + "]" + subpageTitleRegExp.substr(1) //MediaWiki is not case-sensitive on the first letter
wpTextbox1value += (new RegExp("\\[\\[/" + subpageTitleRegExp + "\\|(.*)\]\]")).exec(rawTocPageRequest.responseText)[1]
}
catch (e)
{
//if there was an error, fall back on just adding the section name
wpTextbox1value += subpageTitle.replace(/\//g, ", ")
}
}
wpTextbox1value += "\n<!-- | секція_альт = -->"
wpTextbox1value += "\n<!-- | рік_секції = -->"
wpTextbox1value += "\n<!-- | перевизначити_рік_секції = -->"
wpTextbox1value += "\n<!-- | автор_секції = -->"
wpTextbox1value += "\n<!-- | перевизначити_автора_секції = -->"
wpTextbox1value += "\n<!-- | перекладач_секції = -->"
wpTextbox1value += "\n<!-- | перевизначити_перекладача_секції = -->"
//used for both previous page and next page determination
var indexOfCurrentPageInTableOfContents = -1 //the -1 makes sure that if the value can't be found, "undefined" isn't used instead
//previous
wpTextbox1value += "\n | попередня = "
try
{
rawTocPageWithoutHeader = rawTocPageRequest.responseText.substring(/(\{\{(?:[Hh]eader|[Зз]аголовок)[^\}\}]*)/.exec(rawTocPageRequest.responseText)[1].length) //cut off the header before searching
indexOfCurrentPageInTableOfContents = rawTocPageWithoutHeader.indexOf((new RegExp("\\[\\[/" + subpageTitleRegExp + "[\\||\\]\\]]")).exec(rawTocPageWithoutHeader)[0])
var indexOfTargetLink = rawTocPageWithoutHeader.lastIndexOf("[[/", indexOfCurrentPageInTableOfContents - 3)
var previousPageTitle = /\[\[\/([^\||\]\]]*)/.exec(rawTocPageWithoutHeader.substring(indexOfTargetLink, indexOfCurrentPageInTableOfContents))[1]
wpTextbox1value += "[[" + pathToTOC + previousPageTitle + "|" + beginningOfShortSectionTitle + previousPageTitle.replace(/\//g, ", ") + "]]" //change / to , - better than doing nothing
}
catch (e)
{
//if there was an error, just leave the field blank
}
wpTextbox1value += "\n<!-- | попередня_альт = -->"
//next
wpTextbox1value += "\n | наступна = "
try
{
if (indexOfCurrentPageInTableOfContents != -1) //if we don't know where we are in the list, do not wrap back to the beginning - strangely, an exception doesn't get thrown if I leave indexOfCurrentPageInTableOfContents alone, and the "next" algorithm jumped back to the beginning of the table of contents page
{
var indexOfTargetLink = rawTocPageWithoutHeader.indexOf("[[/", indexOfCurrentPageInTableOfContents + subpageTitle.length + 2)
if (indexOfTargetLink != -1) //if we're at the end of the list, do not wrap back to the beginning
{
var nextPageTitle = /\[\[\/([^\||\]\]]*)/.exec(rawTocPageWithoutHeader.substring(indexOfTargetLink))[1]
wpTextbox1value += "[[" + pathToTOC + nextPageTitle + "|" + beginningOfShortSectionTitle + nextPageTitle.replace(/\//g, ", ") + "]]" //change / to , - better than doing nothing
}
}
}
catch (e)
{
//if there was an error, just leave the field blank
}
wpTextbox1value += "\n<!-- | наступна_альт = -->"
// year (except on subpages)
if( mw.config.get('wgTitle').indexOf("/") == -1 )
{
wpTextbox1value += "\n | рік = ";
}
else
{
wpTextbox1value += "\n<!-- | рік = -->";
}
wpTextbox1value += "\n<!-- | перевизначити_рік = -->";
wpTextbox1value += "\n<!-- | категорії = -->";
wpTextbox1value += "\n | місто = ";
wpTextbox1value += "\n | видавець = ";
wpTextbox1value += "\n | правопис = ";
wpTextbox1value += "\n<!-- | обкладинка = -->";
wpTextbox1value += "\n<!-- | сторінка_обкладинки = -->";
wpTextbox1value += "\n<!-- | мова = -->";
wpTextbox1value += "\n<!-- | мова1 = -->";
wpTextbox1value += "\n<!-- | мова2 = -->";
wpTextbox1value += "\n<!-- | мова3 = -->";
//notes
wpTextbox1.value = wpTextbox1value + "\n | примітки =\n}}\n\n" +
"{" + "{PD-auto\n" +
"<!-- | країна = -->\n" +
" | рік-публікації = \n" +
" | рік-смерті = \n}}";
}
}
// When creating an author page fill field. Always filled, lastname,
// firstname, lastinitial, wikipedia, birth/year filled if an
// article is available on wp:en. Try also to avoid duplicate author:
// by creating a redirect if the wikipedia is non empty, its title
// is different from the current Author:title and an Author:new_title
// exists.
function check_redirect(title, text_box)
{
var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath')
+ "/api.php?format=xml&action=query&prop=info&titles="
+ encodeURIComponent(title);
var request = sajax_init_object();
request.open('GET', url, true);
request.onreadystatechange = function () {
if (request.readyState == 4) {
var xml = request.responseXML;
if (xml == null) return ;
var page = xml.getElementsByTagName( "page" )[0];
if (page.getAttribute("missing") != "")
text_box.value = '#ПЕРЕНАПРАВЛЕННЯ [[' + title + ']]';
}
};
request.send(null);
}
function author_fill_cb(data)
{
try {
var wpTextbox1 = document.getElementById("wpTextbox1");
if (wpTextbox1 && !data.query.pages["-1"]) {
for (var ids in data.query.pages) {
wpTextbox1.value = wpTextbox1.value.replace(/( *\\| *вікіпедія *= *)/, "$1" + data.query.pages[ids].title);
var cats = data.query.pages[ids].categories;
for (var i = 0; i < cats.length; ++i) {
var m = cats[i].title.match(/Категорія:Померли (\d+)$/);
if (m)
wpTextbox1.value = wpTextbox1.value.replace(/( *\\| *рік_смерті *= *)/, "$1" + m[1]);
m = cats[i].title.match(/Категорія:Народились (\d+)$/);
if (m)
wpTextbox1.value = wpTextbox1.value.replace(/( *\\| *рік_народження *= *)/, "$1" + m[1]);
}
break;
}
// This can undo all the above works by preferring to create a redirect to an existing author:
check_redirect('Автор:' + data.query.pages[ids].title, wpTextbox1);
}
}
catch (err) { }
}
function create_script_obj(url)
{
var scriptObj = document.createElement("script");
scriptObj.setAttribute("type", "text/javascript");
scriptObj.setAttribute("src", url);
document.body.appendChild(scriptObj);
}
function split_title()
{
return mw.config.get('wgTitle').replace(/ \(.*\)/, "").split(" ");
}
function get_special_word_pos(words)
{
var i;
for (i = 0; i < words.length; ++i) {
if (words[i] == 'ван' || words[i] == 'фон' ||
words[i] == 'ле' || words[i] == 'де') {
return i;
}
}
return -1;
}
function get_first_name(words)
{
return words.slice(0, get_special_word_pos(words)).join(" ");
}
function get_last_name(words)
{
return words.slice(get_special_word_pos(words)).join(" ");
}
/* Preload Template:Author when starting an author page, derived from [[User:Remember the dot]] code */
function preloadAuthorTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value != "") return;
// try to figure out what value we can fill, broken in some case because
// it's difficult to handle name like Tom Van Moore but Tom van Moore is
// handled correctly.
var words = split_title();
var lastname = get_last_name(words);
var firstname = get_first_name(words);
//no longer need to specifically capture here, data to Wikidata
wpTextbox1.value = "{" + "{автор}}\n\n" +
"== Твори ==\n\n\n" +
"{" + "{PD-auto}}\n" +
"{" + "{Authority control}}";
var base_url = "//uk.wikipedia.org" + mw.config.get('wgScriptPath');
var url = base_url + "/api.php?format=json&redirects"
+ "&callback=author_fill_cb&action=query&prop=categories&cllimit=20&titles="
+ encodeURIComponent(mw.config.get('wgTitle'));
create_script_obj(url);
}
// Preload Template:Translation header when starting a translation page
// Simple preloader based on the preload code for Template:Textinfo
function preloadTranslationHeaderTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "" && !document.URL.match('§ion=new') )
{
wpTextbox1.value = "{" + "{заголовок перекладу\n" +
" | назва = \n" +
" | автор = \n" +
" | секція = \n" +
" | попередня = \n" +
" | наступна = \n" +
" | рік = \n" +
" | мова = \n" +
" | оригінал = \n" +
" | примітки = \n" +
"}}\n"
}
}
if (mw.config.get('wgAction') == "edit")
{
switch (mw.config.get('wgNamespaceNumber'))
{
case 0: //main
$(preloadHeaderTemplate)
break
case 102: //Author
$(preloadAuthorTemplate)
case 114: //Translation
$(preloadTranslationHeaderTemplate)
}
}