]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/changeset.js
Move OAuth requests to fetch
[rails.git] / app / assets / javascripts / index / changeset.js
1 OSM.Changeset = function (map) {
2   var page = {},
3       content = $("#sidebar_content");
4
5   page.pushstate = page.popstate = function (path) {
6     OSM.loadSidebarContent(path, function () {
7       page.load();
8     });
9   };
10
11   page.load = function () {
12     const changesetData = content.find("[data-changeset]").data("changeset");
13     changesetData.type = "changeset";
14
15     var hashParams = OSM.parseHash(window.location.hash);
16     initialize();
17     map.addObject(changesetData, function (bounds) {
18       if (!hashParams.center && bounds.isValid()) {
19         OSM.router.withoutMoveListener(function () {
20           map.fitBounds(bounds);
21         });
22       }
23     });
24   };
25
26   function updateChangeset(method, url, include_data) {
27     const data = new URLSearchParams();
28
29     content.find("#comment-error").prop("hidden", true);
30     content.find("button[data-method][data-url]").prop("disabled", true);
31
32     if (include_data) {
33       data.set("text", content.find("textarea").val());
34     }
35
36     fetch(url, {
37       method: method,
38       headers: { ...OSM.oauth },
39       body: data
40     })
41       .then(response => {
42         if (response.ok) return response;
43         return response.text().then(text => {
44           throw new Error(text);
45         });
46       })
47       .then(() => {
48         OSM.loadSidebarContent(window.location.pathname, page.load);
49       })
50       .catch(error => {
51         content.find("button[data-method][data-url]").prop("disabled", false);
52         content.find("#comment-error")
53           .text(error.message)
54           .prop("hidden", false)
55           .get(0).scrollIntoView({ block: "nearest" });
56       });
57   }
58
59   function initialize() {
60     content.find("button[data-method][data-url]").on("click", function (e) {
61       e.preventDefault();
62       var data = $(e.target).data();
63       var include_data = e.target.name === "comment";
64       updateChangeset(data.method, data.url, include_data);
65     });
66
67     content.find("textarea").on("input", function (e) {
68       const form = e.target.form,
69             disabled = $(e.target).val() === "";
70       form.comment.disabled = disabled;
71     });
72
73     content.find("textarea").val("").trigger("input");
74   }
75
76   page.unload = function () {
77     map.removeObject();
78   };
79
80   return page;
81 };