]> code.citadel.org Git - citadel.git/blob - webcit-ng/static/js/view_mail.js
6db894d130d40c5cd8e0b5da81dbc144a6327287
[citadel.git] / webcit-ng / static / js / view_mail.js
1 // This module handles the view for "mailbox" rooms.
2 //
3 // Copyright (c) 2016-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or
6 // disclosure are subject to the GNU General Public License v3.
7
8
9 var displayed_message = 0;                                                      // ID of message currently being displayed
10 var RefreshMailboxInterval;                                                     // We store our refresh timer here
11 var highest_mailnum;                                                            // This is used to detect newly arrived mail
12 var newmail_notify = {
13         NO  : 0,                                                                // do not perform new mail notifications
14         YES : 1                                                                 // yes, perform new mail notifications
15 };
16 var uploads_in_progress = 0;
17 var uploads = [] ;                                                              // everything the user has uploaded
18
19
20 // This is the async back end for mail_delete_selected()
21 mail_delete_func = async(table, row) => {
22         let m = parseInt(row["id"].substring(12));                              // derive msgnum from row id
23
24         if (is_trash_folder) {
25                 response = await fetch(
26                         "/ctdl/r/" + escapeHTMLURI(current_room) + "/" + m,
27                         {
28                                 method: "DELETE"                                // If this is the Trash folder, delete permanently
29                         },
30                 );
31         }
32         else {
33                 response = await fetch(
34                         "/ctdl/r/" + escapeHTMLURI(current_room) + "/" + m,
35                         {
36                                 method: "MOVE",                                 // Otherwise, move to the Trash folder
37                                 headers: { "Destination" : "/ctdl/r/_TRASH_" }
38                         },
39                 );
40         }
41
42         if (response.ok) {                              // If the server accepted the delete, blank out the message div
43                 table.deleteRow(row.rowIndex);
44                 if (m == displayed_message) {
45                         document.getElementById("ctdl-mailbox-reading-pane").innerHTML = "";
46                         displayed_message = 0;
47                 }
48         }
49 }
50
51
52 // Delete the selected messages (can be activated by mouse click or keypress)
53 function mail_delete_selected() {
54         let table = document.getElementById("ctdl-onscreen-mailbox");
55         let i, row;
56         for (i=0; row=table.rows[i]; ++i) {
57                 if (row.classList.contains("ctdl-mail-selected")) {
58                         mail_delete_func(table, row);
59                 }
60         }
61 }
62
63
64 // Handler function for keypresses detected while the mail view is displayed.  Mainly for deleting messages.
65 function mail_keypress(event) {
66
67         // If the "ctdl-mailbox-pane" no longer exists, the user has navigated to a different part of the site,
68         // so cancel the event listener.
69         try {
70                 document.getElementById("ctdl-mailbox-pane").innerHTML;
71         }
72         catch {
73                 document.removeEventListener("keydown", mail_keypress);
74                 return;
75         }
76
77         const key = event.key.toLowerCase();
78         if (key == "delete") {
79                 mail_delete_selected();
80         }
81
82 }
83
84
85 // Handler function for dragging email messages to other folders
86 function mail_dragstart(event) {
87         let i;
88         let count = 0;
89         let table = document.getElementById("ctdl-onscreen-mailbox");
90         let messages_being_dragged = [] ;
91
92         if (event.target.classList.contains("ctdl-mail-selected")) {
93                 // The row being dragged IS selected.  See if any OTHER rows are selected, and they will come along for the ride.
94                 for (i=1; row=table.rows[i]; ++i) {
95                         if (row.classList.contains("ctdl-mail-selected")) {
96                                 count = count + 1;
97                                 messages_being_dragged.push(row.id);    // Tell the clipboard what's being moved.
98                         }
99                 }
100         }
101         else {
102                 // The row being dragged is NOT selected.  It will be dragged on its own, ignoring the selected rows.
103                 count = 1;
104                 messages_being_dragged.push(event.target.id);           // Tell the clipboard what's being moved.
105         }
106
107         // Set the custom drag image to an envelope + number of messages being dragged
108         d = document.getElementById("ctdl_draggo");
109         d.innerHTML = "<font size='+2'><i class='fa fa-envelope' style='color: red'></i> " + count + "</font>"
110         event.dataTransfer.setDragImage(d, 0, 0);
111         event.dataTransfer.setData("text", messages_being_dragged);
112 }
113
114
115 // Render reply address for a message (FIXME figure out how to deal with "reply-to:")
116 function reply_addr(msg) {
117         //if (msg.locl) {
118                 //return([msg.from]);
119         //}
120         //else {
121                 return([msg.from + " &lt;" + msg.rfca + "&gt;"]);
122         //}
123 }
124
125
126 // Render the To: recipients for a reply-all operation
127 function replyall_to(msg) {
128         return([...reply_addr(msg), ...msg.rcpt]);
129 }
130
131
132 // Render a message into the mailbox view
133 // (We want the message number and the message itself because we need to keep the msgnum for reply purposes)
134 function mail_render_one(msgnum, msg, target_div, include_controls) {
135         let div = "";
136         try {
137                 outmsg =
138                   "<div class=\"ctdl-mmsg-wrapper\">"                           // begin message wrapper
139                 ;
140
141                 if (include_controls) {                                         // omit controls if this is a pull quote
142                         outmsg +=
143                           render_userpic(msg.from)                              // user avatar
144                         + "<div class=\"ctdl-mmsg-content\">"                   // begin content
145                         + "<div class=\"ctdl-msg-header\">"                     // begin header
146                         + "<span class=\"ctdl-msg-header-info\">"               // begin header info on left side
147                         + render_msg_author(msg, views.VIEW_MAILBOX)
148                         + "<span class=\"ctdl-msgdate\">"
149                         + string_timestamp(msg.time,0)
150                         + "</span>"                                             // end msgdate
151                         + "</span>"                                             // end header info on left side
152                         + "<span class=\"ctdl-msg-header-buttons\">"            // begin buttons on right side
153                 
154                         + "<span class=\"ctdl-msg-button\">"                    // Reply (mail is always Quoted)
155                         + "<a href=\"javascript:mail_compose(true,'"+msg.wefw+"','"+msgnum+"', reply_addr(msg), [], 'Re: '+msg.subj);\">"
156                         + "<i class=\"fa fa-reply\"></i> " 
157                         + _("Reply")
158                         + "</a></span>"
159                 
160                         + "<span class=\"ctdl-msg-button\">"                    // Reply-All (mail is always Quoted)
161                         + "<a href=\"javascript:mail_compose(true,'"+msg.wefw+"','"+msgnum+"', replyall_to(msg), msg.cccc, 'Re: '+msg.subj);\">"
162                         + "<i class=\"fa fa-reply-all\"></i> " 
163                         + _("ReplyAll")
164                         + "</a></span>";
165                 
166                         if (can_delete_messages) {
167                                 outmsg +=
168                                 "<span class=\"ctdl-msg-button\">"
169                                 + "<a href=\"javascript:forum_delete_message('"+div+"','"+msg.msgnum+"');\">"
170                                 + "<i class=\"fa fa-trash\"></i> " 
171                                 + _("Delete")
172                                 + "</a></span>";
173                         }
174                 
175                         outmsg +=
176                           "</span>";                                            // end buttons on right side
177
178                         // Display the To: recipients, if any are present
179                         if (msg.rcpt) {
180                                 outmsg += "<br><span>" + _("To:") + " ";
181                                 for (let r=0; r<msg.rcpt.length; ++r) {
182                                         if (r != 0) {
183                                                 outmsg += ", ";
184                                         }
185                                         outmsg += escapeHTML(msg.rcpt[r]);
186                                 }
187                                 outmsg += "</span>";
188                         }
189
190                         // Display the Cc: recipients, if any are present
191                         if (msg.cccc) {
192                                 outmsg += "<br><span>" + _("Cc:") + " ";
193                                 for (let r=0; r<msg.cccc.length; ++r) {
194                                         if (r != 0) {
195                                                 outmsg += ", ";
196                                         }
197                                         outmsg += escapeHTML(msg.cccc[r]);
198                                 }
199                                 outmsg += "</span>";
200                         }
201
202                         // Display a subject line, but only if the message has a subject (internal Citadel messages often don't)
203                         if (msg.subj) {
204                                 outmsg +=
205                                 "<br><span class=\"ctdl-msgsubject\">" + msg.subj + "</span>";
206                         }
207
208                         outmsg +=
209                           "</div>";                                             // end header
210                 }
211
212                 // Display attachments, if any are present
213                 if (msg.part) {
214                         let display_attachments = 0;
215                         for (let r=0; r<msg.part.length; ++r) {
216                                 if (msg.part[r].disp == "attachment") {
217                                         if (display_attachments == 0) {
218                                                 outmsg += "<ul>";
219                                         }
220                                         display_attachments += 1;
221                                         outmsg += "<li>"
222                                                 + "<a href=\"/ctdl/r/" + escapeHTMLURI(current_room) + "/" + msgnum + "/" + msg.part[r].partnum + "/" + escapeHTMLURI(msg.part[r].filename) + "\" target=\"_blank\">"
223                                                 + "<i class=\"fa fa-paperclip\"></i>&nbsp;" + msg.part[r].partnum + ": " + msg.part[r].filename
224                                                 + " (" + msg.part[r].len + " " + _("bytes") + ")"
225                                                 + "</a>"
226                                                 + "</li>";
227                                 }
228                         }
229                         if (display_attachments > 0) {
230                                 outmsg += "</ul><br>";
231                         }
232                 }
233
234
235                 outmsg +=
236                   "<div class=\"ctdl-msg-body\" id=\"" + div + "_body\">"       // begin body
237                 + msg.text
238                 + "</div>"                                                      // end body
239                 + "</div>"                                                      // end content
240                 + "</div>"                                                      // end wrapper
241                 ;
242         }
243         catch(err) {
244                 outmsg = "<div class=\"ctdl-mmsg-wrapper\">" + err.message + "</div>";
245         }
246
247         target_div.innerHTML = outmsg;
248 }
249
250
251 // display an individual message (note: this wants an actual div object, not a string containing the name of a div)
252 function mail_display_message(msgnum, target_div, include_controls) {
253         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/" + msgnum + "/json";
254         mail_fetch_msg = async() => {
255                 response = await fetch(url);
256                 msg = await(response.json());
257                 if (response.ok) {
258                         mail_render_one(msgnum, msg, target_div, include_controls);
259                 }
260         }
261         mail_fetch_msg();
262 }
263
264
265 // A message has been selected...
266 function click_message(event, msgnum) {
267         var table = document.getElementById("ctdl-onscreen-mailbox");
268         var i, m, row;
269
270         // ctrl + click = toggle an individual message without changing existing selection
271         if (event.ctrlKey) {
272                 document.getElementById("ctdl-msgsum-" + msgnum).classList.toggle("ctdl-mail-selected");
273         }
274
275         // shift + click = select a range of messages (start with row 1 because row 0 is the header)
276         else if (event.shiftKey) {
277                 for (i=1; row=table.rows[i]; ++i) {
278                         m = parseInt(row["id"].substring(12));                          // derive msgnum from row id
279                         if (
280                                 ((msgnum >= displayed_message) && (m >= displayed_message) && (m <= msgnum))
281                                 || ((msgnum <= displayed_message) && (m <= displayed_message) && (m >= msgnum))
282                         ) {
283                                 row.classList.add("ctdl-mail-selected");
284                         }
285                         else {
286                                 row.classList.remove("ctdl-mail-selected");
287                         }
288                 }
289         }
290
291         // click + no modifiers = select one message and unselect all others (start with row 1 because row 0 is the header)
292         else {
293                 for (i=1; row=table.rows[i]; ++i) {
294                         if (row["id"] == "ctdl-msgsum-" + msgnum) {
295                                 row.classList.add("ctdl-mail-selected");
296                         }
297                         else {
298                                 row.classList.remove("ctdl-mail-selected");
299                         }
300                 }
301         }
302
303         // display the message if it isn't already displayed
304         if (displayed_message != msgnum) {
305                 displayed_message = msgnum;
306                 mail_display_message(msgnum, document.getElementById("ctdl-mailbox-reading-pane"), 1);
307         }
308 }
309
310
311 // render one row in the mailbox table (this could be called from one of several places)
312 function mail_render_row(msg, is_selected) {
313         let row = "<tr "
314                 + "id=\"ctdl-msgsum-" + msg["msgnum"] + "\" "
315                 + (is_selected ? "class=\"ctdl-mail-selected\" " : "")
316                 + "onClick=\"click_message(event," + msg["msgnum"] + ");\""
317                 + "onselectstart=\"return false;\" "
318                 + "draggable=\"true\" "
319                 + "ondragstart=\"mail_dragstart(event)\" "
320                 + ">"
321                 + "<td class=\"ctdl-mail-subject\">" + msg["subject"] + "</td>"
322                 + "<td class=\"ctdl-mail-sender\">" + msg["author"] + "</td>"
323                 + "<td class=\"ctdl-mail-date\">" + string_timestamp(msg["time"],1) + "</td>"
324                 + "<td class=\"ctdl-mail-msgnum\">" + msg["msgnum"] + "</td>"
325                 + "</tr>";
326         return(row);
327 }
328
329
330 // RENDERER FOR THIS VIEW
331 function view_render_mail() {
332         // Put the "enter new message" button into the topbar
333         document.getElementById("ctdl-newmsg-button").innerHTML = "<i class=\"fa fa-edit\"></i>" + _("Write mail");
334         document.getElementById("ctdl-newmsg-button").style.display = "block";
335
336         // Put the "delete message(s)" button into the topbar
337         let d = document.getElementById("ctdl-delete-button");
338         d.innerHTML = "<i class=\"fa fa-trash\"></i>" + _("Delete");
339         d.style.display = "block";
340         //d.addEventListener("click", mail_delete_selected);
341
342         document.getElementById("ctdl-main").innerHTML
343                 = "<div id=\"ctdl-mailbox-grid-container\" class=\"ctdl-mailbox-grid-container\">"
344                 + "<div id=\"ctdl-mailbox-pane\" class=\"ctdl-mailbox-pane\"></div>"
345                 + "<div id=\"ctdl-mailbox-reading-pane\" class=\"ctdl-mailbox-reading-pane\"></div>"
346                 + "</div>"
347         ;
348
349         highest_mailnum = 0;                                    // Keep track of highest message number to track newly arrived messages
350         render_mailbox_display(newmail_notify.NO);
351         try {                                                   // if this was already set up, clear it so there aren't multiple
352                 clearInterval(RefreshMailboxInterval);
353         }
354         catch {
355         }
356         RefreshMailboxInterval = setInterval(refresh_mail_display, 10000);
357 }
358
359
360 // Refresh the mailbox, either for the first time or whenever needed
361 function refresh_mail_display() {
362         // If the "ctdl-mailbox-pane" no longer exists, the user has navigated to a different part of the site,
363         // so cancel the refresh.
364         try {
365                 document.getElementById("ctdl-mailbox-pane").innerHTML;
366         }
367         catch {
368                 clearInterval(RefreshMailboxInterval);
369                 return;
370         }
371
372         // Ask the server if the room has been written to since our last look at it.
373         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/stat";
374         fetch_stat = async() => {
375                 response = await fetch(url);
376                 stat = await(response.json());
377                 if (stat.room_mtime > room_mtime) {                     // FIXME commented out to force refreshes
378                         room_mtime = stat.room_mtime;
379                         render_mailbox_display(newmail_notify.YES);
380                 }
381         }
382         fetch_stat();
383 }
384
385
386 // This is where the rendering of the message list in the mailbox view is performed.
387 // Set notify to newmail_notify.NO or newmail_notify.YES depending on whether we are interested in the arrival of new messages.
388 function render_mailbox_display(notify) {
389
390         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/mailbox";
391         fetch_mailbox = async() => {
392                 response = await fetch(url);
393                 msgs = await(response.json());
394                 if (response.ok) {
395                         var previously_selected = [];
396                         var oldtable = document.getElementById("ctdl-onscreen-mailbox");
397                         var i, row;
398
399                         // If one or more messages was already selected, remember them so we can re-select them
400                         if ( (displayed_message > 0) && (oldtable) ) {
401                                 for (i=0; row=oldtable.rows[i]; ++i) {
402                                         if (row.classList.contains("ctdl-mail-selected")) {
403                                                 previously_selected.push(parseInt(row["id"].substring(12)));
404                                         }
405                                 }
406                         }
407
408                         // begin rendering the mailbox table
409                         box =   "<table id=\"ctdl-onscreen-mailbox\" class=\"ctdl-mailbox-table\" width=100%><tr>"
410                                 + "<th>" + _("Subject") + "</th>"
411                                 + "<th>" + _("Sender") + "</th>"
412                                 + "<th>" + _("Date") + "</th>"
413                                 + "<th>#</th>"
414                                 + "</tr>";
415
416                         for (let i=0; i<msgs.length; ++i) {
417                                 let m = parseInt(msgs[i].msgnum);
418                                 let s = (previously_selected.includes(m));
419                                 box += mail_render_row(msgs[i], s);
420                                 if (m > highest_mailnum) {
421                                         highest_mailnum = m;
422                                 }
423                         }
424
425                         box +=  "</table>";
426                         document.getElementById("ctdl-mailbox-pane").innerHTML = box;
427                         document.addEventListener("keydown", mail_keypress);
428                 }
429         }
430         fetch_mailbox();
431 }
432
433
434 // Compose a new mail message (called by the Reply button here, or by the dispatcher in views.js)
435 function mail_compose(is_quoted, references, quoted_msgnum, m_to, m_cc, m_subject) {
436         // m_to will be an array of zero or more recipients for the To: field.  Convert it to a string.
437         if (m_to) {
438                 m_to = Array.from(new Set(m_to));       // remove dupes
439                 m_to_str = "";
440                 for (i=0; i<m_to.length; ++i) {
441                         if (i > 0) {
442                                 m_to_str += ", ";
443                         }
444                         m_to_str += m_to[i].replaceAll("<", "&lt;").replaceAll(">", "&gt;");
445                 }
446         }
447         else {
448                 m_to_str = "";
449         }
450
451         // m_to will be an array of zero or more recipients for the Cc: field.  Convert it to a string.
452         if (m_cc) {
453                 m_cc = Array.from(new Set(m_cc));       // remove dupes
454                 m_cc_str = "";
455                 for (i=0; i<m_cc.length; ++i) {
456                         if (i > 0) {
457                                 m_cc_str += ", ";
458                         }
459                         m_cc_str += m_cc[i].replaceAll("<", "&lt;").replaceAll(">", "&gt;");
460                 }
461         }
462         else {
463                 m_cc_str = "";
464         }
465
466         quoted_div_name = randomString();
467
468         // Make the "Write mail" button disappear.  We're already there!
469         document.getElementById("ctdl-newmsg-button").style.display = "none";
470
471         // is_quoted    true or false depending on whether the user selected "reply quoted" (is this appropriate for mail?)
472         // references   list of references, be sure to use this in a reply
473         // msgid        if a reply, the msgid of the most recent message in the chain, the one to which we are replying
474
475         // Now display the screen.  (Yes, I combined regular strings + template literals.  I just learned template literals.  Converting to all template literals would be fine.)
476         compose_screen =
477                 // Hidden values that we are storing right here in the document tree for later
478                   "<input id=\"ctdl_mc_is_quoted\" style=\"display:none\" value=\"" + is_quoted + "\"></input>"
479                 + "<input id=\"ctdl_mc_references\" style=\"display:none\" value=\"" + references + "\"></input>"
480
481                 // Header fields, the composition window, and the button bar are arranged using a Grid layout.
482                 + "<div id=\"ctdl-compose-mail\" class=\"ctdl-compose-mail\">"
483
484                 // Visible To: field, plus a box to make the CC/BCC lines appear
485                 + "<div class=\"ctdl-compose-to-label\">" + _("To:") + "</div>"
486                 + "<div class=\"ctdl-compose-to-line\">"
487                 + "<div class=\"ctdl-compose-to-field\" id=\"ctdl-compose-to-field\" contenteditable=\"true\">" + m_to_str + "</div>"
488                 + "<div class=\"ctdl-cc-bcc-buttons ctdl-msg-button\" id=\"ctdl-cc-bcc-buttons\" "
489                 + "onClick=\"make_cc_bcc_visible()\">"
490                 + _("CC:") + "/" + _("BCC:") + "</div>"
491                 + "</div>"
492
493                 // CC/BCC
494                 + "<div class=\"ctdl-compose-cc-label\" id=\"ctdl-compose-cc-label\">" + _("CC:") + "</div>"
495                 + "<div class=\"ctdl-compose-cc-field\" id=\"ctdl-compose-cc-field\" contenteditable=\"true\">" + m_cc_str + "</div>"
496                 + "<div class=\"ctdl-compose-bcc-label\" id=\"ctdl-compose-bcc-label\">" + _("BCC:") + "</div>"
497                 + "<div class=\"ctdl-compose-bcc-field\" id=\"ctdl-compose-bcc-field\" contenteditable=\"true\"></div>"
498
499                 // Visible subject field
500                 + "<div class=\"ctdl-compose-subject-label\">" + _("Subject:") + "</div>"
501                 + "<div class=\"ctdl-compose-subject-field\" id=\"ctdl-compose-subject-field\" contenteditable=\"true\">" + m_subject + "</div>"
502
503                 // Message composition box
504                 + "<div class=\"ctdl-compose-message-box\" id=\"ctdl-editor-body\" contenteditable=\"true\">"
505         ;
506
507         if (is_quoted) {
508                 compose_screen += "<br><br><blockquote><div id=\"" + quoted_div_name + "\"></div></blockquote>";
509         }
510
511         // The button bar is a Grid element, and is also a Flexbox container.
512         compose_screen += `
513                 </div>
514                 <div class="ctdl-compose-toolbar">
515                 <span class="ctdl-msg-button" onclick="mail_send_message()"><i class="fa fa-paper-plane" style="color:green"></i> ${_("Send message")} </span>
516                 <span class="ctdl-msg-button"> ${_("Save to Drafts")} </span>
517                 <span class="ctdl-msg-button" onClick="show_or_hide_attachments()"><i class="fa fa-paperclip" style="color:grey"></i> ${_("Attachments:")} <span id="ctdl_num_attachments"> ${uploads.length} </span></span>
518                 <span class="ctdl-msg-button">  ${_("Contacts")} </span>
519                 <span class="ctdl-msg-button" onClick="document.getElementById('ctdl-upload').style.display='none';uploads=[];gotoroom(current_room)"><i class="fa fa-trash" style="color:red"></i> ${_("Cancel")} </span>
520                 </div>`
521         ;
522
523         document.getElementById("ctdl-main").innerHTML = compose_screen;
524         mail_display_message(quoted_msgnum, document.getElementById(quoted_div_name), 0);
525         if (m_cc) {
526                 document.getElementById("ctdl-compose-cc-label").style.display = "block";
527                 document.getElementById("ctdl-compose-cc-field").style.display = "block";
528         }
529
530         activate_uploads("ctdl-editor-body");
531 }
532
533
534 // Turn the specified div into a place where we can upload.  (Note: permanently changes the drag-and-drop behavior of that div.)
535 function activate_uploads(parent_div) {
536                 document.getElementById(parent_div).innerHTML += `
537                         <div class="ctdl-upload" id="ctdl-upload">
538                                 <div id="ctdl_attachments_title" class="ctdl-compose-attachments-title">
539                                         <div><h1><i class="fa fa-paperclip" style="color:grey"></i>` + _("Attachments:") + ` <span id="num_attachments">` + uploads.length + `</span></h1></div>
540                                         <div><h1><i class="fas fa-window-close" style="color:red" onClick="show_or_hide_attachments()"></i></h1></div>
541                                 </div>
542                                 <br>
543                                 <ul id="ctdl-upload_list">
544                                 </ul>
545                                 <br>
546                                 <div id="drop-area" class="ctdl-upload-drop-area">
547                                         <form class="my-form">
548                                                 <p>${_("Drop files here to upload")}</p>
549                                                 <input type="file" id="fileElem" multiple accept="*/*" onChange="handle_upload_files(this.files)">
550                                         </form>
551                                 </div>
552                         </div>
553                 `;
554
555                 // activate drag and drop (shamelessly swiped from https://www.smashingmagazine.com/2018/01/drag-drop-file-uploader-vanilla-js/ )
556                 let dropArea = document.getElementById(parent_div);
557                 ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
558                         dropArea.addEventListener(eventName, upload_prevent_defaults, false)
559                 })
560                 ;["dragenter", "dragover"].forEach(eventName => {
561                         dropArea.addEventListener(eventName, upload_highlight, false)
562                 })
563                 ;['dragleave', 'drop'].forEach(eventName => {
564                         dropArea.addEventListener(eventName, upload_unhighlight, false)
565                 })
566                 dropArea.addEventListener('drop', upload_handle_drop, false);
567 }
568
569
570 // prevent drag and drop events from propagating up through the DOM
571 function upload_prevent_defaults(e) {
572         e.preventDefault();
573         e.stopPropagation();
574 }
575
576
577 function upload_handle_drop(e) {
578         let dt = e.dataTransfer;
579         let files = dt.files;
580         handle_upload_files(files);
581 }
582
583
584 function handle_upload_files(files) {
585         ([...files]).forEach(upload_file)
586 }
587
588
589 function upload_file(file) {
590         var url = '/ctdl/a/upload';
591         var xhr = new XMLHttpRequest();
592         var formData = new FormData();
593         xhr.open('POST', url, true);
594       
595         xhr.addEventListener('readystatechange', function(e) {
596                 if (xhr.readyState == 4 && xhr.status == 200) {
597                         // remove the "uploading in progress" message
598                         let li = document.getElementById("ctdl_uploading_" + uploads_in_progress.toString());
599                         li.parentNode.removeChild(li);
600                         uploads_in_progress -= 1;
601
602                         // The response body will be a JSON array of completed uploads.
603                         var j_response = JSON.parse(xhr.response);
604
605                         // Add these uploads to the displayed list
606                         j_response.forEach((item) => {
607                                 let new_upl = document.createElement("li");
608                                 new_upl.innerHTML = item["tempfilename"] + " " + item["uploadfilename"] + " " + item["contenttype"] + " " + item["contentlength"];
609                                 document.getElementById("ctdl-upload_list").appendChild(new_upl);
610                         });
611
612                         // append it to the global list of uploads
613                         uploads.push(j_response);
614                         document.getElementById("num_attachments").innerHTML = uploads.length;
615                 }
616                 else if (xhr.readyState == 4 && xhr.status != 200) {
617                         // remove the "uploading in progress" message (there was an error, so just let it disappear)
618                         let li = document.getElementById("ctdl_uploading_" + uploads_in_progress.toString());
619                         li.parentNode.removeChild(li);
620                         uploads_in_progress -= 1;
621                 }
622         })
623  
624         formData.append('file', file);
625         xhr.send(formData);
626         uploads_in_progress += 1;
627
628         // Make an "uploading in progress" message appear in the uploads list!
629         progress = document.createElement("li");
630         progress.setAttribute("id", "ctdl_uploading_" + uploads_in_progress.toString());
631         progress.innerHTML = `<img src="/ctdl/s/images/throbber.gif" /> ` + _("Processing dropped files...");
632         document.getElementById("ctdl-upload_list").appendChild(progress);
633 }
634
635
636 function upload_highlight(e) {
637         let dropArea = document.getElementById("ctdl-upload");
638         dropArea.classList.add('highlight')
639
640         document.getElementById("ctdl-upload").style.display = "block";         /* also make it appear */
641 }
642       
643 function upload_unhighlight(e) {
644         let dropArea = document.getElementById("ctdl-upload");
645         dropArea.classList.remove('highlight')
646 }
647
648
649 // Show or hide the attachments window in the composer
650 function show_or_hide_attachments() {
651
652         if (document.getElementById("ctdl-upload").style.display == "block") {
653                 document.getElementById("ctdl-upload").style.display = "none";          /* turn it off */
654         }
655         else {
656                 document.getElementById("ctdl-upload").style.display = "block";         /* turn it on */
657         }
658 }
659
660
661 // Called when the user clicks the button to make the hidden "CC" and "BCC" lines appear.
662 // It is also called automatically during a Reply when CC is pre-populated.
663 function make_cc_bcc_visible() {
664         document.getElementById("ctdl-cc-bcc-buttons").style.display = "none";
665         document.getElementById("ctdl-compose-bcc-label").style.display = "block";
666         document.getElementById("ctdl-compose-bcc-field").style.display = "block";
667 }
668
669
670 // Helper function for mail_send_messages() to extract and decode metadata values.
671 function msm_field(element_name, separator) {
672         let s1 = document.getElementById(element_name).innerHTML;
673         let s2 = s1.replaceAll("|",separator);          // Replace "|" with "!" because "|" is a field separator in Citadel
674         let s3 = decodeURI(s2);
675         let s4 = document.createElement("textarea");    // This One Weird Trick Unescapes All HTML Entities
676         s4.innerHTML = s3;
677         let s5 = s4.value;
678         return(s5);
679 }
680
681
682 // Save the posted message to the server
683 function mail_send_message() {
684
685         document.body.style.cursor = "wait";
686         let url = "/ctdl/r/" + escapeHTMLURI(current_room)
687                 + "/dummy_name_for_new_mail"
688                 + "?wefw="      + msm_field("ctdl_mc_references", "!")                          // references (if present)
689                 + "&subj="      + msm_field("ctdl-compose-subject-field", " ")                  // subject (if present)
690                 + "&mailto="    + msm_field("ctdl-compose-to-field", ",")                       // To: (required)
691                 + "&mailcc="    + msm_field("ctdl-compose-cc-field", ",")                       // Cc: (if present)
692                 + "&mailbcc="   + msm_field("ctdl-compose-bcc-field", ",")                      // Bcc: (if present)
693         ;
694         boundary = randomString();
695         body_text =
696                 "--" + boundary + "\r\n"
697                 + "Content-type: text/html\r\n"
698                 + "Content-transfer-encoding: quoted-printable\r\n"
699                 + "\r\n"
700                 + quoted_printable_encode(
701                         "<html><body>" + document.getElementById("ctdl-editor-body").innerHTML + "</body></html>"
702                 ) + "\r\n"
703                 + "--" + boundary + "--\r\n"
704         ;
705
706         var request = new XMLHttpRequest();
707         request.open("PUT", url, true);
708         request.setRequestHeader("Content-type", "multipart/mixed; boundary=\"" + boundary + "\"");
709         request.onreadystatechange = function() {
710                 if (request.readyState == 4) {
711                         document.body.style.cursor = "default";
712                         if (Math.trunc(request.status / 100) == 2) {
713                                 headers = request.getAllResponseHeaders().split("\n");
714                                 for (var i in headers) {
715                                         if (headers[i].startsWith("etag: ")) {
716                                                 new_msg_num = headers[i].split(" ")[1];
717                                         }
718                                 }
719
720                                 // After saving the message, go back to the mailbox view.
721                                 gotoroom(current_room);
722
723                         }
724                         else {
725                                 error_message = request.responseText;
726                                 if (error_message.length == 0) {
727                                         error_message = _("An error has occurred.");
728                                 }
729                                 alert(error_message);                                           // editor remains open
730                         }
731                 }
732         };
733         request.send(body_text);
734 }