]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Merge remote-tracking branch 'upstream/pull/5643'
[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     $("#sidebar_content")
42       .empty();
43
44     $.ajax({
45       url: content_path,
46       dataType: "html",
47       complete: function (xhr) {
48         $("#flash").empty();
49         $("#sidebar_loader").removeClass("delayed-fade-in").hide();
50
51         var content = $(xhr.responseText);
52
53         if (xhr.getResponseHeader("X-Page-Title")) {
54           var title = xhr.getResponseHeader("X-Page-Title");
55           document.title = decodeURIComponent(title);
56         }
57
58         $("head")
59           .find("link[type=\"application/atom+xml\"]")
60           .remove();
61
62         $("head")
63           .append(content.filter("link[type=\"application/atom+xml\"]"));
64
65         $("#sidebar_content").html(content.not("link[type=\"application/atom+xml\"]"));
66
67         if (callback) {
68           callback();
69         }
70       }
71     });
72   };
73
74   var params = OSM.mapParams();
75
76   map.attributionControl.setPrefix("");
77
78   map.updateLayers(params.layers);
79
80   map.on("baselayerchange", function (e) {
81     if (map.getZoom() > e.layer.options.maxZoom) {
82       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
83     }
84   });
85
86   var sidebar = L.OSM.sidebar("#map-ui")
87     .addTo(map);
88
89   var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
90
91   function addControlGroup(controls) {
92     for (const control of controls) control.addTo(map);
93
94     var firstContainer = controls[0].getContainer();
95     $(firstContainer).find(".control-button").first()
96       .addClass("control-button-first");
97
98     var lastContainer = controls[controls.length - 1].getContainer();
99     $(lastContainer).find(".control-button").last()
100       .addClass("control-button-last");
101   }
102
103   addControlGroup([
104     L.OSM.zoom({ position: position }),
105     L.OSM.locate({ position: position })
106   ]);
107
108   addControlGroup([
109     L.OSM.layers({
110       position: position,
111       layers: map.baseLayers,
112       sidebar: sidebar
113     }),
114     L.OSM.key({
115       position: position,
116       sidebar: sidebar
117     }),
118     L.OSM.share({
119       "position": position,
120       "sidebar": sidebar,
121       "short": true
122     })
123   ]);
124
125   addControlGroup([
126     L.OSM.note({
127       position: position,
128       sidebar: sidebar
129     })
130   ]);
131
132   addControlGroup([
133     L.OSM.query({
134       position: position,
135       sidebar: sidebar
136     })
137   ]);
138
139   L.control.scale()
140     .addTo(map);
141
142   OSM.initializeContextMenu(map);
143
144   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
145     OSM.initializeNotesLayer(map);
146     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
147       map.addLayer(map.noteLayer);
148     }
149
150     OSM.initializeDataLayer(map);
151     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
152       map.addLayer(map.dataLayer);
153     }
154
155     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
156       map.addLayer(map.gpsLayer);
157     }
158   }
159
160   $(".leaflet-control .control-button").tooltip({ placement: "left", container: "body" });
161
162   var expiry = new Date();
163   expiry.setYear(expiry.getFullYear() + 10);
164
165   map.on("moveend baselayerchange overlayadd overlayremove", function () {
166     updateLinks(
167       map.getCenter().wrap(),
168       map.getZoom(),
169       map.getLayersCode(),
170       map._object);
171
172     Cookies.set("_osm_location", OSM.locationCookie(map), { secure: true, expires: expiry, path: "/", samesite: "lax" });
173   });
174
175   if (Cookies.get("_osm_welcome") !== "hide") {
176     $(".welcome").removeAttr("hidden");
177   }
178
179   $(".welcome .btn-close").on("click", function () {
180     $(".welcome").hide();
181     Cookies.set("_osm_welcome", "hide", { secure: true, expires: expiry, path: "/", samesite: "lax" });
182   });
183
184   var bannerExpiry = new Date();
185   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
186
187   $("#banner .btn-close").on("click", function (e) {
188     var cookieId = e.target.id;
189     $("#banner").hide();
190     e.preventDefault();
191     if (cookieId) {
192       Cookies.set(cookieId, "hide", { secure: true, expires: bannerExpiry, path: "/", samesite: "lax" });
193     }
194   });
195
196   if (OSM.MATOMO) {
197     map.on("baselayerchange overlayadd", function (e) {
198       if (e.layer.options) {
199         var goal = OSM.MATOMO.goals[e.layer.options.layerId];
200
201         if (goal) {
202           $("body").trigger("matomogoal", goal);
203         }
204       }
205     });
206   }
207
208   if (params.bounds) {
209     map.fitBounds(params.bounds);
210   } else {
211     map.setView([params.lat, params.lon], params.zoom);
212   }
213
214   if (params.marker) {
215     L.marker([params.mlat, params.mlon]).addTo(map);
216   }
217
218   $("#homeanchor").on("click", function (e) {
219     e.preventDefault();
220
221     var data = $(this).data(),
222         center = L.latLng(data.lat, data.lon);
223
224     map.setView(center, data.zoom);
225     L.marker(center, { icon: OSM.getUserIcon() }).addTo(map);
226   });
227
228   function remoteEditHandler(bbox, object) {
229     var 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, function () {
240       if (object && object.type === "note") {
241         const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
242         sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
243       }
244     });
245
246     function sendRemoteEditCommand(url, callback) {
247       fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) })
248         .then(callback)
249         .catch(function () {
250           // eslint-disable-next-line no-alert
251           alert(I18n.t("site.index.remote_failed"));
252         });
253     }
254
255     return false;
256   }
257
258   $("a[data-editor=remote]").click(function (e) {
259     var 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     var 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     var page = {};
302
303     page.pushstate = page.popstate = function (path, id) {
304       OSM.loadSidebarContent(path, function () {
305         addObject(type, id);
306       });
307     };
308
309     page.load = function (path, id) {
310       addObject(type, id, true);
311     };
312
313     function addObject(type, id, center) {
314       map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
315         if (!window.location.hash && bounds.isValid() &&
316             (center || !map.getBounds().contains(bounds))) {
317           OSM.router.withoutMoveListener(function () {
318             map.fitBounds(bounds);
319           });
320         }
321       });
322     }
323
324     page.unload = function () {
325       map.removeObject();
326     };
327
328     return page;
329   };
330
331   OSM.OldBrowse = function () {
332     var page = {};
333
334     page.pushstate = page.popstate = function (path) {
335       OSM.loadSidebarContent(path);
336     };
337
338     return page;
339   };
340
341   var history = OSM.History(map);
342
343   OSM.router = OSM.Router(map, {
344     "/": OSM.Index(map),
345     "/search": OSM.Search(map),
346     "/directions": OSM.Directions(map),
347     "/export": OSM.Export(map),
348     "/note/new": OSM.NewNote(map),
349     "/history/friends": history,
350     "/history/nearby": history,
351     "/history": history,
352     "/user/:display_name/history": history,
353     "/note/:id": OSM.Note(map),
354     "/node/:id(/history)": OSM.Browse(map, "node"),
355     "/node/:id/history/:version": OSM.OldBrowse(),
356     "/way/:id(/history)": OSM.Browse(map, "way"),
357     "/way/:id/history/:version": OSM.OldBrowse(),
358     "/relation/:id(/history)": OSM.Browse(map, "relation"),
359     "/relation/:id/history/:version": OSM.OldBrowse(),
360     "/changeset/:id": OSM.Changeset(map),
361     "/query": OSM.Query(map)
362   });
363
364   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
365     remoteEditHandler(map.getBounds(), params.object);
366     OSM.router.setCurrentPath("/");
367   }
368
369   OSM.router.load();
370
371   $(document).on("click", "a", function (e) {
372     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
373       return;
374     }
375
376     // Open links in a new tab as normal.
377     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
378       return;
379     }
380
381     // Ignore cross-protocol and cross-origin links.
382     if (location.protocol !== this.protocol || location.host !== this.host) {
383       return;
384     }
385
386     if (OSM.router.route(this.pathname + this.search + this.hash)) {
387       e.preventDefault();
388       if (this.pathname !== "/directions") {
389         $("header").addClass("closed");
390       }
391     }
392   });
393
394   $(document).on("click", "#sidebar_content .btn-close", function () {
395     OSM.router.route("/" + OSM.formatHash(map));
396   });
397 });