-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.js
327 lines (281 loc) · 9.57 KB
/
form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
window.addEventListener("load", submitButtonStateChanger)
var captchaWidgetID = null; // global variable to store the captcha widget
window.onloadTurnstileCallback = () => {
captchaWidgetID = turnstile.render("#cf-turnstile", {
sitekey: "0x4AAAAAAAU4_tLhgcruoYjU",
callback: (token) => {
}
});
}
function submitButtonStateChanger() {
let submitBtn = document.getElementById("submit");
let form = document.getElementsByTagName("form")[0];
form.addEventListener("submit", (event) => {
event.preventDefault();
sendVisualizationRequest();
})
let file = document.getElementById("file");
// this file input is present only if the user is not authenticated
if (!file) {
return;
}
if (file.value) {
submitBtn.disabled = false;
}
file.addEventListener("change", function () {
if (this.value) {
submitBtn.disabled = false;
}
})
// let captcha = document.querySelector("#cf-turnstile");
// turnstile.render(captcha, {
// sitekey: "0x4AAAAAAAU4_tLhgcruoYjU",
// callback: (token) => {
// console.log(token);
// }
// });
}
function deleteForm() {
let oldForm = document.querySelector("#visualization-form");
oldForm.remove();
}
function restoreForm() {
let form = document.querySelector("#visualization-form");
document.querySelector("#time-reminder").style.display = "none";
let submitBtn = form.querySelector("#submit");
submitBtn.innerText = "Visualize";
submitBtn.setAttribute("aria-busy", "false");
for (const elem of form.elements) {
elem.disabled = false;
}
}
function snakeCase(text) {
let snake = "";
for (const char of text) {
if (char == " ") {
snake += "_";
continue;
}
snake += char.toLowerCase();
}
return snake;
}
function _createMatplotlibAccordion(result) {
let b64image = result.image;
let title = result.title;
let details = document.createElement("details");
let graphContainer = document.createElement("section");
graphContainer.classList.add("center-container");
let summary = document.createElement("summary");
summary.role = "button";
summary.innerText = title;
let img = document.createElement("img");
img.src = "data:image/png;base64," + b64image;
img.classList.add("graph-image");
let downloadBtn = document.createElement("a");
downloadBtn.role = "button";
downloadBtn.href = img.src;
downloadBtn.download = snakeCase(title + ".png");
downloadBtn.textContent = "Download";
downloadBtn.classList.add("outline");
details.appendChild(summary);
graphContainer.appendChild(img);
graphContainer.appendChild(downloadBtn);
details.appendChild(graphContainer);
return details;
}
function _createPlotlyAccordion(result) {
const title = result.title;
let snakeTitle = snakeCase(title);
const figure = JSON.parse(result.figure);
let details = document.createElement("details");
let graphContainer = document.createElement("section");
graphContainer.classList.add("center-container");
let summary = document.createElement("summary");
summary.role = "button";
summary.innerText = title;
let renderContainer = document.createElement("div");
renderContainer.setAttribute("id", snakeTitle);
// console.log(figure)
Plotly.newPlot(renderContainer, figure.data, figure.layout, {
toImageButtonOptions: {
format: 'png', // one of png, svg, jpeg, webp
filename: snakeTitle,
scale: 1 // Multiply title/legend/axis/canvas sizes by this factor
},
displayModeBar: true,
responsive: true
});
details.appendChild(summary);
graphContainer.appendChild(renderContainer);
details.appendChild(graphContainer);
return details;
}
function createChartAccordion(result) {
if (result.interactive) {
// plotly has been used
return _createPlotlyAccordion(result.result)
} else {
// matplotlib has been used
return _createMatplotlibAccordion(result.result)
}
}
function createErrorModal(heading, content) {
let modal = document.querySelector("#error-modal");
let modalHeading = modal.querySelector("#modal-heading");
modalHeading.innerText = heading;
let modalContent = modal.querySelector("#modal-content");
modalContent.innerText = content;
modal.setAttribute("open", "");
let closeBtn = modal.querySelector(".close");
closeBtn.addEventListener("click", () => {
// visibleModal = null;
document.documentElement.classList.add("modal-is-closing");
setTimeout(() => {
document.documentElement.classList.remove("modal-is-closing", "modal-is-open");
document.documentElement.style.removeProperty("--scrollbar-width");
modal.removeAttribute("open");
}, 400); // 400ms is animation duration
});
}
function blobFromBase64String(base64String) {
const byteCharacters = atob(base64String);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: "image/png" });
return blob;
}
async function downloadAll(results) {
// * currently supports matplotlib rendered charts only
results = results.filter((r) => !r.interactive);
results = results.map((r) => r.result);
if (!results) {
return;
}
const downloadAllBtn = document.createElement("button");
downloadAllBtn.style.textAlign = "center";
downloadAllBtn.style.width = "fit-content";
downloadAllBtn.style.padding = "10px 20px";
downloadAllBtn.innerText = "Download All";
downloadAllBtn.classList.add("outline");
downloadAllBtn.addEventListener("click", async () => {
downloadAllBtn.innerText = "Please wait...";
downloadAllBtn.setAttribute("aria-busy", "true");
const zip = new JSZip();
for (const result of results) {
const title = result.title;
const img = result.image;
const blob = blobFromBase64String(img);
zip.file(`${snakeCase(title)}.png`, blob, { base64: true });
}
const content = await zip.generateAsync({ type: "blob" });
const fileStream = streamSaver.createWriteStream("animeviz_insights.zip", {
size: content.size // Makes the percentage visiable in the download
});
const readableStream = content.stream();
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => {
console.log('done writing')
downloadAllBtn.innerText = "Download All";
downloadAllBtn.setAttribute("aria-busy", "false");
})
.catch((error) => {
console.log(`unable to write zip file: ${error}`)
downloadAllBtn.innerText = "Download All";
createErrorModal("Unable to make a zip file!", "We couldn't make a zip file of all the images. Please try again later.");
downloadAllBtn.setAttribute("aria-busy", "false");
})
}
});
return downloadAllBtn;
}
async function sendVisualizationRequest() {
if (!captchaWidgetID) {
createErrorModal("Captcha not loaded!", "Unable to load the captcha. Please try reloading the webpage.");
return;
}
if (turnstile.isExpired(captchaWidgetID)) {
turnstile.reset(captchaWidgetID);
}
if (!turnstile.getResponse()) {
createErrorModal("You failed to verify the captcha!", "We failed to verify that you're a human. Please try again.");
return;
}
// add busy circle and change submit button text
let submitBtn = document.getElementById("submit");
submitBtn.setAttribute("aria-busy", "true");
submitBtn.innerText = "Please wait...";
// disable form
let formElements = document.getElementById("visualization-form").elements;
for (let i = 0; i < formElements.length; i++) {
formElements[i].disabled = true;
}
let pTag = document.getElementById("time-reminder");
pTag.style.display = "block";
// fetch form data and post it
let disableNSFW = document.getElementById("nsfw");
let interactiveCharts = document.getElementById("interactive");
const data = {
"disable_nsfw": disableNSFW.checked,
"interactive_charts": interactiveCharts.checked
}
let formdata = new FormData();
for (const key in data) {
formdata.append(key, data[key]);
}
let file = document.getElementById("file");
if (file) {
formdata.append("file", file.files[0]);
}
formdata.append("cf-turnstile-response", turnstile.getResponse());
turnstile.remove();
fetch("/visualize", {
method: "POST",
body: formdata
})
.then(response => {
response.json().then(
jsonResp => {
if (!jsonResp.success) {
// alert("the visualization wasn't successfull");
createErrorModal("Unable to visualize your data!", `The server didn't respond with a successfull response: ${jsonResp.message}`);
restoreForm();
return;
}
deleteForm();
let container = document.querySelector(".form-container");
jsonResp.results.forEach(result => {
const accordion = createChartAccordion(result);
container.appendChild(accordion);
});
downloadAll(jsonResp.results)
.then((downloadAllBtn) => {
container.appendChild(downloadAllBtn);
})
.catch((err) => {
// alert("unable to make a zip file");
createErrorModal("Unable to make a zip file!", "We're unable to make a zip file of all the images. Please try again later.");
console.log(err);
});
}
).catch(err => {
console.log("cannot convert response to json");
console.log(response);
console.log(err);
createErrorModal("Unable to visualize!", "The server returned a non-json response. Please try again later.");
restoreForm();
// alert("the server returned a non-json response");
})
})
.catch(err => {
console.log("couldn't send a post request for visualization to the server!");
console.log(err);
createErrorModal("Unable to interact with the server!", "We are unable to connect to our server. Please check your internet connection and try again.");
restoreForm();
// alert("request failed, try again later");
})
}