MediaWiki:Gadget-UnsupportedTitles.js

Chú ý: Sau khi lưu trang này, phải xóa bộ nhớ đệm (cache) của trình duyệt để những thay đổi hiện ra

  • Firefox / Safari: Nhấn giữ phím Shift trong khi nhấn Tải lại (Reload), hoặc nhấn tổ hợp Ctrl-F5 hay Ctrl-R (⌘R trên Mac)
  • Google Chrome: Nhấn tổ hợp Ctrl-Shift-R (⇧⌘R trên Mac)
  • Internet Explorer / Edge: Nhấn giữ phím Ctrl trong khi nhấn Làm tươi (Refresh), hoặc nhấn tổ hợp Ctrl-F5
  • Opera: Nhấn tổ hợp Ctrl-F5.
/*
To get template for titleTag.textContent, process MediaWiki:pagetitle,
open your browser's JavaScript console on a Wiktionary page
and run this code:
((msg) => new mw.Api().getMessages(msg).then((messages) => {
	mw.messages.set(messages);
	const titleTemplate = new mw.Message(mw.messages, msg, ["$1"]).text();
	const {
		before,
		after
	} = /^(?<before>.*)\$1(?<after>.*)/.exec(titleTemplate).groups;
	console.log(JSON.stringify(before), JSON.stringify(after))
})
.fail(console.error))("pagetitle")
We can do this for action=edit and action=submit by replacing
"pagetitle" with "editing" in this snippet.
*/
function setTitle(newTitle) {
	// Set title tag, which determines the title shown in the browser.
	var titleTag = document.getElementsByTagName('title')[0];
	titleTag.textContent = newTitle + " - Wiktionary, từ điển mở";
	
	// Set the text of the first heading above the page content.
	document.getElementById('firstHeading').textContent = newTitle;
}
var UnsupportedTitlesJson = require('./UnsupportedTitles.json');
var prettyPageName = mw.config.get('wgPageName').replace(/_/g, ' ');

function generateCharacterToEscapeMap() {
	var map = {};
	Object.entries(UnsupportedTitlesJson.UnsupportedCharacterEscapes).forEach(function(entry) {
        map[entry[1]] = entry[0];
    });
	return map;
}

/*
 * On subpages of Unsupported titles and Talk:Unsupported titles, show the
 * correct title in the header at the top of the page. For instance, on the page
 * [[Unsupported titles/Left curly bracket]], show the title {.
 *
 * This is not enabled in the mobile version of the site.
 *
 * For all such pages, see [[Special:PrefixIndex/Unsupported titles]].
 */
if (mw.config.get('wgAction') === 'view'
&& (/^(?:Talk:)?Tiêu_đề_không_được_hỗ_trợ\//.test(prettyPageName)
|| UnsupportedTitlesJson.TitleDisplay.hasOwnProperty(prettyPageName))) {
	$(function() {
		try {
			var match = /^(?:Talk:)?Tiêu_đề_không_được_hỗ_trợ\/(.+)$/.exec(prettyPageName);
			var newTitle;
			if (match) {
				var subpage = match && match[1];
				newTitle = UnsupportedTitlesJson.UnsupportedTitles[subpage]
					|| subpage.replace(/`([^`]+)`/g, function(wholeMatch, key) {
						const character = UnsupportedTitlesJson.UnsupportedCharacterEscapes[key];
						return character != null ? character : key;
					});
			} else {
				newTitle = UnsupportedTitlesJson.TitleDisplay[prettyPageName];
			}
			if (mw.config.get('wgCanonicalNamespace') == 'Talk')
				newTitle = 'Talk:' + newTitle;
			
			setTitle(newTitle);
		} catch (e) {
			console.log('Lỗi khi sửa tiêu đề: ' + e.message + '.');
		}
	});
}

/*
 * This redirects a user to the correct Unsupported titles page if they attempt
 * to access an invalid title. For instance, if you attempt to access the page
 * for <
 * https://en.wiktionary.org/wiki/%3C
 * you will be redirected to
 * https://en.wiktionary.org/wiki/Unsupported_titles/Less_than
 */
if (mw.config.get('wgCanonicalSpecialPageName') == 'Badtitle') {
	// Avoid redirecting twice or more. Set this parameter after redirecting
	// and don't redirect if it is already set.
	const alreadyRedirectedParam = "UnsupportedTitleRedirected";
	/*
	 * Generate the name of the page that the user attempted to access using
	 * either the portion of the URL after "/wiki/" or the value of the "title"
	 * parameter in the query. That is, the user is accessing the page using
	 * either the path /wiki/<invalid title> or a path similar to
	 * /w/index.php?title=<invalid title>.
	 *
	 * The actual page displayed if a user attempts to access an invalid title
	 * is the special page with the canonical title [[Special:Badtitle]].
	 */
	if (!mw.util.getParamValue(alreadyRedirectedParam)) {
		var rxArticlePath = new RegExp('^' + mw.config.get('wgArticlePath').replace('$1', '(.*)') + '$');
		var m = rxArticlePath.exec(location.pathname);
		var title = m ? decodeURIComponent(m[1]) : mw.util.getParamValue('title');
		const characterToEscapeMap = generateCharacterToEscapeMap();
		var badTitleSubpage = title.replace(/./g, function (fullMatch) {
			var escapeName = characterToEscapeMap[fullMatch];
			return escapeName != null ? '`' + escapeName + '`' : fullMatch;
		});
		if (badTitleSubpage != title) {
			const url = new URL(location.href);
			const newTitle = 'Tiêu đề không được hỗ trợ/' + badTitleSubpage;
			if (url.searchParams.get("title")) {
				url.searchParams.set("title", newTitle);
			} else {
				url.pathname = mw.util.getUrl(newTitle);
			}
			url.searchParams.set(alreadyRedirectedParam, "1");
			location.href = url;
		}
	}
}