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