MediaWiki:Gadget-linkify.js

Từ điển mở Wiktionary

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.
(function ($) {

var messages = {
	vi: {toolbarButtonName: "Tự động đặt liên kết trong lựa chọn"},
	en: {toolbarButtonName: "Automatically link selected text"},
	es: {toolbarButtonName: "Automáticamente insertar enlaces en la selección"} };

var ignoredWordList = ("ai|bằng|bị|bộ|cho|chưa|chẳng|chỉ|cuối|cuộc|" +
	"các|cách|có|có nghĩa|có thể|cùng|cũng|cả|của|do|dùng|dưới|dừng|giữa|gì|" +
	"gần|hay|hoặc|hơn|khi|khác|không|không bao giờ|không có|không thể|luôn|" +
	"là|làm|làm cho|lại|lắm|lớn|mà|mình|mọi|mỗi|một|nay|nghĩa là|nhau|nhiều|" +
	"nhỏ|như|nhưng|những|nào|này|nó|nếu|nữa|qua|quanh|quá|ra|rất|sau|sẽ|sự|" +
	"theo|thuộc|thành|thể|thêm|thì|thường|thứ|to|tới|trong|trên|trước|trừ|" +
	"tuy|tại|tức|từ|từng|và|vài|vào|vì|vẫn|về|với|xuống|đang|đi|đây|đã|đó|" +
	"được|đấy|đầu|đến|để|đủ|đừng|ở").split("|");
var ignoredWords = {};
$.each(ignoredWordList, function (i, word) {
	ignoredWords[word] = true;
});

/**
 * One less than the maximum number of syllables to be considered as a compound
 * word.
 */
var lookahead = 2;

var tokenRE = /(\s*(?:<!--[\s\S]+?-->|\{\{[\s\S]+?\}\}|\[\[.+?\]\]|[^A-ZÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶĐÈÉẺẼẸÊỀẾỂỄỆÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸỴ\u0300-\u036F{[< ]+|[{[<])\s*)/i;

String.prototype.wiktviUncapitalize = function () {
	return this[0].toLowerCase() + this.substr(1);
};

var userLang = mw.config.get("wgUserLanguage");
function getMessage(name) {
	return (messages[userLang] || messages.vi)[name] || messages.vi[name];
}

$.wiktviLinkify = function (text, callback, debug) {
	var tokens = text.split(tokenRE);
    var displayTokens = [];
    var words = {};
    var existingLinks = {};
    $.each(tokens, function (i, token) {
        if (debug) displayTokens.push(mw.html.escape(token));
        
        var tokenLinks = token.match(/\[\[.+?(?:\|.+?)?\]\]/g);
        $.each(tokenLinks || [], function () {
            existingLinks[this.match(/\[\[(.+?)(?:\|.+?)?\]\]/)[1]] = true;
        });
        
        if (!token || token.match(tokenRE)) return;
        
        var tokenWords = token.split(" ");
        $.each(tokenWords, function (j, word) {
        	for (var k = 0; k < lookahead + 1 && tokenWords[j + k]; k++) {
        		if (k) word += " " + tokenWords[j + k];
	            if (!ignoredWords[word]) words[word] = true;
	            if (word[0] != word[0].toLowerCase()) {
	            	var lowerWord = word.wiktviUncapitalize();
	            	if (!ignoredWords[lowerWord]) {
	            		words[lowerWord] = true;
	            	}
	            }
        	}
        });
        
        if (debug) {
        	displayTokens[i] = "<b style='border: 1px solid gray;'>" + mw.html.escape(token) + "</b>";
        }
    });
    
    var uniqueWords = [];
    $.each(words, function (word) {
        if (!ignoredWords[word]) uniqueWords.push(word);
    });
    
    if (debug) {
	    var uniqueLinks = [];
	    $.each(existingLinks, function (link) {
	        uniqueLinks.push(link);
	    });
	    
        var list = "<pre id='linkify-tokens'>\n" + displayTokens.join("") + "\n</pre>";
        list += "<hr /><p>Các cụm từ sẽ tìm kiếm:</p><p>" + uniqueWords + "</p>";
        list += "<hr /><p>Các cụm từ đã có liên kết:</p><p>" + uniqueLinks + "</p>";
        $("#linkify-progress").html(list).dialog({modal: true});
    }
    
    if (!uniqueWords.length) return;
    
    mw.loader.using("mediawiki.api", function () {
        var api = new mw.Api();
        api.get({
            action: "parse",
            text: "[[" + uniqueWords.join("]] [[") + "]]",
            prop: "links" }).done(function (results) {
            $("#linkify-progress").append("<hr />");
            var displayLinks = [];
            var links = {};
            $.each(results.parse.links, function () {
                if (debug && "exists" in this) displayLinks.push(this["*"]);
                if ("exists" in this) links[this["*"]] = true;
            });
            if (debug) {
            	$("#linkify-progress").append("<p>Các mục từ:</p><p>" + displayLinks + "</p>");
            }
            
            $.each(tokens, function (i, token) {
                if (!token || token.match(tokenRE)) return;
                
                var tokenWords = token.split(" ");
                for (var j = 0; j < tokenWords.length; j++) {
                    var word = [];
                    for (var k = 0; k < lookahead + 1; k++) {
                    	word.push(tokenWords[j + k]);
                    }
                    
                    for (var k = lookahead; k >= 0; k--) {
                    	var compoundWord = word.join(" ");
                    	if (compoundWord in links) {
	                        if ((compoundWord in existingLinks) || ignoredWords[compoundWord]) {
	                            j += k;
	                            break;
	                        }
	                        existingLinks[compoundWord] = true;
	                        tokenWords[j] = "[[" + tokenWords[j];
	                        tokenWords[j + k] += "]]";
	                        j += k;
	                        break;
	                    }
	                    var lowerWord = compoundWord.wiktviUncapitalize();
	                    if (lowerWord in links) {
	                        if ((lowerWord in existingLinks) || ignoredWords[lowerWord]) {
	                            j += k;
	                            break;
	                        }
	                        existingLinks[lowerWord] = true;
	                        tokenWords[j] = "[[" + lowerWord + "|" + tokenWords[j];
	                        tokenWords[j + k] += "]]";
	                        j += k;
	                        break;
	                    }
	                    if (k) word.splice(-1, 1);
	                    else if (!ignoredWords[compoundWord]) {
	                    	var lowerWord = compoundWord.wiktviUncapitalize();
	                    	if (!ignoredWords[lowerWord]) {
			                    existingLinks[compoundWord] = true;
			                    tokenWords[j] = "[[" + tokenWords[j] + "]]";
	                    	}
	                    }
                    }
                }
                tokens[i] = tokenWords.join(" ");
                if (debug) {
                	displayTokens[i] = "<b style='border: 1px solid gray;'>" + mw.html.escape(tokens[i]) + "</b>";
                }
            });
            
            if (debug) {
            	$("#linkify-tokens").html("\n" + displayTokens.join("") + "\n");
            }
            callback(tokens.join(""));
        }).fail(function (error) {
        	console.warn(error);
        	callback();
        });
    });
}

function addLinkifyButton() {
	if ($.wiktviLinkify) {
		$("#wpTextbox1").after($(mw.html.element("div", {
			id: "linkify-progress",
			title: getMessage("toolbarButtonName") })).hide());
	}
    
    mw.loader.using("ext.wikiEditor", function () {
        $("#wpTextbox1").on('wikiEditor-toolbar-buildSection-main', function (evt, section) {
            section.groups.insert.tools.linkify = {
                type: "button",
                action: {
                    type: "callback",
                    execute: function () {
                    	mw.loader.using("jquery.textSelection", function () {
	                    	var selection = $("#wpTextbox1").textSelection("getSelection");
	                    	$.wiktviLinkify(selection, function (linkedText) {
	                    		if (!linkedText) return;
	                    		
	                    		$("#wpTextbox1").textSelection("encapsulateSelection", {
	                    			peri: linkedText,
	                    			replace: true });
	                    	}, $.wiktviLinkify_debug);
                    	});
                    } },
                label: getMessage("toolbarButtonName"),
                icon: "//upload.wikimedia.org/wikipedia/commons/b/ba/Norwegian_link_sign.png" };
        });
    });
};
addLinkifyButton();

})(jQuery);