]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/download_util.js
Rescope variables
[rails.git] / app / assets / javascripts / download_util.js
1 OSM.downloadBlob = function (blob, filename) {
2   const url = URL.createObjectURL(blob);
3   const a = document.createElement("a");
4   a.href = url;
5   a.download = filename;
6   document.body.appendChild(a);
7   a.click();
8   document.body.removeChild(a);
9   URL.revokeObjectURL(url);
10 };
11
12 OSM.showAlert = function (message) {
13   const modalBody = document.getElementById("osm_alert_message");
14   modalBody.textContent = message;
15   const alertModal = new bootstrap.Modal(document.getElementById("osm_alert_modal"));
16   alertModal.show();
17 };
18
19 OSM.getTurboBlobHandler = function (filename) {
20   async function handleExportSuccess({ fetchResponse }) {
21     try {
22       const blob = await fetchResponse.response.blob();
23       OSM.downloadBlob(blob, filename);
24     } catch (err) {
25       notifyExportFailure("(blob error)");
26     }
27   }
28
29   async function handleExportError({ error, fetchResponse }) {
30     try {
31       let detailMessage = error?.message;
32       if (!detailMessage) {
33         detailMessage = await fetchResponse.responseText.then(extractTextFromHTML);
34       }
35       notifyExportFailure(detailMessage);
36     } catch (err) {
37       notifyExportFailure("(unknown)");
38     }
39   }
40
41   function extractTextFromHTML(htmlString) {
42     const parser = new DOMParser();
43     const doc = parser.parseFromString(htmlString, "text/html");
44     return doc.body ? doc.body.textContent.trim() : "(unknown)";
45   }
46
47   function notifyExportFailure(reason) {
48     OSM.showAlert(OSM.i18n.t("javascripts.share.export_failed", { reason }));
49   }
50
51   return function ({ detail }) {
52     if (detail.success) {
53       handleExportSuccess(detail);
54     } else {
55       handleExportError(detail);
56     }
57   };
58 };