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