s4

view s4-main.js @ 906:9f237a8f550d

Add eventListener to newly added TR contents
author HIROSE Yuuji <yuuji@gentei.org>
date Mon, 04 Jan 2021 09:29:37 +0900
parents d9ecb727edcd
children ce1a355e7cb1
line source
1 // 愛
2 (function (){
3 var isOlderJS; // Set in init();
4 var hasTouchPad =
5 (navigator.maxTouchPoints && navigator.maxTouchPoints >0);
6 var myurl = document.URL,
7 mypath = myurl.substring(myurl.lastIndexOf("/"));
8 var art_m_list = [];
9 if (mypath.match(/(.*)\/(.*)/)) {
10 mypath = RegExp.$2;
11 mypath = mypath.substring(0, mypath.lastIndexOf("?"));
12 //alert("mypath="+mypath);
13 }
14 function collectElementsByAttr(elm, attr, val) {
15 var e = document.getElementsByTagName(elm);
16 if (!e) return null;
17 var list = [];
18 for (var i of e) {
19 if (i.getAttribute(attr) == val)
20 list.push(i)
21 }
22 return list;
23 }
24 function nthChildOf(parent, n, elem) { // Return Nth child of type ELEM
25 // N begins with 1
26 var i=0;
27 var le = elem.toLowerCase();
28 for (var c of parent.childNodes) {
29 if (!c.tagName) continue;
30 if (c.tagName.toLowerCase() == le) {
31 if (++i >= n) return c;
32 }
33 }
34 return null;
35 }
36 function insertRedirect(e) {
37 var articleId, textarea = document.getElementById("text");
38 var p = e.target, checked = p.checked;
39 while (p = p.parentNode)
40 if (p.nodeName.match(/^td$/i)) break;
41 if (!p) return;
42 while (p = p.nextSibling)
43 if (p.nodeName.match(/^td$/i)) break;
44 if (!p) return;
45 articleId = p.getAttribute("id");
46 if (textarea && articleId) {
47 var tv = textarea.value, lines;
48 if (tv)
49 lines = tv.split("\n");
50 else
51 lines = [""];
52 var re = new RegExp("[, ]*#"+articleId+"(?![0-9])");
53 checked = (p.nodeName.match(/^input$/)
54 ? p.checked // checkbox obeys its status
55 : !lines[0].match(re)) // a-elment toggles redirection
56 if (checked) {
57 if (!lines[0].match(re)) {
58 var re2 = new RegExp(/>#[#0-9, ]+[0-9]/);
59 if (lines[0].match(re2))
60 lines[0] = lines[0].replace(
61 re2, '$&, '+'#'+articleId);
62 else {
63 if (lines[0] > "") lines[0] = " "+lines[0];
64 lines[0] = ">#"+articleId+lines[0];
65 }
66 }
67 } else { // Remove #xxxxx
68 if (lines[0].match(/^>#[0-9 ,]+#/)) // 2 or more #id's
69 lines[0] = lines[0].replace(
70 new RegExp("^>#"+articleId+"[ ,]*"), ">").replace(
71 new RegExp("[ ,]*#"+articleId), "");
72 else {
73 lines[0] = lines[0].replace(
74 new RegExp(">#"+articleId+"[ ,]*"), "");
75 }
76 }
77 lines[0] = lines[0].replace(/^> *$/, '');
78 textarea.value = lines.join("\n");
79 }
80 }
81 function registPjaxViewers(aHrefList) {
82 let apos=art_m_list.length;
83 for (let a of aHrefList) {
84 let href = a.getAttribute("href");
85 let localvar = apos;
86 let td = a.parentNode,
87 tr = td.parentNode,
88 id = td.id,
89 text = td.textContent,
90 author = tr.getElementsByTagName("a");
91 if (author) author = author[0].getAttribute("title");
92 if (href.match(/\?showattc\+article_m\+([0-9+])/)) {
93 if (td.innerHTML.match(/x読み取り不可/)) {
94 a.removeAttribute("href");
95 continue;
96 }
97 let url = RegExp.lastMatch;
98 // console.log("pjaxView(e, "+href+", "+apos+")");
99 a.addEventListener("click", function(e) {
100 // Shoud use closure local variable: localvar
101 pjaxView(e, href, localvar);
102 }, false);
103 apos++;
104 art_m_list.push({
105 url: href, id: id, author: author, text: text
106 });
107 }
108 }
109 }
110 function registInsertDirect(aHrefList) {
111 for (i of aHrefList)
112 if (i.getAttribute("href").match(/^#[0-9]+$/))
113 if (RegExp.lastMatch == i.innerHTML)
114 i.addEventListener("click", insertRedirect, false)
115 }
116 var ajaxSubmit;
117 function replAddNews(newtable) {
118 let newids = [], idlist=[];
119 let getArticleID = function (td) {
120 return parseInt(td.parentNode.getElementsByTagName("td")[1].id);
121 }
122 for (let i of newtable.querySelectorAll("td.repl"))
123 newids.push(i);
124 newids = newids.sort((a,b)=> {
125 return (getArticleID(a) - getArticleID(b));
126 });
127 for (i of newids)
128 idlist.push(getArticleID(i));
129 console.log("IDList="+idlist.join());
130 let cnt=0, ntr;
131 let current = collectElementsByAttr("td", "class", "repl"),
132 ncur=0, n, icur=0, o, oid, nid, otr;
133 current = document.querySelectorAll('td[class="repl"]');
134 let last=current[current.length-1],
135 tbody = last.parentNode.parentNode;
136 let addEventsToNewTr = function(tr) {
137 let td = tr.getElementsByTagName("td"),
138 td0 = td[0], td1 = td[1];
139 td0.classList.add("new");
140 registInsertDirect(td0.querySelectorAll("a[href]"));
141 registPjaxViewers(td1.querySelectorAll("a[href]"));
142 }
143 // Now reconstruct articles with merge-sort like method
144 outer: for (; ncur<newids.length; ncur++) {
145 n = newids[ncur];
146 if (!n.id) continue;
147 nid = parseInt(n.id);
148 if (nid<=0) continue;
149 ntr = n.parentNode;
150 for (; icur<current.length; icur++) {
151 o = current[icur];
152 otr = o.parentNode;
153 oid = getArticleID(o);
154 if (!oid || oid=="") continue;
155 if (oid >= nid) {
156 addEventsToNewTr(ntr);
157 tbody.insertBefore(ntr, otr);
158 if (oid==nid) otr.remove();
159 cnt++;
160 continue outer;
161 }
162 }
163 // Append absolutely new articles.
164 ntr = n.parentNode;
165 addEventsToNewTr(ntr)
166 tbody.appendChild(ntr);
167 ntr.classList.add("dissolving");
168 let localntr = ntr;
169 setTimeout(() => {
170 localntr.classList.remove("dissolving");
171 localntr.classList.add("emerging");
172 }, 100);
173 cnt++;
174 }
175 ajaxSubmit.textContent = ajaxSubmit.back;
176 ajaxSubmit.disabled = false;
177 console.log("Update "+cnt+"rows");
178 if (cnt>0 && ntr.scrollIntoView) {
179 let option = {behavior: "smooth"};
180 if (!isOlderJS) option.block = "center";
181 try { // Scroll to last updated row
182 ntr.scrollIntoView(option);
183 } catch (e1) {}
184 }
185 return cnt;
186 }
188 function warnFileSize(form) {
189 let szmax = form.querySelector('input[name="filesize_max"]').value;
190 if (!szmax || szmax=="") return;
191 szmax = parseInt(szmax);
192 if (szmax <= 0) return;
193 // szmax = 10000
194 let ng = "", rcval=false, fileexists=false;
195 for (let f of form.querySelectorAll('input[type="file"]')) {
196 let thiserr = false
197 for (let i of f.files) {
198 fileexists = true;
199 let fn = i.name, sz = i.size;
200 console.log("max="+szmax+", fn="+fn+", sz="+sz);
201 if (sz > szmax) {
202 thiserr = true;
203 ng += ((ng>"" ? ", " : "")+fn)
204 }
205 }
206 thiserr ? f.classList.add("warnbg") : f.classList.remove("warnbg");
207 }
208 if (ng>"") {
209 rcval = "File-size Limit Error: "+ng+"\n"+
210 "Should be less than "+szmax+"bytes.\n"+
211 szmax+"バイト未満にしてください"
212 alert(rcval);
213 }
214 if (form.text.value == "") {
215 let w;
216 if (fileexists)
217 w = "Fill the text area\n" +
218 "添付したファイルに関する説明を入れてください。";
219 else
220 w = "Enter your comment!\n何か書き込んでね!";
221 alert(w);
222 rcval = (rcval || w);
223 form.text.classList.add("warnbg");
224 setTimeout(() => {form.text.classList.remove("warnbg");}, 2000)
225 }
226 return rcval;
227 }
228 function ajaxPost(e) {
229 e.preventDefault();
230 let rowid;
231 if (!myurl.match(/replyblog\+([0-9]+)/)) return;
232 rowid = RegExp.$1
233 let myform = document.querySelector("form.replyblog");
234 let data = new FormData(myform),
235 fetchtime = data.get("fetchtime");
236 if (!fetchtime || fetchtime=="") return;
237 ///*XX*/fetchtime = "2020-06-14T00:00:00";data.set("fetchtime", fetchtime)
239 ajaxSubmit = e.target;
240 ajaxSubmit.back = ajaxSubmit.textContent;
241 if (ajaxSubmit.id == "reload") {
242 ajaxSubmit.textContent = "更新中"
243 data.set("text", "")
244 } else {
245 if (warnFileSize(myform)) return;
246 ajaxSubmit.textContent = "送信中";
247 }
248 ajaxSubmit.blur();
249 ajaxSubmit.disabled = true;
250 let act = mypath+"?blog_fetch+"+rowid+"+f:"+fetchtime;
252 function respUpdate(tbody) {
253 let div = document.createElement("div"), form, newform;
254 try {
255 div.innerHTML = tbody;
256 form = div.querySelector("form");
257 } catch (er) {
258 alert("Cannot parse fetch data");
259 return;
260 }
261 let update = replAddNews(form);
262 let dispelem = myform.querySelector("textarea").parentNode;
263 newform = new FormData(form);
264 if (data.get("text") > "") { // Called by submit button
265 myform.reset();
266 // myform.text.value = '';
267 }
268 myform.fetchtime.value = newform.get("fetchtime");
269 myform.id.value = newform.get("id");
270 if (update && update > 0) {
271 let s = update + " new article" +
272 (update>1 ? "s" : "") + " posted";
273 dispInfoMomentary(s, dispelem);
274 }
275 }
276 fetch(act, {
277 method: "POST", body: data,
278 credentials: "include" // For older firefox
279 }).then((resp) => {
280 return resp.text();
281 }).then((tbody) => {
282 respUpdate(tbody);
283 })
284 }
285 function pjaxView(ev, url, mynum) {
286 ev.preventDefault();
287 let box = document.createElement("div")
288 box.setAttribute("class", "pjaxview");
289 let p1 = document.createElement("p"),
290 bt = document.createElement("button"),
291 sl = document.createElement("button"),
292 sr = document.createElement("button"),
293 loading = document.createElement("span"),
294 info = document.createElement("p");
295 info1 = document.createElement("span");
296 info2 = document.createElement("span");
297 iframe = document.createElement("iframe");
298 var curpos = mynum;
299 var historyBase = history.length;
301 function _setPjaxCurposInfo() {
302 let len = art_m_list.length;
303 let cur = art_m_list[curpos]
304 info1.textContent = (1+curpos)+" of "+len+" article #"+cur.id+
305 (cur.author ? " by "+cur.author : "") + ":";
306 info2.textContent = cur.text.trim();
307 info2.setAttribute("class", "border textdigest");
308 }
309 function _resetPjax() {
310 // All we can do surely is to back 1 page,
311 // because we cannot move to desirable entry of history list.
312 history.back();
313 }
314 function setSwipeAct(iframe) {
315 // We cannot use DOMContentLoaded nor iframe.contentWindow here.
316 // PDF.js does not construct contentWindow...?
317 iframe.addEventListener("load", () => {
318 loading.classList.remove("loading");
319 if (!hasTouchPad) return;
320 let ifm = iframe.contentDocument;
321 let startX, moveX, thresh = 100;
322 ifm.addEventListener("touchstart", (e) => {
323 e.preventDefault();
324 startX = e.touches[0].pageX;
325 }, false);
326 ifm.addEventListener("touchmove", (e) => {
327 e.preventDefault();
328 moveX = e.touches[0].pageX;
329 }, false);
330 ifm.addEventListener("touchend", (e) => {
331 if (startX < moveX && startX + thresh < moveX) {
332 switchTo(e, -1);
333 } else if (startX > moveX && startX - thresh > moveX) {
334 switchTo(e, +1);
335 }
336 }, false);
337 }, false);
339 }
340 function switchTo(e, direction) {
341 e.preventDefault();
342 let len = art_m_list.length, cur, newpos, url;
343 newpos = (curpos+len+direction)%len;
344 if (curpos == newpos) return; // No need to switch to same one
345 curpos = newpos;
346 cur = art_m_list[curpos];
347 url = cur.url;
348 // We should remove iframe once to preserve history Object
349 // https://inthetechpit.com/2019/04/20/update-iframe-without-affecting-browser-history/
350 let parent = iframe.parentNode;
351 // alert("D = "+direction);
352 iframe.remove();
353 parent.appendChild(iframe);
354 try {
355 loading.classList.add("loading");
356 iframe.src = url;
357 // iframe.contentDocument.location.replace(url);
358 // location.replace cannot be used because PDF viewer.js
359 // does not have iframe.contentDocument
360 } catch (err) {
361 alert("Cannot load "+src+" : "+err.name);
362 }
363 _setPjaxCurposInfo();
364 setSwipeAct(iframe);
365 }
366 function switchToByKey(e) {
367 // alert("KEY="+e.key);
368 switch (e.key) {
369 case "ArrowLeft":
370 switchTo(e, -1); break;
371 case "ArrowRight":
372 switchTo(e, +1); break;
373 case "Escape":
374 history.back();
375 }
376 }
377 // <div><p>
378 // <button> << </button><button>Dismiss</button><button> >> </button>
379 // </p><p><span> info1 </span> <span> info2 </span></p>
380 // <iframe src="..."></iframe>
381 // </div>
382 // ==> [ << ][Dissmiss][ >> ]
383 // ==> ## of ## article #xxx by AUTHOR
384 sl.textContent = " << ";
385 sr.textContent = " >> ";
386 sl.addEventListener("click", (e) => {switchTo(e, -1);});
387 sr.addEventListener("click", (e) => {switchTo(e, +1);});
388 sl.setAttribute("title", "to="+(mynum-1));
389 sr.setAttribute("title", "to="+(mynum+1));
390 document.body.appendChild(box);
391 bt.textContent = "Click to dismiss / もどる"+mynum;
393 box.appendChild(p1);
394 p1.appendChild(sl); p1.appendChild(bt); p1.appendChild(sr);
395 p1.appendChild(loading);
396 info.appendChild(info1); info.appendChild(info2);
397 loading.textContent=" Loading...";
398 loading.classList.add("hidden");
399 loading.classList.add("loading");
400 box.appendChild(info);
401 iframe.src = url;
403 document.addEventListener("keydown", switchToByKey);
404 //box.addEventListener("click", (e) => {_resetPjax();});
405 bt.addEventListener("click", (e) => {_resetPjax();});
406 // dp.addEventListener("click", (e) => {_resetPjax();});
407 info.addEventListener("click", (e) => {_resetPjax();});
408 box.appendChild(iframe);
410 setSwipeAct(iframe);
412 _setPjaxCurposInfo();
413 bt.focus();
414 setTimeout(() => {box.classList.add("pjaxview2");}, 10);
415 // Finally update history stack
416 if (history.pushState) {
417 let h = location.href.replace(/#.*/, '')+"#pjaxview";
418 history.pushState({url: h}, null, h);
419 window.addEventListener("popstate", (e) => {
420 if (box) {
421 box.remove(); box = null;
422 }
423 }, false);
424 }
425 }
426 function reverseChecks() {
427 var names = collectElementsByAttr("input", "name", "usel");
428 for (let u of names) {
429 u.checked = !u.checked;
430 }
431 }
432 function renumberOL(str, start) {
433 var stra = str.split("\n");
434 for (var i=1; i<stra.length; i++) {
435 if (stra[i].match(/^[1-9][0-9]*\. /)) {
436 let orig=stra[i];
437 stra[i] = (++start)+". "+RegExp.rightContext;
438 } else if (stra[i].match(/^ /)) {
439 continue;
440 } else
441 break;
442 }
443 return stra.join("\n");
444 }
445 function submitThisForm(input) {
446 for (var elm=input.parentNode; elm; elm = elm.parentNode) {
447 if (elm.nodeName.match(/form/i)) {
448 elm.submit();
449 return true;
450 }
451 }
452 return false;
453 }
454 function helpMarkdownBS(e) {
455 var area = e.target, pos = area.selectionStart, text = area.value;
456 if (area.selectionStart != area.selectionEnd) return;
457 if (pos<2) return;
458 if (text.substr(pos-1, 2)=="\n\n") return;
459 var bol = text.lastIndexOf("\n", pos-1),
460 eol = text.indexOf("\n", pos);
461 if (bol<=0 || bol==eol) return;
462 var thisline = text.substring(bol+1, eol==-1 ? text.length : eol);
463 thisline = text.substring(bol+1, pos);
464 if (thisline == "* ") {
465 area.setSelectionRange(pos-2, pos);
466 } else if (thisline.match(/^[1-9][0-9]*\. $/)) {
467 area.setSelectionRange(pos-RegExp.lastMatch.length, pos);
468 }
469 }
470 function helpMarkdownEnter(e) {
471 if (e.keyCode == 13 && !e.shiftKey) {
472 if (e.metaKey && submitThisForm(e.target)) {
473 e.preventDefault();
474 return;
475 }
476 var area = e.target;
477 var pos = area.selectionStart, text = area.value;
478 if (pos==0) return;
479 var last = text.lastIndexOf("\n", pos-1);
480 var rest = text.substring(pos), rest0=rest;
481 var line = last ? text.substring(last+1, pos) : text;
482 var next = rest.substring(rest.indexOf("\n"))||rest;
483 next=next.substring(1);
484 var tail = text.substring(pos-2, pos), br = (tail==" ");
485 var add = "", offset = 1;
486 if (line.startsWith("* ")) {
487 add = "* ";
488 offset += add.length;
489 if (br) {
490 add = " " + "\n" + add;
491 }
492 } else if (line.match(/^([1-9][0-9]*)\. /)) {
493 var ln = parseInt(RegExp.$1), nn=ln+1,
494 len = RegExp.lastMatch.length;
495 add = nn+". ";
496 let toeol = text.substr(pos, text.indexOf("\n"));
497 if (br) {
498 if (next.startsWith(add)) {
499 add=" ".repeat(len);
500 nn = ln;
501 } else {
502 add = " ".repeat(len)+ "\n" + add;
503 offset -= len+1;
504 }
505 }
506 if (next.match(/^[1-9][0-9]*\. /))
507 rest = renumberOL(rest, nn);
508 offset += add.length;
509 } else if (line.match(/^\|( *).+\|/)) {
510 add = "|" + RegExp.$1 + " |";
511 offset += add.length-2;
512 } else {
513 return;
514 }
515 e.preventDefault();
516 if (!document.execCommand("insertText", false, "\n"+add)) {
517 //Firefox
518 area.selectionEnd = area.value.length;
519 area.setRangeText("\n"+add+rest);
520 area.selectionEnd = null;
521 } else {
522 area.selectionEnd = area.value.length;
523 area.setSelectionRange(area.selectionStart, area.value.length);
524 document.execCommand("insertText", false, rest);
525 area.selectionEnd = null;
526 area.focus();
527 }
528 area.selectionStart = pos+offset;
529 return;
530 if (document.execCommand("insertText", false, "\n"+add)) {
531 //area.setSelectionRange(area.selectionStart, text.length);
532 // alert("rest=["+rest+"], add=["+add+"]");
533 alert(text.substring(pos, area.value.length));
534 if (rest != rest0) {
535 area.setSelectionRange(pos, area.value.length);
536 return;
537 document.execCommand("delete");
538 }
539 document.execCommand("insertText", false, rest);
540 } else {
541 // Firefox cannot use insertText in textarea...
542 area.value = text.substring(0, pos) + "\n" + add + rest;
543 }
544 //area.setSelectionRange(pos+length(add));
545 area.selectionStart=area.selectionEnd = (pos + offset);
547 }
548 }
549 function helpMarkdown(e) {
550 switch (e.key) {
551 case "Backspace": helpMarkdownBS(e); break;
552 case "Enter": helpMarkdownEnter(e); break;
553 }
554 }
555 /* Init event listeners */
556 function addFileInput() {
557 var inpfile = collectElementsByAttr("input", "name", "image");
558 if (!inpfile) return;
559 var filled = true;
560 var i, ih;
561 for (i of inpfile) {
562 if (! i.value) filled=false;
563 }
564 if (filled) {
565 ih = i.parentNode.innerHTML;
566 if (ih) {
567 var inpf = ih.substring(ih.indexOf("<input")),
568 newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
569 i.insertAdjacentHTML("afterend", newi)
570 i.nextSibling.nextSibling.addEventListener('change', () => {
571 // next==br next.next==input[type=file]
572 warnFileSize(document.forms[0]);
573 });
574 }
575 }
576 }
577 function initFileInput() { // Multiplies "input type=file"
578 var el, morefile = document.getElementById("morefile");
579 if (morefile) {
580 for (el of collectElementsByAttr("input", "name", "image")) {
581 el.addEventListener("change", function(ev) {
582 if (ev.target.value > "" && ev.target.files.length == 1)
583 morefile.style.visibility = "visible";
584 // No need to hide again, sure?
585 });
586 }
587 morefile.addEventListener("click", addFileInput, null);
588 }
589 // When renaming, select basename part
590 for (el of collectElementsByAttr("input", "class", "mv")) {
591 el.addEventListener("focus", function(ev) {
592 var i = ev.target;
593 if (i) {
594 i.setSelectionRange(0, i.value.lastIndexOf("."));
595 }
596 });
597 }
598 }
599 function initTextarea() {
600 var te = collectElementsByAttr("textarea", "name", "text");
601 if (!te || !te[0]) return;
602 te[0].addEventListener("keydown", helpMarkdown, false);
603 }
604 function initBlogs() {
605 // Auto-complete #xxxx
606 let i, check = collectElementsByAttr("input", "name", "notifyto");
607 if (check)
608 for (i of check) {
609 i.addEventListener("click", insertRedirect, false);
610 }
611 registInsertDirect(document.querySelectorAll("a[href]"));
612 for (i of document.querySelectorAll('input#c[value="送信"]')) {
613 let b = document.createElement("button");
614 b.textContent = "送信!";
615 console.log("b="+b+", tc="+b.textContent);
616 b.addEventListener("click", ajaxPost, false);
617 // i.insertAdjacentElement('afterend', b);
618 b.id = i.id;
619 i.parentNode.replaceChild(b, i);
620 i.remove();
621 }
622 i = document.getElementById("reload");
623 if (i) i.addEventListener("click", ajaxPost, false);
624 for (i of document.querySelectorAll('input[type="file"]')) {
625 i.addEventListener('change', (e) => {
626 warnFileSize(document.forms[0]);
627 }, false)
628 }
629 // Hack article_m links
630 registPjaxViewers(document.querySelectorAll("a[href]"));
631 }
632 function initGrpAction() {
633 var rev = document.getElementById("reverse");
634 if (!rev) return; // Is not grpAction page
635 if (rev.tagName.match(/span/i)) {
636 rev.textContent = " 反転 ";
637 rev.addEventListener("click", reverseChecks, null);
638 }
639 var emailbtn = document.getElementById("email");
640 emailbtn.addEventListener("click", function(ev){
641 // Enlarge box and Select user's checkbox
642 if (!ev.target.checked) return;
643 var x = collectElementsByAttr("div", "class", "foldtabs");
644 if (x && x[0] && x[0].style) {
645 x[0].style.height = "10em";
646 }
647 let myuid = document.getElementById("myuid");
648 if (myuid) {
649 let usel = collectElementsByAttr("input", "name", "usel");
650 if (usel) {
651 for (u of usel) {
652 if (u.value == myuid.value)
653 u.checked = true;
654 }
655 }
656 }
657 }, null);
658 var teamsel = document.getElementById("selteam");
659 if (teamsel) {
660 var usel, p, team;
661 // Select all members of the team
662 teamsel.addEventListener("change", function(ev) {
663 var teamname = teamsel.value,
664 selected = new RegExp('(^| )'+teamname+"($|,)");
665 usel = collectElementsByAttr("input", "name", "usel");
666 if (!usel) return;
667 for (u of usel) {
668 p = u.parentNode; // should be label
669 if (!p) continue;
670 if (teamname == "TEAM") { // Reset all checks
671 u.checked = false; // when "TEAM" is selected
672 } else {
673 p = p.parentNode.parentNode;// should be tr
674 team = nthChildOf(p, 3, "td")
675 if (team && team.textContent
676 && team.textContent.match(selected)) {
677 u.checked = true;
678 }
679 }
680 }
681 }, null);
682 }
683 }
684 function dispInfoMomentary(msg, elem) {
685 // Momentarily display MSG in tooltip-baloon relative to ELEM element.
686 let help = document.createElement("p");
687 elem.style.position = 'relative';
688 elem.style.overflow = 'visible';
689 help.setAttribute("class", "info-tooltip");
690 help.innerHTML = msg;
691 elem.appendChild(help);
692 setTimeout(() => {
693 help.classList.add("dissolving");
694 setTimeout(() => help.remove(), 3000);
695 }, 1000);
696 }
697 function initGrphome() {
698 console.log("initGrphome");
699 // (1)Setup Frozen State Changing Button
700 var ja = navigator.language.match(/ja/i);
702 function toggleFrozen(e, rowid) {
703 let tgt = mypath+"?blog_setfrozen+"+rowid;
704 let td = e.target.parentNode;
705 let tr = td.parentNode;
706 fetch(tgt, {
707 method: "POST",
708 headers: {'Content-Type': 'text/html; charset=utf-8'},
709 credentials: "include"
710 }).then(function(resp) {
711 return resp.text();
712 }).then(function(tbody) {
713 try {
714 var json = JSON.parse(tbody);
715 } catch (e) {
716 return;
717 }
718 let state = json.state, newstate, info;
719 if (json.alert) {
720 alert(json.alert)
721 }
722 if (state.match(/frozen/i)) {
723 newstate = "凍結";
724 info = ja ? newstate+"に設定しました" : 'Set Frozen';
725 } else {
726 newstate = null;
727 info = ja ? '稼動に設定しました' : 'Set Running';
728 }
729 tr.setAttribute("class", newstate);
730 dispInfoMomentary(info, td);
731 });
732 }
733 let btn = document.querySelectorAll("button.toggle-frozen");
734 for (let b of btn) {
735 let rowid = null;
736 let td=b.parentNode, tr = td.parentNode, fr, ru;
737 ru = ja ? "動" : "Running";
738 fr = ja ? "凍" : "Frozen";
739 b.setAttribute('frozen-marker', fr);
740 b.setAttribute('running-marker', ru);
741 for (let a of tr.querySelectorAll("a[href]")) {
742 if (a.getAttribute("href").match(/\?replyblog\+([0-9]+)/)) {
743 rowid = parseInt(RegExp.$1);
744 break;
745 }
746 }
747 if (rowid && rowid>0) {
748 b.addEventListener("click", function(e) {
749 if (!btn) return;
750 toggleFrozen(e, rowid);
751 }, false);
752 b.setAttribute("title", "稼動/凍結をその場で切り替えます\n\
753 Toggle Running/Frozen ("+rowid+")");
754 }
755 }
756 // (2)Setup Column Collapse Button
757 // INCOMPLETE: Cannot restore original state, but it's enough...
758 function toggleColmnWidth(th) {
759 let tbl = document.querySelector("table.dumpblogs");
760 let colname = th.textContent, newwidth;
761 if (th.style.width) {
762 newwidth = null
763 // https://developer.mozilla.org/ja/docs/Web/CSS/table-layout
764 tbl.style.tableLayout = 'auto';
765 tbl.style.width = null;
766 } else {
767 newwidth = "2em";
768 tbl.style.tableLayout = 'fixed';
769 tbl.style.width = '100%';
770 }
771 th.style.width = newwidth;
772 th.style.overflow = "hidden";
773 for (let td of document.querySelectorAll("td."+colname)) {
774 console.log(td.tagName);
775 td.style.width = newwidth;
776 console.log(td.style.width);
777 }
778 }
779 let row1 = document.querySelector("table.dumpblogs tr:first-child");
780 if (row1) {
781 let heads = row1.querySelectorAll("th");
782 for (let h of heads) {
783 h.addEventListener("click", function(e) {
784 toggleColmnWidth(h);
785 }, false);
786 h.setAttribute("title", "Click to shrink these columns");
787 }
788 }
789 }
790 function init() {
791 isOlderJS = !("insertAdjacentElement" in document.body);
792 initGrpAction();
793 initBlogs();
794 initFileInput();
795 initTextarea();
796 initGrphome();
797 }
798 document.addEventListener('DOMContentLoaded', init, null);
799 })();