MediaWiki:Gadget-TemplatePreloader.js
Cache: Sau khi lưu biểu mẫu này, phải xóa bộ nhớ đệm (cache) của trình duyệt để những thay đổi hiện ra:
Firefox, Chrome, Safari, Opera — Shift Internet Explorer — Ctrl Konqueror —
Nếu bạn viết mã JavaScript, chú ý đọc hướng dẫn để tránh mâu thuẫn với mã mặc định của mạng.
/* Tải sẵn [[Bản mẫu:Đầu đề]] khi thêm văn kiện mới */
/* Để được trợ giúp, xem [[Trợ giúp:Công cụ tải trước đầu đề]] */
/*jshint asi:true, eqnull:true, laxbreak:true, forin: false */
/*global mw, $, sajax_init_object */
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
var slashPosition
var indexOfTargetLink
//title
var wpTextbox1value = "{" + "{đầu đề\n | tựa đề = "; // {{đầu đề}}
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 (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) //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
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')
}
//author
wpTextbox1value += "\n | tác giả = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{[\s]*[Đđ]ầu đề[2]?[\s]*[\s\S]*\|[\s]*tác giả[\s]*\=([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/^\s+/,"").replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
//translator
wpTextbox1value += "\n | dịch giả = "
if (isSubpage)
{
try
{
wpTextbox1value += /\{\{[\s]*[Đđ]ầu đề[2]?[\s]*[\s\S]*\|[\s]*dịch giả[\s]*\=([^\||\}\}]*)/.exec(rawTocPageRequest.responseText)[1].replace(/^\s+/,"").replace(/\s+$/,"")
}
catch (e)
{
//if there was an error, just leave the field blank
}
}
//section
wpTextbox1value += "\n | phầ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, ", ")
}
}
//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 | trước = "
try
{
rawTocPageWithoutHeader = rawTocPageRequest.responseText.substring(/(\{\{[Đđ]ầu đề[2]?[^\}\}]*)/.exec(rawTocPageRequest.responseText)[1].length) //cut off the header before searching
indexOfCurrentPageInTableOfContents = rawTocPageWithoutHeader.indexOf((new RegExp("\\[\\[/" + subpageTitleRegExp + "[\\||\\]\\]]")).exec(rawTocPageWithoutHeader)[0])
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
}
//next
wpTextbox1value += "\n | sau = "
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
{
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
}
// year (except on subpages)
if( mw.config.get('wgTitle').indexOf("/") == -1 )
{
wpTextbox1value += "\n | năm = ";
}
//notes
wpTextbox1.value = wpTextbox1value + "\n | ghi chú = \n}}\n\n"
}
}
/* Tải trước [[Bản mẫu:Thông tin văn kiện]] khi bắt đầu một trang thảo luận */
function preloadTextinfoTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value === "" && !document.URL.match('§ion=new') )
{
wpTextbox1.value = "{" + "{thông tin văn kiện\n | ấn bản = \n | nguồn = \n | đóng góp = \n | tiến triển = \n | ghi chú = \n | người duyệt = \n}}\n"; // {{thông tin văn kiện}}
}
}
// Try to fill field when creating an author page. Fields always filled, are
// lastname, firstname, lastinitial, wikipedia. Birth/Death year filled iff 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.
window.author_v2 = {
check_redirect : function (title, text_box)
{
var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath')
+ "/api.php?format=xml&action=query&prop=info&titles="
+ encodeURIComponent(title);
// FIXME: Use of "sajax_init_object" is deprecated. Sajax is deprecated, use jQuery.ajax or mediawiki.api instead.
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 = '#đổi [[' + title + ']]';
}
};
request.send(null);
},
author_fill_callback : function (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(/( *\\| *wikipedia *= *)/, "$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(/Thể loại:Mất (\d+)/);
if (m)
wpTextbox1.value = wpTextbox1.value.replace(/( *\\| *năm mất *= *)/, "$1" + m[1]);
m = cats[i].title.match(/Thể loại:Sinh (\d+)/);
if (m)
wpTextbox1.value = wpTextbox1.value.replace(/( *\\| *năm sinh *= *)/, "$1" + m[1]);
}
break;
}
// This can undo all the above works by preferring to create a redirect to an existing author:
window.author_v2.check_redirect('Tác giả:' + data.query.pages[ids].title, wpTextbox1);
}
}
catch (err) { }
},
create_script_obj : function (url)
{
var scriptObj = document.createElement("script");
scriptObj.setAttribute("type", "text/javascript");
scriptObj.setAttribute("src", url);
document.body.appendChild(scriptObj);
},
split_title : function ()
{
return mw.config.get('wgTitle').replace(/ \(.*\)/, "").split(" ");
},
get_special_word_pos : function (words)
{
var i;
for (i = 0; i < words.length; ++i) {
if (words[i] == 'van' || words[i] == 'von' ||
words[i] == 'le' || words[i] == 'de') {
return i;
}
}
return -1;
},
get_first_name : function (words)
{
return words.slice(0, window.author_v2.get_special_word_pos(words)).join(" ");
},
get_last_name : function(words)
{
return words.slice(window.author_v2.get_special_word_pos(words)).join(" ");
},
get_last_initial : function(words)
{
// get_last_name() can't be used here, we want the last word or the next
// word following a special word
var lastname = words[words.length - 1];
var pos = window.author_v2.get_special_word_pos(words);
if (pos != -1 && pos < words.length - 1)
lastname = words[pos + 1];
var last_initial = lastname.slice(0, 1);
// O'Donnel --> Od
if (lastname.length > 1 && last_initial.charAt(0) == "'")
last_initial = lastname.charAt(1).toLowerCase();
return last_initial;
},
/**
* Cho ra từ tiếng Việt được cho vào, các phụ âm đầu, các nguyên âm ở giữa, và
* các phụ âm cuối. Nếu từ không tuân theo quy tắc chính tả tiếng Việt, hàm này
* cho ra null.
*
* Biểu thức chính quy phỏng theo hàm ckspell() trong phần mở rộng AVIM cho
* Firefox.
*/
componentsOfVietnameseWord : function(word) {
return word.match(/^([CKNP]H|G[HI]|NGH?|QU|T[HR]|[BCDĐGHKLMNPQRSTVX])?([AÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶEÈÉẺẼẸÊỀẾỂỄỆIÌÍỈĨỊOÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢUÙÚỦŨỤƯỪỨỬỮỰYỲÝỶỸỴ]+)([MPT]|CH?|N[GH]?)?$/i);
},
/**
* Cho biết cụm từ có phải tiếng Việt hay không, tùy theo quy tắc
* chính tả tiếng Việt.
*/
areVietnameseWords : function(words) {
for (var i = 0; i < words.length; i++) {
if (!window.author_v2.componentsOfVietnameseWord(words[i])) return false;
}
return true;
},
/* Tải trước [[Bản mẫu:Tác gia]] khi bắt đầu một trang tác gia */
preloadAuthorTemplate : function()
{
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 = window.author_v2.split_title();
var family_first = window.author_v2.areVietnameseWords(words);
var lastname = window.author_v2.get_last_name(words);
var firstname = window.author_v2.get_first_name(words);
var last_initial = window.author_v2.get_last_initial(words);
wpTextbox1.value = "{" + "{tác gia\n" + // {{tác gia}}
" | tên-họ = " + (family_first ? "" : "có") + "\n" +
" | tên = " + (family_first ? lastname : firstname) + "\n" +
" | họ = " + (family_first ? firstname : lastname) + "\n" +
" | chữ đầu tên = " + last_initial + "\n" +
" | năm sinh = <" + "!--hiện dữ liệu được lấy từ wikidata, hãy xóa tham số này nếu khớp-->\n" +
" | năm mất = <" + "!--hiện dữ liệu được lấy từ wikidata, hãy xóa tham số này nếu khớp-->\n" +
" | mô tả = \n" +
// Không nhất thiết phải điền các giá trị sau vì Wikidata đã chứa dữ liệu.
// " | hình = \n" +
// " | wikipedia = \n" +
// " | wikiquote = \n" +
// " | commons = \n" +
// " | commonscat = \n" +
// " | wikidata = \n" +
"}}\n\n" +
"==Tác phẩm==\n\n";
var base_url = "//vi.wikipedia.org" + mw.config.get('wgScriptPath');
var url = base_url + "/api.php?format=json&redirects"
+ "&callback=window.author_v2.author_fill_callback&action=query&prop=categories&cllimit=20&titles="
+ encodeURIComponent(mw.config.get('wgTitle'));
window.author_v2.create_script_obj(url);
}
}
// Tải sẵn Bản mẫu:Đầu đề quy trình khi bắt đầu một trang dự án hoặc trợ giúp
function preloadProcessHeaderTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "" && !document.URL.match('§ion=new') )
{
wpTextbox1.value = "{" + "{Đầu đề quy trình\n | tựa đề = \n | đề mục = \n | trước = \n | sau = \n | viết tắt = \n | ghi chú = \n}}\n"
}
}
// Tải sẵn Bản mẫu:Đầu đề chủ đề khi bắt đầu một trang chủ đề
function preloadPortalHeaderTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "" && !document.URL.match('§ion=new') )
{
wpTextbox1.value = "{" + "{đầu đề chủ đề\n | tựa đề = \n | lớp = \n | phân lớp 1 = \n | phân lớp 2 = \n | cần duyệt = \n | viết tắt = \n | ghi chú = \n}}\n\n==Tác phẩm==\n\n"
}
}
// Tải sẵn Bản mẫu:Duyệt chủ đề khi bắt đầu một trang thảo luận chủ đề
function preloadPortalReviewTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "" && !document.URL.match('§ion=new') )
{
wpTextbox1.value = "{" + "{duyệt chủ đề\n | lớp = \n | phân lớp 1 = \n | phân lớp 2 = \n | người phân loại = \n | người duyệt = \n | ghi chú = \n}}\n"
}
}
// Preload Template:Translation header when starting a translation page
// Simple preloader based on the preload code for Bản mẫu:Thông tin văn kiện
function preloadTranslationHeaderTemplate()
{
var wpTextbox1 = document.getElementById("wpTextbox1")
if (wpTextbox1.value == "" && !document.URL.match('§ion=new') )
{
// wpTextbox1.value = "{" + "{translation header\n | title = \n | author = \n | section = \n | previous = \n | next = \n | year = \n | language = \n | original = \n | notes = \n}}\n"
}
}
// Main preloader loading code:
if (mw.config.get('wgAction') == "edit")
{
switch (mw.config.get('wgNamespaceNumber'))
{
case 0: //chính
$(preloadHeaderTemplate);
break;
case 1: //Thảo luận
$(preloadTextinfoTemplate);
break;
case 4: //Wikisource
$(preloadProcessHeaderTemplate);
break
case 12: //Trợ giúp
$(preloadProcessHeaderTemplate);
break;
case 100: //Chủ đề
$(preloadPortalHeaderTemplate);
break;
case 101: //Thảo luận Chủ đề
$(preloadPortalReviewTemplate);
break;
case 102: //Tác gia
$(window.author_v2.preloadAuthorTemplate);
break;
// case 114: //Translation
// $(preloadTranslationHeaderTemplate);
}
}