s4

view s4-main.js @ 925:713441f69ab8

Key-event Listener should be restricted to "box" div.
author HIROSE Yuuji <yuuji@gentei.org>
date Fri, 15 Jan 2021 07:29:25 +0900
parents 27edbd91022c
children de4a34a2057c
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 ev.preventDefault();
312 let box = document.createElement("div")
313 box.setAttribute("class", "pjaxview");
314 let p1 = document.createElement("p"),
315 bt = document.createElement("button"),
316 sl = document.createElement("button"),
317 sr = document.createElement("button"),
318 loading = document.createElement("span"),
319 info = document.createElement("p");
320 info1 = document.createElement("span");
321 info2 = document.createElement("span");
322 iframe = document.createElement("iframe");
323 var curpos = mynum;
324 var historyBase = history.length;
326 function _setPjaxCurposInfo() {
327 let len = art_m_list.length;
328 let cur = art_m_list[curpos]
329 info1.textContent = (1+curpos)+" of "+len+" article #"+cur.id+
330 (cur.author ? " by "+cur.author : "") + ":";
331 info2.textContent = cur.text.trim();
332 info2.setAttribute("class", "border textdigest");
333 }
334 function _resetPjax() {
335 // All we can do surely is to back 1 page,
336 // because we cannot move to desirable entry of history list.
337 history.back();
338 }
339 function setSwipeAct(iframe) {
340 // We cannot use DOMContentLoaded nor iframe.contentWindow here.
341 // PDF.js does not construct contentWindow...?
342 iframe.addEventListener("load", () => {
343 loading.classList.remove("loading");
344 if (!hasTouchPad) return;
345 let ifm = iframe.contentDocument;
346 let startX, moveX, thresh = 100;
347 ifm.addEventListener("touchstart", (e) => {
348 e.preventDefault();
349 startX = e.touches[0].pageX;
350 }, false);
351 ifm.addEventListener("touchmove", (e) => {
352 e.preventDefault();
353 moveX = e.touches[0].pageX;
354 }, false);
355 ifm.addEventListener("touchend", (e) => {
356 if (startX < moveX && startX + thresh < moveX) {
357 switchTo(e, -1);
358 } else if (startX > moveX && startX - thresh > moveX) {
359 switchTo(e, +1);
360 }
361 }, false);
362 }, false);
364 }
365 function switchTo(e, direction) {
366 e.preventDefault();
367 let len = art_m_list.length, cur, newpos, url;
368 newpos = (curpos+len+direction)%len;
369 if (curpos == newpos) return; // No need to switch to same one
370 curpos = newpos;
371 cur = art_m_list[curpos];
372 url = cur.url;
373 // We should remove iframe once to preserve history Object
374 // https://inthetechpit.com/2019/04/20/update-iframe-without-affecting-browser-history/
375 let parent = iframe.parentNode;
376 // alert("D = "+direction);
377 iframe.remove();
378 parent.appendChild(iframe);
379 try {
380 loading.classList.add("loading");
381 iframe.src = url;
382 // iframe.contentDocument.location.replace(url);
383 // location.replace cannot be used because PDF viewer.js
384 // does not have iframe.contentDocument
385 } catch (err) {
386 alert("Cannot load "+src+" : "+err.name);
387 }
388 _setPjaxCurposInfo();
389 setSwipeAct(iframe);
390 }
391 function switchToByKey(e) {
392 // alert("KEY="+e.key);
393 switch (e.key) {
394 case "ArrowLeft":
395 switchTo(e, -1); break;
396 case "ArrowRight":
397 switchTo(e, +1); break;
398 case "Escape":
399 history.back();
400 }
401 }
402 // <div><p>
403 // <button> << </button><button>Dismiss</button><button> >> </button>
404 // </p><p><span> info1 </span> <span> info2 </span></p>
405 // <iframe src="..."></iframe>
406 // </div>
407 // ==> [ << ][Dissmiss][ >> ]
408 // ==> ## of ## article #xxx by AUTHOR
409 sl.textContent = " << ";
410 sr.textContent = " >> ";
411 sl.addEventListener("click", (e) => {switchTo(e, -1);});
412 sr.addEventListener("click", (e) => {switchTo(e, +1);});
413 sl.setAttribute("title", "to="+(mynum-1));
414 sr.setAttribute("title", "to="+(mynum+1));
415 document.body.appendChild(box);
416 bt.textContent = "Click to dismiss / もどる"+mynum;
418 box.appendChild(p1);
419 p1.appendChild(sl); p1.appendChild(bt); p1.appendChild(sr);
420 p1.appendChild(loading);
421 info.appendChild(info1); info.appendChild(info2);
422 loading.textContent=" Loading...";
423 loading.classList.add("hidden");
424 loading.classList.add("loading");
425 box.appendChild(info);
426 iframe.src = url;
428 box.addEventListener("keydown", switchToByKey);
429 //box.addEventListener("click", (e) => {_resetPjax();});
430 bt.addEventListener("click", (e) => {_resetPjax();});
431 // dp.addEventListener("click", (e) => {_resetPjax();});
432 info.addEventListener("click", (e) => {_resetPjax();});
433 box.appendChild(iframe);
435 setSwipeAct(iframe);
437 _setPjaxCurposInfo();
438 bt.focus();
439 setTimeout(() => {box.classList.add("pjaxview2");}, 10);
440 // Finally update history stack
441 if (history.pushState) {
442 let h = location.href.replace(/#.*/, '')+"#pjaxview";
443 history.pushState({url: h}, null, h);
444 window.addEventListener("popstate", (e) => {
445 if (box) {
446 box.remove(); box = null;
447 }
448 }, false);
449 }
450 }
451 function reverseChecks() {
452 var names = collectElementsByAttr("input", "name", "usel");
453 for (let u of names) {
454 u.checked = !u.checked;
455 }
456 }
457 function renumberOL(str, start) {
458 var stra = str.split("\n");
459 for (var i=1; i<stra.length; i++) {
460 if (stra[i].match(/^[1-9][0-9]*\. /)) {
461 let orig=stra[i];
462 stra[i] = (++start)+". "+RegExp.rightContext;
463 } else if (stra[i].match(/^ /)) {
464 continue;
465 } else
466 break;
467 }
468 return stra.join("\n");
469 }
470 function submitThisForm(input) {
471 for (var elm=input.parentNode; elm; elm = elm.parentNode) {
472 if (elm.nodeName.match(/form/i)) {
473 elm.submit();
474 return true;
475 }
476 }
477 return false;
478 }
479 function helpMarkdownBS(e) {
480 var area = e.target, pos = area.selectionStart, text = area.value;
481 if (area.selectionStart != area.selectionEnd) return;
482 if (pos<2) return;
483 if (text.substr(pos-1, 2)=="\n\n") return;
484 var bol = text.lastIndexOf("\n", pos-1),
485 eol = text.indexOf("\n", pos);
486 if (bol<=0 || bol==eol) return;
487 var thisline = text.substring(bol+1, eol==-1 ? text.length : eol);
488 thisline = text.substring(bol+1, pos);
489 if (thisline == "* ") {
490 area.setSelectionRange(pos-2, pos);
491 } else if (thisline.match(/^[1-9][0-9]*\. $/)) {
492 area.setSelectionRange(pos-RegExp.lastMatch.length, pos);
493 }
494 }
495 function helpMarkdownEnter(e) {
496 if (e.keyCode == 13 && !e.shiftKey) {
497 if (e.metaKey && submitThisForm(e.target)) {
498 e.preventDefault();
499 return;
500 }
501 var area = e.target;
502 var pos = area.selectionStart, text = area.value;
503 if (pos==0) return;
504 var last = text.lastIndexOf("\n", pos-1);
505 var rest = text.substring(pos), rest0=rest;
506 var line = last ? text.substring(last+1, pos) : text;
507 var next = rest.substring(rest.indexOf("\n"))||rest;
508 next=next.substring(1);
509 var tail = text.substring(pos-2, pos), br = (tail==" ");
510 var add = "", offset = 1;
511 if (line.startsWith("* ")) {
512 add = "* ";
513 offset += add.length;
514 if (br) {
515 add = " " + "\n" + add;
516 }
517 } else if (line.match(/^([1-9][0-9]*)\. /)) {
518 var ln = parseInt(RegExp.$1), nn=ln+1,
519 len = RegExp.lastMatch.length;
520 add = nn+". ";
521 let toeol = text.substr(pos, text.indexOf("\n"));
522 if (br) {
523 if (next.startsWith(add)) {
524 add=" ".repeat(len);
525 nn = ln;
526 } else {
527 add = " ".repeat(len)+ "\n" + add;
528 offset -= len+1;
529 }
530 }
531 if (next.match(/^[1-9][0-9]*\. /))
532 rest = renumberOL(rest, nn);
533 offset += add.length;
534 } else if (line.match(/^\|( *).+\|/)) {
535 add = "|" + RegExp.$1 + " |";
536 offset += add.length-2;
537 } else {
538 return;
539 }
540 e.preventDefault();
541 if (!document.execCommand("insertText", false, "\n"+add)) {
542 //Firefox
543 area.selectionEnd = area.value.length;
544 area.setRangeText("\n"+add+rest);
545 area.selectionEnd = null;
546 } else {
547 area.selectionEnd = area.value.length;
548 area.setSelectionRange(area.selectionStart, area.value.length);
549 document.execCommand("insertText", false, rest);
550 area.selectionEnd = null;
551 area.focus();
552 }
553 area.selectionStart = pos+offset;
554 return;
555 if (document.execCommand("insertText", false, "\n"+add)) {
556 //area.setSelectionRange(area.selectionStart, text.length);
557 // alert("rest=["+rest+"], add=["+add+"]");
558 alert(text.substring(pos, area.value.length));
559 if (rest != rest0) {
560 area.setSelectionRange(pos, area.value.length);
561 return;
562 document.execCommand("delete");
563 }
564 document.execCommand("insertText", false, rest);
565 } else {
566 // Firefox cannot use insertText in textarea...
567 area.value = text.substring(0, pos) + "\n" + add + rest;
568 }
569 //area.setSelectionRange(pos+length(add));
570 area.selectionStart=area.selectionEnd = (pos + offset);
572 }
573 }
574 function helpMarkdown(e) {
575 switch (e.key) {
576 case "Backspace": helpMarkdownBS(e); break;
577 case "Enter": helpMarkdownEnter(e); break;
578 }
579 }
580 /* Init event listeners */
581 function addFileInput() {
582 var inpfile = collectElementsByAttr("input", "name", "image");
583 if (!inpfile) return;
584 var filled = true;
585 var i, ih;
586 for (i of inpfile) {
587 if (! i.value) filled=false;
588 }
589 if (filled) {
590 ih = i.parentNode.innerHTML;
591 if (ih) {
592 var inpf = ih.substring(ih.indexOf("<input")),
593 newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
594 i.insertAdjacentHTML("afterend", newi)
595 i.nextSibling.nextSibling.addEventListener('change', () => {
596 // next==br next.next==input[type=file]
597 warnFileSize(document.forms[0]);
598 });
599 }
600 }
601 }
602 function initFileInput() { // Multiplies "input type=file"
603 var el, morefile = document.getElementById("morefile");
604 if (morefile) {
605 for (el of collectElementsByAttr("input", "name", "image")) {
606 el.addEventListener("change", function(ev) {
607 if (ev.target.value > "" && ev.target.files.length == 1)
608 morefile.style.visibility = "visible";
609 // No need to hide again, sure?
610 });
611 }
612 morefile.addEventListener("click", addFileInput, null);
613 }
614 // When renaming, select basename part
615 for (el of collectElementsByAttr("input", "class", "mv")) {
616 el.addEventListener("focus", function(ev) {
617 var i = ev.target;
618 if (i) {
619 i.setSelectionRange(0, i.value.lastIndexOf("."));
620 }
621 });
622 }
623 }
624 function initTextarea() {
625 var te = collectElementsByAttr("textarea", "name", "text");
626 if (!te || !te[0]) return;
627 te[0].addEventListener("keydown", helpMarkdown, false);
628 }
629 function initBlogs() {
630 // Auto-complete #xxxx
631 let i, check = collectElementsByAttr("input", "name", "notifyto");
632 if (check)
633 for (i of check) {
634 i.addEventListener("click", insertRedirect, false);
635 }
636 registInsertDirect(document.querySelectorAll("a[href]"));
637 if (myurl.match(/replyblog\+[0-9]/)
638 && document.querySelector("td.repl")) {
639 // There's no need to provide ajax posting when
640 // no replies written to the blog. Therefore we
641 // assign ajax post when td.repl exists.
642 for (i of document.querySelectorAll('input#c[value="送信"]')) {
643 let b = document.createElement("button");
644 b.textContent = "送信!";
645 console.log("b="+b+", tc="+b.textContent);
646 b.addEventListener("click", ajaxPost, false);
647 // i.insertAdjacentElement('afterend', b);
648 b.setAttribute("class", i.getAttribute("class"))
649 b.setAttribute("title", i.getAttribute("title"))
650 i.parentNode.replaceChild(b, i);
651 b.id = i.id;
652 // i.remove();
653 i.classList.add("aux");
654 i.value = "送信(予備)"
655 b.parentNode.appendChild(i);
656 }
657 i = document.getElementById("reload");
658 if (i) i.addEventListener("click", ajaxPost, false);
659 }
660 for (i of document.querySelectorAll('input[type="file"]')) {
661 i.addEventListener('change', (e) => {
662 warnFileSize(document.forms[0]);
663 }, false)
664 }
665 // Hack article_m links
666 registPjaxViewers(document.querySelectorAll("a[href]"));
667 }
668 function initGrpAction() {
669 var rev = document.getElementById("reverse");
670 if (!rev) return; // Is not grpAction page
671 if (rev.tagName.match(/span/i)) {
672 rev.textContent = " 反転 ";
673 rev.addEventListener("click", reverseChecks, null);
674 }
675 var emailbtn = document.getElementById("email");
676 emailbtn.addEventListener("click", function(ev){
677 // Enlarge box and Select user's checkbox
678 if (!ev.target.checked) return;
679 var x = collectElementsByAttr("div", "class", "foldtabs");
680 if (x && x[0] && x[0].style) {
681 x[0].style.height = "10em";
682 }
683 let myuid = document.getElementById("myuid");
684 if (myuid) {
685 let usel = collectElementsByAttr("input", "name", "usel");
686 if (usel) {
687 for (u of usel) {
688 if (u.value == myuid.value)
689 u.checked = true;
690 }
691 }
692 }
693 }, null);
694 var teamsel = document.getElementById("selteam");
695 if (teamsel) {
696 var usel, p, team;
697 // Select all members of the team
698 teamsel.addEventListener("change", function(ev) {
699 var teamname = teamsel.value,
700 selected = new RegExp('(^| )'+teamname+"($|,)");
701 usel = collectElementsByAttr("input", "name", "usel");
702 if (!usel) return;
703 for (u of usel) {
704 p = u.parentNode; // should be label
705 if (!p) continue;
706 if (teamname == "TEAM") { // Reset all checks
707 u.checked = false; // when "TEAM" is selected
708 } else {
709 p = p.parentNode.parentNode;// should be tr
710 team = nthChildOf(p, 3, "td")
711 if (team && team.textContent
712 && team.textContent.match(selected)) {
713 u.checked = true;
714 }
715 }
716 }
717 }, null);
718 }
719 }
720 function dispInfoMomentary(msg, elem) {
721 // Momentarily display MSG in tooltip-baloon relative to ELEM element.
722 let help = document.createElement("p");
723 elem.style.position = 'relative';
724 elem.style.overflow = 'visible';
725 help.setAttribute("class", "info-tooltip");
726 help.innerHTML = msg;
727 elem.appendChild(help);
728 setTimeout(() => {
729 help.classList.add("dissolving");
730 setTimeout(() => help.remove(), 3000);
731 }, 1000);
732 }
733 function initGrphome() {
734 console.log("initGrphome");
735 // (1)Setup Frozen State Changing Button
736 var ja = navigator.language.match(/ja/i);
738 function toggleFrozen(e, rowid) {
739 let tgt = mypath+"?blog_setfrozen+"+rowid;
740 let td = e.target.parentNode;
741 let tr = td.parentNode;
742 fetch(tgt, {
743 method: "POST",
744 headers: {'Content-Type': 'text/html; charset=utf-8'},
745 credentials: "include"
746 }).then(function(resp) {
747 return resp.text();
748 }).then(function(tbody) {
749 try {
750 var json = JSON.parse(tbody);
751 } catch (e) {
752 return;
753 }
754 let state = json.state, newstate, info;
755 if (json.alert) {
756 alert(json.alert)
757 }
758 if (state.match(/frozen/i)) {
759 newstate = "凍結";
760 info = ja ? newstate+"に設定しました" : 'Set Frozen';
761 } else {
762 newstate = null;
763 info = ja ? '稼動に設定しました' : 'Set Running';
764 }
765 tr.setAttribute("class", newstate);
766 dispInfoMomentary(info, td);
767 });
768 }
769 let btn = document.querySelectorAll("button.toggle-frozen");
770 for (let b of btn) {
771 let rowid = null;
772 let td=b.parentNode, tr = td.parentNode, fr, ru;
773 ru = ja ? "動" : "Running";
774 fr = ja ? "凍" : "Frozen";
775 b.setAttribute('frozen-marker', fr);
776 b.setAttribute('running-marker', ru);
777 for (let a of tr.querySelectorAll("a[href]")) {
778 if (a.getAttribute("href").match(/\?replyblog\+([0-9]+)/)) {
779 rowid = parseInt(RegExp.$1);
780 break;
781 }
782 }
783 if (rowid && rowid>0) {
784 b.addEventListener("click", function(e) {
785 if (!btn) return;
786 toggleFrozen(e, rowid);
787 }, false);
788 b.setAttribute("title", "稼動/凍結をその場で切り替えます\n\
789 Toggle Running/Frozen ("+rowid+")");
790 }
791 }
792 // (2)Setup Column Collapse Button
793 // INCOMPLETE: Cannot restore original state, but it's enough...
794 function toggleColmnWidth(th) {
795 let tbl = document.querySelector("table.dumpblogs");
796 let colname = th.textContent, newwidth;
797 if (th.style.width) {
798 newwidth = null
799 // https://developer.mozilla.org/ja/docs/Web/CSS/table-layout
800 tbl.style.tableLayout = 'auto';
801 tbl.style.width = null;
802 } else {
803 newwidth = "2em";
804 tbl.style.tableLayout = 'fixed';
805 tbl.style.width = '100%';
806 }
807 th.style.width = newwidth;
808 th.style.overflow = "hidden";
809 for (let td of document.querySelectorAll("td."+colname)) {
810 console.log(td.tagName);
811 td.style.width = newwidth;
812 console.log(td.style.width);
813 }
814 }
815 let row1 = document.querySelector("table.dumpblogs tr:first-child");
816 if (row1) {
817 let heads = row1.querySelectorAll("th");
818 for (let h of heads) {
819 h.addEventListener("click", function(e) {
820 toggleColmnWidth(h);
821 }, false);
822 h.setAttribute("title", "Click to shrink these columns");
823 }
824 }
825 }
826 function init() {
827 isOlderJS = !("insertAdjacentElement" in document.body);
828 initGrpAction();
829 initBlogs();
830 initFileInput();
831 initTextarea();
832 initGrphome();
833 }
834 document.addEventListener('DOMContentLoaded', init, null);
835 })();