s4

view s4-main.js @ 899:a4ad4101064d

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