]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/download_util.js
Merge remote-tracking branch 'upstream/pull/6291'
[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.getTurboBlobHandler = function (filename) {
13   function handleExportSuccess({ fetchResponse }) {
14     fetchResponse.response.blob()
15       .then(blob => OSM.downloadBlob(blob, filename))
16       .catch(() => notifyExportFailure("(blob error)"));
17   }
18
19   function handleExportError({ error, fetchResponse }) {
20     Promise.resolve(
21       error?.message ||
22       fetchResponse.responseText.then(extractTextFromHTML)
23     )
24       .then(notifyExportFailure)
25       .catch(() => notifyExportFailure("(unknown)"));
26   }
27
28   function extractTextFromHTML(htmlString) {
29     const parser = new DOMParser();
30     const doc = parser.parseFromString(htmlString, "text/html");
31     return doc.body ? doc.body.textContent.trim() : "(unknown)";
32   }
33
34   function notifyExportFailure(reason) {
35     OSM.showAlert(OSM.i18n.t("javascripts.share.export_failed_title"), reason);
36   }
37
38   return function ({ detail }) {
39     if (detail.success) {
40       handleExportSuccess(detail);
41     } else {
42       handleExportError(detail);
43     }
44   };
45 };
46
47 OSM.turboHtmlResponseHandler = function (event) {
48   const response = event.detail.fetchResponse.response;
49   const contentType = response.headers.get("content-type");
50   if (!response.ok && contentType?.includes("text/html")) {
51     // Prevent Turbo from replacing the current page with an error HTML response
52     // from the export endpoint
53     event.preventDefault();
54     event.stopPropagation();
55   }
56 };