diff s4-main.js @ 898:411ce55c0dae

AJAX posting and PJAX file-viewer initially introduced.
author HIROSE Yuuji <yuuji@gentei.org>
date Sat, 02 Jan 2021 15:15:03 +0900
parents 1dc4007d7c20
children a4ad4101064d
line wrap: on
line diff
--- a/s4-main.js	Thu Dec 31 10:31:13 2020 +0900
+++ b/s4-main.js	Sat Jan 02 15:15:03 2021 +0900
@@ -1,5 +1,16 @@
 // 愛
 (function (){
+    var isOlderJS;	// Set in init();
+    var hasTouchPad =
+	(navigator.maxTouchPoints && navigator.maxTouchPoints >0);
+    var myurl = document.URL,
+	mypath = myurl.substring(myurl.lastIndexOf("/"));
+    var art_m_list = [];
+    if (mypath.match(/(.*)\/(.*)/)) {
+	mypath = RegExp.$2;
+	mypath = mypath.substring(0, mypath.lastIndexOf("?"));
+	//alert("mypath="+mypath);
+    }
     function collectElementsByAttr(elm, attr, val) {
 	var e = document.getElementsByTagName(elm);
 	if (!e) return null;
@@ -67,6 +78,325 @@
 	    textarea.value = lines.join("\n");
 	}
     }
+    function registPjaxViewers(aHrefList) {
+	// if (isOlderJS) return;
+	let apos=art_m_list.length;
+	for (let a of aHrefList) {
+	    let href = a.getAttribute("href");
+	    let localvar = apos;
+	    let td = a.parentNode,
+		tr = td.parentNode,
+		id = td.id,
+		text = td.textContent,
+		author = tr.getElementsByTagName("a");
+	    if (author) author = author[0].getAttribute("title");
+	    if (href.match(/\?showattc\+article_m\+([0-9+])/)) {
+		if (td.innerHTML.match(/x読み取り不可/)) {
+		    a.removeAttribute("href");
+		    continue;
+		}
+		let url = RegExp.lastMatch;
+		// console.log("pjaxView(e, "+href+", "+apos+")");
+		a.addEventListener("click", function(e) {
+		    // Shoud use closure local variable: localvar
+		    pjaxView(e, href, localvar);
+		}, false);
+		apos++;
+		art_m_list.push({
+		    url: href, id: id, author: author, text: text
+		});
+	    }
+	}
+    }
+    var ajaxSubmit;
+    function replAddNews(newtable) {
+	let newids = [], idlist=[];
+	let getArticleID = function (td) {
+	    return parseInt(td.parentNode.getElementsByTagName("td")[1].id);
+	}
+	for (let i of newtable.querySelectorAll("td.repl"))
+	    newids.push(i);
+	newids = newids.sort((a,b)=> {
+	    return (getArticleID(a) - getArticleID(b));
+	});
+	for (i of newids)
+	    idlist.push(getArticleID(i));
+	console.log("IDList="+idlist.join());
+	let cnt=0;
+	let current = collectElementsByAttr("td", "class", "repl"),
+	    ncur=0, n, icur=0, o, oid, nid, otr;
+	current = document.querySelectorAll('td[class="repl"]');
+	let last=current[current.length-1],
+	    tbody = last.parentNode.parentNode;
+	// Now reconstruct articles with merge-sort like method
+	outer: for (; ncur<newids.length; ncur++) {
+	    n = newids[ncur];
+	    if (!n.id) continue;
+	    nid = parseInt(n.id);
+	    if (nid<=0) continue;
+	    let ntr = n.parentNode;
+	    for (; icur<current.length; icur++) {
+		o = current[icur];
+		otr = o.parentNode;
+		oid = getArticleID(o);
+		if (!oid || oid=="") continue;
+		if (oid >= nid) {
+		    ntr.getElementsByTagName("td")[0].classList.add("new");
+		    tbody.insertBefore(ntr, otr);
+		    if (oid==nid) otr.remove();
+		    cnt++;
+		    continue outer;
+		}
+	    }
+	    // Append absolutely new articles.
+	    ntr = n.parentNode;
+	    ntr.getElementsByTagName("td")[0].classList.add("new");
+	    tbody.appendChild(ntr);
+	    registPjaxViewers(ntr.querySelectorAll("a[href]"));
+	    ntr.classList.add("dissolving");
+	    ntr.scrollIntoView({behavior: "smooth"});
+	    setTimeout(() => {
+		ntr.classList.remove("dissolving");
+		ntr.classList.add("emerging");
+	    }, 100);
+	    cnt++;
+	}
+	ajaxSubmit.value = ajaxSubmit.back;
+	ajaxSubmit.disabled = false;
+	console.log("Update "+cnt+"rows");
+	return cnt;
+    }
+
+    function warnFileSize(form) {
+	let szmax = form.querySelector('input[name="filesize_max"]').value;
+	if (!szmax || szmax=="") return;
+	szmax = parseInt(szmax);
+	if (szmax <= 0) return;
+	// szmax = 10000
+	let ng = "", rcval=false, fileexists=false;
+	for (let f of form.querySelectorAll('input[type="file"]')) {
+	    let thiserr = false
+	    for (let i of f.files) {
+		fileexists = true;
+		let fn = i.name, sz = i.size;
+		console.log("max="+szmax+", fn="+fn+", sz="+sz);
+		if (sz > szmax) {
+		    thiserr = true;
+		    ng += ((ng>"" ? ", " : "")+fn)
+		}
+	    }
+	    thiserr ? f.classList.add("warnbg") : f.classList.remove("warnbg");
+	}
+	if (ng>"") {
+	    rcval = "File-size Limit Error: "+ng+"\n"+
+		"Should be less than "+szmax+"bytes.\n"+
+		szmax+"バイト未満にしてください"
+	    alert(rcval);
+	}
+	if (form.text.value == "") {
+	    let w;
+	    if (fileexists)
+		w = "Fill the text area\n" +
+		"添付したファイルに関する説明を入れてください。";
+	    else
+		w = "Enter your comment!\n何か書き込んでね!";
+	    alert(w);
+	    rcval = (rcval || w);
+	    form.text.classList.add("warnbg");
+	    setTimeout(() => {form.text.classList.remove("warnbg");}, 2000)
+	}
+	return rcval;
+    }
+    function ajaxPost(e) {
+	e.preventDefault();
+	let rowid;
+	if (!myurl.match(/replyblog\+([0-9]+)/)) return;
+	rowid = RegExp.$1
+	let myform = document.querySelector("form.replyblog");
+	if (warnFileSize(myform)) return;
+	ajaxSubmit = e.target;
+	ajaxSubmit.back = ajaxSubmit.value;
+	ajaxSubmit.value = "送信中";
+	ajaxSubmit.blur();
+	ajaxSubmit.disabled = true;
+	let data = new FormData(myform),
+	    fetchtime = data.get("fetchtime");
+	if (!fetchtime || fetchtime=="") return;
+	///*XX*/fetchtime = "2020-06-14T00:00:00";data.set("fetchtime", fetchtime)
+	let act = mypath+"?blog_fetch+"+rowid+"+f:"+fetchtime;
+	
+	function respUpdate(tbody) {
+	    let div = document.createElement("div"), form, newform;
+	    try {
+		div.innerHTML = tbody;
+		form = div.querySelector("form");
+	    } catch (er) {
+		alert("Cannot parse fetch data");
+		return;
+	    }
+	    let update = replAddNews(form);
+	    let dispelem = myform.querySelector("textarea").parentNode;
+	    newform = new FormData(form);
+	    myform.reset();
+	    myform.text.value = '';
+	    myform.fetchtime.value = newform.get("fetchtime");
+	    myform.id.value = newform.get("id");
+	    if (update && update > 0) {
+		let s = update + " new article" +
+		    (update>1 ? "s" : "") + " posted";
+		dispInfoMomentary(s, dispelem);
+	    }
+	}
+	fetch(act, {
+	    method: "POST", body: data,
+	    credentials: "include"	// For older firefox
+	}).then((resp) => {
+	    return resp.text();
+	}).then((tbody) => {
+	    respUpdate(tbody);
+	})
+    }
+    function pjaxView(ev, url, mynum) {
+	ev.preventDefault();
+	let box = document.createElement("div")
+	box.setAttribute("class", "pjaxview");
+	let p1 = document.createElement("p"),
+	    bt = document.createElement("button"),
+	    sl = document.createElement("button"),
+	    sr = document.createElement("button"),
+	    loading = document.createElement("span"),
+	    info   = document.createElement("p");
+	    info1  = document.createElement("span");
+	    info2  = document.createElement("span");
+	    iframe = document.createElement("iframe");
+	var curpos = mynum;
+	var historyBase = history.length;
+	
+	function _setPjaxCurposInfo() {
+	    let len = art_m_list.length;
+	    let cur = art_m_list[curpos]
+	    info1.textContent = (1+curpos)+" of "+len+" article #"+cur.id+
+		(cur.author ? " by "+cur.author : "") + ":";
+	    info2.textContent = cur.text.trim();
+	    info2.setAttribute("class", "border textdigest");
+	}
+	function _resetPjax() {
+	    // All we can do surely is to back 1 page,
+	    // because we cannot move to desirable entry of history list.
+	    history.back();
+	}
+	function setSwipeAct(iframe) {
+	    // We cannot use DOMContentLoaded nor iframe.contentWindow here.
+	    // PDF.js does not construct contentWindow...?
+	    iframe.addEventListener("load", () => {
+		loading.classList.remove("loading");
+		if (!hasTouchPad) return;
+		let ifm = iframe.contentDocument;
+		let startX, moveX, thresh = 100;
+		ifm.addEventListener("touchstart", (e) => {
+		    e.preventDefault();
+		    startX = e.touches[0].pageX;
+		}, false);
+		ifm.addEventListener("touchmove", (e) => {
+		    e.preventDefault();
+		    moveX = e.touches[0].pageX;
+		}, false);
+		ifm.addEventListener("touchend", (e) => {
+		    if (startX < moveX && startX + thresh < moveX) {
+			switchTo(e, -1);
+		    } else if (startX > moveX && startX - thresh > moveX) {
+			switchTo(e, +1);
+		    }
+		}, false);
+	    }, false);
+	    
+	}
+	function switchTo(e, direction) {
+	    e.preventDefault();
+	    let len = art_m_list.length, cur, newpos, url;
+	    newpos = (curpos+len+direction)%len;
+	    if (curpos == newpos) return; // No need to switch to same one
+	    curpos = newpos;
+	    cur = art_m_list[curpos];
+	    url = cur.url;
+	    // We should remove iframe once to preserve history Object
+	    // https://inthetechpit.com/2019/04/20/update-iframe-without-affecting-browser-history/
+	    let parent = iframe.parentNode;
+	    // alert("D = "+direction);
+	    iframe.remove();
+	    parent.appendChild(iframe);
+	    try {
+		loading.classList.add("loading");
+		iframe.src = url;
+		// iframe.contentDocument.location.replace(url);
+		// location.replace cannot be used because PDF viewer.js
+		// does not have iframe.contentDocument
+	    } catch (err) {
+		alert("Cannot load "+src+" : "+err.name);
+	    }
+	    _setPjaxCurposInfo();
+	    setSwipeAct(iframe);
+	}
+	function switchToByKey(e) {
+	    // alert("KEY="+e.key);
+	    switch (e.key) {
+	    case "ArrowLeft":
+		switchTo(e, -1); break;
+	    case "ArrowRight":
+		switchTo(e, +1); break;
+	    case "Escape":
+		history.back();
+	    }
+	}
+	// <div><p>
+	// <button> << </button><button>Dismiss</button><button> >> </button>
+	// </p><p><span> info1 </span> <span> info2 </span></p>
+	// <iframe src="..."></iframe>
+	// </div>
+	// ==> [ << ][Dissmiss][ >> ]
+	// ==> ## of ## article #xxx by AUTHOR
+	sl.textContent = " << ";
+	sr.textContent = " >> ";
+	sl.addEventListener("click", (e) => {switchTo(e, -1);});
+	sr.addEventListener("click", (e) => {switchTo(e, +1);});
+	sl.setAttribute("title", "to="+(mynum-1));
+	sr.setAttribute("title", "to="+(mynum+1));
+	document.body.appendChild(box);
+	bt.textContent = "Click to dismiss / もどる"+mynum;
+
+	box.appendChild(p1);
+	p1.appendChild(sl); p1.appendChild(bt); p1.appendChild(sr);
+	p1.appendChild(loading);
+	info.appendChild(info1); info.appendChild(info2);
+	loading.textContent=" Loading...";
+	loading.classList.add("hidden");
+	loading.classList.add("loading");
+	box.appendChild(info);
+	iframe.src = url;
+
+	document.addEventListener("keydown", switchToByKey);
+	//box.addEventListener("click", (e) => {_resetPjax();});
+	bt.addEventListener("click", (e) => {_resetPjax();});
+	// dp.addEventListener("click", (e) => {_resetPjax();});
+	info.addEventListener("click", (e) => {_resetPjax();});
+	box.appendChild(iframe);
+
+	setSwipeAct(iframe);
+
+	_setPjaxCurposInfo();
+	bt.focus();
+	setTimeout(() => {box.classList.add("pjaxview2");}, 10);
+	// Finally update history stack
+	if (history.pushState) {
+	    let h = location.href.replace(/#.*/, '')+"#pjaxview";
+	    history.pushState({url: h}, null, h);
+	    window.addEventListener("popstate", (e) => {
+		if (box) {
+		    box.remove(); box = null;
+		}
+	    }, false);
+	}
+    }
     function reverseChecks() {
 	var names = collectElementsByAttr("input", "name", "usel");
 	for (let u of names) {
@@ -75,7 +405,6 @@
     }
     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];
@@ -192,9 +521,9 @@
 	}
     }
     function helpMarkdown(e) {
-	switch (e.keyCode) {
-	case  8: helpMarkdownBS(e); break;
-	case 13: helpMarkdownEnter(e); break;
+	switch (e.key) {
+	case "Backspace": helpMarkdownBS(e); break;
+	case "Enter":  helpMarkdownEnter(e); break;
 	}
     }
     /* Init event listeners */
@@ -212,7 +541,10 @@
 		var inpf = ih.substring(ih.indexOf("<input")),
 		    newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
 		i.insertAdjacentHTML("afterend", newi)
-		// alert(newi);
+		i.nextSibling.nextSibling.addEventListener('change', () => {
+		    // next==br next.next==input[type=file]
+		    warnFileSize(document.forms[0]);
+		});
 	    }
 	}
     }
@@ -248,12 +580,28 @@
 	var check = collectElementsByAttr("input", "name", "notifyto");
 	if (check)
 	    for (let i of check) {
-		i.addEventListener("click", insertRedirect, null);
+		i.addEventListener("click", insertRedirect, false);
 	    }
-	for (let i of document.getElementsByTagName("a"))
+	for (let i of document.querySelectorAll("a[href]"))
 	    if (i.getAttribute("href").match(/^#[0-9]+$/))
 		if (RegExp.lastMatch == i.innerHTML)
-		    i.addEventListener("click", insertRedirect, null)
+		    i.addEventListener("click", insertRedirect, false)
+	for (let i of document.querySelectorAll('input[value="送信"]')) {
+	    // let b = document.createElement("button");
+	    let b = i;
+	    b.value = "送信!";
+	    console.log("b="+b+", tc="+b.textContent);
+	    b.addEventListener("click", ajaxPost, false);
+	    // i.insertAdjacentElement('afterend', b);
+	}
+	for (let f of document.querySelectorAll('input[type="file"]')) {
+	    let form = document.forms[0];
+	    f.addEventListener('change', (e) => {
+		warnFileSize(form);
+	    }, false)
+	}
+	// Hack article_m links
+	registPjaxViewers(document.querySelectorAll("a[href]"));
     }
     function initGrpAction() {
 	var rev = document.getElementById("reverse");
@@ -323,13 +671,6 @@
     function initGrphome() {
 	console.log("initGrphome");
 	// (1)Setup Frozen State Changing Button
-	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;
 	var ja = navigator.language.match(/ja/i);
 
 	function toggleFrozen(e, rowid) {
@@ -339,6 +680,7 @@
 	    fetch(tgt, {
 		method: "POST",
 		headers: {'Content-Type': 'text/html; charset=utf-8'},
+		credentials: "include"
 	    }).then(function(resp) {
 		return resp.text();
 	    }).then(function(tbody) {
@@ -420,6 +762,7 @@
 	}
     }
     function init() {
+	isOlderJS = !("insertAdjacentElement" in document.body);
 	initGrpAction();
 	initBlogs();
 	initFileInput();

yatex.org