s4

view s4-main.js @ 915:b47f64276427

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