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