view s4-main.js @ 889:5843755e3b30

The beginning of AJAX operations Frozen/Running can be toggled by ajax button
author HIROSE Yuuji <yuuji@gentei.org>
date Thu, 24 Dec 2020 19:42:58 +0900
parents 3e09ac711f69
children c1a5d137740d
line wrap: on
line source

// 愛
(function (){
    function collectElementsByAttr(elm, attr, val) {
	var e = document.getElementsByTagName(elm);
	if (!e) return null;
	var list = [];
	for (var i of e) {
	    if (i.getAttribute(attr) == val)
		list.push(i)
	}
	return list;
    }
    function nthChildOf(parent, n, elem) { // Return Nth child of type ELEM
	// N begins with 1
	var i=0;
	var le = elem.toLowerCase();
	for (var c of parent.childNodes) {
	    if (!c.tagName) continue;
	    if (c.tagName.toLowerCase() == le) {
		if (++i >= n) return c;
	    }
	}
	return null;
    }
    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 reverseChecks() {
	var names = collectElementsByAttr("input", "name", "usel");
	for (let u of names) {
	    u.checked = !u.checked;
	}
    }
    function renumberOL(str, start) {
	var stra = str.split("\n");
		
	for (var i=1; i<stra.length; i++) {
	    if (stra[i].match(/^[1-9][0-9]*\. /)) {
		let orig=stra[i];
		stra[i] = (++start)+". "+RegExp.rightContext;
	    } else if (stra[i].match(/^  /)) {
		continue;
	    } else
		break;
	}
	return stra.join("\n");
    }
    function submitThisForm(input) {
	for (var elm=input.parentNode; elm; elm = elm.parentNode) {
	    if (elm.nodeName.match(/form/i)) {
		elm.submit();
		return true;
	    }
	}
	return false;
    }
    function helpMarkdownBS(e) {
	var area = e.target, pos = area.selectionStart, text = area.value;
	if (area.selectionStart != area.selectionEnd) return;
	if (pos<2) return;
	if (text.substr(pos-1, 2)=="\n\n") return;
	var bol  = text.lastIndexOf("\n", pos-1),
	    eol  = text.indexOf("\n", pos);
	if (bol<=0 || bol==eol) return;
	var thisline = text.substring(bol+1, eol==-1 ? text.length : eol);
	thisline = text.substring(bol+1, pos);
	if (thisline == "* ") {
	    area.setSelectionRange(pos-2, pos);
	} else if (thisline.match(/^[1-9][0-9]*\. $/)) {
	    area.setSelectionRange(pos-RegExp.lastMatch.length, pos);
	}
    }
    function helpMarkdownEnter(e) {
	if (e.keyCode == 13 && !e.shiftKey) {
	    if (e.metaKey && submitThisForm(e.target)) {
		e.preventDefault();
		return;
	    }
	    var area = e.target;
	    var pos  = area.selectionStart, text = area.value;
	    if (pos==0) return;
	    var last = text.lastIndexOf("\n", pos-1);
	    var rest = text.substring(pos), rest0=rest;
	    var line = last ? text.substring(last+1, pos) : text;
	    var next = rest.substring(rest.indexOf("\n"))||rest;
	    next=next.substring(1);
	    var tail = text.substring(pos-2, pos), br = (tail=="  ");
	    var add  = "", offset = 1;
	    if (line.startsWith("* ")) {
		add =  "* ";
		offset += add.length;
		if (br) {
		    add = "  " + "\n" + add;
		}
	    } else if (line.match(/^([1-9][0-9]*)\. /)) {
		var ln = parseInt(RegExp.$1), nn=ln+1,
		    len = RegExp.lastMatch.length;
		add = nn+". ";
		let toeol = text.substr(pos, text.indexOf("\n"));
		if (br) {
		    if (next.startsWith(add)) {
			add=" ".repeat(len);
			nn = ln;
		    } else {
			add = " ".repeat(len)+ "\n" + add;
			offset -= len+1;
		    }
		}
		if (next.match(/^[1-9][0-9]*\. /))
		    rest = renumberOL(rest, nn);
		offset += add.length;
	    } else if (line.match(/^\|( *).+\|/)) {
		add = "|" + RegExp.$1 + " |";
		offset += add.length-2;
	    } else {
		return;
	    }
	    e.preventDefault();
	    if (!document.execCommand("insertText", false, "\n"+add)) {
		//Firefox
		area.selectionEnd = area.value.length;
		area.setRangeText("\n"+add+rest);
		area.selectionEnd = null;
	    } else {
		area.selectionEnd = area.value.length;
		area.setSelectionRange(area.selectionStart, area.value.length);
		document.execCommand("insertText", false, rest);
		area.selectionEnd = null;
		area.focus();
	    }
	    area.selectionStart = pos+offset;
	    return;
	    if (document.execCommand("insertText", false, "\n"+add)) {
		//area.setSelectionRange(area.selectionStart, text.length);
		// alert("rest=["+rest+"], add=["+add+"]");
		alert(text.substring(pos, area.value.length));
		if (rest != rest0) {
		    area.setSelectionRange(pos, area.value.length);
		    return;
		    document.execCommand("delete");
		}
		document.execCommand("insertText", false, rest);
	    } else {
		// Firefox cannot use insertText in textarea...
		area.value = text.substring(0, pos) + "\n" + add + rest;
	    }
	    //area.setSelectionRange(pos+length(add));
	    area.selectionStart=area.selectionEnd = (pos + offset);
	    
	}
    }
    function helpMarkdown(e) {
	switch (e.keyCode) {
	case  8: helpMarkdownBS(e); break;
	case 13: helpMarkdownEnter(e); break;
	}
    }
    /* Init event listeners */
    function addFileInput() {
	var inpfile = collectElementsByAttr("input", "name", "image");
	if (!inpfile) return;
	var filled = true;
	var i, ih;
	for (i of inpfile) {
	    if (! i.value) filled=false;
	}
	if (filled) {
	    ih = i.parentNode.innerHTML;
	    if (ih) {
		var inpf = ih.substring(ih.indexOf("<input")),
		    newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
		i.insertAdjacentHTML("afterend", newi)
		// alert(newi);
	    }
	}
    }
    function initFileInput() { // Multiplies "input type=file"
	var el, morefile = document.getElementById("morefile");
	if (morefile) {
	    for (el of collectElementsByAttr("input", "name", "image")) {
		el.addEventListener("change", function(ev) {
		    if (ev.target.value > "" && ev.target.files.length == 1)
			morefile.style.visibility = "visible";
		    // No need to hide again, sure?
		});
	    }
	    morefile.addEventListener("click", addFileInput, null);
	}
	// When renaming, select basename part
	for (el of collectElementsByAttr("input", "class", "mv")) {
	    el.addEventListener("focus", function(ev) {
		var i = ev.target;
		if (i) {
		    i.setSelectionRange(0, i.value.lastIndexOf("."));
		}
	    });
	}
    }
    function initTextarea() {
	var te = collectElementsByAttr("textarea", "name", "text");
	if (!te || !te[0]) return;
	te[0].addEventListener("keydown", helpMarkdown, false);
    }
    function initBlogs() {
	// Auto-complete #xxxx
	var check = collectElementsByAttr("input", "name", "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)
    }
    function initGrpAction() {
	var rev = document.getElementById("reverse");
	if (!rev) return;	// Is not grpAction page
	if (rev.tagName.match(/span/i)) {
	    rev.textContent = " 反転 ";
	    rev.addEventListener("click", reverseChecks, null);
	}
	var emailbtn = document.getElementById("email");
	emailbtn.addEventListener("click", function(ev){
	    // Enlarge box and Select user's checkbox
	    if (!ev.target.checked) return;
	    var x = collectElementsByAttr("div", "class", "foldtabs");
	    if (x && x[0] && x[0].style) {
		x[0].style.height = "10em";
	    }
	    let myuid = document.getElementById("myuid");
	    if (myuid) {
		let usel = collectElementsByAttr("input", "name", "usel");
		if (usel) {
		    for (u of usel) {
			if (u.value == myuid.value)
			    u.checked = true;
		    }
		}
	    }
	}, null);
	var teamsel = document.getElementById("selteam");
	if (teamsel) {
	    var usel, p, team;
	    // Select all members of the team
	    teamsel.addEventListener("change", function(ev) {
		var teamname = teamsel.value,
		    selected = new RegExp('(^| )'+teamname+"($|,)");
		usel = collectElementsByAttr("input", "name", "usel");
		if (!usel) return;
		for (u of usel) {
		    p = u.parentNode;		// should be label
		    if (!p) continue;
		    if (teamname == "TEAM") {	// Reset all checks
			u.checked = false;	// when "TEAM" is selected
		    } else {
			p = p.parentNode.parentNode;// should be tr
			team = nthChildOf(p, 3, "td")
			if (team && team.textContent
			    && team.textContent.match(selected)) {
			    u.checked = true;
			}
		    }
		}
	    }, null);
	}
    }
    function initGrphome() {
	console.log("initGrphome");
	let btn = document.querySelectorAll("button.toggle-frozen");
	if (!btn) return;
	let url = document.URL,
	    mypath = url.substring(url.lastIndexOf("/"));
	if (mypath.match(/(.*)\/(.*)/)) {
	    mypath = RegExp.$2;
	    mypath = mypath.substring(0, mypath.lastIndexOf("?"));
	    //alert("mypath="+mypath);
	} else return;

	function toggleFrozen(e, rowid) {
	    let tgt = mypath+"?blog_setfrozen+"+rowid;
	    let tr = e.target.parentNode.parentNode;
	    fetch(tgt, {
		method: "POST",
		headers: {'Content-Type': 'text/html; charset=utf-8'},
	    }).then(function(resp) {
		return resp.text();
	    }).then(function(tbody) {
		try {
		    var json = JSON.parse(tbody);
		} catch (e) {
		    return;
		}
		let state = json.state, newstate;
		if (json.alert) {
		    alert(json.alert)
		}
		if (state.match(/frozen/i)) {
		    newstate = "凍結";
		} else {
		    newstate = null;
		}
		tr.setAttribute("class", newstate);
	    });
	}
	for (let b of btn) {
	    let rowid = null;
	    let td=b.parentNode, tr = td.parentNode;
	    for (let a of tr.querySelectorAll("a[href]")) {
		if (a.getAttribute("href").match(/\?replyblog\+([0-9]+)/)) {
		    rowid = parseInt(RegExp.$1);
		    break;
		}
	    }
	    if (rowid && rowid>0) {
		b.addEventListener("click", function(e) {
		    if (!btn) return;
		    toggleFrozen(e, rowid);
		}, false);
		b.setAttribute("title", "稼動/凍結をその場で切り替えます\n\
Toggle Running/Frozen ("+rowid+")");
	    }
	}
    }
    function init() {
	initGrpAction();
	initBlogs();
	initFileInput();
	initTextarea();
	initGrphome();
    }
    document.addEventListener('DOMContentLoaded', init, null);
})();

yatex.org