]> code.citadel.org Git - citadel.git/blob - webcit-ng/static/js/view_forum.js
new license declaration text
[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                 + "<span class=\"ctdl-msg-button\"><a href=\"#\">"              // Delete , show only with permission FIXME
206                 + "<i class=\"fa fa-trash\"></i> " 
207                 + _("Delete")
208                 + "</a></span>"
209         
210                 + "</span>";                                                    // end buttons on right side
211                 if (msg.subj) {
212                         outmsg +=
213                         "<br><span class=\"ctdl-msgsubject\">" + msg.subj + "</span>";
214                 }
215                 outmsg +=
216                   "</div><br>"                                                  // end header
217                 + "<div class=\"ctdl-msg-body\" id=\"" + mdiv + "_body\">"      // begin body
218                 + msg.text
219                 + "</div>"                                                      // end body
220                 + "</div>"                                                      // end content
221                 + "</div>"                                                      // end wrapper
222                 ;
223         }
224         catch(err) {
225                 outmsg = "<div class=\"ctdl-msg-wrapper\">" + err.message + "</div>";
226         }
227
228         div.innerHTML = outmsg;
229         return(div);
230 }
231
232
233 // Compose a references string using existing references plus the message being replied to
234 function compose_references(references, msgid) {
235         if (references.includes("@")) {
236                 refs = references + "|";
237         }
238         else {
239                 refs = "";
240         }
241         refs += msgid;
242
243         // If the resulting string is too big, we can trim it here
244         while (refs.length > 900) {
245                 r = refs.split("|");
246                 r.splice(1,1);          // remove the second element so we keep the root
247                 refs = r.join("|");
248         }
249         return refs;
250 }
251
252
253 // Open a reply box directly below a specific message
254 function open_reply_box(parent_div, is_quoted, references, msgid) {
255         let new_div = document.createElement("div");
256         let new_div_name = randomString();
257         new_div.id = new_div_name;
258
259         document.getElementById(parent_div).append(new_div);
260
261         replybox =
262           "<div class=\"ctdl-msg-wrapper ctdl-msg-reply\">"             // begin message wrapper
263         + "<div class=\"ctdl-avatar\">"                                 // begin avatar
264         + "<img src=\"/ctdl/u/" + current_user + "/userpic\" width=\"32\" "
265         + "onerror=\"this.parentNode.innerHTML='&lt;i class=&quot;fa fa-user-circle fa-2x&quot;&gt;&lt;/i&gt; '\">"
266         + "</div>"                                                      // end avatar
267         + "<div class=\"ctdl-msg-content\">"                            // begin content
268         + "<div class=\"ctdl-msg-header\">"                             // begin header
269         + "<span class=\"ctdl-msg-header-info\">"                       // begin header info on left side
270         + "<span class=\"ctdl-username\">"
271         + current_user                                                  // user = me !
272         + "</span>"
273         + "<span class=\"ctdl-msgdate\">"
274         + convertTimestamp(Date.now() / 1000)                           // the current date/time (temporary for display)
275         + "</span>"
276         + "</span>"                                                     // end header info on left side
277         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
278
279         + "<span class=\"ctdl-msg-button\">"                            // bold button
280         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('bold')\">"
281         + "<i class=\"fa fa-bold fa-fw\"></i>" 
282         + "</a></span>"
283
284         + "<span class=\"ctdl-msg-button\">"                            // italic button
285         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('italic')\">" 
286         + "<i class=\"fa fa-italic fa-fw\"></i>" 
287         + "</a></span>"
288
289         + "<span class=\"ctdl-msg-button\">"                            // list button
290         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('insertunorderedlist')\">"
291         + "<i class=\"fa fa-list fa-fw\"></i>" 
292         + "</a></span>"
293
294         + "<span class=\"ctdl-msg-button\">"                            // link button
295         + "<a href=\"javascript:void(0)\" onclick=\"forum_display_urlbox()\">"
296         + "<i class=\"fa fa-link fa-fw\"></i>" 
297         + "</a></span>"
298
299         + "</span>";                                                    // end buttons on right side
300         //if (msg.subj) {
301                 //replybox +=
302                 //"<br><span id=\"ctdl-subject\" class=\"ctdl-msgsubject\">" + "FIXME subject" + "</span>";
303         //}
304         //else {                                                                // hidden filed for empty subject
305                 replybox += "<span id=\"ctdl-subject\" style=\"display:none\"></span>";
306         //}
307         replybox +=
308           "</div><br>"                                                  // end header
309
310         + "<span id=\"ctdl-replyreferences\" style=\"display:none\">"   // hidden field for references
311         + compose_references(references,msgid) + "</span>"
312                                                                         // begin body
313         + "<div class=\"ctdl-msg-body\" id=\"ctdl-editor-body\" style=\"padding:5px;\" contenteditable=\"true\">"
314         + "\n";                                                         // empty initial content
315
316         if (is_quoted) {
317                 replybox += "<br><blockquote>"
318                         + document.getElementById(parent_div+"_body").innerHTML
319                         + "</blockquote>";
320         }
321
322         replybox +=
323           "</div>"                                                      // end body
324
325         + "<div class=\"ctdl-msg-header\">"                             // begin footer
326         + "<span class=\"ctdl-msg-header-info\">"                       // begin footer info on left side
327         + "&nbsp;"                                                      // (nothing here for now)
328         + "</span>"                                                     // end footer info on left side
329         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
330
331         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_save_message('" + new_div_name + "');\">"
332         + "<i class=\"fa fa-check\" style=\"color:green\"></i> "        // save button
333         + _("Post message")
334         + "</a></span>"
335
336         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_cancel_post('" +  new_div_name + "');\">"
337         + "<i class=\"fa fa-trash\" style=\"color:red\"></i> "          // cancel button
338         + _("Cancel")
339         + "</a></span>"
340
341         + "</span>"                                                     // end buttons on right side
342         + "</div><br>"                                                  // end footer
343
344
345         + "</div>"                                                      // end content
346         + "</div>"                                                      // end wrapper
347
348         + "<div id=\"forum_url_entry_box\" class=\"w3-modal\">"         // begin URL entry modal
349         + "     <div class=\"w3-modal-content w3-animate-top w3-card-4\">"
350         + "             <header class=\"w3-container w3-blue\"> "
351         + "                     <p><span>URL:</span></p>"
352         + "             </header>"
353         + "             <div class=\"w3-container w3-blue\">"
354         + "                     <input id=\"forum_txtFormatUrl\" placeholder=\"http://\" style=\"width:100%\">"
355         + "             </div>"
356         + "             <footer class=\"w3-container w3-blue\">"
357         + "                     <p><span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(true);\">"
358         + "                             <i class=\"fa fa-check\" style=\"color:green\"></i> "
359         +                               _("Save")
360         +                       "</a></span>"
361         + "                     <span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(false);\">"
362         + "                             <i class=\"fa fa-trash\" style=\"color:red\"></i> "
363         +                               _("Cancel")
364         +                       "</a></span></p>"
365         + "             </footer>"
366         + "             </div>"
367         + "     </div>"
368         + "     <input id=\"forum_selection_start\" style=\"display:none\"></input>"    // hidden fields
369         + "     <input id=\"forum_selection_end\" style=\"display:none\"></input>"      // to store selection range
370         + "</div>"                                                      // end URL entry modal
371         ;
372
373         document.getElementById(new_div_name).innerHTML = replybox;
374         document.getElementById(new_div_name).scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
375
376         // These actions must happen *after* the initial render loop completes.
377         setTimeout(function() {
378                 var tag = document.getElementById("ctdl-editor-body");
379                 tag.focus();                                            // sets the focus
380                 window.getSelection().collapse(tag.firstChild, 0);      // positions the cursor
381         }, 0);
382 }
383
384
385 // Abort a message post (it simply destroys the div)
386 function forum_cancel_post(div_name) {
387         document.getElementById(div_name).outerHTML = "";               // make it cease to exist
388 }
389
390
391 // Save the posted message to the server
392 function forum_save_message(editor_div_name) {
393
394         document.body.style.cursor = "wait";
395         wefw = (document.getElementById("ctdl-replyreferences").innerHTML).replaceAll("|","!"); // references (if present)
396         subj = document.getElementById("ctdl-subject").innerHTML;                               // subject (if present)
397
398         url = "/ctdl/r/" + escapeHTMLURI(current_room)
399                 + "/dummy_name_for_new_message"
400                 + "?wefw=" + wefw
401                 + "&subj=" + subj
402         boundary = randomString();
403         body_text =
404                 "--" + boundary + "\r\n"
405                 + "Content-type: text/html\r\n"
406                 + "Content-transfer-encoding: quoted-printable\r\n"
407                 + "\r\n"
408                 + quoted_printable_encode(
409                         "<html><body>" + document.getElementById("ctdl-editor-body").innerHTML + "</body></html>"
410                 ) + "\r\n"
411                 + "--" + boundary + "--\r\n"
412         ;
413
414         var request = new XMLHttpRequest();
415         request.open("PUT", url, true);
416         request.setRequestHeader("Content-type", "multipart/mixed; boundary=\"" + boundary + "\"");
417         request.onreadystatechange = function() {
418                 if (request.readyState == 4) {
419                         document.body.style.cursor = "default";
420                         if (Math.trunc(request.status / 100) == 2) {
421                                 headers = request.getAllResponseHeaders().split("\n");
422                                 for (var i in headers) {
423                                         if (headers[i].startsWith("etag: ")) {
424                                                 new_msg_num = headers[i].split(" ")[1];
425                                         }
426                                 }
427
428                                 // After saving the message, load it back from the server and replace the editor div with it.
429                                 replace_editor_with_final_message = async() => {
430                                         response = await fetch("/ctdl/r/" + escapeHTMLURI(current_room) + "/" + new_msg_num + "/json");
431                                         if (response.ok) {
432                                                 newly_posted_message = await(response.json());
433                                                 forum_render_one(newly_posted_message, document.getElementById(editor_div_name));
434                                         }
435                                 }
436                                 replace_editor_with_final_message();
437
438                         }
439                         else {
440                                 error_message = request.responseText;
441                                 if (error_message.length == 0) {
442                                         error_message = _("An error has occurred.");
443                                 }
444                                 alert(error_message);                                           // editor remains open
445                         }
446                 }
447         };
448         request.send(body_text);
449 }
450
451
452 // Bold, italics, etc.
453 function forum_format(command, value) {
454         document.execCommand(command, false, value);
455 }
456
457
458 // Make the URL entry box appear.
459 // When the user clicks into the URL box it will make the previous focus disappear, so we have to save it.
460 function forum_display_urlbox() {
461         document.getElementById("forum_selection_start").value = window.getSelection().anchorOffset;
462         document.getElementById("forum_selection_end").value = window.getSelection().focusOffset;
463         document.getElementById("forum_url_entry_box").style.display = "block";
464 }
465
466
467 // When the URL box is closed, this gets called.  do_save is true for Save, false for Cancel.
468 function forum_close_urlbox(do_save) {
469         if (do_save) {
470                 var tag = document.getElementById("ctdl-editor-body");
471                 var start_replace = document.getElementById("forum_selection_start").value;     // use saved selection range
472                 var end_replace = document.getElementById("forum_selection_end").value;
473                 new_text = tag.innerHTML.substring(0, start_replace)
474                         + "<a href=\"" + document.getElementById("forum_txtFormatUrl").value + "\">"
475                         + tag.innerHTML.substring(start_replace, end_replace)
476                         + "</a>"
477                         + tag.innerHTML.substring(end_replace);
478                 tag.innerHTML = new_text;
479         }
480         document.getElementById("forum_txtFormatUrl").value = "";                               // clear url box for next time
481         document.getElementById("forum_url_entry_box").style.display = "none";
482 }
483
484
485 // User has clicked the "Post message" button.  This is roughly the same as "reply" except there is no parent message.
486 function forum_entmsg() {
487         open_reply_box("ctdl-newmsg-here", false, "", "");
488 }