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