]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Reevaluate iteration methods
[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           alert(I18n.t("site.index.remote_failed"));
259         });
260     }
261
262     return false;
263   }
264
265   $("a[data-editor=remote]").click(function (e) {
266     var params = OSM.mapParams(this.search);
267     remoteEditHandler(map.getBounds(), params.object);
268     e.preventDefault();
269   });
270
271   if (OSM.params().edit_help) {
272     $("#editanchor")
273       .removeAttr("title")
274       .tooltip({
275         placement: "bottom",
276         title: I18n.t("javascripts.edit_help")
277       })
278       .tooltip("show");
279
280     $("body").one("click", function () {
281       $("#editanchor").tooltip("hide");
282     });
283   }
284
285   OSM.Index = function (map) {
286     var page = {};
287
288     page.pushstate = page.popstate = function () {
289       map.setSidebarOverlaid(true);
290       document.title = I18n.t("layouts.project_name.title");
291     };
292
293     page.load = function () {
294       const params = new URLSearchParams(location.search);
295       if (params.has("query")) {
296         $("#sidebar .search_form input[name=query]").value(params.get("query"));
297       }
298       if (!("autofocus" in document.createElement("input"))) {
299         $("#sidebar .search_form input[name=query]").focus();
300       }
301       return map.getState();
302     };
303
304     return page;
305   };
306
307   OSM.Browse = function (map, type) {
308     var page = {};
309
310     page.pushstate = page.popstate = function (path, id) {
311       OSM.loadSidebarContent(path, function () {
312         addObject(type, id);
313       });
314     };
315
316     page.load = function (path, id) {
317       addObject(type, id, true);
318     };
319
320     function addObject(type, id, center) {
321       map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
322         if (!window.location.hash && bounds.isValid() &&
323             (center || !map.getBounds().contains(bounds))) {
324           OSM.router.withoutMoveListener(function () {
325             map.fitBounds(bounds);
326           });
327         }
328       });
329     }
330
331     page.unload = function () {
332       map.removeObject();
333     };
334
335     return page;
336   };
337
338   OSM.OldBrowse = function () {
339     var page = {};
340
341     page.pushstate = page.popstate = function (path) {
342       OSM.loadSidebarContent(path);
343     };
344
345     return page;
346   };
347
348   var history = OSM.History(map);
349
350   OSM.router = OSM.Router(map, {
351     "/": OSM.Index(map),
352     "/search": OSM.Search(map),
353     "/directions": OSM.Directions(map),
354     "/export": OSM.Export(map),
355     "/note/new": OSM.NewNote(map),
356     "/history/friends": history,
357     "/history/nearby": history,
358     "/history": history,
359     "/user/:display_name/history": history,
360     "/note/:id": OSM.Note(map),
361     "/node/:id(/history)": OSM.Browse(map, "node"),
362     "/node/:id/history/:version": OSM.OldBrowse(),
363     "/way/:id(/history)": OSM.Browse(map, "way"),
364     "/way/:id/history/:version": OSM.OldBrowse(),
365     "/relation/:id(/history)": OSM.Browse(map, "relation"),
366     "/relation/:id/history/:version": OSM.OldBrowse(),
367     "/changeset/:id": OSM.Changeset(map),
368     "/query": OSM.Query(map)
369   });
370
371   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
372     remoteEditHandler(map.getBounds(), params.object);
373     OSM.router.setCurrentPath("/");
374   }
375
376   OSM.router.load();
377
378   $(document).on("click", "a", function (e) {
379     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
380       return;
381     }
382
383     // Open links in a new tab as normal.
384     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
385       return;
386     }
387
388     // Ignore cross-protocol and cross-origin links.
389     if (location.protocol !== this.protocol || location.host !== this.host) {
390       return;
391     }
392
393     if (OSM.router.route(this.pathname + this.search + this.hash)) {
394       e.preventDefault();
395       if (this.pathname !== "/directions") {
396         $("header").addClass("closed");
397       }
398     }
399   });
400
401   $(document).on("click", "#sidebar_content .btn-close", function () {
402     OSM.router.route("/" + OSM.formatHash(map));
403   });
404 });