Newer
Older
s4 / s4-main.js
@HIROSE Yuuji HIROSE Yuuji on 16 Aug 2019 2 KB Redirection also inserted by #XXX anchors
(function (){
    function collectElementsByNameAttr(elm, name) {
	var e = document.getElementsByTagName(elm);
	if (!e) return null;
	var list = [];
	for (var i of e) {
	    if (i.getAttribute("name") == name)
		list.push(i)
	}
	return list;
    }
    function insertRedirect(e) {
	var articleId, textarea = document.getElementById("text");
	var p =	e.target, checked = p.checked;
	while (p = p.parentNode)
	    if (p.nodeName.match(/^td$/i)) break;
	if (!p) return;
	while (p = p.nextSibling)
	    if (p.nodeName.match(/^td$/i)) break;
	if (!p) return;
	articleId = p.getAttribute("id");
	if (textarea && articleId) {
	    var tv = textarea.value, lines;
	    if (tv)
		lines = tv.split("\n");
	    else
		lines = [""];
	    var re = new RegExp("[, ]*#"+articleId+"(?![0-9])");
	    checked = (p.nodeName.match(/^input$/)
		       ? p.checked		// checkbox obeys its status
		       : !lines[0].match(re))	// a-elment toggles redirection
	    if (checked) {
		if (!lines[0].match(re)) {
		    var re2 = new RegExp(/>#[#0-9, ]+[0-9]/);
		    if (lines[0].match(re2))
			lines[0] = lines[0].replace(
			    re2, '$&, '+'#'+articleId);
		    else {
			if (lines[0] > "") lines[0] = " "+lines[0];
			lines[0] = ">#"+articleId+lines[0];
		    }
		}
	    } else {		// Remove #xxxxx
		if (lines[0].match(/^>#[0-9 ,]+#/)) // 2 or more #id's
		    lines[0] = lines[0].replace(
			new RegExp("^>#"+articleId+"[ ,]*"), ">").replace(
			new RegExp("[ ,]*#"+articleId), "");
		else {
		    lines[0] = lines[0].replace(
			new RegExp(">#"+articleId+"[ ,]*"), "");
		}
	    }
	    lines[0] = lines[0].replace(/^> *$/, '');
	    textarea.value = lines.join("\n");
	}
    }
    function init() {
	var el, check = collectElementsByNameAttr("input", "notifyto");
	if (check)
	    for (let i of check) {
		i.addEventListener("click", insertRedirect, null);
	    }
	for (let i of document.getElementsByTagName("a"))
	    if (i.getAttribute("href").match(/^#[0-9]+$/))
		if (RegExp.lastMatch == i.innerHTML)
		    i.addEventListener("click", insertRedirect, null)
    }
    document.addEventListener('DOMContentLoaded', init, null);
})();