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