s4

view s4-main.js @ 930:1221335459c6

Add evaluation code of opening files in normal window
author HIROSE Yuuji <yuuji@gentei.org>
date Tue, 19 Jan 2021 16:12:14 +0900
parents a3623f901e32
children 756c99e27d4f
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 { // TEST: Normal mode
422 let only = document.createElement("button"),
423 h = location.href;
424 only.textContent = ".oO□";
425 only.setAttribute("title", "Open in Normal Window");
426 only.addEventListener("click", function() {
427 location.replace(iframe.src);
428 });
429 p1.appendChild(only);
430 }
431 p1.appendChild(loading);
432 info.appendChild(info1); info.appendChild(info2);
433 loading.textContent=" Loading...";
434 loading.classList.add("hidden");
435 loading.classList.add("loading");
436 box.appendChild(info);
437 iframe.src = url;
439 box.addEventListener("keydown", switchToByKey);
440 //box.addEventListener("click", (e) => {_resetPjax();});
441 bt.addEventListener("click", (e) => {_resetPjax();});
442 // dp.addEventListener("click", (e) => {_resetPjax();});
443 info.addEventListener("click", (e) => {_resetPjax();});
444 box.appendChild(iframe);
446 setSwipeAct(iframe);
448 _setPjaxCurposInfo();
449 bt.focus();
450 setTimeout(() => {box.classList.add("pjaxview2");}, 10);
451 // Finally update history stack
452 if (history.pushState) {
453 let h = location.href.replace(/#.*/, '')+"#pjaxview";
454 history.pushState({url: h}, null, h);
455 window.addEventListener("popstate", (e) => {
456 if (box) {
457 box.remove(); box = null;
458 }
459 }, false);
460 }
461 }
462 function reverseChecks() {
463 var names = collectElementsByAttr("input", "name", "usel");
464 for (let u of names) {
465 u.checked = !u.checked;
466 }
467 }
468 function renumberOL(str, start) {
469 var stra = str.split("\n");
470 for (var i=1; i<stra.length; i++) {
471 if (stra[i].match(/^[1-9][0-9]*\. /)) {
472 let orig=stra[i];
473 stra[i] = (++start)+". "+RegExp.rightContext;
474 } else if (stra[i].match(/^ /)) {
475 continue;
476 } else
477 break;
478 }
479 return stra.join("\n");
480 }
481 function submitThisForm(input) {
482 for (var elm=input.parentNode; elm; elm = elm.parentNode) {
483 if (elm.nodeName.match(/form/i)) {
484 elm.submit();
485 return true;
486 }
487 }
488 return false;
489 }
490 function helpMarkdownBS(e) {
491 var area = e.target, pos = area.selectionStart, text = area.value;
492 if (area.selectionStart != area.selectionEnd) return;
493 if (pos<2) return;
494 if (text.substr(pos-1, 2)=="\n\n") return;
495 var bol = text.lastIndexOf("\n", pos-1),
496 eol = text.indexOf("\n", pos);
497 if (bol<=0 || bol==eol) return;
498 var thisline = text.substring(bol+1, eol==-1 ? text.length : eol);
499 thisline = text.substring(bol+1, pos);
500 if (thisline == "* ") {
501 area.setSelectionRange(pos-2, pos);
502 } else if (thisline.match(/^[1-9][0-9]*\. $/)) {
503 area.setSelectionRange(pos-RegExp.lastMatch.length, pos);
504 }
505 }
506 function helpMarkdownEnter(e) {
507 if (e.keyCode == 13 && !e.shiftKey) {
508 if (e.metaKey && submitThisForm(e.target)) {
509 e.preventDefault();
510 return;
511 }
512 var area = e.target;
513 var pos = area.selectionStart, text = area.value;
514 if (pos==0) return;
515 var last = text.lastIndexOf("\n", pos-1);
516 var rest = text.substring(pos), rest0=rest;
517 var line = last ? text.substring(last+1, pos) : text;
518 var next = rest.substring(rest.indexOf("\n"))||rest;
519 next=next.substring(1);
520 var tail = text.substring(pos-2, pos), br = (tail==" ");
521 var add = "", offset = 1;
522 if (line.startsWith("* ")) {
523 add = "* ";
524 offset += add.length;
525 if (br) {
526 add = " " + "\n" + add;
527 }
528 } else if (line.match(/^([1-9][0-9]*)\. /)) {
529 var ln = parseInt(RegExp.$1), nn=ln+1,
530 len = RegExp.lastMatch.length;
531 add = nn+". ";
532 let toeol = text.substr(pos, text.indexOf("\n"));
533 if (br) {
534 if (next.startsWith(add)) {
535 add=" ".repeat(len);
536 nn = ln;
537 } else {
538 add = " ".repeat(len)+ "\n" + add;
539 offset -= len+1;
540 }
541 }
542 if (next.match(/^[1-9][0-9]*\. /))
543 rest = renumberOL(rest, nn);
544 offset += add.length;
545 } else if (line.match(/^\|( *).+\|/)) {
546 add = "|" + RegExp.$1 + " |";
547 offset += add.length-2;
548 } else {
549 return;
550 }
551 e.preventDefault();
552 if (!document.execCommand("insertText", false, "\n"+add)) {
553 //Firefox
554 area.selectionEnd = area.value.length;
555 area.setRangeText("\n"+add+rest);
556 area.selectionEnd = null;
557 } else {
558 area.selectionEnd = area.value.length;
559 area.setSelectionRange(area.selectionStart, area.value.length);
560 document.execCommand("insertText", false, rest);
561 area.selectionEnd = null;
562 area.focus();
563 }
564 area.selectionStart = pos+offset;
565 return;
566 if (document.execCommand("insertText", false, "\n"+add)) {
567 //area.setSelectionRange(area.selectionStart, text.length);
568 // alert("rest=["+rest+"], add=["+add+"]");
569 alert(text.substring(pos, area.value.length));
570 if (rest != rest0) {
571 area.setSelectionRange(pos, area.value.length);
572 return;
573 document.execCommand("delete");
574 }
575 document.execCommand("insertText", false, rest);
576 } else {
577 // Firefox cannot use insertText in textarea...
578 area.value = text.substring(0, pos) + "\n" + add + rest;
579 }
580 //area.setSelectionRange(pos+length(add));
581 area.selectionStart=area.selectionEnd = (pos + offset);
583 }
584 }
585 function helpMarkdown(e) {
586 switch (e.key) {
587 case "Backspace": helpMarkdownBS(e); break;
588 case "Enter": helpMarkdownEnter(e); break;
589 }
590 }
591 /* Init event listeners */
592 function addFileInput() {
593 var inpfile = collectElementsByAttr("input", "name", "image");
594 if (!inpfile) return;
595 var filled = true;
596 var i, ih;
597 for (i of inpfile) {
598 if (! i.value) filled=false;
599 }
600 if (filled) {
601 ih = i.parentNode.innerHTML;
602 if (ih) {
603 var inpf = ih.substring(ih.indexOf("<input")),
604 newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
605 i.insertAdjacentHTML("afterend", newi)
606 i.nextSibling.nextSibling.addEventListener('change', () => {
607 // next==br next.next==input[type=file]
608 warnFileSize(document.forms[0]);
609 });
610 }
611 }
612 }
613 function initFileInput() { // Multiplies "input type=file"
614 var el, morefile = document.getElementById("morefile");
615 if (morefile) {
616 for (el of collectElementsByAttr("input", "name", "image")) {
617 el.addEventListener("change", function(ev) {
618 if (ev.target.value > "" && ev.target.files.length == 1)
619 morefile.style.visibility = "visible";
620 // No need to hide again, sure?
621 });
622 }
623 morefile.addEventListener("click", addFileInput, null);
624 }
625 // When renaming, select basename part
626 for (el of collectElementsByAttr("input", "class", "mv")) {
627 el.addEventListener("focus", function(ev) {
628 var i = ev.target;
629 if (i) {
630 i.setSelectionRange(0, i.value.lastIndexOf("."));
631 }
632 });
633 }
634 }
635 function initTextarea() {
636 var te = collectElementsByAttr("textarea", "name", "text");
637 if (!te || !te[0]) return;
638 te[0].addEventListener("keydown", helpMarkdown, false);
639 }
640 function initBlogs() {
641 // Auto-complete #xxxx
642 let i, check = collectElementsByAttr("input", "name", "notifyto");
643 if (check)
644 for (i of check) {
645 i.addEventListener("click", insertRedirect, false);
646 }
647 registInsertDirect(document.querySelectorAll("a[href]"));
648 if (myurl.match(/replyblog\+[0-9]/)
649 && document.querySelector("td.repl")) {
650 // There's no need to provide ajax posting when
651 // no replies written to the blog. Therefore we
652 // assign ajax post when td.repl exists.
653 for (i of document.querySelectorAll('input#c[value="送信"]')) {
654 let b = document.createElement("button");
655 b.textContent = "送信!";
656 console.log("b="+b+", tc="+b.textContent);
657 b.addEventListener("click", ajaxPost, false);
658 // i.insertAdjacentElement('afterend', b);
659 b.setAttribute("class", i.getAttribute("class"))
660 b.setAttribute("title", i.getAttribute("title"))
661 i.parentNode.replaceChild(b, i);
662 b.id = i.id;
663 // i.remove();
664 i.classList.add("aux");
665 i.value = "送信(予備)"
666 b.parentNode.appendChild(i);
667 }
668 i = document.getElementById("reload");
669 if (i) i.addEventListener("click", ajaxPost, false);
670 }
671 for (i of document.querySelectorAll('input[type="file"]')) {
672 i.addEventListener('change', (e) => {
673 warnFileSize(document.forms[0]);
674 }, false)
675 }
676 // Hack article_m links
677 registPjaxViewers(document.querySelectorAll("a[href]"));
678 }
679 function initGrpAction() {
680 var rev = document.getElementById("reverse");
681 if (!rev) return; // Is not grpAction page
682 if (rev.tagName.match(/span/i)) {
683 rev.textContent = " 反転 ";
684 rev.addEventListener("click", reverseChecks, null);
685 }
686 var emailbtn = document.getElementById("email");
687 emailbtn.addEventListener("click", function(ev){
688 // Enlarge box and Select user's checkbox
689 if (!ev.target.checked) return;
690 var x = collectElementsByAttr("div", "class", "foldtabs");
691 if (x && x[0] && x[0].style) {
692 x[0].style.height = "10em";
693 }
694 let myuid = document.getElementById("myuid");
695 if (myuid) {
696 let usel = collectElementsByAttr("input", "name", "usel");
697 if (usel) {
698 for (u of usel) {
699 if (u.value == myuid.value)
700 u.checked = true;
701 }
702 }
703 }
704 }, null);
705 var teamsel = document.getElementById("selteam");
706 if (teamsel) {
707 var usel, p, team;
708 // Select all members of the team
709 teamsel.addEventListener("change", function(ev) {
710 var teamname = teamsel.value,
711 selected = new RegExp('(^| )'+teamname+"($|,)");
712 usel = collectElementsByAttr("input", "name", "usel");
713 if (!usel) return;
714 for (u of usel) {
715 p = u.parentNode; // should be label
716 if (!p) continue;
717 if (teamname == "TEAM") { // Reset all checks
718 u.checked = false; // when "TEAM" is selected
719 } else {
720 p = p.parentNode.parentNode;// should be tr
721 team = nthChildOf(p, 3, "td")
722 if (team && team.textContent
723 && team.textContent.match(selected)) {
724 u.checked = true;
725 }
726 }
727 }
728 }, null);
729 }
730 }
731 function dispInfoMomentary(msg, elem) {
732 // Momentarily display MSG in tooltip-baloon relative to ELEM element.
733 let help = document.createElement("p");
734 elem.style.position = 'relative';
735 elem.style.overflow = 'visible';
736 help.setAttribute("class", "info-tooltip");
737 help.innerHTML = msg;
738 elem.appendChild(help);
739 setTimeout(() => {
740 help.classList.add("dissolving");
741 setTimeout(() => help.remove(), 3000);
742 }, 1000);
743 }
744 function initGrphome() {
745 console.log("initGrphome");
746 // (1)Setup Frozen State Changing Button
747 var ja = navigator.language.match(/ja/i);
749 function toggleFrozen(e, rowid) {
750 let tgt = mypath+"?blog_setfrozen+"+rowid;
751 let td = e.target.parentNode;
752 let tr = td.parentNode;
753 fetch(tgt, {
754 method: "POST",
755 headers: {'Content-Type': 'text/html; charset=utf-8'},
756 credentials: "include"
757 }).then(function(resp) {
758 return resp.text();
759 }).then(function(tbody) {
760 try {
761 var json = JSON.parse(tbody);
762 } catch (e) {
763 return;
764 }
765 let state = json.state, newstate, info;
766 if (json.alert) {
767 alert(json.alert)
768 }
769 if (state.match(/frozen/i)) {
770 newstate = "凍結";
771 info = ja ? newstate+"に設定しました" : 'Set Frozen';
772 } else {
773 newstate = null;
774 info = ja ? '稼動に設定しました' : 'Set Running';
775 }
776 tr.setAttribute("class", newstate);
777 dispInfoMomentary(info, td);
778 });
779 }
780 let btn = document.querySelectorAll("button.toggle-frozen");
781 for (let b of btn) {
782 let rowid = null;
783 let td=b.parentNode, tr = td.parentNode, fr, ru;
784 ru = ja ? "動" : "Running";
785 fr = ja ? "凍" : "Frozen";
786 b.setAttribute('frozen-marker', fr);
787 b.setAttribute('running-marker', ru);
788 for (let a of tr.querySelectorAll("a[href]")) {
789 if (a.getAttribute("href").match(/\?replyblog\+([0-9]+)/)) {
790 rowid = parseInt(RegExp.$1);
791 break;
792 }
793 }
794 if (rowid && rowid>0) {
795 b.addEventListener("click", function(e) {
796 if (!btn) return;
797 toggleFrozen(e, rowid);
798 }, false);
799 b.setAttribute("title", "稼動/凍結をその場で切り替えます\n\
800 Toggle Running/Frozen ("+rowid+")");
801 }
802 }
803 // (2)Setup Column Collapse Button
804 // INCOMPLETE: Cannot restore original state, but it's enough...
805 function toggleColmnWidth(th) {
806 let tbl = document.querySelector("table.dumpblogs");
807 let colname = th.textContent, newwidth;
808 if (th.style.width) {
809 newwidth = null
810 // https://developer.mozilla.org/ja/docs/Web/CSS/table-layout
811 tbl.style.tableLayout = 'auto';
812 tbl.style.width = null;
813 } else {
814 newwidth = "2em";
815 tbl.style.tableLayout = 'fixed';
816 tbl.style.width = '100%';
817 }
818 th.style.width = newwidth;
819 th.style.overflow = "hidden";
820 for (let td of document.querySelectorAll("td."+colname)) {
821 console.log(td.tagName);
822 td.style.width = newwidth;
823 console.log(td.style.width);
824 }
825 }
826 let row1 = document.querySelector("table.dumpblogs tr:first-child");
827 if (row1) {
828 let heads = row1.querySelectorAll("th");
829 for (let h of heads) {
830 h.addEventListener("click", function(e) {
831 toggleColmnWidth(h);
832 }, false);
833 h.setAttribute("title", "Click to shrink these columns");
834 }
835 }
836 }
837 function init() {
838 isOlderJS = !("insertAdjacentElement" in document.body);
839 initGrpAction();
840 initBlogs();
841 initFileInput();
842 initTextarea();
843 initGrphome();
844 }
845 document.addEventListener('DOMContentLoaded', init, null);
846 })();