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