]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Return promise from sendRemoteEditCommand()
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require leaflet.sidebar
3 //= require leaflet.sidebar-pane
4 //= require leaflet.locatecontrol/dist/L.Control.Locate.umd
5 //= require leaflet.locate
6 //= require leaflet.layers
7 //= require leaflet.key
8 //= require leaflet.note
9 //= require leaflet.share
10 //= require leaflet.polyline
11 //= require leaflet.query
12 //= require leaflet.contextmenu
13 //= require index/contextmenu
14 //= require index/search
15 //= require index/layers/data
16 //= require index/export
17 //= require index/layers/notes
18 //= require index/history
19 //= require index/note
20 //= require index/new_note
21 //= require index/directions
22 //= require index/changeset
23 //= require index/query
24 //= require index/home
25 //= require router
26
27 $(document).ready(function () {
28   const map = new L.OSM.Map("map", {
29     zoomControl: false,
30     layerControl: false,
31     contextmenu: true,
32     worldCopyJump: true
33   });
34
35   OSM.loadSidebarContent = function (path, callback) {
36     let content_path = path;
37
38     map.setSidebarOverlaid(false);
39
40     $("#sidebar_loader").show().addClass("delayed-fade-in");
41
42     // Prevent caching the XHR response as a full-page URL
43     // https://github.com/openstreetmap/openstreetmap-website/issues/5663
44     if (content_path.indexOf("?") >= 0) {
45       content_path += "&xhr=1";
46     } else {
47       content_path += "?xhr=1";
48     }
49
50     $("#sidebar_content")
51       .empty();
52
53     fetch(content_path, { headers: { "accept": "text/html", "x-requested-with": "XMLHttpRequest" } })
54       .then(response => {
55         $("#flash").empty();
56         $("#sidebar_loader").removeClass("delayed-fade-in").hide();
57
58         const title = response.headers.get("X-Page-Title");
59         if (title) document.title = decodeURIComponent(title);
60
61         return response.text();
62       })
63       .then(html => {
64         const content = $(html);
65
66         $("head")
67           .find("link[type=\"application/atom+xml\"]")
68           .remove();
69
70         $("head")
71           .append(content.filter("link[type=\"application/atom+xml\"]"));
72
73         $("#sidebar_content").html(content.not("link[type=\"application/atom+xml\"]"));
74
75         if (callback) {
76           callback();
77         }
78       });
79   };
80
81   const token = $("head").data("oauthToken");
82   if (token) OSM.oauth = { authorization: "Bearer " + token };
83
84   const params = OSM.mapParams();
85
86   map.attributionControl.setPrefix("");
87
88   map.updateLayers(params.layers);
89
90   map.on("baselayerchange", function (e) {
91     if (map.getZoom() > e.layer.options.maxZoom) {
92       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
93     }
94   });
95
96   const sidebar = L.OSM.sidebar("#map-ui")
97     .addTo(map);
98
99   const position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
100
101   function addControlGroup(controls) {
102     for (const control of controls) control.addTo(map);
103
104     const firstContainer = controls[0].getContainer();
105     $(firstContainer).find(".control-button").first()
106       .addClass("control-button-first");
107
108     const lastContainer = controls[controls.length - 1].getContainer();
109     $(lastContainer).find(".control-button").last()
110       .addClass("control-button-last");
111   }
112
113   addControlGroup([
114     L.OSM.zoom({ position: position }),
115     L.OSM.locate({ position: position })
116   ]);
117
118   addControlGroup([
119     L.OSM.layers({
120       position: position,
121       layers: map.baseLayers,
122       sidebar: sidebar
123     }),
124     L.OSM.key({
125       position: position,
126       sidebar: sidebar
127     }),
128     L.OSM.share({
129       "position": position,
130       "sidebar": sidebar,
131       "short": true
132     })
133   ]);
134
135   addControlGroup([
136     L.OSM.note({
137       position: position,
138       sidebar: sidebar
139     })
140   ]);
141
142   addControlGroup([
143     L.OSM.query({
144       position: position,
145       sidebar: sidebar
146     })
147   ]);
148
149   L.control.scale()
150     .addTo(map);
151
152   OSM.initializeContextMenu(map);
153
154   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
155     OSM.initializeNotesLayer(map);
156     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
157       map.addLayer(map.noteLayer);
158     }
159
160     OSM.initializeDataLayer(map);
161     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
162       map.addLayer(map.dataLayer);
163     }
164
165     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
166       map.addLayer(map.gpsLayer);
167     }
168   }
169
170   $(".leaflet-control .control-button").tooltip({ placement: "left", container: "body" });
171
172   const expiry = new Date();
173   expiry.setYear(expiry.getFullYear() + 10);
174
175   map.on("moveend baselayerchange overlayadd overlayremove", function () {
176     updateLinks(
177       map.getCenter().wrap(),
178       map.getZoom(),
179       map.getLayersCode(),
180       map._object);
181
182     Cookies.set("_osm_location", OSM.locationCookie(map), { secure: true, expires: expiry, path: "/", samesite: "lax" });
183   });
184
185   if (Cookies.get("_osm_welcome") !== "hide") {
186     $(".welcome").removeAttr("hidden");
187   }
188
189   $(".welcome .btn-close").on("click", function () {
190     $(".welcome").hide();
191     Cookies.set("_osm_welcome", "hide", { secure: true, expires: expiry, path: "/", samesite: "lax" });
192   });
193
194   const bannerExpiry = new Date();
195   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
196
197   $("#banner .btn-close").on("click", function (e) {
198     const cookieId = e.target.id;
199     $("#banner").hide();
200     e.preventDefault();
201     if (cookieId) {
202       Cookies.set(cookieId, "hide", { secure: true, expires: bannerExpiry, path: "/", samesite: "lax" });
203     }
204   });
205
206   if (OSM.MATOMO) {
207     map.on("baselayerchange overlayadd", function (e) {
208       if (e.layer.options) {
209         const goal = OSM.MATOMO.goals[e.layer.options.layerId];
210
211         if (goal) {
212           $("body").trigger("matomogoal", goal);
213         }
214       }
215     });
216   }
217
218   if (params.bounds) {
219     map.fitBounds(params.bounds);
220   } else {
221     map.setView([params.lat, params.lon], params.zoom);
222   }
223
224   if (params.marker) {
225     L.marker([params.mlat, params.mlon]).addTo(map);
226   }
227
228   function remoteEditHandler(bbox, object) {
229     const remoteEditHost = "http://127.0.0.1:8111",
230           osmHost = location.protocol + "//" + location.host,
231           query = new URLSearchParams({
232             left: bbox.getWest() - 0.0001,
233             top: bbox.getNorth() + 0.0001,
234             right: bbox.getEast() + 0.0001,
235             bottom: bbox.getSouth() - 0.0001
236           });
237
238     if (object && object.type !== "note") query.set("select", object.type + object.id); // can't select notes
239     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + query)
240       .then(() => {
241         if (object && object.type === "note") {
242           const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
243           sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
244         }
245       })
246       .catch(() => {
247         // eslint-disable-next-line no-alert
248         alert(I18n.t("site.index.remote_failed"));
249       });
250
251     function sendRemoteEditCommand(url) {
252       return fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) });
253     }
254
255     return false;
256   }
257
258   $("a[data-editor=remote]").click(function (e) {
259     const params = OSM.mapParams(this.search);
260     remoteEditHandler(map.getBounds(), params.object);
261     e.preventDefault();
262   });
263
264   if (OSM.params().edit_help) {
265     $("#editanchor")
266       .removeAttr("title")
267       .tooltip({
268         placement: "bottom",
269         title: I18n.t("javascripts.edit_help")
270       })
271       .tooltip("show");
272
273     $("body").one("click", function () {
274       $("#editanchor").tooltip("hide");
275     });
276   }
277
278   OSM.Index = function (map) {
279     const page = {};
280
281     page.pushstate = page.popstate = function () {
282       map.setSidebarOverlaid(true);
283       document.title = I18n.t("layouts.project_name.title");
284     };
285
286     page.load = function () {
287       const params = new URLSearchParams(location.search);
288       if (params.has("query")) {
289         $("#sidebar .search_form input[name=query]").value(params.get("query"));
290       }
291       if (!("autofocus" in document.createElement("input"))) {
292         $("#sidebar .search_form input[name=query]").focus();
293       }
294       return map.getState();
295     };
296
297     return page;
298   };
299
300   OSM.Browse = function (map, type) {
301     const page = {};
302
303     page.pushstate = page.popstate = function (path, id, version) {
304       OSM.loadSidebarContent(path, function () {
305         addObject(type, id, version);
306       });
307     };
308
309     page.load = function (path, id, version) {
310       addObject(type, id, version, true);
311     };
312
313     function addObject(type, id, version, center) {
314       const hashParams = OSM.parseHash(window.location.hash);
315       map.addObject({ type: type, id: parseInt(id, 10), version: version && parseInt(version, 10) }, function (bounds) {
316         if (!hashParams.center && bounds.isValid() &&
317             (center || !map.getBounds().contains(bounds))) {
318           OSM.router.withoutMoveListener(function () {
319             map.fitBounds(bounds);
320           });
321         }
322       });
323     }
324
325     page.unload = function () {
326       map.removeObject();
327     };
328
329     return page;
330   };
331
332   OSM.OldBrowse = function () {
333     const page = {};
334
335     page.pushstate = page.popstate = function (path) {
336       OSM.loadSidebarContent(path);
337     };
338
339     return page;
340   };
341
342   const history = OSM.History(map);
343
344   OSM.router = OSM.Router(map, {
345     "/": OSM.Index(map),
346     "/search": OSM.Search(map),
347     "/directions": OSM.Directions(map),
348     "/export": OSM.Export(map),
349     "/note/new": OSM.NewNote(map),
350     "/history/friends": history,
351     "/history/nearby": history,
352     "/history": history,
353     "/user/:display_name/history": history,
354     "/note/:id": OSM.Note(map),
355     "/node/:id(/history)": OSM.Browse(map, "node"),
356     "/node/:id/history/:version": OSM.Browse(map, "node"),
357     "/way/:id(/history)": OSM.Browse(map, "way"),
358     "/way/:id/history/:version": OSM.OldBrowse(),
359     "/relation/:id(/history)": OSM.Browse(map, "relation"),
360     "/relation/:id/history/:version": OSM.OldBrowse(),
361     "/changeset/:id": OSM.Changeset(map),
362     "/query": OSM.Query(map),
363     "/account/home": OSM.Home(map)
364   });
365
366   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
367     remoteEditHandler(map.getBounds(), params.object);
368     OSM.router.setCurrentPath("/");
369   }
370
371   OSM.router.load();
372
373   $(document).on("click", "a", function (e) {
374     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
375       return;
376     }
377
378     // Open links in a new tab as normal.
379     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
380       return;
381     }
382
383     // Ignore cross-protocol and cross-origin links.
384     if (location.protocol !== this.protocol || location.host !== this.host) {
385       return;
386     }
387
388     if (OSM.router.route(this.pathname + this.search + this.hash)) {
389       e.preventDefault();
390       if (this.pathname !== "/directions") {
391         $("header").addClass("closed");
392       }
393     }
394   });
395
396   $(document).on("click", "#sidebar_content .btn-close", function () {
397     OSM.router.route("/" + OSM.formatHash(map));
398   });
399 });