]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Merge remote-tracking branch 'upstream/pull/5600'
[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 router
25
26 $(document).ready(function () {
27   var map = new L.OSM.Map("map", {
28     zoomControl: false,
29     layerControl: false,
30     contextmenu: true,
31     worldCopyJump: true
32   });
33
34   OSM.loadSidebarContent = function (path, callback) {
35     var content_path = path;
36
37     map.setSidebarOverlaid(false);
38
39     $("#sidebar_loader").show().addClass("delayed-fade-in");
40
41     // IE<10 doesn't respect Vary: X-Requested-With header, so
42     // prevent caching the XHR response as a full-page URL.
43     if (content_path.indexOf("?") >= 0) {
44       content_path += "&xhr=1";
45     } else {
46       content_path += "?xhr=1";
47     }
48
49     $("#sidebar_content")
50       .empty();
51
52     $.ajax({
53       url: content_path,
54       dataType: "html",
55       complete: function (xhr) {
56         $("#flash").empty();
57         $("#sidebar_loader").removeClass("delayed-fade-in").hide();
58
59         var content = $(xhr.responseText);
60
61         if (xhr.getResponseHeader("X-Page-Title")) {
62           var title = xhr.getResponseHeader("X-Page-Title");
63           document.title = decodeURIComponent(title);
64         }
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
82   var params = OSM.mapParams();
83
84   map.attributionControl.setPrefix("");
85
86   map.updateLayers(params.layers);
87
88   map.on("baselayerchange", function (e) {
89     if (map.getZoom() > e.layer.options.maxZoom) {
90       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
91     }
92   });
93
94   var sidebar = L.OSM.sidebar("#map-ui")
95     .addTo(map);
96
97   var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
98
99   function addControlGroup(controls) {
100     controls.forEach(function (control) {
101       control.addTo(map);
102     });
103
104     var firstContainer = controls[0].getContainer();
105     $(firstContainer).find(".control-button").first()
106       .addClass("control-button-first");
107
108     var 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   var 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   var bannerExpiry = new Date();
195   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
196
197   $("#banner .btn-close").on("click", function (e) {
198     var 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         var 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   $("#homeanchor").on("click", function (e) {
229     e.preventDefault();
230
231     var data = $(this).data(),
232         center = L.latLng(data.lat, data.lon);
233
234     map.setView(center, data.zoom);
235     L.marker(center, { icon: OSM.getUserIcon() }).addTo(map);
236   });
237
238   function remoteEditHandler(bbox, object) {
239     var remoteEditHost = "http://127.0.0.1:8111",
240         osmHost = location.protocol + "//" + location.host,
241         query = new URLSearchParams({
242           left: bbox.getWest() - 0.0001,
243           top: bbox.getNorth() + 0.0001,
244           right: bbox.getEast() + 0.0001,
245           bottom: bbox.getSouth() - 0.0001
246         });
247
248     if (object && object.type !== "note") query.set("select", object.type + object.id); // can't select notes
249     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + query, function () {
250       if (object && object.type === "note") {
251         const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
252         sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
253       }
254     });
255
256     function sendRemoteEditCommand(url, callback) {
257       fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) })
258         .then(callback)
259         .catch(function () {
260           alert(I18n.t("site.index.remote_failed"));
261         });
262     }
263
264     return false;
265   }
266
267   $("a[data-editor=remote]").click(function (e) {
268     var params = OSM.mapParams(this.search);
269     remoteEditHandler(map.getBounds(), params.object);
270     e.preventDefault();
271   });
272
273   if (OSM.params().edit_help) {
274     $("#editanchor")
275       .removeAttr("title")
276       .tooltip({
277         placement: "bottom",
278         title: I18n.t("javascripts.edit_help")
279       })
280       .tooltip("show");
281
282     $("body").one("click", function () {
283       $("#editanchor").tooltip("hide");
284     });
285   }
286
287   OSM.Index = function (map) {
288     var page = {};
289
290     page.pushstate = page.popstate = function () {
291       map.setSidebarOverlaid(true);
292       document.title = I18n.t("layouts.project_name.title");
293     };
294
295     page.load = function () {
296       const params = new URLSearchParams(location.search);
297       if (params.has("query")) {
298         $("#sidebar .search_form input[name=query]").value(params.get("query"));
299       }
300       if (!("autofocus" in document.createElement("input"))) {
301         $("#sidebar .search_form input[name=query]").focus();
302       }
303       return map.getState();
304     };
305
306     return page;
307   };
308
309   OSM.Browse = function (map, type) {
310     var page = {};
311
312     page.pushstate = page.popstate = function (path, id) {
313       OSM.loadSidebarContent(path, function () {
314         addObject(type, id);
315       });
316     };
317
318     page.load = function (path, id) {
319       addObject(type, id, true);
320     };
321
322     function addObject(type, id, center) {
323       map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
324         if (!window.location.hash && bounds.isValid() &&
325             (center || !map.getBounds().contains(bounds))) {
326           OSM.router.withoutMoveListener(function () {
327             map.fitBounds(bounds);
328           });
329         }
330       });
331     }
332
333     page.unload = function () {
334       map.removeObject();
335     };
336
337     return page;
338   };
339
340   OSM.OldBrowse = function () {
341     var page = {};
342
343     page.pushstate = page.popstate = function (path) {
344       OSM.loadSidebarContent(path);
345     };
346
347     return page;
348   };
349
350   var history = OSM.History(map);
351
352   OSM.router = OSM.Router(map, {
353     "/": OSM.Index(map),
354     "/search": OSM.Search(map),
355     "/directions": OSM.Directions(map),
356     "/export": OSM.Export(map),
357     "/note/new": OSM.NewNote(map),
358     "/history/friends": history,
359     "/history/nearby": history,
360     "/history": history,
361     "/user/:display_name/history": history,
362     "/note/:id": OSM.Note(map),
363     "/node/:id(/history)": OSM.Browse(map, "node"),
364     "/node/:id/history/:version": OSM.OldBrowse(),
365     "/way/:id(/history)": OSM.Browse(map, "way"),
366     "/way/:id/history/:version": OSM.OldBrowse(),
367     "/relation/:id(/history)": OSM.Browse(map, "relation"),
368     "/relation/:id/history/:version": OSM.OldBrowse(),
369     "/changeset/:id": OSM.Changeset(map),
370     "/query": OSM.Query(map)
371   });
372
373   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
374     remoteEditHandler(map.getBounds(), params.object);
375     OSM.router.setCurrentPath("/");
376   }
377
378   OSM.router.load();
379
380   $(document).on("click", "a", function (e) {
381     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
382       return;
383     }
384
385     // Open links in a new tab as normal.
386     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
387       return;
388     }
389
390     // Ignore cross-protocol and cross-origin links.
391     if (location.protocol !== this.protocol || location.host !== this.host) {
392       return;
393     }
394
395     if (OSM.router.route(this.pathname + this.search + this.hash)) {
396       e.preventDefault();
397       if (this.pathname !== "/directions") {
398         $("header").addClass("closed");
399       }
400     }
401   });
402
403   $(document).on("click", "#sidebar_content .btn-close", function () {
404     OSM.router.route("/" + OSM.formatHash(map));
405   });
406 });