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