]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/download_util.js
Extract notifyExportFailure helper
[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, filename) {
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(event) {
30     let detailMessage;
31     try {
32       detailMessage = event?.detail?.error?.message;
33       if (!detailMessage) {
34         const responseText = await event.detail.fetchResponse.responseText;
35         const parser = new DOMParser();
36         const doc = parser.parseFromString(responseText, "text/html");
37         detailMessage = doc.body ? doc.body.textContent.trim() : "(unknown)";
38       }
39     } catch (err) {
40       detailMessage = "(unknown)";
41     }
42     notifyExportFailure(detailMessage);
43   }
44
45   function notifyExportFailure(reason) {
46     OSM.showAlert(OSM.i18n.t("javascripts.share.export_failed", { reason }));
47   }
48
49   return function (event) {
50     if (event.detail.success) {
51       handleExportSuccess(event.detail.fetchResponse, filename);
52     } else {
53       handleExportError(event);
54     }
55   };
56 };