upload.js: when removing an attachment, delete the div
[citadel.git] / webcit-ng / static / js / upload.js
1 // Handle any tasks which require uploading files to the server (such as attachments)
2 // h/t https://www.smashingmagazine.com/2018/01/drag-drop-file-uploader-vanilla-js/ which inspired the design of this module
3 //
4 // Copyright (c) 2016-2023 by the citadel.org team
5 //
6 // This program is open source software.  Use, duplication, or
7 // disclosure are subject to the GNU General Public License v3.
8
9 var uploads_in_progress = 0;
10 var uploads = [] ;                                                              // everything the user has uploaded
11
12
13 // Remove the upload window completely (even if it's hidden)
14 function deactivate_uploads() {
15         upload_window = document.getElementById('ctdl-upload');
16         if (upload_window) {
17                 upload_window.remove();
18         }
19 }
20
21
22 // Turn the specified div into a place where we can upload.  (Note: permanently changes the drag-and-drop behavior of that div.)
23 function activate_uploads(parent_div) {
24                 document.getElementById(parent_div).innerHTML += `
25                         <div class="ctdl-upload" id="ctdl-upload">
26                                 <div id="ctdl_attachments_title" class="ctdl-compose-attachments-title">
27                                         <div><h1><i class="fa fa-paperclip" style="color:grey"></i>` + _("Attachments:") + ` <span id="num_attachments">` + uploads.length + `</span></h1></div>
28                                         <div><h1><i class="fas fa-window-close" style="color:red" onClick="show_or_hide_upload_window()"></i></h1></div>
29                                 </div>
30                                 <br>
31                                 <ul id="ctdl-upload_list">
32                                 </ul>
33                                 <br>
34                                 <div id="drop-area" class="ctdl-upload-drop-area">
35                                         <form class="ctdl-upload-form">
36                                                 <p>${_("Drop files here to upload")}</p>
37                                                 <input type="file" id="fileElem" multiple accept="*/*" onChange="handle_upload_files(this.files)">
38                                         </form>
39                                 </div>
40                         </div>
41                 `;
42
43                 // activate drag and drop
44                 let dropArea = document.getElementById(parent_div);
45                 ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
46                         dropArea.addEventListener(eventName, upload_prevent_defaults, false)
47                 })
48                 ;["dragenter", "dragover"].forEach(eventName => {
49                         dropArea.addEventListener(eventName, upload_highlight, false)
50                 })
51                 ;['dragleave', 'drop'].forEach(eventName => {
52                         dropArea.addEventListener(eventName, upload_unhighlight, false)
53                 })
54                 dropArea.addEventListener('drop', upload_handle_drop, false);
55 }
56
57
58 // prevent drag and drop events from propagating up through the DOM
59 function upload_prevent_defaults(e) {
60         e.preventDefault();
61         e.stopPropagation();
62 }
63
64
65 function upload_handle_drop(e) {
66         let dt = e.dataTransfer;
67         let files = dt.files;
68         handle_upload_files(files);
69 }
70
71
72 function handle_upload_files(files) {
73         ([...files]).forEach(upload_file)
74 }
75
76
77 // Delete an uploaded item from the list
78 delete_upload = async(ref) => {
79
80         response = await fetch(
81                 "/ctdl/p/" + ref, { method: "DELETE" }
82         );
83
84         if (response.ok) {                              // If the server accepted the delete, remove it from the screen
85                 console.log("server deleted " + ref);
86                 var el = document.getElementById(ref);
87                 el.parentNode.removeChild(el);
88         }
89 }
90
91
92 function upload_file(file) {
93         var url = '/ctdl/p/';
94         var xhr = new XMLHttpRequest();
95         var formData = new FormData();
96         xhr.open('POST', url, true);
97       
98         xhr.addEventListener('readystatechange', function(e) {
99                 if (xhr.readyState == 4 && xhr.status == 200) {
100                         // remove the "uploading in progress" message
101                         let li = document.getElementById("ctdl_uploading_" + uploads_in_progress.toString());
102                         li.parentNode.removeChild(li);
103                         uploads_in_progress -= 1;
104
105                         // The response body will be a JSON array of completed uploads.
106                         var j_response = JSON.parse(xhr.response);
107
108                         // Add these uploads to the displayed list
109                         j_response.forEach((item) => {
110                                 let new_upl = document.createElement("li");
111                                 new_upl.setAttribute("id", item["ref"]);        // set the element id to the upload reference
112                                 new_upl.innerHTML = `<i class="fa-solid fa-circle-xmark" style="color:red" onClick="delete_upload('` + item["ref"] + `')"></i>`
113                                 + `&nbsp;`
114                                 + item["uploadfilename"] + " (" + item["contenttype"] + ", " + item["contentlength"] + " " + _("bytes") + ")";
115                                 document.getElementById("ctdl-upload_list").appendChild(new_upl);
116
117                                 // append it to the global list of uploads
118                                 uploads.push(item);
119                         });
120                         document.getElementById("num_attachments").innerHTML = uploads.length;
121                 }
122                 else if (xhr.readyState == 4 && xhr.status != 200) {
123                         // remove the "uploading in progress" message (there was an error, so just let it disappear)
124                         let li = document.getElementById("ctdl_uploading_" + uploads_in_progress.toString());
125                         li.parentNode.removeChild(li);
126                         uploads_in_progress -= 1;
127                 }
128         })
129  
130         formData.append('file', file);
131         xhr.send(formData);
132         uploads_in_progress += 1;
133
134         // Make an "uploading in progress" message appear in the uploads list!
135         progress = document.createElement("li");
136         progress.setAttribute("id", "ctdl_uploading_" + uploads_in_progress.toString());
137         progress.innerHTML = `<img src="/ctdl/s/images/dotcrawl.gif" /> ` + _("Processing dropped files...");
138         document.getElementById("ctdl-upload_list").appendChild(progress);
139 }
140
141
142 // called when the user drags a file into the upload area
143 function upload_highlight(e) {
144         let dropArea = document.getElementById("ctdl-upload");
145         dropArea.classList.add('highlight')
146
147         document.getElementById("ctdl-upload").style.display = "block";         /* also make it appear */
148 }
149
150
151 // called when the user is no longer dragging a file into the upload area
152 function upload_unhighlight(e) {
153         let dropArea = document.getElementById("ctdl-upload");
154         dropArea.classList.remove('highlight')
155 }
156
157
158 // Show or hide the attachments window in the composer
159 function show_or_hide_upload_window() {
160
161         if (document.getElementById("ctdl-upload").style.display == "block") {
162                 document.getElementById("ctdl-upload").style.display = "none";          /* turn it off */
163         }
164         else {
165                 document.getElementById("ctdl-upload").style.display = "block";         /* turn it on */
166         }
167 }
168
169
170 // Helper function for flush_uploads()
171 flush_one_upload = async(ref) => {
172         response = await fetch(
173                 "/ctdl/p/" + ref, { method: "DELETE" }
174         );
175         // We don't have any interest in the server response.
176 }
177
178
179 // Flush all uploaded files and close the window
180 function flush_uploads() {
181         upload_window = document.getElementById('ctdl-upload');
182
183         if (upload_window) {
184                 upload_window.style.display='none';
185         }
186
187         // tell the server to delete the files
188         uploads.forEach(u => {
189                 flush_one_upload(u.ref);
190         });
191         uploads=[];
192
193         deactivate_uploads();   // this makes the window get destroyed too
194 }