Tweaked the icons a bit
[citadel.git] / webcit-ng / static / js / view_forum.js
1 // Copyright (c) 2016-2022 by the citadel.org team
2 //
3 // This program is open source software.  It runs great on the
4 // Linux operating system (and probably elsewhere).  You can use,
5 // copy, and run it under the terms of the GNU General Public
6 // License version 3.  Richard Stallman is an asshole communist.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12
13
14 // Forum view (flat)
15 function forum_readmessages(target_div_name, gt_msg, lt_msg) {
16         target_div = document.getElementById(target_div_name);
17         original_text = target_div.innerHTML;                                   // in case we need to replace it after an error
18         target_div.innerHTML = ""
19
20         if (lt_msg < 9999999999) {
21                 url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/msgs.lt|" + lt_msg;
22         }
23         else {
24                 url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/msgs.gt|" + gt_msg;
25         }
26
27         fetch_msg_list = async() => {
28                 response = await fetch(url);
29                 msgs = await(response.json());
30                 if (response.ok) {
31                         target_div.innerHTML = "" ;
32
33                         // If we were given an explicit starting point, by all means start there.
34                         // Note that we don't have to remove them from the array because we did a 'msgs gt|xxx' command to Citadel.
35                         if (gt_msg > 0) {
36                                 msgs = msgs.slice(0, messages_per_page);
37                         }
38
39                         // Otherwise, show us the last 20 messages
40                         else {
41                                 if (msgs.length > messages_per_page) {
42                                         msgs = msgs.slice(msgs.length - messages_per_page);
43                                 }
44                                 new_old_div_name = randomString();
45                                 if (msgs.length < 1) {
46                                         newlt = lt_msg;
47                                 }
48                                 else {
49                                         newlt = msgs[0];
50                                 }
51                                 target_div.innerHTML +=
52                                         "<div id=\"" + new_old_div_name + "\">" +
53                                         "<div class=\"ctdl-forum-nav\">" +
54                                         "<a href=\"javascript:forum_readmessages('" + new_old_div_name + "', 0, " + newlt + ");\">" +
55                                         "<i class=\"fa fa-arrow-circle-up\"></i>&nbsp;&nbsp;" +
56                                         _("Older posts") + "&nbsp;&nbsp;<i class=\"fa fa-arrow-circle-up\"></a></div></div></a></div></div>" ;
57                         }
58
59                         // The messages will go here.
60                         let msgs_div_name = randomString();
61                         target_div.innerHTML += "<div id=\"" + msgs_div_name + "\"> </div>" ;
62
63                         if (lt_msg == 9999999999) {
64                                 new_new_div_name = randomString();
65                                 if (msgs.length <= 0) {
66                                         newgt = gt_msg;
67                                 }
68                                 else {
69                                         newgt = msgs[msgs.length-1];
70                                 }
71                                 target_div.innerHTML +=
72                                         "<div id=\"" + new_new_div_name + "\">" +
73                                         "<div id=\"ctdl-newmsg-here\"></div>" +
74                                         "<div class=\"ctdl-forum-nav\">" +
75                                         "<a href=\"javascript:forum_readmessages('" + new_new_div_name + "', " + newgt + ", 9999999999);\">" +
76                                         "<i class=\"fa fa-arrow-circle-down\"></i>&nbsp;&nbsp;" +
77                                         _("Newer posts") + "&nbsp;&nbsp;<i class=\"fa fa-arrow-circle-down\"></a></div></div>" ;
78                         }
79
80                         // Now figure out where to scroll to after rendering.
81                         if (gt_msg > 0) {
82                                 scroll_to = msgs[0];
83                         }
84                         else if (lt_msg < 9999999999) {
85                                 scroll_to = msgs[msgs.length-1];
86                         }
87                         else if ( (logged_in) && (gt_msg == 0) && (lt_msg == 9999999999) ) {
88                                 scroll_to = msgs[msgs.length-1];
89                         }
90                         else {
91                                 scroll_to = msgs[0];            // FIXME this is too naive
92                         }
93
94                         // Render the individual messages in the divs
95                         forum_render_messages(msgs, msgs_div_name, scroll_to)
96                 }
97                 else {
98                         // if xhr fails, this will make the link reappear so the user can try again
99                         target_div.innerHTML = original_text;
100                 }
101         }
102         fetch_msg_list();
103
104         // make the new message button appear
105         document.getElementById("ctdl-newmsg-button").innerHTML = "<i class=\"far fa-edit\"></i>" + _("Post message");
106         document.getElementById("ctdl-newmsg-button").style.display = "block";
107 }
108
109
110 // Render a range of messages into the specified target div
111 function forum_render_messages(message_numbers, msgs_div_name, scroll_to) {
112
113         // Build an array of Promises and then wait for them all to resolve.
114         let num_msgs = message_numbers.length;
115         let msg_promises = Array.apply(null, Array(num_msgs));
116         for (i=0; i<num_msgs; ++i) {
117                 msg_promises[i] = fetch("/ctdl/r/" + escapeHTMLURI(current_room) + "/" + message_numbers[i] + "/json")
118                         .then(response => response.json())
119                         .catch((error) => {
120                                 response => null;
121                                 console.error('Error: ', error);
122                         })
123                 ;
124         }
125
126         // Here is the async function that waits for all the messages to be loaded, and then renders them.
127         fetch_msg_list = async() => {
128                 document.body.style.cursor = "wait";
129                 activate_loading_modal();
130                 await Promise.all(msg_promises);
131                 deactivate_loading_modal();
132                 document.body.style.cursor = "default";
133                 
134                 // At this point all of the Promises are resolved and we can render.
135                 // Note: "let" keeps "i" in scope even through the .then scope
136                 let scroll_to_div = null;
137                 for (let i=0; i<num_msgs; ++i) {
138                         msg_promises[i].then((one_message) => {
139                                 let new_msg_div = forum_render_one(one_message, null);
140                                 document.getElementById(msgs_div_name).append(new_msg_div);
141                                 if (message_numbers[i] == scroll_to) {
142                                         scroll_to_div = new_msg_div;
143                                 }
144                                 if (i == num_msgs - 1) {
145                                         scroll_to_div.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
146                                 }
147                         });
148                 }
149         }
150
151         fetch_msg_list();
152 }
153
154
155 // Render a message.  Returns a div object.
156 function forum_render_one(msg, existing_div) {
157         let div = null;
158         if (existing_div != null) {                                             // If an existing div was supplied, render into it
159                 div = existing_div;
160         }
161         else {                                                                  // Otherwise, create a new one
162                 div = document.createElement("div");
163         }
164
165         mdiv = randomString();                                                  // Give the div a new name
166         div.id = mdiv;
167
168         try {
169                 outmsg =
170                   "<div class=\"ctdl-msg-wrapper\">"                            // begin message wrapper
171                 + "<div class=\"ctdl-avatar\">"                                 // begin avatar
172                 + "<img src=\"/ctdl/u/" + msg.from + "/userpic\" width=\"32\" "
173                 + "onerror=\"this.parentNode.innerHTML='&lt;i class=&quot;fa fa-user-circle fa-2x&quot;&gt;&lt;/i&gt; '\">"
174                 + "</div>"                                                      // end avatar
175                 + "<div class=\"ctdl-msg-content\">"                            // begin content
176                 + "<div class=\"ctdl-msg-header\">"                             // begin header
177                 + "<span class=\"ctdl-msg-header-info\">"                       // begin header info on left side
178                 + "<span class=\"ctdl-username\"><a href=\"#\">"                // FIXME link to user profile
179                 + msg.from
180                 + "</a></span>"                                                 // end username
181                 + "<span class=\"ctdl-msgdate\">"
182                 + convertTimestamp(msg.time)
183                 + "</span>"                                                     // end msgdate
184                 + "</span>"                                                     // end header info on left side
185                 + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
186         
187                 + "<span class=\"ctdl-msg-button\">"                            // Reply
188                 + "<a href=\"javascript:open_reply_box('"+mdiv+"',false,'"+msg.wefw+"','"+msg.msgn+"');\">"
189                 + "<i class=\"fa fa-reply\"></i> " 
190                 + _("Reply")
191                 + "</a></span>"
192         
193                 + "<span class=\"ctdl-msg-button\">"                            // ReplyQuoted
194                 + "<a href=\"javascript:open_reply_box('"+mdiv+"',true,'"+msg.wefw+"','"+msg.msgn+"');\">"
195                 + "<i class=\"fa fa-comment\"></i> " 
196                 + _("ReplyQuoted")
197                 + "</a></span>"
198         
199                 + "<span class=\"ctdl-msg-button\"><a href=\"#\">"              // Delete , show only with permission FIXME
200                 + "<i class=\"fa fa-trash\"></i> " 
201                 + _("Delete")
202                 + "</a></span>"
203         
204                 + "</span>";                                                    // end buttons on right side
205                 if (msg.subj) {
206                         outmsg +=
207                         "<br><span class=\"ctdl-msgsubject\">" + msg.subj + "</span>";
208                 }
209                 outmsg +=
210                   "</div><br>"                                                  // end header
211                 + "<div class=\"ctdl-msg-body\" id=\"" + mdiv + "_body\">"      // begin body
212                 + msg.text
213                 + "</div>"                                                      // end body
214                 + "</div>"                                                      // end content
215                 + "</div>"                                                      // end wrapper
216                 ;
217         }
218         catch(err) {
219                 outmsg = "<div class=\"ctdl-msg-wrapper\">" + err.message + "</div>";
220         }
221
222         div.innerHTML = outmsg;
223         return(div);
224 }
225
226
227 // Compose a references string using existing references plus the message being replied to
228 function compose_references(references, msgid) {
229         if (references.includes("@")) {
230                 refs = references + "|";
231         }
232         else {
233                 refs = "";
234         }
235         refs += msgid;
236
237         // If the resulting string is too big, we can trim it here
238         while (refs.length > 900) {
239                 r = refs.split("|");
240                 r.splice(1,1);          // remove the second element so we keep the root
241                 refs = r.join("|");
242         }
243         return refs;
244 }
245
246
247 // Open a reply box directly below a specific message
248 function open_reply_box(parent_div, is_quoted, references, msgid) {
249         let new_div = document.createElement("div");
250         let new_div_name = randomString();
251         new_div.id = new_div_name;
252
253         document.getElementById(parent_div).append(new_div);
254
255         replybox =
256           "<div class=\"ctdl-msg-wrapper ctdl-msg-reply\">"             // begin message wrapper
257         + "<div class=\"ctdl-avatar\">"                                 // begin avatar
258         + "<img src=\"/ctdl/u/" + current_user + "/userpic\" width=\"32\" "
259         + "onerror=\"this.parentNode.innerHTML='&lt;i class=&quot;fa fa-user-circle fa-2x&quot;&gt;&lt;/i&gt; '\">"
260         + "</div>"                                                      // end avatar
261         + "<div class=\"ctdl-msg-content\">"                            // begin content
262         + "<div class=\"ctdl-msg-header\">"                             // begin header
263         + "<span class=\"ctdl-msg-header-info\">"                       // begin header info on left side
264         + "<span class=\"ctdl-username\">"
265         + current_user                                                  // user = me !
266         + "</span>"
267         + "<span class=\"ctdl-msgdate\">"
268         + convertTimestamp(Date.now() / 1000)                           // the current date/time (temporary for display)
269         + "</span>"
270         + "</span>"                                                     // end header info on left side
271         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
272
273         + "<span class=\"ctdl-msg-button\">"                            // bold button
274         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('bold')\">"
275         + "<i class=\"fa fa-bold fa-fw\"></i>" 
276         + "</a></span>"
277
278         + "<span class=\"ctdl-msg-button\">"                            // italic button
279         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('italic')\">" 
280         + "<i class=\"fa fa-italic fa-fw\"></i>" 
281         + "</a></span>"
282
283         + "<span class=\"ctdl-msg-button\">"                            // list button
284         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('insertunorderedlist')\">"
285         + "<i class=\"fa fa-list fa-fw\"></i>" 
286         + "</a></span>"
287
288         + "<span class=\"ctdl-msg-button\">"                            // link button
289         + "<a href=\"javascript:void(0)\" onclick=\"forum_display_urlbox()\">"
290         + "<i class=\"fa fa-link fa-fw\"></i>" 
291         + "</a></span>"
292
293         + "</span>";                                                    // end buttons on right side
294         //if (msg.subj) {
295                 //replybox +=
296                 //"<br><span id=\"ctdl-subject\" class=\"ctdl-msgsubject\">" + "FIXME subject" + "</span>";
297         //}
298         //else {                                                                // hidden filed for empty subject
299                 replybox += "<span id=\"ctdl-subject\" style=\"display:none\"></span>";
300         //}
301         replybox +=
302           "</div><br>"                                                  // end header
303
304         + "<span id=\"ctdl-replyreferences\" style=\"display:none\">"   // hidden field for references
305         + compose_references(references,msgid) + "</span>"
306                                                                         // begin body
307         + "<div class=\"ctdl-msg-body\" id=\"ctdl-editor-body\" style=\"padding:5px;\" contenteditable=\"true\">"
308         + "\n";                                                         // empty initial content
309
310         if (is_quoted) {
311                 replybox += "<br><blockquote>"
312                         + document.getElementById(parent_div+"_body").innerHTML
313                         + "</blockquote>";
314         }
315
316         replybox +=
317           "</div>"                                                      // end body
318
319         + "<div class=\"ctdl-msg-header\">"                             // begin footer
320         + "<span class=\"ctdl-msg-header-info\">"                       // begin footer info on left side
321         + "&nbsp;"                                                      // (nothing here for now)
322         + "</span>"                                                     // end footer info on left side
323         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
324
325         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_save_message('" + new_div_name + "');\">"
326         + "<i class=\"fa fa-check\" style=\"color:green\"></i> "        // save button
327         + _("Post message")
328         + "</a></span>"
329
330         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_cancel_post('" +  new_div_name + "');\">"
331         + "<i class=\"fa fa-trash\" style=\"color:red\"></i> "          // cancel button
332         + _("Cancel")
333         + "</a></span>"
334
335         + "</span>"                                                     // end buttons on right side
336         + "</div><br>"                                                  // end footer
337
338
339         + "</div>"                                                      // end content
340         + "</div>"                                                      // end wrapper
341
342         + "<div id=\"forum_url_entry_box\" class=\"w3-modal\">"         // begin URL entry modal
343         + "     <div class=\"w3-modal-content w3-animate-top w3-card-4\">"
344         + "             <header class=\"w3-container w3-blue\"> "
345         + "                     <p><span>URL:</span></p>"
346         + "             </header>"
347         + "             <div class=\"w3-container w3-blue\">"
348         + "                     <input id=\"forum_txtFormatUrl\" placeholder=\"http://\" style=\"width:100%\">"
349         + "             </div>"
350         + "             <footer class=\"w3-container w3-blue\">"
351         + "                     <p><span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(true);\">"
352         + "                             <i class=\"fa fa-check\" style=\"color:green\"></i> "
353         +                               _("Save")
354         +                       "</a></span>"
355         + "                     <span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(false);\">"
356         + "                             <i class=\"fa fa-trash\" style=\"color:red\"></i> "
357         +                               _("Cancel")
358         +                       "</a></span></p>"
359         + "             </footer>"
360         + "             </div>"
361         + "     </div>"
362         + "     <input id=\"forum_selection_start\" style=\"display:none\"></input>"    // hidden fields
363         + "     <input id=\"forum_selection_end\" style=\"display:none\"></input>"      // to store selection range
364         + "</div>"                                                      // end URL entry modal
365         ;
366
367         document.getElementById(new_div_name).innerHTML = replybox;
368         document.getElementById(new_div_name).scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
369
370         // These actions must happen *after* the initial render loop completes.
371         setTimeout(function() {
372                 var tag = document.getElementById("ctdl-editor-body");
373                 tag.focus();                                            // sets the focus
374                 window.getSelection().collapse(tag.firstChild, 0);      // positions the cursor
375         }, 0);
376 }
377
378
379 // Abort a message post (it simply destroys the div)
380 function forum_cancel_post(div_name) {
381         document.getElementById(div_name).outerHTML = "";               // make it cease to exist
382 }
383
384
385 // Save the posted message to the server
386 function forum_save_message(editor_div_name) {
387
388         document.body.style.cursor = "wait";
389         wefw = (document.getElementById("ctdl-replyreferences").innerHTML).replaceAll("|","!"); // references (if present)
390         subj = document.getElementById("ctdl-subject").innerHTML;                               // subject (if present)
391
392         url = "/ctdl/r/" + escapeHTMLURI(current_room)
393                 + "/dummy_name_for_new_message"
394                 + "?wefw=" + wefw
395                 + "&subj=" + subj
396         boundary = randomString();
397         body_text =
398                 "--" + boundary + "\r\n"
399                 + "Content-type: text/html\r\n"
400                 + "Content-transfer-encoding: quoted-printable\r\n"
401                 + "\r\n"
402                 + quoted_printable_encode(
403                         "<html><body>" + document.getElementById("ctdl-editor-body").innerHTML + "</body></html>"
404                 ) + "\r\n"
405                 + "--" + boundary + "--\r\n"
406         ;
407
408         var request = new XMLHttpRequest();
409         request.open("PUT", url, true);
410         request.setRequestHeader("Content-type", "multipart/mixed; boundary=\"" + boundary + "\"");
411         request.onreadystatechange = function() {
412                 if (request.readyState == 4) {
413                         document.body.style.cursor = "default";
414                         if (Math.trunc(request.status / 100) == 2) {
415                                 headers = request.getAllResponseHeaders().split("\n");
416                                 for (var i in headers) {
417                                         if (headers[i].startsWith("etag: ")) {
418                                                 new_msg_num = headers[i].split(" ")[1];
419                                         }
420                                 }
421
422                                 // After saving the message, load it back from the server and replace the editor div with it.
423                                 replace_editor_with_final_message = async() => {
424                                         response = await fetch("/ctdl/r/" + escapeHTMLURI(current_room) + "/" + new_msg_num + "/json");
425                                         if (response.ok) {
426                                                 newly_posted_message = await(response.json());
427                                                 forum_render_one(newly_posted_message, document.getElementById(editor_div_name));
428                                         }
429                                 }
430                                 replace_editor_with_final_message();
431
432                         }
433                         else {
434                                 error_message = request.responseText;
435                                 if (error_message.length == 0) {
436                                         error_message = _("An error has occurred.");
437                                 }
438                                 alert(error_message);                                           // editor remains open
439                         }
440                 }
441         };
442         request.send(body_text);
443 }
444
445
446 // Bold, italics, etc.
447 function forum_format(command, value) {
448         document.execCommand(command, false, value);
449 }
450
451
452 // Make the URL entry box appear.
453 // When the user clicks into the URL box it will make the previous focus disappear, so we have to save it.
454 function forum_display_urlbox() {
455         document.getElementById("forum_selection_start").value = window.getSelection().anchorOffset;
456         document.getElementById("forum_selection_end").value = window.getSelection().focusOffset;
457         document.getElementById("forum_url_entry_box").style.display = "block";
458 }
459
460
461 // When the URL box is closed, this gets called.  do_save is true for Save, false for Cancel.
462 function forum_close_urlbox(do_save) {
463         if (do_save) {
464                 var tag = document.getElementById("ctdl-editor-body");
465                 var start_replace = document.getElementById("forum_selection_start").value;     // use saved selection range
466                 var end_replace = document.getElementById("forum_selection_end").value;
467                 new_text = tag.innerHTML.substring(0, start_replace)
468                         + "<a href=\"" + document.getElementById("forum_txtFormatUrl").value + "\">"
469                         + tag.innerHTML.substring(start_replace, end_replace)
470                         + "</a>"
471                         + tag.innerHTML.substring(end_replace);
472                 tag.innerHTML = new_text;
473         }
474         document.getElementById("forum_txtFormatUrl").value = "";                               // clear url box for next time
475         document.getElementById("forum_url_entry_box").style.display = "none";
476 }
477
478
479 // User has clicked the "Post message" button.  This is roughly the same as "reply" except there is no parent message.
480 function forum_entmsg() {
481         open_reply_box("ctdl-newmsg-here", false, "", "");
482 }