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