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