s4

view s4-main.js @ 928:a3623f901e32

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