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