s4

view s4-main.js @ 943:b8d09525a0b4

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