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