]> code.citadel.org Git - citadel.git/blob - webcit-ng/static/js/view_forum.js
babf0aa0658c851dcd01c2330c98efd1bcdc07b1
[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 nav buttons appear (post a new message, skip this room, goto next room)
105
106         document.getElementById("ctdl-newmsg-button").innerHTML = "<i class=\"fa fa-edit\"></i>" + _("Post message");
107         document.getElementById("ctdl-newmsg-button").style.display = "block";
108
109         document.getElementById("ctdl-skip-button").innerHTML = "<i class=\"fa fa-arrow-alt-circle-right\"></i>" + _("Skip this room");
110         document.getElementById("ctdl-skip-button").style.display = "block";
111
112         document.getElementById("ctdl-goto-button").innerHTML = "<i class=\"fa fa-arrow-circle-right\"></i>" + _("Goto next room");
113         document.getElementById("ctdl-goto-button").style.display = "block";
114 }
115
116
117 // Render a range of messages into the specified target div
118 function forum_render_messages(message_numbers, msgs_div_name, scroll_to) {
119
120         // Build an array of Promises and then wait for them all to resolve.
121         let num_msgs = message_numbers.length;
122         let msg_promises = Array.apply(null, Array(num_msgs));
123         for (i=0; i<num_msgs; ++i) {
124                 msg_promises[i] = fetch("/ctdl/r/" + escapeHTMLURI(current_room) + "/" + message_numbers[i] + "/json")
125                         .then(response => response.json())
126                         .catch((error) => {
127                                 response => null;
128                                 console.error('Error: ', error);
129                         })
130                 ;
131         }
132
133         // Here is the async function that waits for all the messages to be loaded, and then renders them.
134         fetch_msg_list = async() => {
135                 document.body.style.cursor = "wait";
136                 activate_loading_modal();
137                 await Promise.all(msg_promises);
138                 deactivate_loading_modal();
139                 document.body.style.cursor = "default";
140                 
141                 // At this point all of the Promises are resolved and we can render.
142                 // Note: "let" keeps "i" in scope even through the .then scope
143                 let scroll_to_div = null;
144                 for (let i=0; i<num_msgs; ++i) {
145                         msg_promises[i].then((one_message) => {
146                                 let new_msg_div = forum_render_one(one_message, null);
147                                 document.getElementById(msgs_div_name).append(new_msg_div);
148                                 if (message_numbers[i] == scroll_to) {
149                                         scroll_to_div = new_msg_div;
150                                 }
151                                 if (i == num_msgs - 1) {
152                                         scroll_to_div.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
153                                 }
154                         });
155                 }
156         }
157
158         fetch_msg_list();
159
160         // Make a note of the highest message number we saw, so we can mark it when we "Goto next room"
161         // (Compared to the text client, this is actually more like <A>bandon than <G>oto)
162         if ((num_msgs > 0) && (message_numbers[num_msgs-1] > last_seen)) {
163                 last_seen = message_numbers[num_msgs-1];
164         }
165 }
166
167
168 // Render a message.  Returns a div object.
169 function forum_render_one(msg, existing_div) {
170         let div = null;
171         if (existing_div != null) {                                             // If an existing div was supplied, render into it
172                 div = existing_div;
173         }
174         else {                                                                  // Otherwise, create a new one
175                 div = document.createElement("div");
176         }
177
178         mdiv = randomString();                                                  // Give the div a new name
179         div.id = mdiv;
180
181         try {
182                 outmsg =
183                   "<div class=\"ctdl-msg-wrapper\">"                            // begin message wrapper
184                 + "<div class=\"ctdl-avatar\" onClick=\"javascript:user_profile('" + msg.from + "');\">"
185                 + "<img src=\"/ctdl/u/" + msg.from + "/userpic\" width=\"32\" "
186                 + "onerror=\"this.parentNode.innerHTML='&lt;i class=&quot;fa fa-user-circle fa-2x&quot;&gt;&lt;/i&gt; '\">"
187                 + "</div>"                                                      // end avatar
188                 + "<div class=\"ctdl-msg-content\">"                            // begin content
189                 + "<div class=\"ctdl-msg-header\">"                             // begin header
190                 + "<span class=\"ctdl-msg-header-info\">"                       // begin header info on left side
191                 + "<span class=\"ctdl-username\" onClick=\"javascript:user_profile('" + msg.from + "');\">"
192                 + msg.from
193                 + "</a></span>"                                                 // end username
194                 + "<span class=\"ctdl-msgdate\">"
195                 + convertTimestamp(msg.time)
196                 + "</span>"                                                     // end msgdate
197                 + "</span>"                                                     // end header info on left side
198                 + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
199         
200                 + "<span class=\"ctdl-msg-button\">"                            // Reply
201                 + "<a href=\"javascript:open_reply_box('"+mdiv+"',false,'"+msg.wefw+"','"+msg.msgn+"');\">"
202                 + "<i class=\"fa fa-reply\"></i> " 
203                 + _("Reply")
204                 + "</a></span>"
205         
206                 + "<span class=\"ctdl-msg-button\">"                            // ReplyQuoted
207                 + "<a href=\"javascript:open_reply_box('"+mdiv+"',true,'"+msg.wefw+"','"+msg.msgn+"');\">"
208                 + "<i class=\"fa fa-comment\"></i> " 
209                 + _("ReplyQuoted")
210                 + "</a></span>"
211         
212                 + "<span class=\"ctdl-msg-button\"><a href=\"#\">"              // Delete , show only with permission FIXME
213                 + "<i class=\"fa fa-trash\"></i> " 
214                 + _("Delete")
215                 + "</a></span>"
216         
217                 + "</span>";                                                    // end buttons on right side
218                 if (msg.subj) {
219                         outmsg +=
220                         "<br><span class=\"ctdl-msgsubject\">" + msg.subj + "</span>";
221                 }
222                 outmsg +=
223                   "</div><br>"                                                  // end header
224                 + "<div class=\"ctdl-msg-body\" id=\"" + mdiv + "_body\">"      // begin body
225                 + msg.text
226                 + "</div>"                                                      // end body
227                 + "</div>"                                                      // end content
228                 + "</div>"                                                      // end wrapper
229                 ;
230         }
231         catch(err) {
232                 outmsg = "<div class=\"ctdl-msg-wrapper\">" + err.message + "</div>";
233         }
234
235         div.innerHTML = outmsg;
236         return(div);
237 }
238
239
240 // Compose a references string using existing references plus the message being replied to
241 function compose_references(references, msgid) {
242         if (references.includes("@")) {
243                 refs = references + "|";
244         }
245         else {
246                 refs = "";
247         }
248         refs += msgid;
249
250         // If the resulting string is too big, we can trim it here
251         while (refs.length > 900) {
252                 r = refs.split("|");
253                 r.splice(1,1);          // remove the second element so we keep the root
254                 refs = r.join("|");
255         }
256         return refs;
257 }
258
259
260 // Open a reply box directly below a specific message
261 function open_reply_box(parent_div, is_quoted, references, msgid) {
262         let new_div = document.createElement("div");
263         let new_div_name = randomString();
264         new_div.id = new_div_name;
265
266         document.getElementById(parent_div).append(new_div);
267
268         replybox =
269           "<div class=\"ctdl-msg-wrapper ctdl-msg-reply\">"             // begin message wrapper
270         + "<div class=\"ctdl-avatar\">"                                 // begin avatar
271         + "<img src=\"/ctdl/u/" + current_user + "/userpic\" width=\"32\" "
272         + "onerror=\"this.parentNode.innerHTML='&lt;i class=&quot;fa fa-user-circle fa-2x&quot;&gt;&lt;/i&gt; '\">"
273         + "</div>"                                                      // end avatar
274         + "<div class=\"ctdl-msg-content\">"                            // begin content
275         + "<div class=\"ctdl-msg-header\">"                             // begin header
276         + "<span class=\"ctdl-msg-header-info\">"                       // begin header info on left side
277         + "<span class=\"ctdl-username\">"
278         + current_user                                                  // user = me !
279         + "</span>"
280         + "<span class=\"ctdl-msgdate\">"
281         + convertTimestamp(Date.now() / 1000)                           // the current date/time (temporary for display)
282         + "</span>"
283         + "</span>"                                                     // end header info on left side
284         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
285
286         + "<span class=\"ctdl-msg-button\">"                            // bold button
287         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('bold')\">"
288         + "<i class=\"fa fa-bold fa-fw\"></i>" 
289         + "</a></span>"
290
291         + "<span class=\"ctdl-msg-button\">"                            // italic button
292         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('italic')\">" 
293         + "<i class=\"fa fa-italic fa-fw\"></i>" 
294         + "</a></span>"
295
296         + "<span class=\"ctdl-msg-button\">"                            // list button
297         + "<a href=\"javascript:void(0)\" onclick=\"forum_format('insertunorderedlist')\">"
298         + "<i class=\"fa fa-list fa-fw\"></i>" 
299         + "</a></span>"
300
301         + "<span class=\"ctdl-msg-button\">"                            // link button
302         + "<a href=\"javascript:void(0)\" onclick=\"forum_display_urlbox()\">"
303         + "<i class=\"fa fa-link fa-fw\"></i>" 
304         + "</a></span>"
305
306         + "</span>";                                                    // end buttons on right side
307         //if (msg.subj) {
308                 //replybox +=
309                 //"<br><span id=\"ctdl-subject\" class=\"ctdl-msgsubject\">" + "FIXME subject" + "</span>";
310         //}
311         //else {                                                                // hidden filed for empty subject
312                 replybox += "<span id=\"ctdl-subject\" style=\"display:none\"></span>";
313         //}
314         replybox +=
315           "</div><br>"                                                  // end header
316
317         + "<span id=\"ctdl-replyreferences\" style=\"display:none\">"   // hidden field for references
318         + compose_references(references,msgid) + "</span>"
319                                                                         // begin body
320         + "<div class=\"ctdl-msg-body\" id=\"ctdl-editor-body\" style=\"padding:5px;\" contenteditable=\"true\">"
321         + "\n";                                                         // empty initial content
322
323         if (is_quoted) {
324                 replybox += "<br><blockquote>"
325                         + document.getElementById(parent_div+"_body").innerHTML
326                         + "</blockquote>";
327         }
328
329         replybox +=
330           "</div>"                                                      // end body
331
332         + "<div class=\"ctdl-msg-header\">"                             // begin footer
333         + "<span class=\"ctdl-msg-header-info\">"                       // begin footer info on left side
334         + "&nbsp;"                                                      // (nothing here for now)
335         + "</span>"                                                     // end footer info on left side
336         + "<span class=\"ctdl-msg-header-buttons\">"                    // begin buttons on right side
337
338         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_save_message('" + new_div_name + "');\">"
339         + "<i class=\"fa fa-check\" style=\"color:green\"></i> "        // save button
340         + _("Post message")
341         + "</a></span>"
342
343         + "<span class=\"ctdl-msg-button\"><a href=\"javascript:forum_cancel_post('" +  new_div_name + "');\">"
344         + "<i class=\"fa fa-trash\" style=\"color:red\"></i> "          // cancel button
345         + _("Cancel")
346         + "</a></span>"
347
348         + "</span>"                                                     // end buttons on right side
349         + "</div><br>"                                                  // end footer
350
351
352         + "</div>"                                                      // end content
353         + "</div>"                                                      // end wrapper
354
355         + "<div id=\"forum_url_entry_box\" class=\"w3-modal\">"         // begin URL entry modal
356         + "     <div class=\"w3-modal-content w3-animate-top w3-card-4\">"
357         + "             <header class=\"w3-container w3-blue\"> "
358         + "                     <p><span>URL:</span></p>"
359         + "             </header>"
360         + "             <div class=\"w3-container w3-blue\">"
361         + "                     <input id=\"forum_txtFormatUrl\" placeholder=\"http://\" style=\"width:100%\">"
362         + "             </div>"
363         + "             <footer class=\"w3-container w3-blue\">"
364         + "                     <p><span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(true);\">"
365         + "                             <i class=\"fa fa-check\" style=\"color:green\"></i> "
366         +                               _("Save")
367         +                       "</a></span>"
368         + "                     <span class=\"ctdl-msg-button\"><a href=\"javascript:forum_close_urlbox(false);\">"
369         + "                             <i class=\"fa fa-trash\" style=\"color:red\"></i> "
370         +                               _("Cancel")
371         +                       "</a></span></p>"
372         + "             </footer>"
373         + "             </div>"
374         + "     </div>"
375         + "     <input id=\"forum_selection_start\" style=\"display:none\"></input>"    // hidden fields
376         + "     <input id=\"forum_selection_end\" style=\"display:none\"></input>"      // to store selection range
377         + "</div>"                                                      // end URL entry modal
378         ;
379
380         document.getElementById(new_div_name).innerHTML = replybox;
381         document.getElementById(new_div_name).scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
382
383         // These actions must happen *after* the initial render loop completes.
384         setTimeout(function() {
385                 var tag = document.getElementById("ctdl-editor-body");
386                 tag.focus();                                            // sets the focus
387                 window.getSelection().collapse(tag.firstChild, 0);      // positions the cursor
388         }, 0);
389 }
390
391
392 // Abort a message post (it simply destroys the div)
393 function forum_cancel_post(div_name) {
394         document.getElementById(div_name).outerHTML = "";               // make it cease to exist
395 }
396
397
398 // Save the posted message to the server
399 function forum_save_message(editor_div_name) {
400
401         document.body.style.cursor = "wait";
402         wefw = (document.getElementById("ctdl-replyreferences").innerHTML).replaceAll("|","!"); // references (if present)
403         subj = document.getElementById("ctdl-subject").innerHTML;                               // subject (if present)
404
405         url = "/ctdl/r/" + escapeHTMLURI(current_room)
406                 + "/dummy_name_for_new_message"
407                 + "?wefw=" + wefw
408                 + "&subj=" + subj
409         boundary = randomString();
410         body_text =
411                 "--" + boundary + "\r\n"
412                 + "Content-type: text/html\r\n"
413                 + "Content-transfer-encoding: quoted-printable\r\n"
414                 + "\r\n"
415                 + quoted_printable_encode(
416                         "<html><body>" + document.getElementById("ctdl-editor-body").innerHTML + "</body></html>"
417                 ) + "\r\n"
418                 + "--" + boundary + "--\r\n"
419         ;
420
421         var request = new XMLHttpRequest();
422         request.open("PUT", url, true);
423         request.setRequestHeader("Content-type", "multipart/mixed; boundary=\"" + boundary + "\"");
424         request.onreadystatechange = function() {
425                 if (request.readyState == 4) {
426                         document.body.style.cursor = "default";
427                         if (Math.trunc(request.status / 100) == 2) {
428                                 headers = request.getAllResponseHeaders().split("\n");
429                                 for (var i in headers) {
430                                         if (headers[i].startsWith("etag: ")) {
431                                                 new_msg_num = headers[i].split(" ")[1];
432                                         }
433                                 }
434
435                                 // After saving the message, load it back from the server and replace the editor div with it.
436                                 replace_editor_with_final_message = async() => {
437                                         response = await fetch("/ctdl/r/" + escapeHTMLURI(current_room) + "/" + new_msg_num + "/json");
438                                         if (response.ok) {
439                                                 newly_posted_message = await(response.json());
440                                                 forum_render_one(newly_posted_message, document.getElementById(editor_div_name));
441                                         }
442                                 }
443                                 replace_editor_with_final_message();
444
445                         }
446                         else {
447                                 error_message = request.responseText;
448                                 if (error_message.length == 0) {
449                                         error_message = _("An error has occurred.");
450                                 }
451                                 alert(error_message);                                           // editor remains open
452                         }
453                 }
454         };
455         request.send(body_text);
456 }
457
458
459 // Bold, italics, etc.
460 function forum_format(command, value) {
461         document.execCommand(command, false, value);
462 }
463
464
465 // Make the URL entry box appear.
466 // When the user clicks into the URL box it will make the previous focus disappear, so we have to save it.
467 function forum_display_urlbox() {
468         document.getElementById("forum_selection_start").value = window.getSelection().anchorOffset;
469         document.getElementById("forum_selection_end").value = window.getSelection().focusOffset;
470         document.getElementById("forum_url_entry_box").style.display = "block";
471 }
472
473
474 // When the URL box is closed, this gets called.  do_save is true for Save, false for Cancel.
475 function forum_close_urlbox(do_save) {
476         if (do_save) {
477                 var tag = document.getElementById("ctdl-editor-body");
478                 var start_replace = document.getElementById("forum_selection_start").value;     // use saved selection range
479                 var end_replace = document.getElementById("forum_selection_end").value;
480                 new_text = tag.innerHTML.substring(0, start_replace)
481                         + "<a href=\"" + document.getElementById("forum_txtFormatUrl").value + "\">"
482                         + tag.innerHTML.substring(start_replace, end_replace)
483                         + "</a>"
484                         + tag.innerHTML.substring(end_replace);
485                 tag.innerHTML = new_text;
486         }
487         document.getElementById("forum_txtFormatUrl").value = "";                               // clear url box for next time
488         document.getElementById("forum_url_entry_box").style.display = "none";
489 }
490
491
492 // User has clicked the "Post message" button.  This is roughly the same as "reply" except there is no parent message.
493 function forum_entmsg() {
494         open_reply_box("ctdl-newmsg-here", false, "", "");
495 }