s4

view s4-main.js @ 939:6c2f8bb3cc6e

Activate direct link to attached files
author HIROSE Yuuji <yuuji@gentei.org>
date Mon, 06 Sep 2021 09:11:25 +0900
parents 627a7fdf3e16
children b8d09525a0b4
line source
1 // 愛
2 (function (){
3 var isOlderJS; // Set in init();
4 var hasTouchPad =
5 (navigator.maxTouchPoints && navigator.maxTouchPoints >0);
6 var myurl = document.URL,
7 mypath = myurl.substring(myurl.lastIndexOf("/"));
8 var art_m_list = [];
9 let input_pdfsw = 'input[name="comppdf"]';
10 if (mypath.match(/(.*)\/(.*)/)) {
11 mypath = RegExp.$2;
12 mypath = mypath.substring(0, mypath.lastIndexOf("?"));
13 //alert("mypath="+mypath);
14 }
15 function collectElementsByAttr(elm, attr, val) {
16 var e = document.getElementsByTagName(elm);
17 if (!e) return null;
18 var list = [];
19 for (var i of e) {
20 if (i.getAttribute(attr) == val)
21 list.push(i)
22 }
23 return list;
24 }
25 function nthChildOf(parent, n, elem) { // Return Nth child of type ELEM
26 // N begins with 1
27 var i=0;
28 var le = elem.toLowerCase();
29 for (var c of parent.childNodes) {
30 if (!c.tagName) continue;
31 if (c.tagName.toLowerCase() == le) {
32 if (++i >= n) return c;
33 }
34 }
35 return null;
36 }
37 function insertRedirect(e) {
38 var articleId, textarea = document.getElementById("text");
39 var p = e.target, checked = p.checked;
40 while (p = p.parentNode)
41 if (p.nodeName.match(/^td$/i)) break;
42 if (!p) return;
43 while (p = p.nextSibling)
44 if (p.nodeName.match(/^td$/i)) break;
45 if (!p) return;
46 articleId = p.getAttribute("id");
47 if (textarea && articleId) {
48 var tv = textarea.value, lines;
49 if (tv)
50 lines = tv.split("\n");
51 else
52 lines = [""];
53 var re = new RegExp("[, ]*#"+articleId+"(?![0-9])");
54 checked = (p.nodeName.match(/^input$/)
55 ? p.checked // checkbox obeys its status
56 : !lines[0].match(re)) // a-elment toggles redirection
57 if (checked) {
58 if (!lines[0].match(re)) {
59 var re2 = new RegExp(/>#[#0-9, ]+[0-9]/);
60 if (lines[0].match(re2))
61 lines[0] = lines[0].replace(
62 re2, '$&, '+'#'+articleId);
63 else {
64 if (lines[0] > "") lines[0] = " "+lines[0];
65 lines[0] = ">#"+articleId+lines[0];
66 }
67 }
68 } else { // Remove #xxxxx
69 if (lines[0].match(/^>#[0-9 ,]+#/)) // 2 or more #id's
70 lines[0] = lines[0].replace(
71 new RegExp("^>#"+articleId+"[ ,]*"), ">").replace(
72 new RegExp("[ ,]*#"+articleId), "");
73 else {
74 lines[0] = lines[0].replace(
75 new RegExp(">#"+articleId+"[ ,]*"), "");
76 }
77 }
78 lines[0] = lines[0].replace(/^> *$/, '');
79 textarea.value = lines.join("\n");
80 }
81 }
82 function registPjaxViewers(aHrefList) {
83 let apos=art_m_list.length;
84 for (let a of aHrefList) {
85 let href = a.getAttribute("href");
86 let localvar = apos;
87 let td = a.parentNode,
88 tr = td.parentNode,
89 id = td.id,
90 text = td.textContent,
91 author = tr.getElementsByTagName("a");
92 if (author) author = author[0].getAttribute("title");
93 if (href.match(/\?showattc\+article_m\+([0-9]+)$/)) {
94 if (td.innerHTML.match(/読み取り不可/)) {
95 a.removeAttribute("href");
96 continue;
97 }
98 let url = RegExp.lastMatch;
99 // console.log("pjaxView(e, "+href+", "+apos+")");
100 a.addEventListener("click", function(e) {
101 // Shoud use closure local variable: localvar
102 pjaxView(e, href, localvar);
103 }, false);
104 apos++;
105 art_m_list.push({
106 url: href, id: id, author: author, text: text
107 });
108 }
109 }
110 }
111 function registInsertDirect(aHrefList) {
112 for (i of aHrefList)
113 if (i.getAttribute("href").match(/^#[0-9]+$/))
114 if (RegExp.lastMatch == i.innerHTML)
115 i.addEventListener("click", insertRedirect, false)
116 }
117 var ajaxSubmit;
118 function replAddNews(newtable) {
119 let newids = [], idlist=[];
120 let getArticleID = function (td) {
121 return parseInt(td.parentNode.getElementsByTagName("td")[1].id);
122 }
123 for (let i of newtable.querySelectorAll("td.repl"))
124 newids.push(i);
125 newids = newids.sort((a,b)=> {
126 return (getArticleID(a) - getArticleID(b));
127 });
128 for (i of newids)
129 idlist.push(getArticleID(i));
130 console.log("IDList="+idlist.join());
131 let cnt=0, ntr;
132 let current = collectElementsByAttr("td", "class", "repl"),
133 ncur=0, n, icur=0, o, oid, nid, otr;
134 current = document.querySelectorAll('td[class="repl"]');
135 let last=current[current.length-1],
136 tbody = last.parentNode.parentNode;
137 let addEventsToNewTr = function(tr) {
138 let td = tr.getElementsByTagName("td"),
139 td0 = td[0], td1 = td[1];
140 td0.classList.add("new");
141 registInsertDirect(td0.querySelectorAll("a[href]"));
142 registPjaxViewers(td1.querySelectorAll("a[href]"));
143 }
144 // Erase all "new article" flags before merging
145 for (let i of document.querySelectorAll("td.new"))
146 i.classList.remove("new");
147 // Now reconstruct articles with merge-sort like method
148 outer: for (; ncur<newids.length; ncur++) {
149 n = newids[ncur];
150 if (!n.id) continue;
151 nid = parseInt(n.id);
152 if (nid<=0) continue;
153 ntr = n.parentNode;
154 for (; icur<current.length; icur++) {
155 o = current[icur];
156 otr = o.parentNode;
157 oid = getArticleID(o);
158 if (!oid || oid=="") continue;
159 if (oid >= nid) {
160 addEventsToNewTr(ntr);
161 tbody.insertBefore(ntr, otr);
162 if (oid==nid) otr.remove();
163 cnt++;
164 continue outer;
165 }
166 }
167 // Append absolutely new articles.
168 ntr = n.parentNode;
169 addEventsToNewTr(ntr)
170 tbody.appendChild(ntr);
171 ntr.classList.add("dissolving");
172 let localntr = ntr;
173 setTimeout(() => {
174 localntr.classList.remove("dissolving");
175 localntr.classList.add("emerging");
176 }, 100);
177 cnt++;
178 }
179 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(e) {
482 var input = e.target, ajaxpost = document.getElementById("c");
483 for (var elm=input.parentNode; elm; elm = elm.parentNode) {
484 if (ajaxpost) {
485 ajaxpost.click();
486 return true;
487 } else if (elm.nodeName.match(/form/i)) {
488 elm.submit();
489 return true;
490 }
491 }
492 return false;
493 }
494 function helpMarkdownBS(e) {
495 var area = e.target, pos = area.selectionStart, text = area.value;
496 if (area.selectionStart != area.selectionEnd) return;
497 if (pos<2) return;
498 if (text.substr(pos-1, 2)=="\n\n") return;
499 var bol = text.lastIndexOf("\n", pos-1),
500 eol = text.indexOf("\n", pos);
501 if (bol<=0 || bol==eol) return;
502 var thisline = text.substring(bol+1, eol==-1 ? text.length : eol);
503 thisline = text.substring(bol+1, pos);
504 if (thisline == "* ") {
505 area.setSelectionRange(pos-2, pos);
506 } else if (thisline.match(/^[1-9][0-9]*\. $/)) {
507 area.setSelectionRange(pos-RegExp.lastMatch.length, pos);
508 }
509 }
510 function helpMarkdownEnter(e) {
511 if (e.keyCode == 13 && !e.shiftKey) {
512 if (e.ctrlKey && submitThisForm(e)) {
513 e.preventDefault();
514 return;
515 }
516 var area = e.target;
517 var pos = area.selectionStart, text = area.value;
518 if (pos==0) return;
519 var last = text.lastIndexOf("\n", pos-1);
520 var rest = text.substring(pos), rest0=rest;
521 var line = last ? text.substring(last+1, pos) : text;
522 var next = rest.substring(rest.indexOf("\n"))||rest;
523 next=next.substring(1);
524 var tail = text.substring(pos-2, pos), br = (tail==" ");
525 var add = "", offset = 1;
526 if (line.startsWith("* ")) {
527 add = "* ";
528 offset += add.length;
529 if (br) {
530 add = " " + "\n" + add;
531 }
532 } else if (line.match(/^([1-9][0-9]*)\. /)) {
533 var ln = parseInt(RegExp.$1), nn=ln+1,
534 len = RegExp.lastMatch.length;
535 add = nn+". ";
536 let toeol = text.substr(pos, text.indexOf("\n"));
537 if (br) {
538 if (next.startsWith(add)) {
539 add=" ".repeat(len);
540 nn = ln;
541 } else {
542 add = " ".repeat(len)+ "\n" + add;
543 offset -= len+1;
544 }
545 }
546 if (next.match(/^[1-9][0-9]*\. /))
547 rest = renumberOL(rest, nn);
548 offset += add.length;
549 } else if (line.match(/^\|( *).+\|/)) {
550 add = "|" + RegExp.$1 + " |";
551 offset += add.length-2;
552 } else {
553 return;
554 }
555 e.preventDefault();
556 if (!document.execCommand("insertText", false, "\n"+add)) {
557 //Firefox
558 area.selectionEnd = area.value.length;
559 area.setRangeText("\n"+add+rest);
560 area.selectionEnd = null;
561 } else {
562 area.selectionEnd = area.value.length;
563 area.setSelectionRange(area.selectionStart, area.value.length);
564 document.execCommand("insertText", false, rest);
565 area.selectionEnd = null;
566 area.focus();
567 }
568 area.selectionStart = pos+offset;
569 return;
570 if (document.execCommand("insertText", false, "\n"+add)) {
571 //area.setSelectionRange(area.selectionStart, text.length);
572 // alert("rest=["+rest+"], add=["+add+"]");
573 alert(text.substring(pos, area.value.length));
574 if (rest != rest0) {
575 area.setSelectionRange(pos, area.value.length);
576 return;
577 document.execCommand("delete");
578 }
579 document.execCommand("insertText", false, rest);
580 } else {
581 // Firefox cannot use insertText in textarea...
582 area.value = text.substring(0, pos) + "\n" + add + rest;
583 }
584 //area.setSelectionRange(pos+length(add));
585 area.selectionStart=area.selectionEnd = (pos + offset);
587 }
588 }
589 function helpMarkdown(e) {
590 switch (e.key) {
591 case "Backspace": helpMarkdownBS(e); break;
592 case "Enter": helpMarkdownEnter(e); break;
593 }
594 }
595 /* Init event listeners */
596 function addFileInput() {
597 var inpfile = collectElementsByAttr("input", "name", "image");
598 if (!inpfile) return;
599 var filled = true;
600 var i, ih;
601 for (i of inpfile) {
602 if (! i.value) filled=false;
603 }
604 if (filled) {
605 ih = i.parentNode.innerHTML;
606 if (ih) {
607 var inpf = ih.substring(ih.indexOf("<input")),
608 newi = "<br>"+inpf.substring(0, inpf.indexOf(">")+1);
609 i.insertAdjacentHTML("afterend", newi)
610 i.nextSibling.nextSibling.addEventListener('change', () => {
611 // next==br next.next==input[type=file]
612 warnFileSize(document.forms[0]);
613 });
614 }
615 }
616 }
617 function initFileInput() { // Multiplies "input type=file"
618 var el, morefile = document.getElementById("morefile");
619 if (morefile) {
620 for (el of collectElementsByAttr("input", "name", "image")) {
621 el.addEventListener("change", function(ev) {
622 if (ev.target.value > "" && ev.target.files.length == 1)
623 morefile.style.visibility = "visible";
624 // No need to hide again, sure?
625 });
626 }
627 morefile.addEventListener("click", addFileInput, null);
628 }
629 // When renaming, select basename part
630 for (el of collectElementsByAttr("input", "class", "mv")) {
631 el.addEventListener("focus", function(ev) {
632 var i = ev.target;
633 if (i) {
634 i.setSelectionRange(0, i.value.lastIndexOf("."));
635 }
636 });
637 }
638 }
639 function initTextarea() {
640 var te = collectElementsByAttr("textarea", "name", "text");
641 if (!te || !te[0]) return;
642 te[0].addEventListener("keydown", helpMarkdown, false);
643 }
644 function initBlogs() {
645 // Auto-complete #xxxx
646 let i, check = collectElementsByAttr("input", "name", "notifyto");
647 if (check)
648 for (i of check) {
649 i.addEventListener("click", insertRedirect, false);
650 }
651 registInsertDirect(document.querySelectorAll("a[href]"));
652 if (myurl.match(/replyblog\+[0-9]/)
653 && document.querySelector("td.repl")) {
654 // There's no need to provide ajax posting when
655 // no replies written to the blog. Therefore we
656 // assign ajax post when td.repl exists.
657 for (i of document.querySelectorAll('input#c[value="送信"]')) {
658 let b = document.createElement("button");
659 b.textContent = "送信!";
660 console.log("b="+b+", tc="+b.textContent);
661 b.addEventListener("click", ajaxPost, false);
662 // i.insertAdjacentElement('afterend', b);
663 b.setAttribute("class", i.getAttribute("class"))
664 b.setAttribute("title", i.getAttribute("title"))
665 i.parentNode.replaceChild(b, i);
666 b.id = i.id;
667 // i.remove();
668 i.classList.add("aux");
669 i.value = "送信(予備)"
670 b.parentNode.appendChild(i);
671 }
672 i = document.getElementById("reload");
673 if (i) i.addEventListener("click", ajaxPost, false);
674 }
675 for (i of document.querySelectorAll('input[type="file"]')) {
676 i.addEventListener('change', (e) => {
677 warnFileSize(document.forms[0]);
678 }, false)
679 }
680 // Hack article_m links
681 registPjaxViewers(document.querySelectorAll("a[href]"));
682 }
683 function initGrpAction() {
684 var rev = document.getElementById("reverse");
685 if (!rev) return; // Is not grpAction page
686 if (rev.tagName.match(/span/i)) {
687 rev.textContent = " 反転 ";
688 rev.addEventListener("click", reverseChecks, null);
689 }
690 var emailbtn = document.getElementById("email");
691 emailbtn.addEventListener("click", function(ev){
692 // Enlarge box and Select user's checkbox
693 if (!ev.target.checked) return;
694 var x = collectElementsByAttr("div", "class", "foldtabs");
695 if (x && x[0] && x[0].style) {
696 x[0].style.height = "10em";
697 }
698 let myuid = document.getElementById("myuid");
699 if (myuid) {
700 let usel = collectElementsByAttr("input", "name", "usel");
701 if (usel) {
702 for (u of usel) {
703 if (u.value == myuid.value)
704 u.checked = true;
705 }
706 }
707 }
708 }, null);
709 var teamsel = document.getElementById("selteam");
710 if (teamsel) {
711 var usel, p, team;
712 // Select all members of the team
713 teamsel.addEventListener("change", function(ev) {
714 var teamname = teamsel.value,
715 selected = new RegExp('(^| )'+teamname+"($|,)");
716 usel = collectElementsByAttr("input", "name", "usel");
717 if (!usel) return;
718 for (u of usel) {
719 p = u.parentNode; // should be label
720 if (!p) continue;
721 if (teamname == "TEAM") { // Reset all checks
722 u.checked = false; // when "TEAM" is selected
723 } else {
724 p = p.parentNode.parentNode;// should be tr
725 team = nthChildOf(p, 4, "td")
726 if (team && team.textContent
727 && team.textContent.match(selected)) {
728 u.checked = true;
729 }
730 }
731 }
732 }, null);
733 }
734 }
735 function dispInfoMomentary(msg, elem) {
736 // Momentarily display MSG in tooltip-baloon relative to ELEM element.
737 let help = document.createElement("p");
738 elem.style.position = 'relative';
739 elem.style.overflow = 'visible';
740 help.setAttribute("class", "info-tooltip");
741 help.innerHTML = msg;
742 elem.appendChild(help);
743 setTimeout(() => {
744 help.classList.add("dissolving");
745 setTimeout(() => help.remove(), 3000);
746 }, 1000);
747 }
748 function initGrphome() {
749 console.log("initGrphome");
750 // (1)Setup Frozen State Changing Button
751 var ja = navigator.language.match(/ja/i);
753 function toggleFrozen(e, rowid) {
754 let tgt = mypath+"?blog_setfrozen+"+rowid;
755 let td = e.target.parentNode;
756 let tr = td.parentNode;
757 fetch(tgt, {
758 method: "POST",
759 headers: {'Content-Type': 'text/html; charset=utf-8'},
760 credentials: "include"
761 }).then(function(resp) {
762 return resp.text();
763 }).then(function(tbody) {
764 try {
765 var json = JSON.parse(tbody);
766 } catch (e) {
767 return;
768 }
769 let state = json.state, newstate, info;
770 if (json.alert) {
771 alert(json.alert)
772 }
773 if (state.match(/frozen/i)) {
774 newstate = "凍結";
775 info = ja ? newstate+"に設定しました" : 'Set Frozen';
776 } else {
777 newstate = null;
778 info = ja ? '稼動に設定しました' : 'Set Running';
779 }
780 tr.setAttribute("class", newstate);
781 dispInfoMomentary(info, td);
782 });
783 }
784 let btn = document.querySelectorAll("button.toggle-frozen");
785 for (let b of btn) {
786 let rowid = null;
787 let td=b.parentNode, tr = td.parentNode, fr, ru;
788 ru = ja ? "動" : "Running";
789 fr = ja ? "凍" : "Frozen";
790 b.setAttribute('frozen-marker', fr);
791 b.setAttribute('running-marker', ru);
792 for (let a of tr.querySelectorAll("a[href]")) {
793 if (a.getAttribute("href").match(/\?replyblog\+([0-9]+)/)) {
794 rowid = parseInt(RegExp.$1);
795 break;
796 }
797 }
798 if (rowid && rowid>0) {
799 b.addEventListener("click", function(e) {
800 if (!btn) return;
801 toggleFrozen(e, rowid);
802 }, false);
803 b.setAttribute("title", "稼動/凍結をその場で切り替えます\n\
804 Toggle Running/Frozen ("+rowid+")");
805 }
806 }
807 // (2)Setup Column Collapse Button
808 // INCOMPLETE: Cannot restore original state, but it's enough...
809 function toggleColmnWidth(th) {
810 let tbl = document.querySelector("table.dumpblogs");
811 let colname = th.textContent, newwidth;
812 if (th.style.width) {
813 newwidth = null
814 // https://developer.mozilla.org/ja/docs/Web/CSS/table-layout
815 tbl.style.tableLayout = 'auto';
816 tbl.style.width = null;
817 } else {
818 newwidth = "2em";
819 tbl.style.tableLayout = 'fixed';
820 tbl.style.width = '100%';
821 }
822 th.style.width = newwidth;
823 th.style.overflow = "hidden";
824 for (let td of document.querySelectorAll("td."+colname)) {
825 console.log(td.tagName);
826 td.style.width = newwidth;
827 console.log(td.style.width);
828 }
829 }
830 let row1 = document.querySelector("table.dumpblogs tr:first-child");
831 if (row1) {
832 let heads = row1.querySelectorAll("th");
833 for (let h of heads) {
834 h.addEventListener("click", function(e) {
835 toggleColmnWidth(h);
836 }, false);
837 h.setAttribute("title", "Click to shrink these columns");
838 }
839 }
840 }
841 function init() {
842 isOlderJS = !("insertAdjacentElement" in document.body);
843 initGrpAction();
844 initBlogs();
845 initFileInput();
846 initTextarea();
847 initGrphome();
848 }
849 document.addEventListener('DOMContentLoaded', init, null);
850 })();