]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Merge branch 'pull/5627'
[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     for (const control of controls) control.addTo(map);
101
102     var firstContainer = controls[0].getContainer();
103     $(firstContainer).find(".control-button").first()
104       .addClass("control-button-first");
105
106     var lastContainer = controls[controls.length - 1].getContainer();
107     $(lastContainer).find(".control-button").last()
108       .addClass("control-button-last");
109   }
110
111   addControlGroup([
112     L.OSM.zoom({ position: position }),
113     L.OSM.locate({ position: position })
114   ]);
115
116   addControlGroup([
117     L.OSM.layers({
118       position: position,
119       layers: map.baseLayers,
120       sidebar: sidebar
121     }),
122     L.OSM.key({
123       position: position,
124       sidebar: sidebar
125     }),
126     L.OSM.share({
127       "position": position,
128       "sidebar": sidebar,
129       "short": true
130     })
131   ]);
132
133   addControlGroup([
134     L.OSM.note({
135       position: position,
136       sidebar: sidebar
137     })
138   ]);
139
140   addControlGroup([
141     L.OSM.query({
142       position: position,
143       sidebar: sidebar
144     })
145   ]);
146
147   L.control.scale()
148     .addTo(map);
149
150   OSM.initializeContextMenu(map);
151
152   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
153     OSM.initializeNotesLayer(map);
154     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
155       map.addLayer(map.noteLayer);
156     }
157
158     OSM.initializeDataLayer(map);
159     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
160       map.addLayer(map.dataLayer);
161     }
162
163     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
164       map.addLayer(map.gpsLayer);
165     }
166   }
167
168   $(".leaflet-control .control-button").tooltip({ placement: "left", container: "body" });
169
170   var expiry = new Date();
171   expiry.setYear(expiry.getFullYear() + 10);
172
173   map.on("moveend baselayerchange overlayadd overlayremove", function () {
174     updateLinks(
175       map.getCenter().wrap(),
176       map.getZoom(),
177       map.getLayersCode(),
178       map._object);
179
180     Cookies.set("_osm_location", OSM.locationCookie(map), { secure: true, expires: expiry, path: "/", samesite: "lax" });
181   });
182
183   if (Cookies.get("_osm_welcome") !== "hide") {
184     $(".welcome").removeAttr("hidden");
185   }
186
187   $(".welcome .btn-close").on("click", function () {
188     $(".welcome").hide();
189     Cookies.set("_osm_welcome", "hide", { secure: true, expires: expiry, path: "/", samesite: "lax" });
190   });
191
192   var bannerExpiry = new Date();
193   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
194
195   $("#banner .btn-close").on("click", function (e) {
196     var cookieId = e.target.id;
197     $("#banner").hide();
198     e.preventDefault();
199     if (cookieId) {
200       Cookies.set(cookieId, "hide", { secure: true, expires: bannerExpiry, path: "/", samesite: "lax" });
201     }
202   });
203
204   if (OSM.MATOMO) {
205     map.on("baselayerchange overlayadd", function (e) {
206       if (e.layer.options) {
207         var goal = OSM.MATOMO.goals[e.layer.options.layerId];
208
209         if (goal) {
210           $("body").trigger("matomogoal", goal);
211         }
212       }
213     });
214   }
215
216   if (params.bounds) {
217     map.fitBounds(params.bounds);
218   } else {
219     map.setView([params.lat, params.lon], params.zoom);
220   }
221
222   if (params.marker) {
223     L.marker([params.mlat, params.mlon]).addTo(map);
224   }
225
226   $("#homeanchor").on("click", function (e) {
227     e.preventDefault();
228
229     var data = $(this).data(),
230         center = L.latLng(data.lat, data.lon);
231
232     map.setView(center, data.zoom);
233     L.marker(center, { icon: OSM.getUserIcon() }).addTo(map);
234   });
235
236   function remoteEditHandler(bbox, object) {
237     var remoteEditHost = "http://127.0.0.1:8111",
238         osmHost = location.protocol + "//" + location.host,
239         query = new URLSearchParams({
240           left: bbox.getWest() - 0.0001,
241           top: bbox.getNorth() + 0.0001,
242           right: bbox.getEast() + 0.0001,
243           bottom: bbox.getSouth() - 0.0001
244         });
245
246     if (object && object.type !== "note") query.set("select", object.type + object.id); // can't select notes
247     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + query, function () {
248       if (object && object.type === "note") {
249         const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
250         sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
251       }
252     });
253
254     function sendRemoteEditCommand(url, callback) {
255       fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) })
256         .then(callback)
257         .catch(function () {
258           // eslint-disable-next-line no-alert
259           alert(I18n.t("site.index.remote_failed"));
260         });
261     }
262
263     return false;
264   }
265
266   $("a[data-editor=remote]").click(function (e) {
267     var params = OSM.mapParams(this.search);
268     remoteEditHandler(map.getBounds(), params.object);
269     e.preventDefault();
270   });
271
272   if (OSM.params().edit_help) {
273     $("#editanchor")
274       .removeAttr("title")
275       .tooltip({
276         placement: "bottom",
277         title: I18n.t("javascripts.edit_help")
278       })
279       .tooltip("show");
280
281     $("body").one("click", function () {
282       $("#editanchor").tooltip("hide");
283     });
284   }
285
286   OSM.Index = function (map) {
287     var page = {};
288
289     page.pushstate = page.popstate = function () {
290       map.setSidebarOverlaid(true);
291       document.title = I18n.t("layouts.project_name.title");
292     };
293
294     page.load = function () {
295       const params = new URLSearchParams(location.search);
296       if (params.has("query")) {
297         $("#sidebar .search_form input[name=query]").value(params.get("query"));
298       }
299       if (!("autofocus" in document.createElement("input"))) {
300         $("#sidebar .search_form input[name=query]").focus();
301       }
302       return map.getState();
303     };
304
305     return page;
306   };
307
308   OSM.Browse = function (map, type) {
309     var page = {};
310
311     page.pushstate = page.popstate = function (path, id) {
312       OSM.loadSidebarContent(path, function () {
313         addObject(type, id);
314       });
315     };
316
317     page.load = function (path, id) {
318       addObject(type, id, true);
319     };
320
321     function addObject(type, id, center) {
322       map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
323         if (!window.location.hash && bounds.isValid() &&
324             (center || !map.getBounds().contains(bounds))) {
325           OSM.router.withoutMoveListener(function () {
326             map.fitBounds(bounds);
327           });
328         }
329       });
330     }
331
332     page.unload = function () {
333       map.removeObject();
334     };
335
336     return page;
337   };
338
339   OSM.OldBrowse = function () {
340     var page = {};
341
342     page.pushstate = page.popstate = function (path) {
343       OSM.loadSidebarContent(path);
344     };
345
346     return page;
347   };
348
349   var history = OSM.History(map);
350
351   OSM.router = OSM.Router(map, {
352     "/": OSM.Index(map),
353     "/search": OSM.Search(map),
354     "/directions": OSM.Directions(map),
355     "/export": OSM.Export(map),
356     "/note/new": OSM.NewNote(map),
357     "/history/friends": history,
358     "/history/nearby": history,
359     "/history": history,
360     "/user/:display_name/history": history,
361     "/note/:id": OSM.Note(map),
362     "/node/:id(/history)": OSM.Browse(map, "node"),
363     "/node/:id/history/:version": OSM.OldBrowse(),
364     "/way/:id(/history)": OSM.Browse(map, "way"),
365     "/way/:id/history/:version": OSM.OldBrowse(),
366     "/relation/:id(/history)": OSM.Browse(map, "relation"),
367     "/relation/:id/history/:version": OSM.OldBrowse(),
368     "/changeset/:id": OSM.Changeset(map),
369     "/query": OSM.Query(map)
370   });
371
372   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
373     remoteEditHandler(map.getBounds(), params.object);
374     OSM.router.setCurrentPath("/");
375   }
376
377   OSM.router.load();
378
379   $(document).on("click", "a", function (e) {
380     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
381       return;
382     }
383
384     // Open links in a new tab as normal.
385     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
386       return;
387     }
388
389     // Ignore cross-protocol and cross-origin links.
390     if (location.protocol !== this.protocol || location.host !== this.host) {
391       return;
392     }
393
394     if (OSM.router.route(this.pathname + this.search + this.hash)) {
395       e.preventDefault();
396       if (this.pathname !== "/directions") {
397         $("header").addClass("closed");
398       }
399     }
400   });
401
402   $(document).on("click", "#sidebar_content .btn-close", function () {
403     OSM.router.route("/" + OSM.formatHash(map));
404   });
405 });